]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - lib/Sema/SemaExpr.cpp
Update clang to r86140.
[FreeBSD/FreeBSD.git] / lib / Sema / SemaExpr.cpp
1 //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements semantic analysis for expressions.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "Sema.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/DeclObjC.h"
17 #include "clang/AST/DeclTemplate.h"
18 #include "clang/AST/ExprCXX.h"
19 #include "clang/AST/ExprObjC.h"
20 #include "clang/Basic/PartialDiagnostic.h"
21 #include "clang/Basic/SourceManager.h"
22 #include "clang/Basic/TargetInfo.h"
23 #include "clang/Lex/LiteralSupport.h"
24 #include "clang/Lex/Preprocessor.h"
25 #include "clang/Parse/DeclSpec.h"
26 #include "clang/Parse/Designator.h"
27 #include "clang/Parse/Scope.h"
28 using namespace clang;
29
30
31 /// \brief Determine whether the use of this declaration is valid, and
32 /// emit any corresponding diagnostics.
33 ///
34 /// This routine diagnoses various problems with referencing
35 /// declarations that can occur when using a declaration. For example,
36 /// it might warn if a deprecated or unavailable declaration is being
37 /// used, or produce an error (and return true) if a C++0x deleted
38 /// function is being used.
39 ///
40 /// If IgnoreDeprecated is set to true, this should not want about deprecated
41 /// decls.
42 ///
43 /// \returns true if there was an error (this declaration cannot be
44 /// referenced), false otherwise.
45 ///
46 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc) {
47   // See if the decl is deprecated.
48   if (D->getAttr<DeprecatedAttr>()) {
49     EmitDeprecationWarning(D, Loc);
50   }
51
52   // See if the decl is unavailable
53   if (D->getAttr<UnavailableAttr>()) {
54     Diag(Loc, diag::warn_unavailable) << D->getDeclName();
55     Diag(D->getLocation(), diag::note_unavailable_here) << 0;
56   }
57   
58   // See if this is a deleted function.
59   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
60     if (FD->isDeleted()) {
61       Diag(Loc, diag::err_deleted_function_use);
62       Diag(D->getLocation(), diag::note_unavailable_here) << true;
63       return true;
64     }
65   }
66
67   return false;
68 }
69
70 /// DiagnoseSentinelCalls - This routine checks on method dispatch calls
71 /// (and other functions in future), which have been declared with sentinel
72 /// attribute. It warns if call does not have the sentinel argument.
73 ///
74 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
75                                  Expr **Args, unsigned NumArgs) {
76   const SentinelAttr *attr = D->getAttr<SentinelAttr>();
77   if (!attr)
78     return;
79   int sentinelPos = attr->getSentinel();
80   int nullPos = attr->getNullPos();
81
82   // FIXME. ObjCMethodDecl and FunctionDecl need be derived from the same common
83   // base class. Then we won't be needing two versions of the same code.
84   unsigned int i = 0;
85   bool warnNotEnoughArgs = false;
86   int isMethod = 0;
87   if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
88     // skip over named parameters.
89     ObjCMethodDecl::param_iterator P, E = MD->param_end();
90     for (P = MD->param_begin(); (P != E && i < NumArgs); ++P) {
91       if (nullPos)
92         --nullPos;
93       else
94         ++i;
95     }
96     warnNotEnoughArgs = (P != E || i >= NumArgs);
97     isMethod = 1;
98   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
99     // skip over named parameters.
100     ObjCMethodDecl::param_iterator P, E = FD->param_end();
101     for (P = FD->param_begin(); (P != E && i < NumArgs); ++P) {
102       if (nullPos)
103         --nullPos;
104       else
105         ++i;
106     }
107     warnNotEnoughArgs = (P != E || i >= NumArgs);
108   } else if (VarDecl *V = dyn_cast<VarDecl>(D)) {
109     // block or function pointer call.
110     QualType Ty = V->getType();
111     if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
112       const FunctionType *FT = Ty->isFunctionPointerType()
113       ? Ty->getAs<PointerType>()->getPointeeType()->getAs<FunctionType>()
114       : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
115       if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT)) {
116         unsigned NumArgsInProto = Proto->getNumArgs();
117         unsigned k;
118         for (k = 0; (k != NumArgsInProto && i < NumArgs); k++) {
119           if (nullPos)
120             --nullPos;
121           else
122             ++i;
123         }
124         warnNotEnoughArgs = (k != NumArgsInProto || i >= NumArgs);
125       }
126       if (Ty->isBlockPointerType())
127         isMethod = 2;
128     } else
129       return;
130   } else
131     return;
132
133   if (warnNotEnoughArgs) {
134     Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
135     Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
136     return;
137   }
138   int sentinel = i;
139   while (sentinelPos > 0 && i < NumArgs-1) {
140     --sentinelPos;
141     ++i;
142   }
143   if (sentinelPos > 0) {
144     Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
145     Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
146     return;
147   }
148   while (i < NumArgs-1) {
149     ++i;
150     ++sentinel;
151   }
152   Expr *sentinelExpr = Args[sentinel];
153   if (sentinelExpr && (!sentinelExpr->getType()->isPointerType() ||
154                        !sentinelExpr->isNullPointerConstant(Context,
155                                             Expr::NPC_ValueDependentIsNull))) {
156     Diag(Loc, diag::warn_missing_sentinel) << isMethod;
157     Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
158   }
159   return;
160 }
161
162 SourceRange Sema::getExprRange(ExprTy *E) const {
163   Expr *Ex = (Expr *)E;
164   return Ex? Ex->getSourceRange() : SourceRange();
165 }
166
167 //===----------------------------------------------------------------------===//
168 //  Standard Promotions and Conversions
169 //===----------------------------------------------------------------------===//
170
171 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
172 void Sema::DefaultFunctionArrayConversion(Expr *&E) {
173   QualType Ty = E->getType();
174   assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
175
176   if (Ty->isFunctionType())
177     ImpCastExprToType(E, Context.getPointerType(Ty),
178                       CastExpr::CK_FunctionToPointerDecay);
179   else if (Ty->isArrayType()) {
180     // In C90 mode, arrays only promote to pointers if the array expression is
181     // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
182     // type 'array of type' is converted to an expression that has type 'pointer
183     // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
184     // that has type 'array of type' ...".  The relevant change is "an lvalue"
185     // (C90) to "an expression" (C99).
186     //
187     // C++ 4.2p1:
188     // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
189     // T" can be converted to an rvalue of type "pointer to T".
190     //
191     if (getLangOptions().C99 || getLangOptions().CPlusPlus ||
192         E->isLvalue(Context) == Expr::LV_Valid)
193       ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
194                         CastExpr::CK_ArrayToPointerDecay);
195   }
196 }
197
198 /// UsualUnaryConversions - Performs various conversions that are common to most
199 /// operators (C99 6.3). The conversions of array and function types are
200 /// sometimes surpressed. For example, the array->pointer conversion doesn't
201 /// apply if the array is an argument to the sizeof or address (&) operators.
202 /// In these instances, this routine should *not* be called.
203 Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
204   QualType Ty = Expr->getType();
205   assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
206
207   // C99 6.3.1.1p2:
208   //
209   //   The following may be used in an expression wherever an int or
210   //   unsigned int may be used:
211   //     - an object or expression with an integer type whose integer
212   //       conversion rank is less than or equal to the rank of int
213   //       and unsigned int.
214   //     - A bit-field of type _Bool, int, signed int, or unsigned int.
215   //
216   //   If an int can represent all values of the original type, the
217   //   value is converted to an int; otherwise, it is converted to an
218   //   unsigned int. These are called the integer promotions. All
219   //   other types are unchanged by the integer promotions.
220   QualType PTy = Context.isPromotableBitField(Expr);
221   if (!PTy.isNull()) {
222     ImpCastExprToType(Expr, PTy, CastExpr::CK_IntegralCast);
223     return Expr;
224   }
225   if (Ty->isPromotableIntegerType()) {
226     QualType PT = Context.getPromotedIntegerType(Ty);
227     ImpCastExprToType(Expr, PT, CastExpr::CK_IntegralCast);
228     return Expr;
229   }
230
231   DefaultFunctionArrayConversion(Expr);
232   return Expr;
233 }
234
235 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
236 /// do not have a prototype. Arguments that have type float are promoted to
237 /// double. All other argument types are converted by UsualUnaryConversions().
238 void Sema::DefaultArgumentPromotion(Expr *&Expr) {
239   QualType Ty = Expr->getType();
240   assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
241
242   // If this is a 'float' (CVR qualified or typedef) promote to double.
243   if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
244     if (BT->getKind() == BuiltinType::Float)
245       return ImpCastExprToType(Expr, Context.DoubleTy,
246                                CastExpr::CK_FloatingCast);
247
248   UsualUnaryConversions(Expr);
249 }
250
251 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
252 /// will warn if the resulting type is not a POD type, and rejects ObjC
253 /// interfaces passed by value.  This returns true if the argument type is
254 /// completely illegal.
255 bool Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT) {
256   DefaultArgumentPromotion(Expr);
257
258   if (Expr->getType()->isObjCInterfaceType()) {
259     Diag(Expr->getLocStart(),
260          diag::err_cannot_pass_objc_interface_to_vararg)
261       << Expr->getType() << CT;
262     return true;
263   }
264
265   if (!Expr->getType()->isPODType())
266     Diag(Expr->getLocStart(), diag::warn_cannot_pass_non_pod_arg_to_vararg)
267       << Expr->getType() << CT;
268
269   return false;
270 }
271
272
273 /// UsualArithmeticConversions - Performs various conversions that are common to
274 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
275 /// routine returns the first non-arithmetic type found. The client is
276 /// responsible for emitting appropriate error diagnostics.
277 /// FIXME: verify the conversion rules for "complex int" are consistent with
278 /// GCC.
279 QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
280                                           bool isCompAssign) {
281   if (!isCompAssign)
282     UsualUnaryConversions(lhsExpr);
283
284   UsualUnaryConversions(rhsExpr);
285
286   // For conversion purposes, we ignore any qualifiers.
287   // For example, "const float" and "float" are equivalent.
288   QualType lhs =
289     Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
290   QualType rhs =
291     Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
292
293   // If both types are identical, no conversion is needed.
294   if (lhs == rhs)
295     return lhs;
296
297   // If either side is a non-arithmetic type (e.g. a pointer), we are done.
298   // The caller can deal with this (e.g. pointer + int).
299   if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
300     return lhs;
301
302   // Perform bitfield promotions.
303   QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(lhsExpr);
304   if (!LHSBitfieldPromoteTy.isNull())
305     lhs = LHSBitfieldPromoteTy;
306   QualType RHSBitfieldPromoteTy = Context.isPromotableBitField(rhsExpr);
307   if (!RHSBitfieldPromoteTy.isNull())
308     rhs = RHSBitfieldPromoteTy;
309
310   QualType destType = Context.UsualArithmeticConversionsType(lhs, rhs);
311   if (!isCompAssign)
312     ImpCastExprToType(lhsExpr, destType, CastExpr::CK_Unknown);
313   ImpCastExprToType(rhsExpr, destType, CastExpr::CK_Unknown);
314   return destType;
315 }
316
317 //===----------------------------------------------------------------------===//
318 //  Semantic Analysis for various Expression Types
319 //===----------------------------------------------------------------------===//
320
321
322 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
323 /// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
324 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
325 /// multiple tokens.  However, the common case is that StringToks points to one
326 /// string.
327 ///
328 Action::OwningExprResult
329 Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
330   assert(NumStringToks && "Must have at least one string!");
331
332   StringLiteralParser Literal(StringToks, NumStringToks, PP);
333   if (Literal.hadError)
334     return ExprError();
335
336   llvm::SmallVector<SourceLocation, 4> StringTokLocs;
337   for (unsigned i = 0; i != NumStringToks; ++i)
338     StringTokLocs.push_back(StringToks[i].getLocation());
339
340   QualType StrTy = Context.CharTy;
341   if (Literal.AnyWide) StrTy = Context.getWCharType();
342   if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
343
344   // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
345   if (getLangOptions().CPlusPlus)
346     StrTy.addConst();
347
348   // Get an array type for the string, according to C99 6.4.5.  This includes
349   // the nul terminator character as well as the string length for pascal
350   // strings.
351   StrTy = Context.getConstantArrayType(StrTy,
352                                  llvm::APInt(32, Literal.GetNumStringChars()+1),
353                                        ArrayType::Normal, 0);
354
355   // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
356   return Owned(StringLiteral::Create(Context, Literal.GetString(),
357                                      Literal.GetStringLength(),
358                                      Literal.AnyWide, StrTy,
359                                      &StringTokLocs[0],
360                                      StringTokLocs.size()));
361 }
362
363 /// ShouldSnapshotBlockValueReference - Return true if a reference inside of
364 /// CurBlock to VD should cause it to be snapshotted (as we do for auto
365 /// variables defined outside the block) or false if this is not needed (e.g.
366 /// for values inside the block or for globals).
367 ///
368 /// This also keeps the 'hasBlockDeclRefExprs' in the BlockSemaInfo records
369 /// up-to-date.
370 ///
371 static bool ShouldSnapshotBlockValueReference(BlockSemaInfo *CurBlock,
372                                               ValueDecl *VD) {
373   // If the value is defined inside the block, we couldn't snapshot it even if
374   // we wanted to.
375   if (CurBlock->TheDecl == VD->getDeclContext())
376     return false;
377
378   // If this is an enum constant or function, it is constant, don't snapshot.
379   if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
380     return false;
381
382   // If this is a reference to an extern, static, or global variable, no need to
383   // snapshot it.
384   // FIXME: What about 'const' variables in C++?
385   if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
386     if (!Var->hasLocalStorage())
387       return false;
388
389   // Blocks that have these can't be constant.
390   CurBlock->hasBlockDeclRefExprs = true;
391
392   // If we have nested blocks, the decl may be declared in an outer block (in
393   // which case that outer block doesn't get "hasBlockDeclRefExprs") or it may
394   // be defined outside all of the current blocks (in which case the blocks do
395   // all get the bit).  Walk the nesting chain.
396   for (BlockSemaInfo *NextBlock = CurBlock->PrevBlockInfo; NextBlock;
397        NextBlock = NextBlock->PrevBlockInfo) {
398     // If we found the defining block for the variable, don't mark the block as
399     // having a reference outside it.
400     if (NextBlock->TheDecl == VD->getDeclContext())
401       break;
402
403     // Otherwise, the DeclRef from the inner block causes the outer one to need
404     // a snapshot as well.
405     NextBlock->hasBlockDeclRefExprs = true;
406   }
407
408   return true;
409 }
410
411
412
413 /// BuildDeclRefExpr - Build a DeclRefExpr.
414 Sema::OwningExprResult
415 Sema::BuildDeclRefExpr(NamedDecl *D, QualType Ty, SourceLocation Loc,
416                        bool TypeDependent, bool ValueDependent,
417                        const CXXScopeSpec *SS) {
418   if (Context.getCanonicalType(Ty) == Context.UndeducedAutoTy) {
419     Diag(Loc,
420          diag::err_auto_variable_cannot_appear_in_own_initializer)
421       << D->getDeclName();
422     return ExprError();
423   }
424
425   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
426     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
427       if (const FunctionDecl *FD = MD->getParent()->isLocalClass()) {
428         if (VD->hasLocalStorage() && VD->getDeclContext() != CurContext) {
429           Diag(Loc, diag::err_reference_to_local_var_in_enclosing_function)
430             << D->getIdentifier() << FD->getDeclName();
431           Diag(D->getLocation(), diag::note_local_variable_declared_here)
432             << D->getIdentifier();
433           return ExprError();
434         }
435       }
436     }
437   }
438
439   MarkDeclarationReferenced(Loc, D);
440
441   return Owned(DeclRefExpr::Create(Context, 
442                               SS? (NestedNameSpecifier *)SS->getScopeRep() : 0, 
443                                    SS? SS->getRange() : SourceRange(), 
444                                    D, Loc, 
445                                    Ty, TypeDependent, ValueDependent));
446 }
447
448 /// getObjectForAnonymousRecordDecl - Retrieve the (unnamed) field or
449 /// variable corresponding to the anonymous union or struct whose type
450 /// is Record.
451 static Decl *getObjectForAnonymousRecordDecl(ASTContext &Context,
452                                              RecordDecl *Record) {
453   assert(Record->isAnonymousStructOrUnion() &&
454          "Record must be an anonymous struct or union!");
455
456   // FIXME: Once Decls are directly linked together, this will be an O(1)
457   // operation rather than a slow walk through DeclContext's vector (which
458   // itself will be eliminated). DeclGroups might make this even better.
459   DeclContext *Ctx = Record->getDeclContext();
460   for (DeclContext::decl_iterator D = Ctx->decls_begin(),
461                                DEnd = Ctx->decls_end();
462        D != DEnd; ++D) {
463     if (*D == Record) {
464       // The object for the anonymous struct/union directly
465       // follows its type in the list of declarations.
466       ++D;
467       assert(D != DEnd && "Missing object for anonymous record");
468       assert(!cast<NamedDecl>(*D)->getDeclName() && "Decl should be unnamed");
469       return *D;
470     }
471   }
472
473   assert(false && "Missing object for anonymous record");
474   return 0;
475 }
476
477 /// \brief Given a field that represents a member of an anonymous
478 /// struct/union, build the path from that field's context to the
479 /// actual member.
480 ///
481 /// Construct the sequence of field member references we'll have to
482 /// perform to get to the field in the anonymous union/struct. The
483 /// list of members is built from the field outward, so traverse it
484 /// backwards to go from an object in the current context to the field
485 /// we found.
486 ///
487 /// \returns The variable from which the field access should begin,
488 /// for an anonymous struct/union that is not a member of another
489 /// class. Otherwise, returns NULL.
490 VarDecl *Sema::BuildAnonymousStructUnionMemberPath(FieldDecl *Field,
491                                    llvm::SmallVectorImpl<FieldDecl *> &Path) {
492   assert(Field->getDeclContext()->isRecord() &&
493          cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion()
494          && "Field must be stored inside an anonymous struct or union");
495
496   Path.push_back(Field);
497   VarDecl *BaseObject = 0;
498   DeclContext *Ctx = Field->getDeclContext();
499   do {
500     RecordDecl *Record = cast<RecordDecl>(Ctx);
501     Decl *AnonObject = getObjectForAnonymousRecordDecl(Context, Record);
502     if (FieldDecl *AnonField = dyn_cast<FieldDecl>(AnonObject))
503       Path.push_back(AnonField);
504     else {
505       BaseObject = cast<VarDecl>(AnonObject);
506       break;
507     }
508     Ctx = Ctx->getParent();
509   } while (Ctx->isRecord() &&
510            cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion());
511
512   return BaseObject;
513 }
514
515 Sema::OwningExprResult
516 Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc,
517                                                FieldDecl *Field,
518                                                Expr *BaseObjectExpr,
519                                                SourceLocation OpLoc) {
520   llvm::SmallVector<FieldDecl *, 4> AnonFields;
521   VarDecl *BaseObject = BuildAnonymousStructUnionMemberPath(Field,
522                                                             AnonFields);
523
524   // Build the expression that refers to the base object, from
525   // which we will build a sequence of member references to each
526   // of the anonymous union objects and, eventually, the field we
527   // found via name lookup.
528   bool BaseObjectIsPointer = false;
529   Qualifiers BaseQuals;
530   if (BaseObject) {
531     // BaseObject is an anonymous struct/union variable (and is,
532     // therefore, not part of another non-anonymous record).
533     if (BaseObjectExpr) BaseObjectExpr->Destroy(Context);
534     MarkDeclarationReferenced(Loc, BaseObject);
535     BaseObjectExpr = new (Context) DeclRefExpr(BaseObject,BaseObject->getType(),
536                                                SourceLocation());
537     BaseQuals
538       = Context.getCanonicalType(BaseObject->getType()).getQualifiers();
539   } else if (BaseObjectExpr) {
540     // The caller provided the base object expression. Determine
541     // whether its a pointer and whether it adds any qualifiers to the
542     // anonymous struct/union fields we're looking into.
543     QualType ObjectType = BaseObjectExpr->getType();
544     if (const PointerType *ObjectPtr = ObjectType->getAs<PointerType>()) {
545       BaseObjectIsPointer = true;
546       ObjectType = ObjectPtr->getPointeeType();
547     }
548     BaseQuals
549       = Context.getCanonicalType(ObjectType).getQualifiers();
550   } else {
551     // We've found a member of an anonymous struct/union that is
552     // inside a non-anonymous struct/union, so in a well-formed
553     // program our base object expression is "this".
554     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
555       if (!MD->isStatic()) {
556         QualType AnonFieldType
557           = Context.getTagDeclType(
558                      cast<RecordDecl>(AnonFields.back()->getDeclContext()));
559         QualType ThisType = Context.getTagDeclType(MD->getParent());
560         if ((Context.getCanonicalType(AnonFieldType)
561                == Context.getCanonicalType(ThisType)) ||
562             IsDerivedFrom(ThisType, AnonFieldType)) {
563           // Our base object expression is "this".
564           BaseObjectExpr = new (Context) CXXThisExpr(SourceLocation(),
565                                                      MD->getThisType(Context));
566           BaseObjectIsPointer = true;
567         }
568       } else {
569         return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
570           << Field->getDeclName());
571       }
572       BaseQuals = Qualifiers::fromCVRMask(MD->getTypeQualifiers());
573     }
574
575     if (!BaseObjectExpr)
576       return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
577         << Field->getDeclName());
578   }
579
580   // Build the implicit member references to the field of the
581   // anonymous struct/union.
582   Expr *Result = BaseObjectExpr;
583   Qualifiers ResultQuals = BaseQuals;
584   for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
585          FI = AnonFields.rbegin(), FIEnd = AnonFields.rend();
586        FI != FIEnd; ++FI) {
587     QualType MemberType = (*FI)->getType();
588     Qualifiers MemberTypeQuals =
589       Context.getCanonicalType(MemberType).getQualifiers();
590
591     // CVR attributes from the base are picked up by members,
592     // except that 'mutable' members don't pick up 'const'.
593     if ((*FI)->isMutable())
594       ResultQuals.removeConst();
595
596     // GC attributes are never picked up by members.
597     ResultQuals.removeObjCGCAttr();
598
599     // TR 18037 does not allow fields to be declared with address spaces.
600     assert(!MemberTypeQuals.hasAddressSpace());
601
602     Qualifiers NewQuals = ResultQuals + MemberTypeQuals;
603     if (NewQuals != MemberTypeQuals)
604       MemberType = Context.getQualifiedType(MemberType, NewQuals);
605
606     MarkDeclarationReferenced(Loc, *FI);
607     // FIXME: Might this end up being a qualified name?
608     Result = new (Context) MemberExpr(Result, BaseObjectIsPointer, *FI,
609                                       OpLoc, MemberType);
610     BaseObjectIsPointer = false;
611     ResultQuals = NewQuals;
612   }
613
614   return Owned(Result);
615 }
616
617 Sema::OwningExprResult Sema::ActOnIdExpression(Scope *S,
618                                                const CXXScopeSpec &SS,
619                                                UnqualifiedId &Name,
620                                                bool HasTrailingLParen,
621                                                bool IsAddressOfOperand) {
622   if (Name.getKind() == UnqualifiedId::IK_TemplateId) {
623     ASTTemplateArgsPtr TemplateArgsPtr(*this,
624                                        Name.TemplateId->getTemplateArgs(),
625                                        Name.TemplateId->getTemplateArgIsType(),
626                                        Name.TemplateId->NumArgs);
627     return ActOnTemplateIdExpr(SS, 
628                                TemplateTy::make(Name.TemplateId->Template), 
629                                Name.TemplateId->TemplateNameLoc,
630                                Name.TemplateId->LAngleLoc,
631                                TemplateArgsPtr,
632                                Name.TemplateId->getTemplateArgLocations(),
633                                Name.TemplateId->RAngleLoc);
634   }
635   
636   // FIXME: We lose a bunch of source information by doing this. Later,
637   // we'll want to merge ActOnDeclarationNameExpr's logic into 
638   // ActOnIdExpression.
639   return ActOnDeclarationNameExpr(S, 
640                                   Name.StartLocation,
641                                   GetNameFromUnqualifiedId(Name),
642                                   HasTrailingLParen,
643                                   &SS,
644                                   IsAddressOfOperand);
645 }
646
647 /// ActOnDeclarationNameExpr - The parser has read some kind of name
648 /// (e.g., a C++ id-expression (C++ [expr.prim]p1)). This routine
649 /// performs lookup on that name and returns an expression that refers
650 /// to that name. This routine isn't directly called from the parser,
651 /// because the parser doesn't know about DeclarationName. Rather,
652 /// this routine is called by ActOnIdExpression, which contains a
653 /// parsed UnqualifiedId.
654 ///
655 /// HasTrailingLParen indicates whether this identifier is used in a
656 /// function call context.  LookupCtx is only used for a C++
657 /// qualified-id (foo::bar) to indicate the class or namespace that
658 /// the identifier must be a member of.
659 ///
660 /// isAddressOfOperand means that this expression is the direct operand
661 /// of an address-of operator. This matters because this is the only
662 /// situation where a qualified name referencing a non-static member may
663 /// appear outside a member function of this class.
664 Sema::OwningExprResult
665 Sema::ActOnDeclarationNameExpr(Scope *S, SourceLocation Loc,
666                                DeclarationName Name, bool HasTrailingLParen,
667                                const CXXScopeSpec *SS,
668                                bool isAddressOfOperand) {
669   // Could be enum-constant, value decl, instance variable, etc.
670   if (SS && SS->isInvalid())
671     return ExprError();
672
673   // C++ [temp.dep.expr]p3:
674   //   An id-expression is type-dependent if it contains:
675   //     -- a nested-name-specifier that contains a class-name that
676   //        names a dependent type.
677   // FIXME: Member of the current instantiation.
678   if (SS && isDependentScopeSpecifier(*SS)) {
679     return Owned(new (Context) UnresolvedDeclRefExpr(Name, Context.DependentTy,
680                                                      Loc, SS->getRange(),
681                 static_cast<NestedNameSpecifier *>(SS->getScopeRep()),
682                                                      isAddressOfOperand));
683   }
684
685   LookupResult Lookup;
686   LookupParsedName(Lookup, S, SS, Name, LookupOrdinaryName, false, true, Loc);
687
688   if (Lookup.isAmbiguous()) {
689     DiagnoseAmbiguousLookup(Lookup, Name, Loc,
690                             SS && SS->isSet() ? SS->getRange()
691                                               : SourceRange());
692     return ExprError();
693   }
694
695   NamedDecl *D = Lookup.getAsSingleDecl(Context);
696
697   // If this reference is in an Objective-C method, then ivar lookup happens as
698   // well.
699   IdentifierInfo *II = Name.getAsIdentifierInfo();
700   if (II && getCurMethodDecl()) {
701     // There are two cases to handle here.  1) scoped lookup could have failed,
702     // in which case we should look for an ivar.  2) scoped lookup could have
703     // found a decl, but that decl is outside the current instance method (i.e.
704     // a global variable).  In these two cases, we do a lookup for an ivar with
705     // this name, if the lookup sucedes, we replace it our current decl.
706     if (D == 0 || D->isDefinedOutsideFunctionOrMethod()) {
707       ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
708       ObjCInterfaceDecl *ClassDeclared;
709       if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
710         // Check if referencing a field with __attribute__((deprecated)).
711         if (DiagnoseUseOfDecl(IV, Loc))
712           return ExprError();
713
714         // If we're referencing an invalid decl, just return this as a silent
715         // error node.  The error diagnostic was already emitted on the decl.
716         if (IV->isInvalidDecl())
717           return ExprError();
718
719         bool IsClsMethod = getCurMethodDecl()->isClassMethod();
720         // If a class method attemps to use a free standing ivar, this is
721         // an error.
722         if (IsClsMethod && D && !D->isDefinedOutsideFunctionOrMethod())
723            return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
724                            << IV->getDeclName());
725         // If a class method uses a global variable, even if an ivar with
726         // same name exists, use the global.
727         if (!IsClsMethod) {
728           if (IV->getAccessControl() == ObjCIvarDecl::Private &&
729               ClassDeclared != IFace)
730            Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
731           // FIXME: This should use a new expr for a direct reference, don't
732           // turn this into Self->ivar, just return a BareIVarExpr or something.
733           IdentifierInfo &II = Context.Idents.get("self");
734           UnqualifiedId SelfName;
735           SelfName.setIdentifier(&II, SourceLocation());          
736           CXXScopeSpec SelfScopeSpec;
737           OwningExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
738                                                         SelfName, false, false);
739           MarkDeclarationReferenced(Loc, IV);
740           return Owned(new (Context)
741                        ObjCIvarRefExpr(IV, IV->getType(), Loc,
742                                        SelfExpr.takeAs<Expr>(), true, true));
743         }
744       }
745     } else if (getCurMethodDecl()->isInstanceMethod()) {
746       // We should warn if a local variable hides an ivar.
747       ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
748       ObjCInterfaceDecl *ClassDeclared;
749       if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
750         if (IV->getAccessControl() != ObjCIvarDecl::Private ||
751             IFace == ClassDeclared)
752           Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
753       }
754     }
755     // Needed to implement property "super.method" notation.
756     if (D == 0 && II->isStr("super")) {
757       QualType T;
758
759       if (getCurMethodDecl()->isInstanceMethod())
760         T = Context.getObjCObjectPointerType(Context.getObjCInterfaceType(
761                                       getCurMethodDecl()->getClassInterface()));
762       else
763         T = Context.getObjCClassType();
764       return Owned(new (Context) ObjCSuperExpr(Loc, T));
765     }
766   }
767
768   // Determine whether this name might be a candidate for
769   // argument-dependent lookup.
770   bool ADL = getLangOptions().CPlusPlus && (!SS || !SS->isSet()) &&
771              HasTrailingLParen;
772
773   if (ADL && D == 0) {
774     // We've seen something of the form
775     //
776     //   identifier(
777     //
778     // and we did not find any entity by the name
779     // "identifier". However, this identifier is still subject to
780     // argument-dependent lookup, so keep track of the name.
781     return Owned(new (Context) UnresolvedFunctionNameExpr(Name,
782                                                           Context.OverloadTy,
783                                                           Loc));
784   }
785
786   if (D == 0) {
787     // Otherwise, this could be an implicitly declared function reference (legal
788     // in C90, extension in C99).
789     if (HasTrailingLParen && II &&
790         !getLangOptions().CPlusPlus) // Not in C++.
791       D = ImplicitlyDefineFunction(Loc, *II, S);
792     else {
793       // If this name wasn't predeclared and if this is not a function call,
794       // diagnose the problem.
795       if (SS && !SS->isEmpty())
796         return ExprError(Diag(Loc, diag::err_no_member)
797                            << Name << computeDeclContext(*SS, false)
798                            << SS->getRange());
799       else if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
800                Name.getNameKind() == DeclarationName::CXXConversionFunctionName)
801         return ExprError(Diag(Loc, diag::err_undeclared_use)
802           << Name.getAsString());
803       else
804         return ExprError(Diag(Loc, diag::err_undeclared_var_use) << Name);
805     }
806   }
807
808   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
809     // Warn about constructs like:
810     //   if (void *X = foo()) { ... } else { X }.
811     // In the else block, the pointer is always false.
812
813     // FIXME: In a template instantiation, we don't have scope
814     // information to check this property.
815     if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
816       Scope *CheckS = S;
817       while (CheckS) {
818         if (CheckS->isWithinElse() &&
819             CheckS->getControlParent()->isDeclScope(DeclPtrTy::make(Var))) {
820           if (Var->getType()->isBooleanType())
821             ExprError(Diag(Loc, diag::warn_value_always_false)
822                       << Var->getDeclName());
823           else
824             ExprError(Diag(Loc, diag::warn_value_always_zero)
825                       << Var->getDeclName());
826           break;
827         }
828
829         // Move up one more control parent to check again.
830         CheckS = CheckS->getControlParent();
831         if (CheckS)
832           CheckS = CheckS->getParent();
833       }
834     }
835   } else if (FunctionDecl *Func = dyn_cast<FunctionDecl>(D)) {
836     if (!getLangOptions().CPlusPlus && !Func->hasPrototype()) {
837       // C99 DR 316 says that, if a function type comes from a
838       // function definition (without a prototype), that type is only
839       // used for checking compatibility. Therefore, when referencing
840       // the function, we pretend that we don't have the full function
841       // type.
842       if (DiagnoseUseOfDecl(Func, Loc))
843         return ExprError();
844
845       QualType T = Func->getType();
846       QualType NoProtoType = T;
847       if (const FunctionProtoType *Proto = T->getAs<FunctionProtoType>())
848         NoProtoType = Context.getFunctionNoProtoType(Proto->getResultType());
849       return BuildDeclRefExpr(Func, NoProtoType, Loc, false, false, SS);
850     }
851   }
852
853   return BuildDeclarationNameExpr(Loc, D, HasTrailingLParen, SS, isAddressOfOperand);
854 }
855 /// \brief Cast member's object to its own class if necessary.
856 bool
857 Sema::PerformObjectMemberConversion(Expr *&From, NamedDecl *Member) {
858   if (FieldDecl *FD = dyn_cast<FieldDecl>(Member))
859     if (CXXRecordDecl *RD =
860         dyn_cast<CXXRecordDecl>(FD->getDeclContext())) {
861       QualType DestType =
862         Context.getCanonicalType(Context.getTypeDeclType(RD));
863       if (DestType->isDependentType() || From->getType()->isDependentType())
864         return false;
865       QualType FromRecordType = From->getType();
866       QualType DestRecordType = DestType;
867       if (FromRecordType->getAs<PointerType>()) {
868         DestType = Context.getPointerType(DestType);
869         FromRecordType = FromRecordType->getPointeeType();
870       }
871       if (!Context.hasSameUnqualifiedType(FromRecordType, DestRecordType) &&
872           CheckDerivedToBaseConversion(FromRecordType,
873                                        DestRecordType,
874                                        From->getSourceRange().getBegin(),
875                                        From->getSourceRange()))
876         return true;
877       ImpCastExprToType(From, DestType, CastExpr::CK_DerivedToBase,
878                         /*isLvalue=*/true);
879     }
880   return false;
881 }
882
883 /// \brief Build a MemberExpr AST node.
884 static MemberExpr *BuildMemberExpr(ASTContext &C, Expr *Base, bool isArrow,
885                                    const CXXScopeSpec *SS, NamedDecl *Member,
886                                    SourceLocation Loc, QualType Ty) {
887   if (SS && SS->isSet())
888     return MemberExpr::Create(C, Base, isArrow,
889                               (NestedNameSpecifier *)SS->getScopeRep(),
890                               SS->getRange(), Member, Loc,
891                               // FIXME: Explicit template argument lists
892                               false, SourceLocation(), 0, 0, SourceLocation(),
893                               Ty);
894
895   return new (C) MemberExpr(Base, isArrow, Member, Loc, Ty);
896 }
897
898 /// \brief Complete semantic analysis for a reference to the given declaration.
899 Sema::OwningExprResult
900 Sema::BuildDeclarationNameExpr(SourceLocation Loc, NamedDecl *D,
901                                bool HasTrailingLParen,
902                                const CXXScopeSpec *SS,
903                                bool isAddressOfOperand) {
904   assert(D && "Cannot refer to a NULL declaration");
905   DeclarationName Name = D->getDeclName();
906
907   // If this is an expression of the form &Class::member, don't build an
908   // implicit member ref, because we want a pointer to the member in general,
909   // not any specific instance's member.
910   if (isAddressOfOperand && SS && !SS->isEmpty() && !HasTrailingLParen) {
911     DeclContext *DC = computeDeclContext(*SS);
912     if (D && isa<CXXRecordDecl>(DC)) {
913       QualType DType;
914       if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
915         DType = FD->getType().getNonReferenceType();
916       } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
917         DType = Method->getType();
918       } else if (isa<OverloadedFunctionDecl>(D)) {
919         DType = Context.OverloadTy;
920       }
921       // Could be an inner type. That's diagnosed below, so ignore it here.
922       if (!DType.isNull()) {
923         // The pointer is type- and value-dependent if it points into something
924         // dependent.
925         bool Dependent = DC->isDependentContext();
926         return BuildDeclRefExpr(D, DType, Loc, Dependent, Dependent, SS);
927       }
928     }
929   }
930
931   // We may have found a field within an anonymous union or struct
932   // (C++ [class.union]).
933   // FIXME: This needs to happen post-isImplicitMemberReference?
934   if (FieldDecl *FD = dyn_cast<FieldDecl>(D))
935     if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
936       return BuildAnonymousStructUnionMemberReference(Loc, FD);
937
938   // Cope with an implicit member access in a C++ non-static member function.
939   QualType ThisType, MemberType;
940   if (isImplicitMemberReference(SS, D, Loc, ThisType, MemberType)) {
941     Expr *This = new (Context) CXXThisExpr(SourceLocation(), ThisType);
942     MarkDeclarationReferenced(Loc, D);
943     if (PerformObjectMemberConversion(This, D))
944       return ExprError();
945
946     bool ShouldCheckUse = true;
947     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
948       // Don't diagnose the use of a virtual member function unless it's
949       // explicitly qualified.
950       if (MD->isVirtual() && (!SS || !SS->isSet()))
951         ShouldCheckUse = false;
952     }
953
954     if (ShouldCheckUse && DiagnoseUseOfDecl(D, Loc))
955       return ExprError();
956     return Owned(BuildMemberExpr(Context, This, true, SS, D,
957                                  Loc, MemberType));
958   }
959
960   if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
961     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
962       if (MD->isStatic())
963         // "invalid use of member 'x' in static member function"
964         return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
965           << FD->getDeclName());
966     }
967
968     // Any other ways we could have found the field in a well-formed
969     // program would have been turned into implicit member expressions
970     // above.
971     return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
972       << FD->getDeclName());
973   }
974
975   if (isa<TypedefDecl>(D))
976     return ExprError(Diag(Loc, diag::err_unexpected_typedef) << Name);
977   if (isa<ObjCInterfaceDecl>(D))
978     return ExprError(Diag(Loc, diag::err_unexpected_interface) << Name);
979   if (isa<NamespaceDecl>(D))
980     return ExprError(Diag(Loc, diag::err_unexpected_namespace) << Name);
981
982   // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
983   if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D))
984     return BuildDeclRefExpr(Ovl, Context.OverloadTy, Loc,
985                            false, false, SS);
986   else if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
987     return BuildDeclRefExpr(Template, Context.OverloadTy, Loc,
988                             false, false, SS);
989   else if (UnresolvedUsingDecl *UD = dyn_cast<UnresolvedUsingDecl>(D))
990     return BuildDeclRefExpr(UD, Context.DependentTy, Loc,
991                             /*TypeDependent=*/true,
992                             /*ValueDependent=*/true, SS);
993
994   ValueDecl *VD = cast<ValueDecl>(D);
995
996   // Check whether this declaration can be used. Note that we suppress
997   // this check when we're going to perform argument-dependent lookup
998   // on this function name, because this might not be the function
999   // that overload resolution actually selects.
1000   bool ADL = getLangOptions().CPlusPlus && (!SS || !SS->isSet()) &&
1001              HasTrailingLParen;
1002   if (!(ADL && isa<FunctionDecl>(VD)) && DiagnoseUseOfDecl(VD, Loc))
1003     return ExprError();
1004
1005   // Only create DeclRefExpr's for valid Decl's.
1006   if (VD->isInvalidDecl())
1007     return ExprError();
1008
1009   // If the identifier reference is inside a block, and it refers to a value
1010   // that is outside the block, create a BlockDeclRefExpr instead of a
1011   // DeclRefExpr.  This ensures the value is treated as a copy-in snapshot when
1012   // the block is formed.
1013   //
1014   // We do not do this for things like enum constants, global variables, etc,
1015   // as they do not get snapshotted.
1016   //
1017   if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
1018     MarkDeclarationReferenced(Loc, VD);
1019     QualType ExprTy = VD->getType().getNonReferenceType();
1020     // The BlocksAttr indicates the variable is bound by-reference.
1021     if (VD->getAttr<BlocksAttr>())
1022       return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, true));
1023     // This is to record that a 'const' was actually synthesize and added.
1024     bool constAdded = !ExprTy.isConstQualified();
1025     // Variable will be bound by-copy, make it const within the closure.
1026
1027     ExprTy.addConst();
1028     return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, false,
1029                                                 constAdded));
1030   }
1031   // If this reference is not in a block or if the referenced variable is
1032   // within the block, create a normal DeclRefExpr.
1033
1034   bool TypeDependent = false;
1035   bool ValueDependent = false;
1036   if (getLangOptions().CPlusPlus) {
1037     // C++ [temp.dep.expr]p3:
1038     //   An id-expression is type-dependent if it contains:
1039     //     - an identifier that was declared with a dependent type,
1040     if (VD->getType()->isDependentType())
1041       TypeDependent = true;
1042     //     - FIXME: a template-id that is dependent,
1043     //     - a conversion-function-id that specifies a dependent type,
1044     else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1045              Name.getCXXNameType()->isDependentType())
1046       TypeDependent = true;
1047     //     - a nested-name-specifier that contains a class-name that
1048     //       names a dependent type.
1049     else if (SS && !SS->isEmpty()) {
1050       for (DeclContext *DC = computeDeclContext(*SS);
1051            DC; DC = DC->getParent()) {
1052         // FIXME: could stop early at namespace scope.
1053         if (DC->isRecord()) {
1054           CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
1055           if (Context.getTypeDeclType(Record)->isDependentType()) {
1056             TypeDependent = true;
1057             break;
1058           }
1059         }
1060       }
1061     }
1062
1063     // C++ [temp.dep.constexpr]p2:
1064     //
1065     //   An identifier is value-dependent if it is:
1066     //     - a name declared with a dependent type,
1067     if (TypeDependent)
1068       ValueDependent = true;
1069     //     - the name of a non-type template parameter,
1070     else if (isa<NonTypeTemplateParmDecl>(VD))
1071       ValueDependent = true;
1072     //    - a constant with integral or enumeration type and is
1073     //      initialized with an expression that is value-dependent
1074     else if (const VarDecl *Dcl = dyn_cast<VarDecl>(VD)) {
1075       if (Context.getCanonicalType(Dcl->getType()).getCVRQualifiers()
1076           == Qualifiers::Const &&
1077           Dcl->getInit()) {
1078         ValueDependent = Dcl->getInit()->isValueDependent();
1079       }
1080     }
1081   }
1082
1083   return BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc,
1084                           TypeDependent, ValueDependent, SS);
1085 }
1086
1087 Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
1088                                                  tok::TokenKind Kind) {
1089   PredefinedExpr::IdentType IT;
1090
1091   switch (Kind) {
1092   default: assert(0 && "Unknown simple primary expr!");
1093   case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
1094   case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
1095   case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
1096   }
1097
1098   // Pre-defined identifiers are of type char[x], where x is the length of the
1099   // string.
1100
1101   Decl *currentDecl = getCurFunctionOrMethodDecl();
1102   if (!currentDecl) {
1103     Diag(Loc, diag::ext_predef_outside_function);
1104     currentDecl = Context.getTranslationUnitDecl();
1105   }
1106
1107   QualType ResTy;
1108   if (cast<DeclContext>(currentDecl)->isDependentContext()) {
1109     ResTy = Context.DependentTy;
1110   } else {
1111     unsigned Length =
1112       PredefinedExpr::ComputeName(Context, IT, currentDecl).length();
1113
1114     llvm::APInt LengthI(32, Length + 1);
1115     ResTy = Context.CharTy.withConst();
1116     ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
1117   }
1118   return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
1119 }
1120
1121 Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
1122   llvm::SmallString<16> CharBuffer;
1123   CharBuffer.resize(Tok.getLength());
1124   const char *ThisTokBegin = &CharBuffer[0];
1125   unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
1126
1127   CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1128                             Tok.getLocation(), PP);
1129   if (Literal.hadError())
1130     return ExprError();
1131
1132   QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
1133
1134   return Owned(new (Context) CharacterLiteral(Literal.getValue(),
1135                                               Literal.isWide(),
1136                                               type, Tok.getLocation()));
1137 }
1138
1139 Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
1140   // Fast path for a single digit (which is quite common).  A single digit
1141   // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
1142   if (Tok.getLength() == 1) {
1143     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
1144     unsigned IntSize = Context.Target.getIntWidth();
1145     return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
1146                     Context.IntTy, Tok.getLocation()));
1147   }
1148
1149   llvm::SmallString<512> IntegerBuffer;
1150   // Add padding so that NumericLiteralParser can overread by one character.
1151   IntegerBuffer.resize(Tok.getLength()+1);
1152   const char *ThisTokBegin = &IntegerBuffer[0];
1153
1154   // Get the spelling of the token, which eliminates trigraphs, etc.
1155   unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
1156
1157   NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1158                                Tok.getLocation(), PP);
1159   if (Literal.hadError)
1160     return ExprError();
1161
1162   Expr *Res;
1163
1164   if (Literal.isFloatingLiteral()) {
1165     QualType Ty;
1166     if (Literal.isFloat)
1167       Ty = Context.FloatTy;
1168     else if (!Literal.isLong)
1169       Ty = Context.DoubleTy;
1170     else
1171       Ty = Context.LongDoubleTy;
1172
1173     const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
1174
1175     // isExact will be set by GetFloatValue().
1176     bool isExact = false;
1177     llvm::APFloat Val = Literal.GetFloatValue(Format, &isExact);
1178     Res = new (Context) FloatingLiteral(Val, isExact, Ty, Tok.getLocation());
1179
1180   } else if (!Literal.isIntegerLiteral()) {
1181     return ExprError();
1182   } else {
1183     QualType Ty;
1184
1185     // long long is a C99 feature.
1186     if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
1187         Literal.isLongLong)
1188       Diag(Tok.getLocation(), diag::ext_longlong);
1189
1190     // Get the value in the widest-possible width.
1191     llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
1192
1193     if (Literal.GetIntegerValue(ResultVal)) {
1194       // If this value didn't fit into uintmax_t, warn and force to ull.
1195       Diag(Tok.getLocation(), diag::warn_integer_too_large);
1196       Ty = Context.UnsignedLongLongTy;
1197       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
1198              "long long is not intmax_t?");
1199     } else {
1200       // If this value fits into a ULL, try to figure out what else it fits into
1201       // according to the rules of C99 6.4.4.1p5.
1202
1203       // Octal, Hexadecimal, and integers with a U suffix are allowed to
1204       // be an unsigned int.
1205       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
1206
1207       // Check from smallest to largest, picking the smallest type we can.
1208       unsigned Width = 0;
1209       if (!Literal.isLong && !Literal.isLongLong) {
1210         // Are int/unsigned possibilities?
1211         unsigned IntSize = Context.Target.getIntWidth();
1212
1213         // Does it fit in a unsigned int?
1214         if (ResultVal.isIntN(IntSize)) {
1215           // Does it fit in a signed int?
1216           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
1217             Ty = Context.IntTy;
1218           else if (AllowUnsigned)
1219             Ty = Context.UnsignedIntTy;
1220           Width = IntSize;
1221         }
1222       }
1223
1224       // Are long/unsigned long possibilities?
1225       if (Ty.isNull() && !Literal.isLongLong) {
1226         unsigned LongSize = Context.Target.getLongWidth();
1227
1228         // Does it fit in a unsigned long?
1229         if (ResultVal.isIntN(LongSize)) {
1230           // Does it fit in a signed long?
1231           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
1232             Ty = Context.LongTy;
1233           else if (AllowUnsigned)
1234             Ty = Context.UnsignedLongTy;
1235           Width = LongSize;
1236         }
1237       }
1238
1239       // Finally, check long long if needed.
1240       if (Ty.isNull()) {
1241         unsigned LongLongSize = Context.Target.getLongLongWidth();
1242
1243         // Does it fit in a unsigned long long?
1244         if (ResultVal.isIntN(LongLongSize)) {
1245           // Does it fit in a signed long long?
1246           if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
1247             Ty = Context.LongLongTy;
1248           else if (AllowUnsigned)
1249             Ty = Context.UnsignedLongLongTy;
1250           Width = LongLongSize;
1251         }
1252       }
1253
1254       // If we still couldn't decide a type, we probably have something that
1255       // does not fit in a signed long long, but has no U suffix.
1256       if (Ty.isNull()) {
1257         Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
1258         Ty = Context.UnsignedLongLongTy;
1259         Width = Context.Target.getLongLongWidth();
1260       }
1261
1262       if (ResultVal.getBitWidth() != Width)
1263         ResultVal.trunc(Width);
1264     }
1265     Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
1266   }
1267
1268   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
1269   if (Literal.isImaginary)
1270     Res = new (Context) ImaginaryLiteral(Res,
1271                                         Context.getComplexType(Res->getType()));
1272
1273   return Owned(Res);
1274 }
1275
1276 Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
1277                                               SourceLocation R, ExprArg Val) {
1278   Expr *E = Val.takeAs<Expr>();
1279   assert((E != 0) && "ActOnParenExpr() missing expr");
1280   return Owned(new (Context) ParenExpr(L, R, E));
1281 }
1282
1283 /// The UsualUnaryConversions() function is *not* called by this routine.
1284 /// See C99 6.3.2.1p[2-4] for more details.
1285 bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
1286                                      SourceLocation OpLoc,
1287                                      const SourceRange &ExprRange,
1288                                      bool isSizeof) {
1289   if (exprType->isDependentType())
1290     return false;
1291
1292   // C99 6.5.3.4p1:
1293   if (exprType->isFunctionType()) {
1294     // alignof(function) is allowed as an extension.
1295     if (isSizeof)
1296       Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
1297     return false;
1298   }
1299
1300   // Allow sizeof(void)/alignof(void) as an extension.
1301   if (exprType->isVoidType()) {
1302     Diag(OpLoc, diag::ext_sizeof_void_type)
1303       << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
1304     return false;
1305   }
1306
1307   if (RequireCompleteType(OpLoc, exprType,
1308                           isSizeof ? diag::err_sizeof_incomplete_type :
1309                           PDiag(diag::err_alignof_incomplete_type)
1310                             << ExprRange))
1311     return true;
1312
1313   // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
1314   if (LangOpts.ObjCNonFragileABI && exprType->isObjCInterfaceType()) {
1315     Diag(OpLoc, diag::err_sizeof_nonfragile_interface)
1316       << exprType << isSizeof << ExprRange;
1317     return true;
1318   }
1319
1320   return false;
1321 }
1322
1323 bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc,
1324                             const SourceRange &ExprRange) {
1325   E = E->IgnoreParens();
1326
1327   // alignof decl is always ok.
1328   if (isa<DeclRefExpr>(E))
1329     return false;
1330
1331   // Cannot know anything else if the expression is dependent.
1332   if (E->isTypeDependent())
1333     return false;
1334
1335   if (E->getBitField()) {
1336     Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
1337     return true;
1338   }
1339
1340   // Alignment of a field access is always okay, so long as it isn't a
1341   // bit-field.
1342   if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
1343     if (isa<FieldDecl>(ME->getMemberDecl()))
1344       return false;
1345
1346   return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
1347 }
1348
1349 /// \brief Build a sizeof or alignof expression given a type operand.
1350 Action::OwningExprResult
1351 Sema::CreateSizeOfAlignOfExpr(DeclaratorInfo *DInfo,
1352                               SourceLocation OpLoc,
1353                               bool isSizeOf, SourceRange R) {
1354   if (!DInfo)
1355     return ExprError();
1356
1357   QualType T = DInfo->getType();
1358
1359   if (!T->isDependentType() &&
1360       CheckSizeOfAlignOfOperand(T, OpLoc, R, isSizeOf))
1361     return ExprError();
1362
1363   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1364   return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, DInfo,
1365                                                Context.getSizeType(), OpLoc,
1366                                                R.getEnd()));
1367 }
1368
1369 /// \brief Build a sizeof or alignof expression given an expression
1370 /// operand.
1371 Action::OwningExprResult
1372 Sema::CreateSizeOfAlignOfExpr(Expr *E, SourceLocation OpLoc,
1373                               bool isSizeOf, SourceRange R) {
1374   // Verify that the operand is valid.
1375   bool isInvalid = false;
1376   if (E->isTypeDependent()) {
1377     // Delay type-checking for type-dependent expressions.
1378   } else if (!isSizeOf) {
1379     isInvalid = CheckAlignOfExpr(E, OpLoc, R);
1380   } else if (E->getBitField()) {  // C99 6.5.3.4p1.
1381     Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
1382     isInvalid = true;
1383   } else {
1384     isInvalid = CheckSizeOfAlignOfOperand(E->getType(), OpLoc, R, true);
1385   }
1386
1387   if (isInvalid)
1388     return ExprError();
1389
1390   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1391   return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, E,
1392                                                Context.getSizeType(), OpLoc,
1393                                                R.getEnd()));
1394 }
1395
1396 /// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
1397 /// the same for @c alignof and @c __alignof
1398 /// Note that the ArgRange is invalid if isType is false.
1399 Action::OwningExprResult
1400 Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
1401                              void *TyOrEx, const SourceRange &ArgRange) {
1402   // If error parsing type, ignore.
1403   if (TyOrEx == 0) return ExprError();
1404
1405   if (isType) {
1406     DeclaratorInfo *DInfo;
1407     (void) GetTypeFromParser(TyOrEx, &DInfo);
1408     return CreateSizeOfAlignOfExpr(DInfo, OpLoc, isSizeof, ArgRange);
1409   }
1410
1411   Expr *ArgEx = (Expr *)TyOrEx;
1412   Action::OwningExprResult Result
1413     = CreateSizeOfAlignOfExpr(ArgEx, OpLoc, isSizeof, ArgEx->getSourceRange());
1414
1415   if (Result.isInvalid())
1416     DeleteExpr(ArgEx);
1417
1418   return move(Result);
1419 }
1420
1421 QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc, bool isReal) {
1422   if (V->isTypeDependent())
1423     return Context.DependentTy;
1424
1425   // These operators return the element type of a complex type.
1426   if (const ComplexType *CT = V->getType()->getAs<ComplexType>())
1427     return CT->getElementType();
1428
1429   // Otherwise they pass through real integer and floating point types here.
1430   if (V->getType()->isArithmeticType())
1431     return V->getType();
1432
1433   // Reject anything else.
1434   Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
1435     << (isReal ? "__real" : "__imag");
1436   return QualType();
1437 }
1438
1439
1440
1441 Action::OwningExprResult
1442 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
1443                           tok::TokenKind Kind, ExprArg Input) {
1444   // Since this might be a postfix expression, get rid of ParenListExprs.
1445   Input = MaybeConvertParenListExprToParenExpr(S, move(Input));
1446   Expr *Arg = (Expr *)Input.get();
1447
1448   UnaryOperator::Opcode Opc;
1449   switch (Kind) {
1450   default: assert(0 && "Unknown unary op!");
1451   case tok::plusplus:   Opc = UnaryOperator::PostInc; break;
1452   case tok::minusminus: Opc = UnaryOperator::PostDec; break;
1453   }
1454
1455   if (getLangOptions().CPlusPlus &&
1456       (Arg->getType()->isRecordType() || Arg->getType()->isEnumeralType())) {
1457     // Which overloaded operator?
1458     OverloadedOperatorKind OverOp =
1459       (Opc == UnaryOperator::PostInc)? OO_PlusPlus : OO_MinusMinus;
1460
1461     // C++ [over.inc]p1:
1462     //
1463     //     [...] If the function is a member function with one
1464     //     parameter (which shall be of type int) or a non-member
1465     //     function with two parameters (the second of which shall be
1466     //     of type int), it defines the postfix increment operator ++
1467     //     for objects of that type. When the postfix increment is
1468     //     called as a result of using the ++ operator, the int
1469     //     argument will have value zero.
1470     Expr *Args[2] = {
1471       Arg,
1472       new (Context) IntegerLiteral(llvm::APInt(Context.Target.getIntWidth(), 0,
1473                           /*isSigned=*/true), Context.IntTy, SourceLocation())
1474     };
1475
1476     // Build the candidate set for overloading
1477     OverloadCandidateSet CandidateSet;
1478     AddOperatorCandidates(OverOp, S, OpLoc, Args, 2, CandidateSet);
1479
1480     // Perform overload resolution.
1481     OverloadCandidateSet::iterator Best;
1482     switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
1483     case OR_Success: {
1484       // We found a built-in operator or an overloaded operator.
1485       FunctionDecl *FnDecl = Best->Function;
1486
1487       if (FnDecl) {
1488         // We matched an overloaded operator. Build a call to that
1489         // operator.
1490
1491         // Convert the arguments.
1492         if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1493           if (PerformObjectArgumentInitialization(Arg, Method))
1494             return ExprError();
1495         } else {
1496           // Convert the arguments.
1497           if (PerformCopyInitialization(Arg,
1498                                         FnDecl->getParamDecl(0)->getType(),
1499                                         "passing"))
1500             return ExprError();
1501         }
1502
1503         // Determine the result type
1504         QualType ResultTy = FnDecl->getResultType().getNonReferenceType();
1505
1506         // Build the actual expression node.
1507         Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
1508                                                  SourceLocation());
1509         UsualUnaryConversions(FnExpr);
1510
1511         Input.release();
1512         Args[0] = Arg;
1513         
1514         ExprOwningPtr<CXXOperatorCallExpr> 
1515           TheCall(this, new (Context) CXXOperatorCallExpr(Context, OverOp, 
1516                                                           FnExpr, Args, 2, 
1517                                                           ResultTy, OpLoc));
1518         
1519         if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(), 
1520                                 FnDecl))
1521           return ExprError();
1522         return Owned(TheCall.release());
1523
1524       } else {
1525         // We matched a built-in operator. Convert the arguments, then
1526         // break out so that we will build the appropriate built-in
1527         // operator node.
1528         if (PerformCopyInitialization(Arg, Best->BuiltinTypes.ParamTypes[0],
1529                                       "passing"))
1530           return ExprError();
1531
1532         break;
1533       }
1534     }
1535
1536     case OR_No_Viable_Function: {
1537       // No viable function; try checking this as a built-in operator, which
1538       // will fail and provide a diagnostic. Then, print the overload
1539       // candidates.
1540       OwningExprResult Result = CreateBuiltinUnaryOp(OpLoc, Opc, move(Input));
1541       assert(Result.isInvalid() && 
1542              "C++ postfix-unary operator overloading is missing candidates!");
1543       if (Result.isInvalid())
1544         PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
1545       
1546       return move(Result);
1547     }
1548         
1549     case OR_Ambiguous:
1550       Diag(OpLoc,  diag::err_ovl_ambiguous_oper)
1551           << UnaryOperator::getOpcodeStr(Opc)
1552           << Arg->getSourceRange();
1553       PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1554       return ExprError();
1555
1556     case OR_Deleted:
1557       Diag(OpLoc, diag::err_ovl_deleted_oper)
1558         << Best->Function->isDeleted()
1559         << UnaryOperator::getOpcodeStr(Opc)
1560         << Arg->getSourceRange();
1561       PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1562       return ExprError();
1563     }
1564
1565     // Either we found no viable overloaded operator or we matched a
1566     // built-in operator. In either case, fall through to trying to
1567     // build a built-in operation.
1568   }
1569
1570   Input.release();
1571   Input = Arg;
1572   return CreateBuiltinUnaryOp(OpLoc, Opc, move(Input));
1573 }
1574
1575 Action::OwningExprResult
1576 Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
1577                               ExprArg Idx, SourceLocation RLoc) {
1578   // Since this might be a postfix expression, get rid of ParenListExprs.
1579   Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
1580
1581   Expr *LHSExp = static_cast<Expr*>(Base.get()),
1582        *RHSExp = static_cast<Expr*>(Idx.get());
1583
1584   if (getLangOptions().CPlusPlus &&
1585       (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
1586     Base.release();
1587     Idx.release();
1588     return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
1589                                                   Context.DependentTy, RLoc));
1590   }
1591
1592   if (getLangOptions().CPlusPlus &&
1593       (LHSExp->getType()->isRecordType() ||
1594        LHSExp->getType()->isEnumeralType() ||
1595        RHSExp->getType()->isRecordType() ||
1596        RHSExp->getType()->isEnumeralType())) {
1597     return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, move(Base),move(Idx));
1598   }
1599
1600   return CreateBuiltinArraySubscriptExpr(move(Base), LLoc, move(Idx), RLoc);
1601 }
1602
1603
1604 Action::OwningExprResult
1605 Sema::CreateBuiltinArraySubscriptExpr(ExprArg Base, SourceLocation LLoc,
1606                                      ExprArg Idx, SourceLocation RLoc) {
1607   Expr *LHSExp = static_cast<Expr*>(Base.get());
1608   Expr *RHSExp = static_cast<Expr*>(Idx.get());
1609
1610   // Perform default conversions.
1611   DefaultFunctionArrayConversion(LHSExp);
1612   DefaultFunctionArrayConversion(RHSExp);
1613
1614   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
1615
1616   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
1617   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
1618   // in the subscript position. As a result, we need to derive the array base
1619   // and index from the expression types.
1620   Expr *BaseExpr, *IndexExpr;
1621   QualType ResultType;
1622   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
1623     BaseExpr = LHSExp;
1624     IndexExpr = RHSExp;
1625     ResultType = Context.DependentTy;
1626   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
1627     BaseExpr = LHSExp;
1628     IndexExpr = RHSExp;
1629     ResultType = PTy->getPointeeType();
1630   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
1631      // Handle the uncommon case of "123[Ptr]".
1632     BaseExpr = RHSExp;
1633     IndexExpr = LHSExp;
1634     ResultType = PTy->getPointeeType();
1635   } else if (const ObjCObjectPointerType *PTy =
1636                LHSTy->getAs<ObjCObjectPointerType>()) {
1637     BaseExpr = LHSExp;
1638     IndexExpr = RHSExp;
1639     ResultType = PTy->getPointeeType();
1640   } else if (const ObjCObjectPointerType *PTy =
1641                RHSTy->getAs<ObjCObjectPointerType>()) {
1642      // Handle the uncommon case of "123[Ptr]".
1643     BaseExpr = RHSExp;
1644     IndexExpr = LHSExp;
1645     ResultType = PTy->getPointeeType();
1646   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
1647     BaseExpr = LHSExp;    // vectors: V[123]
1648     IndexExpr = RHSExp;
1649
1650     // FIXME: need to deal with const...
1651     ResultType = VTy->getElementType();
1652   } else if (LHSTy->isArrayType()) {
1653     // If we see an array that wasn't promoted by
1654     // DefaultFunctionArrayConversion, it must be an array that
1655     // wasn't promoted because of the C90 rule that doesn't
1656     // allow promoting non-lvalue arrays.  Warn, then
1657     // force the promotion here.
1658     Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
1659         LHSExp->getSourceRange();
1660     ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
1661                       CastExpr::CK_ArrayToPointerDecay);
1662     LHSTy = LHSExp->getType();
1663
1664     BaseExpr = LHSExp;
1665     IndexExpr = RHSExp;
1666     ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
1667   } else if (RHSTy->isArrayType()) {
1668     // Same as previous, except for 123[f().a] case
1669     Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
1670         RHSExp->getSourceRange();
1671     ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
1672                       CastExpr::CK_ArrayToPointerDecay);
1673     RHSTy = RHSExp->getType();
1674
1675     BaseExpr = RHSExp;
1676     IndexExpr = LHSExp;
1677     ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
1678   } else {
1679     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
1680        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
1681   }
1682   // C99 6.5.2.1p1
1683   if (!(IndexExpr->getType()->isIntegerType() &&
1684         IndexExpr->getType()->isScalarType()) && !IndexExpr->isTypeDependent())
1685     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
1686                      << IndexExpr->getSourceRange());
1687
1688   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
1689        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
1690          && !IndexExpr->isTypeDependent())
1691     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
1692
1693   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
1694   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
1695   // type. Note that Functions are not objects, and that (in C99 parlance)
1696   // incomplete types are not object types.
1697   if (ResultType->isFunctionType()) {
1698     Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
1699       << ResultType << BaseExpr->getSourceRange();
1700     return ExprError();
1701   }
1702
1703   if (!ResultType->isDependentType() &&
1704       RequireCompleteType(LLoc, ResultType,
1705                           PDiag(diag::err_subscript_incomplete_type)
1706                             << BaseExpr->getSourceRange()))
1707     return ExprError();
1708
1709   // Diagnose bad cases where we step over interface counts.
1710   if (ResultType->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
1711     Diag(LLoc, diag::err_subscript_nonfragile_interface)
1712       << ResultType << BaseExpr->getSourceRange();
1713     return ExprError();
1714   }
1715
1716   Base.release();
1717   Idx.release();
1718   return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
1719                                                 ResultType, RLoc));
1720 }
1721
1722 QualType Sema::
1723 CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
1724                         const IdentifierInfo *CompName,
1725                         SourceLocation CompLoc) {
1726   // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
1727   // see FIXME there.
1728   //
1729   // FIXME: This logic can be greatly simplified by splitting it along
1730   // halving/not halving and reworking the component checking.
1731   const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
1732
1733   // The vector accessor can't exceed the number of elements.
1734   const char *compStr = CompName->getNameStart();
1735
1736   // This flag determines whether or not the component is one of the four
1737   // special names that indicate a subset of exactly half the elements are
1738   // to be selected.
1739   bool HalvingSwizzle = false;
1740
1741   // This flag determines whether or not CompName has an 's' char prefix,
1742   // indicating that it is a string of hex values to be used as vector indices.
1743   bool HexSwizzle = *compStr == 's' || *compStr == 'S';
1744
1745   // Check that we've found one of the special components, or that the component
1746   // names must come from the same set.
1747   if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
1748       !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
1749     HalvingSwizzle = true;
1750   } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
1751     do
1752       compStr++;
1753     while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
1754   } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
1755     do
1756       compStr++;
1757     while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
1758   }
1759
1760   if (!HalvingSwizzle && *compStr) {
1761     // We didn't get to the end of the string. This means the component names
1762     // didn't come from the same set *or* we encountered an illegal name.
1763     Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
1764       << std::string(compStr,compStr+1) << SourceRange(CompLoc);
1765     return QualType();
1766   }
1767
1768   // Ensure no component accessor exceeds the width of the vector type it
1769   // operates on.
1770   if (!HalvingSwizzle) {
1771     compStr = CompName->getNameStart();
1772
1773     if (HexSwizzle)
1774       compStr++;
1775
1776     while (*compStr) {
1777       if (!vecType->isAccessorWithinNumElements(*compStr++)) {
1778         Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
1779           << baseType << SourceRange(CompLoc);
1780         return QualType();
1781       }
1782     }
1783   }
1784
1785   // If this is a halving swizzle, verify that the base type has an even
1786   // number of elements.
1787   if (HalvingSwizzle && (vecType->getNumElements() & 1U)) {
1788     Diag(OpLoc, diag::err_ext_vector_component_requires_even)
1789       << baseType << SourceRange(CompLoc);
1790     return QualType();
1791   }
1792
1793   // The component accessor looks fine - now we need to compute the actual type.
1794   // The vector type is implied by the component accessor. For example,
1795   // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
1796   // vec4.s0 is a float, vec4.s23 is a vec3, etc.
1797   // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
1798   unsigned CompSize = HalvingSwizzle ? vecType->getNumElements() / 2
1799                                      : CompName->getLength();
1800   if (HexSwizzle)
1801     CompSize--;
1802
1803   if (CompSize == 1)
1804     return vecType->getElementType();
1805
1806   QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
1807   // Now look up the TypeDefDecl from the vector type. Without this,
1808   // diagostics look bad. We want extended vector types to appear built-in.
1809   for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
1810     if (ExtVectorDecls[i]->getUnderlyingType() == VT)
1811       return Context.getTypedefType(ExtVectorDecls[i]);
1812   }
1813   return VT; // should never get here (a typedef type should always be found).
1814 }
1815
1816 static Decl *FindGetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
1817                                                 IdentifierInfo *Member,
1818                                                 const Selector &Sel,
1819                                                 ASTContext &Context) {
1820
1821   if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
1822     return PD;
1823   if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
1824     return OMD;
1825
1826   for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
1827        E = PDecl->protocol_end(); I != E; ++I) {
1828     if (Decl *D = FindGetterNameDeclFromProtocolList(*I, Member, Sel,
1829                                                      Context))
1830       return D;
1831   }
1832   return 0;
1833 }
1834
1835 static Decl *FindGetterNameDecl(const ObjCObjectPointerType *QIdTy,
1836                                 IdentifierInfo *Member,
1837                                 const Selector &Sel,
1838                                 ASTContext &Context) {
1839   // Check protocols on qualified interfaces.
1840   Decl *GDecl = 0;
1841   for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
1842        E = QIdTy->qual_end(); I != E; ++I) {
1843     if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
1844       GDecl = PD;
1845       break;
1846     }
1847     // Also must look for a getter name which uses property syntax.
1848     if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
1849       GDecl = OMD;
1850       break;
1851     }
1852   }
1853   if (!GDecl) {
1854     for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
1855          E = QIdTy->qual_end(); I != E; ++I) {
1856       // Search in the protocol-qualifier list of current protocol.
1857       GDecl = FindGetterNameDeclFromProtocolList(*I, Member, Sel, Context);
1858       if (GDecl)
1859         return GDecl;
1860     }
1861   }
1862   return GDecl;
1863 }
1864
1865 Action::OwningExprResult
1866 Sema::BuildMemberReferenceExpr(Scope *S, ExprArg Base, SourceLocation OpLoc,
1867                                tok::TokenKind OpKind, SourceLocation MemberLoc,
1868                                DeclarationName MemberName,
1869                                bool HasExplicitTemplateArgs,
1870                                SourceLocation LAngleLoc,
1871                                const TemplateArgumentLoc *ExplicitTemplateArgs,
1872                                unsigned NumExplicitTemplateArgs,
1873                                SourceLocation RAngleLoc,
1874                                DeclPtrTy ObjCImpDecl, const CXXScopeSpec *SS,
1875                                NamedDecl *FirstQualifierInScope) {
1876   if (SS && SS->isInvalid())
1877     return ExprError();
1878
1879   // Since this might be a postfix expression, get rid of ParenListExprs.
1880   Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
1881
1882   Expr *BaseExpr = Base.takeAs<Expr>();
1883   assert(BaseExpr && "no base expression");
1884
1885   // Perform default conversions.
1886   DefaultFunctionArrayConversion(BaseExpr);
1887
1888   QualType BaseType = BaseExpr->getType();
1889   // If this is an Objective-C pseudo-builtin and a definition is provided then
1890   // use that.
1891   if (BaseType->isObjCIdType()) {
1892     // We have an 'id' type. Rather than fall through, we check if this
1893     // is a reference to 'isa'.
1894     if (BaseType != Context.ObjCIdRedefinitionType) {
1895       BaseType = Context.ObjCIdRedefinitionType;
1896       ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
1897     }
1898   }
1899   assert(!BaseType.isNull() && "no type for member expression");
1900
1901   // Handle properties on ObjC 'Class' types.
1902   if (OpKind == tok::period && BaseType->isObjCClassType()) {
1903     // Also must look for a getter name which uses property syntax.
1904     IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1905     Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
1906     if (ObjCMethodDecl *MD = getCurMethodDecl()) {
1907       ObjCInterfaceDecl *IFace = MD->getClassInterface();
1908       ObjCMethodDecl *Getter;
1909       // FIXME: need to also look locally in the implementation.
1910       if ((Getter = IFace->lookupClassMethod(Sel))) {
1911         // Check the use of this method.
1912         if (DiagnoseUseOfDecl(Getter, MemberLoc))
1913           return ExprError();
1914       }
1915       // If we found a getter then this may be a valid dot-reference, we
1916       // will look for the matching setter, in case it is needed.
1917       Selector SetterSel =
1918       SelectorTable::constructSetterName(PP.getIdentifierTable(),
1919                                          PP.getSelectorTable(), Member);
1920       ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
1921       if (!Setter) {
1922         // If this reference is in an @implementation, also check for 'private'
1923         // methods.
1924         Setter = IFace->lookupPrivateInstanceMethod(SetterSel);
1925       }
1926       // Look through local category implementations associated with the class.
1927       if (!Setter)
1928         Setter = IFace->getCategoryClassMethod(SetterSel);
1929       
1930       if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
1931         return ExprError();
1932       
1933       if (Getter || Setter) {
1934         QualType PType;
1935         
1936         if (Getter)
1937           PType = Getter->getResultType();
1938         else
1939           // Get the expression type from Setter's incoming parameter.
1940           PType = (*(Setter->param_end() -1))->getType();
1941         // FIXME: we must check that the setter has property type.
1942         return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter, 
1943                                                   PType,
1944                                                   Setter, MemberLoc, BaseExpr));
1945       }
1946       return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1947                        << MemberName << BaseType);
1948     }
1949   }
1950   
1951   if (BaseType->isObjCClassType() &&
1952       BaseType != Context.ObjCClassRedefinitionType) {
1953     BaseType = Context.ObjCClassRedefinitionType;
1954     ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
1955   }
1956   
1957   // Get the type being accessed in BaseType.  If this is an arrow, the BaseExpr
1958   // must have pointer type, and the accessed type is the pointee.
1959   if (OpKind == tok::arrow) {
1960     if (BaseType->isDependentType()) {
1961       NestedNameSpecifier *Qualifier = 0;
1962       if (SS) {
1963         Qualifier = static_cast<NestedNameSpecifier *>(SS->getScopeRep());
1964         if (!FirstQualifierInScope)
1965           FirstQualifierInScope = FindFirstQualifierInScope(S, Qualifier);
1966       }
1967
1968       return Owned(CXXUnresolvedMemberExpr::Create(Context, BaseExpr, true,
1969                                                    OpLoc, Qualifier,
1970                                             SS? SS->getRange() : SourceRange(),
1971                                                    FirstQualifierInScope,
1972                                                    MemberName,
1973                                                    MemberLoc,
1974                                                    HasExplicitTemplateArgs,
1975                                                    LAngleLoc,
1976                                                    ExplicitTemplateArgs,
1977                                                    NumExplicitTemplateArgs,
1978                                                    RAngleLoc));
1979     }
1980     else if (const PointerType *PT = BaseType->getAs<PointerType>())
1981       BaseType = PT->getPointeeType();
1982     else if (BaseType->isObjCObjectPointerType())
1983       ;
1984     else
1985       return ExprError(Diag(MemberLoc,
1986                             diag::err_typecheck_member_reference_arrow)
1987         << BaseType << BaseExpr->getSourceRange());
1988   } else if (BaseType->isDependentType()) {
1989       // Require that the base type isn't a pointer type
1990       // (so we'll report an error for)
1991       // T* t;
1992       // t.f;
1993       //
1994       // In Obj-C++, however, the above expression is valid, since it could be
1995       // accessing the 'f' property if T is an Obj-C interface. The extra check
1996       // allows this, while still reporting an error if T is a struct pointer.
1997       const PointerType *PT = BaseType->getAs<PointerType>();
1998
1999       if (!PT || (getLangOptions().ObjC1 &&
2000                   !PT->getPointeeType()->isRecordType())) {
2001         NestedNameSpecifier *Qualifier = 0;
2002         if (SS) {
2003           Qualifier = static_cast<NestedNameSpecifier *>(SS->getScopeRep());
2004           if (!FirstQualifierInScope)
2005             FirstQualifierInScope = FindFirstQualifierInScope(S, Qualifier);
2006         }
2007
2008         return Owned(CXXUnresolvedMemberExpr::Create(Context,
2009                                                      BaseExpr, false,
2010                                                      OpLoc,
2011                                                      Qualifier,
2012                                             SS? SS->getRange() : SourceRange(),
2013                                                      FirstQualifierInScope,
2014                                                      MemberName,
2015                                                      MemberLoc,
2016                                                      HasExplicitTemplateArgs,
2017                                                      LAngleLoc,
2018                                                      ExplicitTemplateArgs,
2019                                                      NumExplicitTemplateArgs,
2020                                                      RAngleLoc));
2021       }
2022     }
2023
2024   // Handle field access to simple records.  This also handles access to fields
2025   // of the ObjC 'id' struct.
2026   if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
2027     RecordDecl *RDecl = RTy->getDecl();
2028     if (RequireCompleteType(OpLoc, BaseType,
2029                             PDiag(diag::err_typecheck_incomplete_tag)
2030                               << BaseExpr->getSourceRange()))
2031       return ExprError();
2032
2033     DeclContext *DC = RDecl;
2034     if (SS && SS->isSet()) {
2035       // If the member name was a qualified-id, look into the
2036       // nested-name-specifier.
2037       DC = computeDeclContext(*SS, false);
2038       
2039       if (!isa<TypeDecl>(DC)) {
2040         Diag(MemberLoc, diag::err_qualified_member_nonclass)
2041           << DC << SS->getRange();
2042         return ExprError();
2043       }
2044
2045       // FIXME: If DC is not computable, we should build a
2046       // CXXUnresolvedMemberExpr.
2047       assert(DC && "Cannot handle non-computable dependent contexts in lookup");
2048     }
2049
2050     // The record definition is complete, now make sure the member is valid.
2051     LookupResult Result;
2052     LookupQualifiedName(Result, DC, MemberName, LookupMemberName, false);
2053
2054     if (Result.empty())
2055       return ExprError(Diag(MemberLoc, diag::err_no_member)
2056                << MemberName << DC << BaseExpr->getSourceRange());
2057     if (Result.isAmbiguous()) {
2058       DiagnoseAmbiguousLookup(Result, MemberName, MemberLoc,
2059                               BaseExpr->getSourceRange());
2060       return ExprError();
2061     }
2062
2063     NamedDecl *MemberDecl = Result.getAsSingleDecl(Context);
2064
2065     if (SS && SS->isSet()) {
2066       TypeDecl* TyD = cast<TypeDecl>(MemberDecl->getDeclContext());
2067       QualType BaseTypeCanon
2068         = Context.getCanonicalType(BaseType).getUnqualifiedType();
2069       QualType MemberTypeCanon
2070         = Context.getCanonicalType(Context.getTypeDeclType(TyD));
2071
2072       if (BaseTypeCanon != MemberTypeCanon &&
2073           !IsDerivedFrom(BaseTypeCanon, MemberTypeCanon))
2074         return ExprError(Diag(SS->getBeginLoc(),
2075                               diag::err_not_direct_base_or_virtual)
2076                          << MemberTypeCanon << BaseTypeCanon);
2077     }
2078
2079     // If the decl being referenced had an error, return an error for this
2080     // sub-expr without emitting another error, in order to avoid cascading
2081     // error cases.
2082     if (MemberDecl->isInvalidDecl())
2083       return ExprError();
2084
2085     bool ShouldCheckUse = true;
2086     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
2087       // Don't diagnose the use of a virtual member function unless it's
2088       // explicitly qualified.
2089       if (MD->isVirtual() && (!SS || !SS->isSet()))
2090         ShouldCheckUse = false;
2091     }
2092
2093     // Check the use of this field
2094     if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc))
2095       return ExprError();
2096
2097     if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
2098       // We may have found a field within an anonymous union or struct
2099       // (C++ [class.union]).
2100       if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
2101         return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
2102                                                         BaseExpr, OpLoc);
2103
2104       // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
2105       QualType MemberType = FD->getType();
2106       if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>())
2107         MemberType = Ref->getPointeeType();
2108       else {
2109         Qualifiers BaseQuals = BaseType.getQualifiers();
2110         BaseQuals.removeObjCGCAttr();
2111         if (FD->isMutable()) BaseQuals.removeConst();
2112
2113         Qualifiers MemberQuals
2114           = Context.getCanonicalType(MemberType).getQualifiers();
2115
2116         Qualifiers Combined = BaseQuals + MemberQuals;
2117         if (Combined != MemberQuals)
2118           MemberType = Context.getQualifiedType(MemberType, Combined);
2119       }
2120
2121       MarkDeclarationReferenced(MemberLoc, FD);
2122       if (PerformObjectMemberConversion(BaseExpr, FD))
2123         return ExprError();
2124       return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2125                                    FD, MemberLoc, MemberType));
2126     }
2127
2128     if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
2129       MarkDeclarationReferenced(MemberLoc, MemberDecl);
2130       return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2131                                    Var, MemberLoc,
2132                                    Var->getType().getNonReferenceType()));
2133     }
2134     if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl)) {
2135       MarkDeclarationReferenced(MemberLoc, MemberDecl);
2136       return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2137                                    MemberFn, MemberLoc,
2138                                    MemberFn->getType()));
2139     }
2140     if (FunctionTemplateDecl *FunTmpl
2141           = dyn_cast<FunctionTemplateDecl>(MemberDecl)) {
2142       MarkDeclarationReferenced(MemberLoc, MemberDecl);
2143
2144       if (HasExplicitTemplateArgs)
2145         return Owned(MemberExpr::Create(Context, BaseExpr, OpKind == tok::arrow,
2146                              (NestedNameSpecifier *)(SS? SS->getScopeRep() : 0),
2147                                        SS? SS->getRange() : SourceRange(),
2148                                         FunTmpl, MemberLoc, true,
2149                                         LAngleLoc, ExplicitTemplateArgs,
2150                                         NumExplicitTemplateArgs, RAngleLoc,
2151                                         Context.OverloadTy));
2152
2153       return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2154                                    FunTmpl, MemberLoc,
2155                                    Context.OverloadTy));
2156     }
2157     if (OverloadedFunctionDecl *Ovl
2158           = dyn_cast<OverloadedFunctionDecl>(MemberDecl)) {
2159       if (HasExplicitTemplateArgs)
2160         return Owned(MemberExpr::Create(Context, BaseExpr, OpKind == tok::arrow,
2161                              (NestedNameSpecifier *)(SS? SS->getScopeRep() : 0),
2162                                         SS? SS->getRange() : SourceRange(),
2163                                         Ovl, MemberLoc, true,
2164                                         LAngleLoc, ExplicitTemplateArgs,
2165                                         NumExplicitTemplateArgs, RAngleLoc,
2166                                         Context.OverloadTy));
2167
2168       return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2169                                    Ovl, MemberLoc, Context.OverloadTy));
2170     }
2171     if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
2172       MarkDeclarationReferenced(MemberLoc, MemberDecl);
2173       return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2174                                    Enum, MemberLoc, Enum->getType()));
2175     }
2176     if (isa<TypeDecl>(MemberDecl))
2177       return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type)
2178         << MemberName << int(OpKind == tok::arrow));
2179
2180     // We found a declaration kind that we didn't expect. This is a
2181     // generic error message that tells the user that she can't refer
2182     // to this member with '.' or '->'.
2183     return ExprError(Diag(MemberLoc,
2184                           diag::err_typecheck_member_reference_unknown)
2185       << MemberName << int(OpKind == tok::arrow));
2186   }
2187
2188   // Handle pseudo-destructors (C++ [expr.pseudo]). Since anything referring
2189   // into a record type was handled above, any destructor we see here is a
2190   // pseudo-destructor.
2191   if (MemberName.getNameKind() == DeclarationName::CXXDestructorName) {
2192     // C++ [expr.pseudo]p2:
2193     //   The left hand side of the dot operator shall be of scalar type. The
2194     //   left hand side of the arrow operator shall be of pointer to scalar
2195     //   type.
2196     if (!BaseType->isScalarType())
2197       return Owned(Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
2198                      << BaseType << BaseExpr->getSourceRange());
2199
2200     //   [...] The type designated by the pseudo-destructor-name shall be the
2201     //   same as the object type.
2202     if (!MemberName.getCXXNameType()->isDependentType() &&
2203         !Context.hasSameUnqualifiedType(BaseType, MemberName.getCXXNameType()))
2204       return Owned(Diag(OpLoc, diag::err_pseudo_dtor_type_mismatch)
2205                      << BaseType << MemberName.getCXXNameType()
2206                      << BaseExpr->getSourceRange() << SourceRange(MemberLoc));
2207
2208     //   [...] Furthermore, the two type-names in a pseudo-destructor-name of
2209     //   the form
2210     //
2211     //       ::[opt] nested-name-specifier[opt] type-name ::  Ìƒ type-name
2212     //
2213     //   shall designate the same scalar type.
2214     //
2215     // FIXME: DPG can't see any way to trigger this particular clause, so it
2216     // isn't checked here.
2217
2218     // FIXME: We've lost the precise spelling of the type by going through
2219     // DeclarationName. Can we do better?
2220     return Owned(new (Context) CXXPseudoDestructorExpr(Context, BaseExpr,
2221                                                        OpKind == tok::arrow,
2222                                                        OpLoc,
2223                             (NestedNameSpecifier *)(SS? SS->getScopeRep() : 0),
2224                                             SS? SS->getRange() : SourceRange(),
2225                                                    MemberName.getCXXNameType(),
2226                                                        MemberLoc));
2227   }
2228
2229   // Handle access to Objective-C instance variables, such as "Obj->ivar" and
2230   // (*Obj).ivar.
2231   if ((OpKind == tok::arrow && BaseType->isObjCObjectPointerType()) ||
2232       (OpKind == tok::period && BaseType->isObjCInterfaceType())) {
2233     const ObjCObjectPointerType *OPT = BaseType->getAs<ObjCObjectPointerType>();
2234     const ObjCInterfaceType *IFaceT =
2235       OPT ? OPT->getInterfaceType() : BaseType->getAs<ObjCInterfaceType>();
2236     if (IFaceT) {
2237       IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
2238
2239       ObjCInterfaceDecl *IDecl = IFaceT->getDecl();
2240       ObjCInterfaceDecl *ClassDeclared;
2241       ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
2242
2243       if (IV) {
2244         // If the decl being referenced had an error, return an error for this
2245         // sub-expr without emitting another error, in order to avoid cascading
2246         // error cases.
2247         if (IV->isInvalidDecl())
2248           return ExprError();
2249
2250         // Check whether we can reference this field.
2251         if (DiagnoseUseOfDecl(IV, MemberLoc))
2252           return ExprError();
2253         if (IV->getAccessControl() != ObjCIvarDecl::Public &&
2254             IV->getAccessControl() != ObjCIvarDecl::Package) {
2255           ObjCInterfaceDecl *ClassOfMethodDecl = 0;
2256           if (ObjCMethodDecl *MD = getCurMethodDecl())
2257             ClassOfMethodDecl =  MD->getClassInterface();
2258           else if (ObjCImpDecl && getCurFunctionDecl()) {
2259             // Case of a c-function declared inside an objc implementation.
2260             // FIXME: For a c-style function nested inside an objc implementation
2261             // class, there is no implementation context available, so we pass
2262             // down the context as argument to this routine. Ideally, this context
2263             // need be passed down in the AST node and somehow calculated from the
2264             // AST for a function decl.
2265             Decl *ImplDecl = ObjCImpDecl.getAs<Decl>();
2266             if (ObjCImplementationDecl *IMPD =
2267                 dyn_cast<ObjCImplementationDecl>(ImplDecl))
2268               ClassOfMethodDecl = IMPD->getClassInterface();
2269             else if (ObjCCategoryImplDecl* CatImplClass =
2270                         dyn_cast<ObjCCategoryImplDecl>(ImplDecl))
2271               ClassOfMethodDecl = CatImplClass->getClassInterface();
2272           }
2273
2274           if (IV->getAccessControl() == ObjCIvarDecl::Private) {
2275             if (ClassDeclared != IDecl ||
2276                 ClassOfMethodDecl != ClassDeclared)
2277               Diag(MemberLoc, diag::error_private_ivar_access)
2278                 << IV->getDeclName();
2279           } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
2280             // @protected
2281             Diag(MemberLoc, diag::error_protected_ivar_access)
2282               << IV->getDeclName();
2283         }
2284
2285         return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
2286                                                    MemberLoc, BaseExpr,
2287                                                    OpKind == tok::arrow));
2288       }
2289       return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
2290                          << IDecl->getDeclName() << MemberName
2291                          << BaseExpr->getSourceRange());
2292     }
2293   }
2294   // Handle properties on 'id' and qualified "id".
2295   if (OpKind == tok::period && (BaseType->isObjCIdType() ||
2296                                 BaseType->isObjCQualifiedIdType())) {
2297     const ObjCObjectPointerType *QIdTy = BaseType->getAs<ObjCObjectPointerType>();
2298     IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
2299
2300     // Check protocols on qualified interfaces.
2301     Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
2302     if (Decl *PMDecl = FindGetterNameDecl(QIdTy, Member, Sel, Context)) {
2303       if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
2304         // Check the use of this declaration
2305         if (DiagnoseUseOfDecl(PD, MemberLoc))
2306           return ExprError();
2307
2308         return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
2309                                                        MemberLoc, BaseExpr));
2310       }
2311       if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
2312         // Check the use of this method.
2313         if (DiagnoseUseOfDecl(OMD, MemberLoc))
2314           return ExprError();
2315
2316         return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel,
2317                                                    OMD->getResultType(),
2318                                                    OMD, OpLoc, MemberLoc,
2319                                                    NULL, 0));
2320       }
2321     }
2322
2323     return ExprError(Diag(MemberLoc, diag::err_property_not_found)
2324                        << MemberName << BaseType);
2325   }
2326   // Handle Objective-C property access, which is "Obj.property" where Obj is a
2327   // pointer to a (potentially qualified) interface type.
2328   const ObjCObjectPointerType *OPT;
2329   if (OpKind == tok::period &&
2330       (OPT = BaseType->getAsObjCInterfacePointerType())) {
2331     const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
2332     ObjCInterfaceDecl *IFace = IFaceT->getDecl();
2333     IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
2334
2335     // Search for a declared property first.
2336     if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
2337       // Check whether we can reference this property.
2338       if (DiagnoseUseOfDecl(PD, MemberLoc))
2339         return ExprError();
2340       QualType ResTy = PD->getType();
2341       Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
2342       ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
2343       if (DiagnosePropertyAccessorMismatch(PD, Getter, MemberLoc))
2344         ResTy = Getter->getResultType();
2345       return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy,
2346                                                      MemberLoc, BaseExpr));
2347     }
2348     // Check protocols on qualified interfaces.
2349     for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
2350          E = OPT->qual_end(); I != E; ++I)
2351       if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
2352         // Check whether we can reference this property.
2353         if (DiagnoseUseOfDecl(PD, MemberLoc))
2354           return ExprError();
2355
2356         return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
2357                                                        MemberLoc, BaseExpr));
2358       }
2359     for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
2360          E = OPT->qual_end(); I != E; ++I)
2361       if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
2362         // Check whether we can reference this property.
2363         if (DiagnoseUseOfDecl(PD, MemberLoc))
2364           return ExprError();
2365
2366         return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
2367                                                        MemberLoc, BaseExpr));
2368       }
2369     // If that failed, look for an "implicit" property by seeing if the nullary
2370     // selector is implemented.
2371
2372     // FIXME: The logic for looking up nullary and unary selectors should be
2373     // shared with the code in ActOnInstanceMessage.
2374
2375     Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
2376     ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
2377
2378     // If this reference is in an @implementation, check for 'private' methods.
2379     if (!Getter)
2380       Getter = IFace->lookupPrivateInstanceMethod(Sel);
2381
2382     // Look through local category implementations associated with the class.
2383     if (!Getter)
2384       Getter = IFace->getCategoryInstanceMethod(Sel);
2385     if (Getter) {
2386       // Check if we can reference this property.
2387       if (DiagnoseUseOfDecl(Getter, MemberLoc))
2388         return ExprError();
2389     }
2390     // If we found a getter then this may be a valid dot-reference, we
2391     // will look for the matching setter, in case it is needed.
2392     Selector SetterSel =
2393       SelectorTable::constructSetterName(PP.getIdentifierTable(),
2394                                          PP.getSelectorTable(), Member);
2395     ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
2396     if (!Setter) {
2397       // If this reference is in an @implementation, also check for 'private'
2398       // methods.
2399       Setter = IFace->lookupPrivateInstanceMethod(SetterSel);
2400     }
2401     // Look through local category implementations associated with the class.
2402     if (!Setter)
2403       Setter = IFace->getCategoryInstanceMethod(SetterSel);
2404
2405     if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2406       return ExprError();
2407
2408     if (Getter || Setter) {
2409       QualType PType;
2410
2411       if (Getter)
2412         PType = Getter->getResultType();
2413       else
2414         // Get the expression type from Setter's incoming parameter.
2415         PType = (*(Setter->param_end() -1))->getType();
2416       // FIXME: we must check that the setter has property type.
2417       return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter, PType,
2418                                       Setter, MemberLoc, BaseExpr));
2419     }
2420     return ExprError(Diag(MemberLoc, diag::err_property_not_found)
2421       << MemberName << BaseType);
2422   }
2423
2424   // Handle the following exceptional case (*Obj).isa.
2425   if (OpKind == tok::period &&
2426       BaseType->isSpecificBuiltinType(BuiltinType::ObjCId) &&
2427       MemberName.getAsIdentifierInfo()->isStr("isa"))
2428     return Owned(new (Context) ObjCIsaExpr(BaseExpr, false, MemberLoc,
2429                                            Context.getObjCIdType()));
2430
2431   // Handle 'field access' to vectors, such as 'V.xx'.
2432   if (BaseType->isExtVectorType()) {
2433     IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
2434     QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
2435     if (ret.isNull())
2436       return ExprError();
2437     return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, *Member,
2438                                                     MemberLoc));
2439   }
2440
2441   Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
2442     << BaseType << BaseExpr->getSourceRange();
2443
2444   // If the user is trying to apply -> or . to a function or function
2445   // pointer, it's probably because they forgot parentheses to call
2446   // the function. Suggest the addition of those parentheses.
2447   if (BaseType == Context.OverloadTy ||
2448       BaseType->isFunctionType() ||
2449       (BaseType->isPointerType() &&
2450        BaseType->getAs<PointerType>()->isFunctionType())) {
2451     SourceLocation Loc = PP.getLocForEndOfToken(BaseExpr->getLocEnd());
2452     Diag(Loc, diag::note_member_reference_needs_call)
2453       << CodeModificationHint::CreateInsertion(Loc, "()");
2454   }
2455
2456   return ExprError();
2457 }
2458
2459 Sema::OwningExprResult Sema::ActOnMemberAccessExpr(Scope *S, ExprArg Base,
2460                                                    SourceLocation OpLoc,
2461                                                    tok::TokenKind OpKind,
2462                                                    const CXXScopeSpec &SS,
2463                                                    UnqualifiedId &Member,
2464                                                    DeclPtrTy ObjCImpDecl,
2465                                                    bool HasTrailingLParen) {
2466   if (Member.getKind() == UnqualifiedId::IK_TemplateId) {
2467     TemplateName Template
2468       = TemplateName::getFromVoidPointer(Member.TemplateId->Template);
2469     
2470     // FIXME: We're going to end up looking up the template based on its name,
2471     // twice!
2472     DeclarationName Name;
2473     if (TemplateDecl *ActualTemplate = Template.getAsTemplateDecl())
2474       Name = ActualTemplate->getDeclName();
2475     else if (OverloadedFunctionDecl *Ovl = Template.getAsOverloadedFunctionDecl())
2476       Name = Ovl->getDeclName();
2477     else {
2478       DependentTemplateName *DTN = Template.getAsDependentTemplateName();
2479       if (DTN->isIdentifier())
2480         Name = DTN->getIdentifier();
2481       else
2482         Name = Context.DeclarationNames.getCXXOperatorName(DTN->getOperator());
2483     }
2484     
2485     // Translate the parser's template argument list in our AST format.
2486     ASTTemplateArgsPtr TemplateArgsPtr(*this,
2487                                        Member.TemplateId->getTemplateArgs(),
2488                                        Member.TemplateId->getTemplateArgIsType(),
2489                                        Member.TemplateId->NumArgs);
2490     
2491     llvm::SmallVector<TemplateArgumentLoc, 16> TemplateArgs;
2492     translateTemplateArguments(TemplateArgsPtr, 
2493                                Member.TemplateId->getTemplateArgLocations(),
2494                                TemplateArgs);
2495     TemplateArgsPtr.release();
2496     
2497     // Do we have the save the actual template name? We might need it...
2498     return BuildMemberReferenceExpr(S, move(Base), OpLoc, OpKind, 
2499                                     Member.TemplateId->TemplateNameLoc,
2500                                     Name, true, Member.TemplateId->LAngleLoc,
2501                                     TemplateArgs.data(), TemplateArgs.size(),
2502                                     Member.TemplateId->RAngleLoc, DeclPtrTy(),
2503                                     &SS);
2504   }
2505   
2506   // FIXME: We lose a lot of source information by mapping directly to the
2507   // DeclarationName.
2508   OwningExprResult Result
2509     = BuildMemberReferenceExpr(S, move(Base), OpLoc, OpKind,
2510                                Member.getSourceRange().getBegin(),
2511                                GetNameFromUnqualifiedId(Member),
2512                                ObjCImpDecl, &SS);
2513   
2514   if (Result.isInvalid() || HasTrailingLParen || 
2515       Member.getKind() != UnqualifiedId::IK_DestructorName)
2516     return move(Result);
2517   
2518   // The only way a reference to a destructor can be used is to
2519   // immediately call them. Since the next token is not a '(', produce a
2520   // diagnostic and build the call now.
2521   Expr *E = (Expr *)Result.get();
2522   SourceLocation ExpectedLParenLoc
2523     = PP.getLocForEndOfToken(Member.getSourceRange().getEnd());
2524   Diag(E->getLocStart(), diag::err_dtor_expr_without_call)
2525     << isa<CXXPseudoDestructorExpr>(E)
2526     << CodeModificationHint::CreateInsertion(ExpectedLParenLoc, "()");
2527   
2528   return ActOnCallExpr(0, move(Result), ExpectedLParenLoc,
2529                        MultiExprArg(*this, 0, 0), 0, ExpectedLParenLoc);
2530 }
2531
2532 Sema::OwningExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
2533                                                     FunctionDecl *FD,
2534                                                     ParmVarDecl *Param) {
2535   if (Param->hasUnparsedDefaultArg()) {
2536     Diag (CallLoc,
2537           diag::err_use_of_default_argument_to_function_declared_later) <<
2538       FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
2539     Diag(UnparsedDefaultArgLocs[Param],
2540           diag::note_default_argument_declared_here);
2541   } else {
2542     if (Param->hasUninstantiatedDefaultArg()) {
2543       Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
2544
2545       // Instantiate the expression.
2546       MultiLevelTemplateArgumentList ArgList = getTemplateInstantiationArgs(FD);
2547
2548       InstantiatingTemplate Inst(*this, CallLoc, Param,
2549                                  ArgList.getInnermost().getFlatArgumentList(),
2550                                  ArgList.getInnermost().flat_size());
2551
2552       OwningExprResult Result = SubstExpr(UninstExpr, ArgList);
2553       if (Result.isInvalid())
2554         return ExprError();
2555
2556       if (SetParamDefaultArgument(Param, move(Result),
2557                                   /*FIXME:EqualLoc*/
2558                                   UninstExpr->getSourceRange().getBegin()))
2559         return ExprError();
2560     }
2561
2562     Expr *DefaultExpr = Param->getDefaultArg();
2563
2564     // If the default expression creates temporaries, we need to
2565     // push them to the current stack of expression temporaries so they'll
2566     // be properly destroyed.
2567     if (CXXExprWithTemporaries *E
2568           = dyn_cast_or_null<CXXExprWithTemporaries>(DefaultExpr)) {
2569       assert(!E->shouldDestroyTemporaries() &&
2570              "Can't destroy temporaries in a default argument expr!");
2571       for (unsigned I = 0, N = E->getNumTemporaries(); I != N; ++I)
2572         ExprTemporaries.push_back(E->getTemporary(I));
2573     }
2574   }
2575
2576   // We already type-checked the argument, so we know it works.
2577   return Owned(CXXDefaultArgExpr::Create(Context, Param));
2578 }
2579
2580 /// ConvertArgumentsForCall - Converts the arguments specified in
2581 /// Args/NumArgs to the parameter types of the function FDecl with
2582 /// function prototype Proto. Call is the call expression itself, and
2583 /// Fn is the function expression. For a C++ member function, this
2584 /// routine does not attempt to convert the object argument. Returns
2585 /// true if the call is ill-formed.
2586 bool
2587 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
2588                               FunctionDecl *FDecl,
2589                               const FunctionProtoType *Proto,
2590                               Expr **Args, unsigned NumArgs,
2591                               SourceLocation RParenLoc) {
2592   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
2593   // assignment, to the types of the corresponding parameter, ...
2594   unsigned NumArgsInProto = Proto->getNumArgs();
2595   unsigned NumArgsToCheck = NumArgs;
2596   bool Invalid = false;
2597
2598   // If too few arguments are available (and we don't have default
2599   // arguments for the remaining parameters), don't make the call.
2600   if (NumArgs < NumArgsInProto) {
2601     if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
2602       return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
2603         << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
2604     // Use default arguments for missing arguments
2605     NumArgsToCheck = NumArgsInProto;
2606     Call->setNumArgs(Context, NumArgsInProto);
2607   }
2608
2609   // If too many are passed and not variadic, error on the extras and drop
2610   // them.
2611   if (NumArgs > NumArgsInProto) {
2612     if (!Proto->isVariadic()) {
2613       Diag(Args[NumArgsInProto]->getLocStart(),
2614            diag::err_typecheck_call_too_many_args)
2615         << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
2616         << SourceRange(Args[NumArgsInProto]->getLocStart(),
2617                        Args[NumArgs-1]->getLocEnd());
2618       // This deletes the extra arguments.
2619       Call->setNumArgs(Context, NumArgsInProto);
2620       Invalid = true;
2621     }
2622     NumArgsToCheck = NumArgsInProto;
2623   }
2624
2625   // Continue to check argument types (even if we have too few/many args).
2626   for (unsigned i = 0; i != NumArgsToCheck; i++) {
2627     QualType ProtoArgType = Proto->getArgType(i);
2628
2629     Expr *Arg;
2630     if (i < NumArgs) {
2631       Arg = Args[i];
2632
2633       if (RequireCompleteType(Arg->getSourceRange().getBegin(),
2634                               ProtoArgType,
2635                               PDiag(diag::err_call_incomplete_argument)
2636                                 << Arg->getSourceRange()))
2637         return true;
2638
2639       // Pass the argument.
2640       if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
2641         return true;
2642     } else {
2643       ParmVarDecl *Param = FDecl->getParamDecl(i);
2644
2645       OwningExprResult ArgExpr =
2646         BuildCXXDefaultArgExpr(Call->getSourceRange().getBegin(),
2647                                FDecl, Param);
2648       if (ArgExpr.isInvalid())
2649         return true;
2650
2651       Arg = ArgExpr.takeAs<Expr>();
2652     }
2653
2654     Call->setArg(i, Arg);
2655   }
2656
2657   // If this is a variadic call, handle args passed through "...".
2658   if (Proto->isVariadic()) {
2659     VariadicCallType CallType = VariadicFunction;
2660     if (Fn->getType()->isBlockPointerType())
2661       CallType = VariadicBlock; // Block
2662     else if (isa<MemberExpr>(Fn))
2663       CallType = VariadicMethod;
2664
2665     // Promote the arguments (C99 6.5.2.2p7).
2666     for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
2667       Expr *Arg = Args[i];
2668       Invalid |= DefaultVariadicArgumentPromotion(Arg, CallType);
2669       Call->setArg(i, Arg);
2670     }
2671   }
2672
2673   return Invalid;
2674 }
2675
2676 /// \brief "Deconstruct" the function argument of a call expression to find 
2677 /// the underlying declaration (if any), the name of the called function, 
2678 /// whether argument-dependent lookup is available, whether it has explicit
2679 /// template arguments, etc.
2680 void Sema::DeconstructCallFunction(Expr *FnExpr,
2681                                    NamedDecl *&Function,
2682                                    DeclarationName &Name,
2683                                    NestedNameSpecifier *&Qualifier,
2684                                    SourceRange &QualifierRange,
2685                                    bool &ArgumentDependentLookup,
2686                                    bool &HasExplicitTemplateArguments,
2687                            const TemplateArgumentLoc *&ExplicitTemplateArgs,
2688                                    unsigned &NumExplicitTemplateArgs) {
2689   // Set defaults for all of the output parameters.
2690   Function = 0;
2691   Name = DeclarationName();
2692   Qualifier = 0;
2693   QualifierRange = SourceRange();
2694   ArgumentDependentLookup = getLangOptions().CPlusPlus;
2695   HasExplicitTemplateArguments = false;
2696   
2697   // If we're directly calling a function, get the appropriate declaration.
2698   // Also, in C++, keep track of whether we should perform argument-dependent
2699   // lookup and whether there were any explicitly-specified template arguments.
2700   while (true) {
2701     if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(FnExpr))
2702       FnExpr = IcExpr->getSubExpr();
2703     else if (ParenExpr *PExpr = dyn_cast<ParenExpr>(FnExpr)) {
2704       // Parentheses around a function disable ADL
2705       // (C++0x [basic.lookup.argdep]p1).
2706       ArgumentDependentLookup = false;
2707       FnExpr = PExpr->getSubExpr();
2708     } else if (isa<UnaryOperator>(FnExpr) &&
2709                cast<UnaryOperator>(FnExpr)->getOpcode()
2710                == UnaryOperator::AddrOf) {
2711       FnExpr = cast<UnaryOperator>(FnExpr)->getSubExpr();
2712     } else if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(FnExpr)) {
2713       Function = dyn_cast<NamedDecl>(DRExpr->getDecl());
2714       if ((Qualifier = DRExpr->getQualifier())) {
2715         ArgumentDependentLookup = false;
2716         QualifierRange = DRExpr->getQualifierRange();
2717       }      
2718       break;
2719     } else if (UnresolvedFunctionNameExpr *DepName
2720                = dyn_cast<UnresolvedFunctionNameExpr>(FnExpr)) {
2721       Name = DepName->getName();
2722       break;
2723     } else if (TemplateIdRefExpr *TemplateIdRef
2724                = dyn_cast<TemplateIdRefExpr>(FnExpr)) {
2725       Function = TemplateIdRef->getTemplateName().getAsTemplateDecl();
2726       if (!Function)
2727         Function = TemplateIdRef->getTemplateName().getAsOverloadedFunctionDecl();
2728       HasExplicitTemplateArguments = true;
2729       ExplicitTemplateArgs = TemplateIdRef->getTemplateArgs();
2730       NumExplicitTemplateArgs = TemplateIdRef->getNumTemplateArgs();
2731       
2732       // C++ [temp.arg.explicit]p6:
2733       //   [Note: For simple function names, argument dependent lookup (3.4.2)
2734       //   applies even when the function name is not visible within the
2735       //   scope of the call. This is because the call still has the syntactic
2736       //   form of a function call (3.4.1). But when a function template with
2737       //   explicit template arguments is used, the call does not have the
2738       //   correct syntactic form unless there is a function template with
2739       //   that name visible at the point of the call. If no such name is
2740       //   visible, the call is not syntactically well-formed and
2741       //   argument-dependent lookup does not apply. If some such name is
2742       //   visible, argument dependent lookup applies and additional function
2743       //   templates may be found in other namespaces.
2744       //
2745       // The summary of this paragraph is that, if we get to this point and the
2746       // template-id was not a qualified name, then argument-dependent lookup
2747       // is still possible.
2748       if ((Qualifier = TemplateIdRef->getQualifier())) {
2749         ArgumentDependentLookup = false;
2750         QualifierRange = TemplateIdRef->getQualifierRange();
2751       }
2752       break;
2753     } else {
2754       // Any kind of name that does not refer to a declaration (or
2755       // set of declarations) disables ADL (C++0x [basic.lookup.argdep]p3).
2756       ArgumentDependentLookup = false;
2757       break;
2758     }
2759   }
2760 }
2761
2762 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
2763 /// This provides the location of the left/right parens and a list of comma
2764 /// locations.
2765 Action::OwningExprResult
2766 Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
2767                     MultiExprArg args,
2768                     SourceLocation *CommaLocs, SourceLocation RParenLoc) {
2769   unsigned NumArgs = args.size();
2770
2771   // Since this might be a postfix expression, get rid of ParenListExprs.
2772   fn = MaybeConvertParenListExprToParenExpr(S, move(fn));
2773
2774   Expr *Fn = fn.takeAs<Expr>();
2775   Expr **Args = reinterpret_cast<Expr**>(args.release());
2776   assert(Fn && "no function call expression");
2777   FunctionDecl *FDecl = NULL;
2778   NamedDecl *NDecl = NULL;
2779   DeclarationName UnqualifiedName;
2780
2781   if (getLangOptions().CPlusPlus) {
2782     // If this is a pseudo-destructor expression, build the call immediately.
2783     if (isa<CXXPseudoDestructorExpr>(Fn)) {
2784       if (NumArgs > 0) {
2785         // Pseudo-destructor calls should not have any arguments.
2786         Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
2787           << CodeModificationHint::CreateRemoval(
2788                                     SourceRange(Args[0]->getLocStart(),
2789                                                 Args[NumArgs-1]->getLocEnd()));
2790
2791         for (unsigned I = 0; I != NumArgs; ++I)
2792           Args[I]->Destroy(Context);
2793
2794         NumArgs = 0;
2795       }
2796
2797       return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
2798                                           RParenLoc));
2799     }
2800
2801     // Determine whether this is a dependent call inside a C++ template,
2802     // in which case we won't do any semantic analysis now.
2803     // FIXME: Will need to cache the results of name lookup (including ADL) in
2804     // Fn.
2805     bool Dependent = false;
2806     if (Fn->isTypeDependent())
2807       Dependent = true;
2808     else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
2809       Dependent = true;
2810
2811     if (Dependent)
2812       return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
2813                                           Context.DependentTy, RParenLoc));
2814
2815     // Determine whether this is a call to an object (C++ [over.call.object]).
2816     if (Fn->getType()->isRecordType())
2817       return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
2818                                                 CommaLocs, RParenLoc));
2819
2820     // Determine whether this is a call to a member function.
2821     if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(Fn->IgnoreParens())) {
2822       NamedDecl *MemDecl = MemExpr->getMemberDecl();
2823       if (isa<OverloadedFunctionDecl>(MemDecl) ||
2824           isa<CXXMethodDecl>(MemDecl) ||
2825           (isa<FunctionTemplateDecl>(MemDecl) &&
2826            isa<CXXMethodDecl>(
2827                 cast<FunctionTemplateDecl>(MemDecl)->getTemplatedDecl())))
2828         return Owned(BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
2829                                                CommaLocs, RParenLoc));
2830     }
2831     
2832     // Determine whether this is a call to a pointer-to-member function.
2833     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Fn->IgnoreParens())) {
2834       if (BO->getOpcode() == BinaryOperator::PtrMemD ||
2835           BO->getOpcode() == BinaryOperator::PtrMemI) {
2836         if (const FunctionProtoType *FPT = 
2837               dyn_cast<FunctionProtoType>(BO->getType())) {
2838           QualType ResultTy = FPT->getResultType().getNonReferenceType();
2839       
2840           ExprOwningPtr<CXXMemberCallExpr> 
2841             TheCall(this, new (Context) CXXMemberCallExpr(Context, BO, Args, 
2842                                                           NumArgs, ResultTy,
2843                                                           RParenLoc));
2844         
2845           if (CheckCallReturnType(FPT->getResultType(), 
2846                                   BO->getRHS()->getSourceRange().getBegin(), 
2847                                   TheCall.get(), 0))
2848             return ExprError();
2849
2850           if (ConvertArgumentsForCall(&*TheCall, BO, 0, FPT, Args, NumArgs, 
2851                                       RParenLoc))
2852             return ExprError();
2853
2854           return Owned(MaybeBindToTemporary(TheCall.release()).release());
2855         }
2856         return ExprError(Diag(Fn->getLocStart(), 
2857                               diag::err_typecheck_call_not_function)
2858                               << Fn->getType() << Fn->getSourceRange());
2859       }
2860     }
2861   }
2862
2863   // If we're directly calling a function, get the appropriate declaration.
2864   // Also, in C++, keep track of whether we should perform argument-dependent
2865   // lookup and whether there were any explicitly-specified template arguments.
2866   bool ADL = true;
2867   bool HasExplicitTemplateArgs = 0;
2868   const TemplateArgumentLoc *ExplicitTemplateArgs = 0;
2869   unsigned NumExplicitTemplateArgs = 0;
2870   NestedNameSpecifier *Qualifier = 0;
2871   SourceRange QualifierRange;
2872   DeconstructCallFunction(Fn, NDecl, UnqualifiedName, Qualifier, QualifierRange,
2873                           ADL,HasExplicitTemplateArgs, ExplicitTemplateArgs,
2874                           NumExplicitTemplateArgs);
2875
2876   OverloadedFunctionDecl *Ovl = 0;
2877   FunctionTemplateDecl *FunctionTemplate = 0;
2878   if (NDecl) {
2879     FDecl = dyn_cast<FunctionDecl>(NDecl);
2880     if ((FunctionTemplate = dyn_cast<FunctionTemplateDecl>(NDecl)))
2881       FDecl = FunctionTemplate->getTemplatedDecl();
2882     else
2883       FDecl = dyn_cast<FunctionDecl>(NDecl);
2884     Ovl = dyn_cast<OverloadedFunctionDecl>(NDecl);
2885   }
2886
2887   if (Ovl || FunctionTemplate ||
2888       (getLangOptions().CPlusPlus && (FDecl || UnqualifiedName))) {
2889     // We don't perform ADL for implicit declarations of builtins.
2890     if (FDecl && FDecl->getBuiltinID() && FDecl->isImplicit())
2891       ADL = false;
2892
2893     // We don't perform ADL in C.
2894     if (!getLangOptions().CPlusPlus)
2895       ADL = false;
2896
2897     if (Ovl || FunctionTemplate || ADL) {
2898       FDecl = ResolveOverloadedCallFn(Fn, NDecl, UnqualifiedName,
2899                                       HasExplicitTemplateArgs,
2900                                       ExplicitTemplateArgs,
2901                                       NumExplicitTemplateArgs,
2902                                       LParenLoc, Args, NumArgs, CommaLocs,
2903                                       RParenLoc, ADL);
2904       if (!FDecl)
2905         return ExprError();
2906
2907       Fn = FixOverloadedFunctionReference(Fn, FDecl);
2908     }
2909   }
2910
2911   // Promote the function operand.
2912   UsualUnaryConversions(Fn);
2913
2914   // Make the call expr early, before semantic checks.  This guarantees cleanup
2915   // of arguments and function on error.
2916   ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn,
2917                                                                Args, NumArgs,
2918                                                                Context.BoolTy,
2919                                                                RParenLoc));
2920
2921   const FunctionType *FuncT;
2922   if (!Fn->getType()->isBlockPointerType()) {
2923     // C99 6.5.2.2p1 - "The expression that denotes the called function shall
2924     // have type pointer to function".
2925     const PointerType *PT = Fn->getType()->getAs<PointerType>();
2926     if (PT == 0)
2927       return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2928         << Fn->getType() << Fn->getSourceRange());
2929     FuncT = PT->getPointeeType()->getAs<FunctionType>();
2930   } else { // This is a block call.
2931     FuncT = Fn->getType()->getAs<BlockPointerType>()->getPointeeType()->
2932                 getAs<FunctionType>();
2933   }
2934   if (FuncT == 0)
2935     return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2936       << Fn->getType() << Fn->getSourceRange());
2937
2938   // Check for a valid return type
2939   if (CheckCallReturnType(FuncT->getResultType(), 
2940                           Fn->getSourceRange().getBegin(), TheCall.get(),
2941                           FDecl))
2942     return ExprError();
2943
2944   // We know the result type of the call, set it.
2945   TheCall->setType(FuncT->getResultType().getNonReferenceType());
2946
2947   if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
2948     if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
2949                                 RParenLoc))
2950       return ExprError();
2951   } else {
2952     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
2953
2954     if (FDecl) {
2955       // Check if we have too few/too many template arguments, based
2956       // on our knowledge of the function definition.
2957       const FunctionDecl *Def = 0;
2958       if (FDecl->getBody(Def) && NumArgs != Def->param_size()) {
2959         const FunctionProtoType *Proto =
2960             Def->getType()->getAs<FunctionProtoType>();
2961         if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size())) {
2962           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
2963             << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
2964         }
2965       }
2966     }
2967
2968     // Promote the arguments (C99 6.5.2.2p6).
2969     for (unsigned i = 0; i != NumArgs; i++) {
2970       Expr *Arg = Args[i];
2971       DefaultArgumentPromotion(Arg);
2972       if (RequireCompleteType(Arg->getSourceRange().getBegin(),
2973                               Arg->getType(),
2974                               PDiag(diag::err_call_incomplete_argument)
2975                                 << Arg->getSourceRange()))
2976         return ExprError();
2977       TheCall->setArg(i, Arg);
2978     }
2979   }
2980
2981   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
2982     if (!Method->isStatic())
2983       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
2984         << Fn->getSourceRange());
2985
2986   // Check for sentinels
2987   if (NDecl)
2988     DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
2989
2990   // Do special checking on direct calls to functions.
2991   if (FDecl) {
2992     if (CheckFunctionCall(FDecl, TheCall.get()))
2993       return ExprError();
2994
2995     if (unsigned BuiltinID = FDecl->getBuiltinID())
2996       return CheckBuiltinFunctionCall(BuiltinID, TheCall.take());
2997   } else if (NDecl) {
2998     if (CheckBlockCall(NDecl, TheCall.get()))
2999       return ExprError();
3000   }
3001
3002   return MaybeBindToTemporary(TheCall.take());
3003 }
3004
3005 Action::OwningExprResult
3006 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
3007                            SourceLocation RParenLoc, ExprArg InitExpr) {
3008   assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
3009   //FIXME: Preserve type source info.
3010   QualType literalType = GetTypeFromParser(Ty);
3011   // FIXME: put back this assert when initializers are worked out.
3012   //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
3013   Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
3014
3015   if (literalType->isArrayType()) {
3016     if (literalType->isVariableArrayType())
3017       return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
3018         << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
3019   } else if (!literalType->isDependentType() &&
3020              RequireCompleteType(LParenLoc, literalType,
3021                       PDiag(diag::err_typecheck_decl_incomplete_type)
3022                         << SourceRange(LParenLoc,
3023                                        literalExpr->getSourceRange().getEnd())))
3024     return ExprError();
3025
3026   if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
3027                             DeclarationName(), /*FIXME:DirectInit=*/false))
3028     return ExprError();
3029
3030   bool isFileScope = getCurFunctionOrMethodDecl() == 0;
3031   if (isFileScope) { // 6.5.2.5p3
3032     if (CheckForConstantInitializer(literalExpr, literalType))
3033       return ExprError();
3034   }
3035   InitExpr.release();
3036   return Owned(new (Context) CompoundLiteralExpr(LParenLoc, literalType,
3037                                                  literalExpr, isFileScope));
3038 }
3039
3040 Action::OwningExprResult
3041 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
3042                     SourceLocation RBraceLoc) {
3043   unsigned NumInit = initlist.size();
3044   Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
3045
3046   // Semantic analysis for initializers is done by ActOnDeclarator() and
3047   // CheckInitializer() - it requires knowledge of the object being intialized.
3048
3049   InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit,
3050                                                RBraceLoc);
3051   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
3052   return Owned(E);
3053 }
3054
3055 static CastExpr::CastKind getScalarCastKind(ASTContext &Context,
3056                                             QualType SrcTy, QualType DestTy) {
3057   if (Context.getCanonicalType(SrcTy).getUnqualifiedType() ==
3058       Context.getCanonicalType(DestTy).getUnqualifiedType())
3059     return CastExpr::CK_NoOp;
3060
3061   if (SrcTy->hasPointerRepresentation()) {
3062     if (DestTy->hasPointerRepresentation())
3063       return CastExpr::CK_BitCast;
3064     if (DestTy->isIntegerType())
3065       return CastExpr::CK_PointerToIntegral;
3066   }
3067   
3068   if (SrcTy->isIntegerType()) {
3069     if (DestTy->isIntegerType())
3070       return CastExpr::CK_IntegralCast;
3071     if (DestTy->hasPointerRepresentation())
3072       return CastExpr::CK_IntegralToPointer;
3073     if (DestTy->isRealFloatingType())
3074       return CastExpr::CK_IntegralToFloating;
3075   }
3076   
3077   if (SrcTy->isRealFloatingType()) {
3078     if (DestTy->isRealFloatingType())
3079       return CastExpr::CK_FloatingCast;
3080     if (DestTy->isIntegerType())
3081       return CastExpr::CK_FloatingToIntegral;
3082   }
3083   
3084   // FIXME: Assert here.
3085   // assert(false && "Unhandled cast combination!");
3086   return CastExpr::CK_Unknown;
3087 }
3088
3089 /// CheckCastTypes - Check type constraints for casting between types.
3090 bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr,
3091                           CastExpr::CastKind& Kind,
3092                           CXXMethodDecl *& ConversionDecl,
3093                           bool FunctionalStyle) {
3094   if (getLangOptions().CPlusPlus)
3095     return CXXCheckCStyleCast(TyR, castType, castExpr, Kind, FunctionalStyle,
3096                               ConversionDecl);
3097
3098   DefaultFunctionArrayConversion(castExpr);
3099
3100   // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
3101   // type needs to be scalar.
3102   if (castType->isVoidType()) {
3103     // Cast to void allows any expr type.
3104     Kind = CastExpr::CK_ToVoid;
3105     return false;
3106   }
3107   
3108   if (!castType->isScalarType() && !castType->isVectorType()) {
3109     if (Context.getCanonicalType(castType).getUnqualifiedType() ==
3110         Context.getCanonicalType(castExpr->getType().getUnqualifiedType()) &&
3111         (castType->isStructureType() || castType->isUnionType())) {
3112       // GCC struct/union extension: allow cast to self.
3113       // FIXME: Check that the cast destination type is complete.
3114       Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
3115         << castType << castExpr->getSourceRange();
3116       Kind = CastExpr::CK_NoOp;
3117       return false;
3118     }
3119     
3120     if (castType->isUnionType()) {
3121       // GCC cast to union extension
3122       RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
3123       RecordDecl::field_iterator Field, FieldEnd;
3124       for (Field = RD->field_begin(), FieldEnd = RD->field_end();
3125            Field != FieldEnd; ++Field) {
3126         if (Context.getCanonicalType(Field->getType()).getUnqualifiedType() ==
3127             Context.getCanonicalType(castExpr->getType()).getUnqualifiedType()) {
3128           Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
3129             << castExpr->getSourceRange();
3130           break;
3131         }
3132       }
3133       if (Field == FieldEnd)
3134         return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
3135           << castExpr->getType() << castExpr->getSourceRange();
3136       Kind = CastExpr::CK_ToUnion;
3137       return false;
3138     }
3139     
3140     // Reject any other conversions to non-scalar types.
3141     return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
3142       << castType << castExpr->getSourceRange();
3143   }
3144   
3145   if (!castExpr->getType()->isScalarType() && 
3146       !castExpr->getType()->isVectorType()) {
3147     return Diag(castExpr->getLocStart(),
3148                 diag::err_typecheck_expect_scalar_operand)
3149       << castExpr->getType() << castExpr->getSourceRange();
3150   }
3151   
3152   if (castType->isExtVectorType()) 
3153     return CheckExtVectorCast(TyR, castType, castExpr, Kind);
3154   
3155   if (castType->isVectorType())
3156     return CheckVectorCast(TyR, castType, castExpr->getType(), Kind);
3157   if (castExpr->getType()->isVectorType())
3158     return CheckVectorCast(TyR, castExpr->getType(), castType, Kind);
3159
3160   if (getLangOptions().ObjC1 && isa<ObjCSuperExpr>(castExpr))
3161     return Diag(castExpr->getLocStart(), diag::err_illegal_super_cast) << TyR;
3162   
3163   if (isa<ObjCSelectorExpr>(castExpr))
3164     return Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
3165   
3166   if (!castType->isArithmeticType()) {
3167     QualType castExprType = castExpr->getType();
3168     if (!castExprType->isIntegralType() && castExprType->isArithmeticType())
3169       return Diag(castExpr->getLocStart(),
3170                   diag::err_cast_pointer_from_non_pointer_int)
3171         << castExprType << castExpr->getSourceRange();
3172   } else if (!castExpr->getType()->isArithmeticType()) {
3173     if (!castType->isIntegralType() && castType->isArithmeticType())
3174       return Diag(castExpr->getLocStart(),
3175                   diag::err_cast_pointer_to_non_pointer_int)
3176         << castType << castExpr->getSourceRange();
3177   }
3178
3179   Kind = getScalarCastKind(Context, castExpr->getType(), castType);
3180   return false;
3181 }
3182
3183 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
3184                            CastExpr::CastKind &Kind) {
3185   assert(VectorTy->isVectorType() && "Not a vector type!");
3186
3187   if (Ty->isVectorType() || Ty->isIntegerType()) {
3188     if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
3189       return Diag(R.getBegin(),
3190                   Ty->isVectorType() ?
3191                   diag::err_invalid_conversion_between_vectors :
3192                   diag::err_invalid_conversion_between_vector_and_integer)
3193         << VectorTy << Ty << R;
3194   } else
3195     return Diag(R.getBegin(),
3196                 diag::err_invalid_conversion_between_vector_and_scalar)
3197       << VectorTy << Ty << R;
3198
3199   Kind = CastExpr::CK_BitCast;
3200   return false;
3201 }
3202
3203 bool Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *&CastExpr, 
3204                               CastExpr::CastKind &Kind) {
3205   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
3206   
3207   QualType SrcTy = CastExpr->getType();
3208   
3209   // If SrcTy is a VectorType, the total size must match to explicitly cast to
3210   // an ExtVectorType.
3211   if (SrcTy->isVectorType()) {
3212     if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
3213       return Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
3214         << DestTy << SrcTy << R;
3215     Kind = CastExpr::CK_BitCast;
3216     return false;
3217   }
3218
3219   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
3220   // conversion will take place first from scalar to elt type, and then
3221   // splat from elt type to vector.
3222   if (SrcTy->isPointerType())
3223     return Diag(R.getBegin(),
3224                 diag::err_invalid_conversion_between_vector_and_scalar)
3225       << DestTy << SrcTy << R;
3226
3227   QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
3228   ImpCastExprToType(CastExpr, DestElemTy,
3229                     getScalarCastKind(Context, SrcTy, DestElemTy));
3230   
3231   Kind = CastExpr::CK_VectorSplat;
3232   return false;
3233 }
3234
3235 Action::OwningExprResult
3236 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, TypeTy *Ty,
3237                     SourceLocation RParenLoc, ExprArg Op) {
3238   CastExpr::CastKind Kind = CastExpr::CK_Unknown;
3239
3240   assert((Ty != 0) && (Op.get() != 0) &&
3241          "ActOnCastExpr(): missing type or expr");
3242
3243   Expr *castExpr = (Expr *)Op.get();
3244   //FIXME: Preserve type source info.
3245   QualType castType = GetTypeFromParser(Ty);
3246
3247   // If the Expr being casted is a ParenListExpr, handle it specially.
3248   if (isa<ParenListExpr>(castExpr))
3249     return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, move(Op),castType);
3250   CXXMethodDecl *Method = 0;
3251   if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr,
3252                      Kind, Method))
3253     return ExprError();
3254
3255   if (Method) {
3256     OwningExprResult CastArg = BuildCXXCastArgument(LParenLoc, castType, Kind,
3257                                                     Method, move(Op));
3258
3259     if (CastArg.isInvalid())
3260       return ExprError();
3261
3262     castExpr = CastArg.takeAs<Expr>();
3263   } else {
3264     Op.release();
3265   }
3266
3267   return Owned(new (Context) CStyleCastExpr(castType.getNonReferenceType(),
3268                                             Kind, castExpr, castType,
3269                                             LParenLoc, RParenLoc));
3270 }
3271
3272 /// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
3273 /// of comma binary operators.
3274 Action::OwningExprResult
3275 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, ExprArg EA) {
3276   Expr *expr = EA.takeAs<Expr>();
3277   ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
3278   if (!E)
3279     return Owned(expr);
3280
3281   OwningExprResult Result(*this, E->getExpr(0));
3282
3283   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
3284     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, move(Result),
3285                         Owned(E->getExpr(i)));
3286
3287   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), move(Result));
3288 }
3289
3290 Action::OwningExprResult
3291 Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
3292                                SourceLocation RParenLoc, ExprArg Op,
3293                                QualType Ty) {
3294   ParenListExpr *PE = (ParenListExpr *)Op.get();
3295
3296   // If this is an altivec initializer, '(' type ')' '(' init, ..., init ')'
3297   // then handle it as such.
3298   if (getLangOptions().AltiVec && Ty->isVectorType()) {
3299     if (PE->getNumExprs() == 0) {
3300       Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
3301       return ExprError();
3302     }
3303
3304     llvm::SmallVector<Expr *, 8> initExprs;
3305     for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
3306       initExprs.push_back(PE->getExpr(i));
3307
3308     // FIXME: This means that pretty-printing the final AST will produce curly
3309     // braces instead of the original commas.
3310     Op.release();
3311     InitListExpr *E = new (Context) InitListExpr(LParenLoc, &initExprs[0],
3312                                                  initExprs.size(), RParenLoc);
3313     E->setType(Ty);
3314     return ActOnCompoundLiteral(LParenLoc, Ty.getAsOpaquePtr(), RParenLoc,
3315                                 Owned(E));
3316   } else {
3317     // This is not an AltiVec-style cast, so turn the ParenListExpr into a
3318     // sequence of BinOp comma operators.
3319     Op = MaybeConvertParenListExprToParenExpr(S, move(Op));
3320     return ActOnCastExpr(S, LParenLoc, Ty.getAsOpaquePtr(), RParenLoc,move(Op));
3321   }
3322 }
3323
3324 Action::OwningExprResult Sema::ActOnParenListExpr(SourceLocation L,
3325                                                   SourceLocation R,
3326                                                   MultiExprArg Val) {
3327   unsigned nexprs = Val.size();
3328   Expr **exprs = reinterpret_cast<Expr**>(Val.release());
3329   assert((exprs != 0) && "ActOnParenListExpr() missing expr list");
3330   Expr *expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
3331   return Owned(expr);
3332 }
3333
3334 /// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
3335 /// In that case, lhs = cond.
3336 /// C99 6.5.15
3337 QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
3338                                         SourceLocation QuestionLoc) {
3339   // C++ is sufficiently different to merit its own checker.
3340   if (getLangOptions().CPlusPlus)
3341     return CXXCheckConditionalOperands(Cond, LHS, RHS, QuestionLoc);
3342
3343   CheckSignCompare(LHS, RHS, QuestionLoc, diag::warn_mixed_sign_conditional);
3344
3345   UsualUnaryConversions(Cond);
3346   UsualUnaryConversions(LHS);
3347   UsualUnaryConversions(RHS);
3348   QualType CondTy = Cond->getType();
3349   QualType LHSTy = LHS->getType();
3350   QualType RHSTy = RHS->getType();
3351
3352   // first, check the condition.
3353   if (!CondTy->isScalarType()) { // C99 6.5.15p2
3354     Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
3355       << CondTy;
3356     return QualType();
3357   }
3358
3359   // Now check the two expressions.
3360   if (LHSTy->isVectorType() || RHSTy->isVectorType())
3361     return CheckVectorOperands(QuestionLoc, LHS, RHS);
3362
3363   // If both operands have arithmetic type, do the usual arithmetic conversions
3364   // to find a common type: C99 6.5.15p3,5.
3365   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
3366     UsualArithmeticConversions(LHS, RHS);
3367     return LHS->getType();
3368   }
3369
3370   // If both operands are the same structure or union type, the result is that
3371   // type.
3372   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
3373     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
3374       if (LHSRT->getDecl() == RHSRT->getDecl())
3375         // "If both the operands have structure or union type, the result has
3376         // that type."  This implies that CV qualifiers are dropped.
3377         return LHSTy.getUnqualifiedType();
3378     // FIXME: Type of conditional expression must be complete in C mode.
3379   }
3380
3381   // C99 6.5.15p5: "If both operands have void type, the result has void type."
3382   // The following || allows only one side to be void (a GCC-ism).
3383   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
3384     if (!LHSTy->isVoidType())
3385       Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
3386         << RHS->getSourceRange();
3387     if (!RHSTy->isVoidType())
3388       Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
3389         << LHS->getSourceRange();
3390     ImpCastExprToType(LHS, Context.VoidTy, CastExpr::CK_ToVoid);
3391     ImpCastExprToType(RHS, Context.VoidTy, CastExpr::CK_ToVoid);
3392     return Context.VoidTy;
3393   }
3394   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
3395   // the type of the other operand."
3396   if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
3397       RHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
3398     // promote the null to a pointer.
3399     ImpCastExprToType(RHS, LHSTy, CastExpr::CK_Unknown);
3400     return LHSTy;
3401   }
3402   if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
3403       LHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
3404     ImpCastExprToType(LHS, RHSTy, CastExpr::CK_Unknown);
3405     return RHSTy;
3406   }
3407   // Handle things like Class and struct objc_class*.  Here we case the result
3408   // to the pseudo-builtin, because that will be implicitly cast back to the
3409   // redefinition type if an attempt is made to access its fields.
3410   if (LHSTy->isObjCClassType() &&
3411       (RHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
3412     ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
3413     return LHSTy;
3414   }
3415   if (RHSTy->isObjCClassType() &&
3416       (LHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
3417     ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
3418     return RHSTy;
3419   }
3420   // And the same for struct objc_object* / id
3421   if (LHSTy->isObjCIdType() &&
3422       (RHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
3423     ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
3424     return LHSTy;
3425   }
3426   if (RHSTy->isObjCIdType() &&
3427       (LHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
3428     ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
3429     return RHSTy;
3430   }
3431   // Handle block pointer types.
3432   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
3433     if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
3434       if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
3435         QualType destType = Context.getPointerType(Context.VoidTy);
3436         ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
3437         ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
3438         return destType;
3439       }
3440       Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
3441             << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3442       return QualType();
3443     }
3444     // We have 2 block pointer types.
3445     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3446       // Two identical block pointer types are always compatible.
3447       return LHSTy;
3448     }
3449     // The block pointer types aren't identical, continue checking.
3450     QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
3451     QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
3452
3453     if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
3454                                     rhptee.getUnqualifiedType())) {
3455       Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
3456         << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3457       // In this situation, we assume void* type. No especially good
3458       // reason, but this is what gcc does, and we do have to pick
3459       // to get a consistent AST.
3460       QualType incompatTy = Context.getPointerType(Context.VoidTy);
3461       ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
3462       ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
3463       return incompatTy;
3464     }
3465     // The block pointer types are compatible.
3466     ImpCastExprToType(LHS, LHSTy, CastExpr::CK_BitCast);
3467     ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
3468     return LHSTy;
3469   }
3470   // Check constraints for Objective-C object pointers types.
3471   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
3472
3473     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3474       // Two identical object pointer types are always compatible.
3475       return LHSTy;
3476     }
3477     const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>();
3478     const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>();
3479     QualType compositeType = LHSTy;
3480
3481     // If both operands are interfaces and either operand can be
3482     // assigned to the other, use that type as the composite
3483     // type. This allows
3484     //   xxx ? (A*) a : (B*) b
3485     // where B is a subclass of A.
3486     //
3487     // Additionally, as for assignment, if either type is 'id'
3488     // allow silent coercion. Finally, if the types are
3489     // incompatible then make sure to use 'id' as the composite
3490     // type so the result is acceptable for sending messages to.
3491
3492     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
3493     // It could return the composite type.
3494     if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
3495       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
3496     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
3497       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
3498     } else if ((LHSTy->isObjCQualifiedIdType() ||
3499                 RHSTy->isObjCQualifiedIdType()) &&
3500                 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
3501       // Need to handle "id<xx>" explicitly.
3502       // GCC allows qualified id and any Objective-C type to devolve to
3503       // id. Currently localizing to here until clear this should be
3504       // part of ObjCQualifiedIdTypesAreCompatible.
3505       compositeType = Context.getObjCIdType();
3506     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
3507       compositeType = Context.getObjCIdType();
3508     } else if (!(compositeType = 
3509                  Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
3510       ;
3511     else {
3512       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
3513         << LHSTy << RHSTy
3514         << LHS->getSourceRange() << RHS->getSourceRange();
3515       QualType incompatTy = Context.getObjCIdType();
3516       ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
3517       ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
3518       return incompatTy;
3519     }
3520     // The object pointer types are compatible.
3521     ImpCastExprToType(LHS, compositeType, CastExpr::CK_BitCast);
3522     ImpCastExprToType(RHS, compositeType, CastExpr::CK_BitCast);
3523     return compositeType;
3524   }
3525   // Check Objective-C object pointer types and 'void *'
3526   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
3527     QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
3528     QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
3529     QualType destPointee
3530       = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
3531     QualType destType = Context.getPointerType(destPointee);
3532     // Add qualifiers if necessary.
3533     ImpCastExprToType(LHS, destType, CastExpr::CK_NoOp);
3534     // Promote to void*.
3535     ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
3536     return destType;
3537   }
3538   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
3539     QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
3540     QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
3541     QualType destPointee
3542       = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
3543     QualType destType = Context.getPointerType(destPointee);
3544     // Add qualifiers if necessary.
3545     ImpCastExprToType(RHS, destType, CastExpr::CK_NoOp);
3546     // Promote to void*.
3547     ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
3548     return destType;
3549   }
3550   // Check constraints for C object pointers types (C99 6.5.15p3,6).
3551   if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
3552     // get the "pointed to" types
3553     QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
3554     QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
3555
3556     // ignore qualifiers on void (C99 6.5.15p3, clause 6)
3557     if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
3558       // Figure out necessary qualifiers (C99 6.5.15p6)
3559       QualType destPointee
3560         = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
3561       QualType destType = Context.getPointerType(destPointee);
3562       // Add qualifiers if necessary.
3563       ImpCastExprToType(LHS, destType, CastExpr::CK_NoOp);
3564       // Promote to void*.
3565       ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
3566       return destType;
3567     }
3568     if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
3569       QualType destPointee
3570         = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
3571       QualType destType = Context.getPointerType(destPointee);
3572       // Add qualifiers if necessary.
3573       ImpCastExprToType(LHS, destType, CastExpr::CK_NoOp);
3574       // Promote to void*.
3575       ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
3576       return destType;
3577     }
3578
3579     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3580       // Two identical pointer types are always compatible.
3581       return LHSTy;
3582     }
3583     if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
3584                                     rhptee.getUnqualifiedType())) {
3585       Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
3586         << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3587       // In this situation, we assume void* type. No especially good
3588       // reason, but this is what gcc does, and we do have to pick
3589       // to get a consistent AST.
3590       QualType incompatTy = Context.getPointerType(Context.VoidTy);
3591       ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
3592       ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
3593       return incompatTy;
3594     }
3595     // The pointer types are compatible.
3596     // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
3597     // differently qualified versions of compatible types, the result type is
3598     // a pointer to an appropriately qualified version of the *composite*
3599     // type.
3600     // FIXME: Need to calculate the composite type.
3601     // FIXME: Need to add qualifiers
3602     ImpCastExprToType(LHS, LHSTy, CastExpr::CK_BitCast);
3603     ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
3604     return LHSTy;
3605   }
3606
3607   // GCC compatibility: soften pointer/integer mismatch.
3608   if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
3609     Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
3610       << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3611     ImpCastExprToType(LHS, RHSTy, CastExpr::CK_IntegralToPointer);
3612     return RHSTy;
3613   }
3614   if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
3615     Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
3616       << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3617     ImpCastExprToType(RHS, LHSTy, CastExpr::CK_IntegralToPointer);
3618     return LHSTy;
3619   }
3620
3621   // Otherwise, the operands are not compatible.
3622   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
3623     << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3624   return QualType();
3625 }
3626
3627 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
3628 /// in the case of a the GNU conditional expr extension.
3629 Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
3630                                                   SourceLocation ColonLoc,
3631                                                   ExprArg Cond, ExprArg LHS,
3632                                                   ExprArg RHS) {
3633   Expr *CondExpr = (Expr *) Cond.get();
3634   Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
3635
3636   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
3637   // was the condition.
3638   bool isLHSNull = LHSExpr == 0;
3639   if (isLHSNull)
3640     LHSExpr = CondExpr;
3641
3642   QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
3643                                              RHSExpr, QuestionLoc);
3644   if (result.isNull())
3645     return ExprError();
3646
3647   Cond.release();
3648   LHS.release();
3649   RHS.release();
3650   return Owned(new (Context) ConditionalOperator(CondExpr, QuestionLoc,
3651                                                  isLHSNull ? 0 : LHSExpr,
3652                                                  ColonLoc, RHSExpr, result));
3653 }
3654
3655 // CheckPointerTypesForAssignment - This is a very tricky routine (despite
3656 // being closely modeled after the C99 spec:-). The odd characteristic of this
3657 // routine is it effectively iqnores the qualifiers on the top level pointee.
3658 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
3659 // FIXME: add a couple examples in this comment.
3660 Sema::AssignConvertType
3661 Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
3662   QualType lhptee, rhptee;
3663
3664   if ((lhsType->isObjCClassType() &&
3665        (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
3666      (rhsType->isObjCClassType() &&
3667        (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
3668       return Compatible;
3669   }
3670
3671   // get the "pointed to" type (ignoring qualifiers at the top level)
3672   lhptee = lhsType->getAs<PointerType>()->getPointeeType();
3673   rhptee = rhsType->getAs<PointerType>()->getPointeeType();
3674
3675   // make sure we operate on the canonical type
3676   lhptee = Context.getCanonicalType(lhptee);
3677   rhptee = Context.getCanonicalType(rhptee);
3678
3679   AssignConvertType ConvTy = Compatible;
3680
3681   // C99 6.5.16.1p1: This following citation is common to constraints
3682   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
3683   // qualifiers of the type *pointed to* by the right;
3684   // FIXME: Handle ExtQualType
3685   if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
3686     ConvTy = CompatiblePointerDiscardsQualifiers;
3687
3688   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
3689   // incomplete type and the other is a pointer to a qualified or unqualified
3690   // version of void...
3691   if (lhptee->isVoidType()) {
3692     if (rhptee->isIncompleteOrObjectType())
3693       return ConvTy;
3694
3695     // As an extension, we allow cast to/from void* to function pointer.
3696     assert(rhptee->isFunctionType());
3697     return FunctionVoidPointer;
3698   }
3699
3700   if (rhptee->isVoidType()) {
3701     if (lhptee->isIncompleteOrObjectType())
3702       return ConvTy;
3703
3704     // As an extension, we allow cast to/from void* to function pointer.
3705     assert(lhptee->isFunctionType());
3706     return FunctionVoidPointer;
3707   }
3708   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
3709   // unqualified versions of compatible types, ...
3710   lhptee = lhptee.getUnqualifiedType();
3711   rhptee = rhptee.getUnqualifiedType();
3712   if (!Context.typesAreCompatible(lhptee, rhptee)) {
3713     // Check if the pointee types are compatible ignoring the sign.
3714     // We explicitly check for char so that we catch "char" vs
3715     // "unsigned char" on systems where "char" is unsigned.
3716     if (lhptee->isCharType())
3717       lhptee = Context.UnsignedCharTy;
3718     else if (lhptee->isSignedIntegerType())
3719       lhptee = Context.getCorrespondingUnsignedType(lhptee);
3720     
3721     if (rhptee->isCharType())
3722       rhptee = Context.UnsignedCharTy;
3723     else if (rhptee->isSignedIntegerType())
3724       rhptee = Context.getCorrespondingUnsignedType(rhptee);
3725
3726     if (lhptee == rhptee) {
3727       // Types are compatible ignoring the sign. Qualifier incompatibility
3728       // takes priority over sign incompatibility because the sign
3729       // warning can be disabled.
3730       if (ConvTy != Compatible)
3731         return ConvTy;
3732       return IncompatiblePointerSign;
3733     }
3734     // General pointer incompatibility takes priority over qualifiers.
3735     return IncompatiblePointer;
3736   }
3737   return ConvTy;
3738 }
3739
3740 /// CheckBlockPointerTypesForAssignment - This routine determines whether two
3741 /// block pointer types are compatible or whether a block and normal pointer
3742 /// are compatible. It is more restrict than comparing two function pointer
3743 // types.
3744 Sema::AssignConvertType
3745 Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
3746                                           QualType rhsType) {
3747   QualType lhptee, rhptee;
3748
3749   // get the "pointed to" type (ignoring qualifiers at the top level)
3750   lhptee = lhsType->getAs<BlockPointerType>()->getPointeeType();
3751   rhptee = rhsType->getAs<BlockPointerType>()->getPointeeType();
3752
3753   // make sure we operate on the canonical type
3754   lhptee = Context.getCanonicalType(lhptee);
3755   rhptee = Context.getCanonicalType(rhptee);
3756
3757   AssignConvertType ConvTy = Compatible;
3758
3759   // For blocks we enforce that qualifiers are identical.
3760   if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
3761     ConvTy = CompatiblePointerDiscardsQualifiers;
3762
3763   if (!Context.typesAreCompatible(lhptee, rhptee))
3764     return IncompatibleBlockPointer;
3765   return ConvTy;
3766 }
3767
3768 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
3769 /// has code to accommodate several GCC extensions when type checking
3770 /// pointers. Here are some objectionable examples that GCC considers warnings:
3771 ///
3772 ///  int a, *pint;
3773 ///  short *pshort;
3774 ///  struct foo *pfoo;
3775 ///
3776 ///  pint = pshort; // warning: assignment from incompatible pointer type
3777 ///  a = pint; // warning: assignment makes integer from pointer without a cast
3778 ///  pint = a; // warning: assignment makes pointer from integer without a cast
3779 ///  pint = pfoo; // warning: assignment from incompatible pointer type
3780 ///
3781 /// As a result, the code for dealing with pointers is more complex than the
3782 /// C99 spec dictates.
3783 ///
3784 Sema::AssignConvertType
3785 Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
3786   // Get canonical types.  We're not formatting these types, just comparing
3787   // them.
3788   lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
3789   rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
3790
3791   if (lhsType == rhsType)
3792     return Compatible; // Common case: fast path an exact match.
3793
3794   if ((lhsType->isObjCClassType() &&
3795        (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
3796      (rhsType->isObjCClassType() &&
3797        (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
3798       return Compatible;
3799   }
3800
3801   // If the left-hand side is a reference type, then we are in a
3802   // (rare!) case where we've allowed the use of references in C,
3803   // e.g., as a parameter type in a built-in function. In this case,
3804   // just make sure that the type referenced is compatible with the
3805   // right-hand side type. The caller is responsible for adjusting
3806   // lhsType so that the resulting expression does not have reference
3807   // type.
3808   if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
3809     if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
3810       return Compatible;
3811     return Incompatible;
3812   }
3813   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
3814   // to the same ExtVector type.
3815   if (lhsType->isExtVectorType()) {
3816     if (rhsType->isExtVectorType())
3817       return lhsType == rhsType ? Compatible : Incompatible;
3818     if (!rhsType->isVectorType() && rhsType->isArithmeticType())
3819       return Compatible;
3820   }
3821
3822   if (lhsType->isVectorType() || rhsType->isVectorType()) {
3823     // If we are allowing lax vector conversions, and LHS and RHS are both
3824     // vectors, the total size only needs to be the same. This is a bitcast;
3825     // no bits are changed but the result type is different.
3826     if (getLangOptions().LaxVectorConversions &&
3827         lhsType->isVectorType() && rhsType->isVectorType()) {
3828       if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
3829         return IncompatibleVectors;
3830     }
3831     return Incompatible;
3832   }
3833
3834   if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
3835     return Compatible;
3836
3837   if (isa<PointerType>(lhsType)) {
3838     if (rhsType->isIntegerType())
3839       return IntToPointer;
3840
3841     if (isa<PointerType>(rhsType))
3842       return CheckPointerTypesForAssignment(lhsType, rhsType);
3843
3844     // In general, C pointers are not compatible with ObjC object pointers.
3845     if (isa<ObjCObjectPointerType>(rhsType)) {
3846       if (lhsType->isVoidPointerType()) // an exception to the rule.
3847         return Compatible;
3848       return IncompatiblePointer;
3849     }
3850     if (rhsType->getAs<BlockPointerType>()) {
3851       if (lhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
3852         return Compatible;
3853
3854       // Treat block pointers as objects.
3855       if (getLangOptions().ObjC1 && lhsType->isObjCIdType())
3856         return Compatible;
3857     }
3858     return Incompatible;
3859   }
3860
3861   if (isa<BlockPointerType>(lhsType)) {
3862     if (rhsType->isIntegerType())
3863       return IntToBlockPointer;
3864
3865     // Treat block pointers as objects.
3866     if (getLangOptions().ObjC1 && rhsType->isObjCIdType())
3867       return Compatible;
3868
3869     if (rhsType->isBlockPointerType())
3870       return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
3871
3872     if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
3873       if (RHSPT->getPointeeType()->isVoidType())
3874         return Compatible;
3875     }
3876     return Incompatible;
3877   }
3878
3879   if (isa<ObjCObjectPointerType>(lhsType)) {
3880     if (rhsType->isIntegerType())
3881       return IntToPointer;
3882
3883     // In general, C pointers are not compatible with ObjC object pointers.
3884     if (isa<PointerType>(rhsType)) {
3885       if (rhsType->isVoidPointerType()) // an exception to the rule.
3886         return Compatible;
3887       return IncompatiblePointer;
3888     }
3889     if (rhsType->isObjCObjectPointerType()) {
3890       if (lhsType->isObjCBuiltinType() || rhsType->isObjCBuiltinType())
3891         return Compatible;
3892       if (Context.typesAreCompatible(lhsType, rhsType))
3893         return Compatible;
3894       if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
3895         return IncompatibleObjCQualifiedId;
3896       return IncompatiblePointer;
3897     }
3898     if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
3899       if (RHSPT->getPointeeType()->isVoidType())
3900         return Compatible;
3901     }
3902     // Treat block pointers as objects.
3903     if (rhsType->isBlockPointerType())
3904       return Compatible;
3905     return Incompatible;
3906   }
3907   if (isa<PointerType>(rhsType)) {
3908     // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
3909     if (lhsType == Context.BoolTy)
3910       return Compatible;
3911
3912     if (lhsType->isIntegerType())
3913       return PointerToInt;
3914
3915     if (isa<PointerType>(lhsType))
3916       return CheckPointerTypesForAssignment(lhsType, rhsType);
3917
3918     if (isa<BlockPointerType>(lhsType) &&
3919         rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
3920       return Compatible;
3921     return Incompatible;
3922   }
3923   if (isa<ObjCObjectPointerType>(rhsType)) {
3924     // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
3925     if (lhsType == Context.BoolTy)
3926       return Compatible;
3927
3928     if (lhsType->isIntegerType())
3929       return PointerToInt;
3930
3931     // In general, C pointers are not compatible with ObjC object pointers.
3932     if (isa<PointerType>(lhsType)) {
3933       if (lhsType->isVoidPointerType()) // an exception to the rule.
3934         return Compatible;
3935       return IncompatiblePointer;
3936     }
3937     if (isa<BlockPointerType>(lhsType) &&
3938         rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
3939       return Compatible;
3940     return Incompatible;
3941   }
3942
3943   if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
3944     if (Context.typesAreCompatible(lhsType, rhsType))
3945       return Compatible;
3946   }
3947   return Incompatible;
3948 }
3949
3950 /// \brief Constructs a transparent union from an expression that is
3951 /// used to initialize the transparent union.
3952 static void ConstructTransparentUnion(ASTContext &C, Expr *&E,
3953                                       QualType UnionType, FieldDecl *Field) {
3954   // Build an initializer list that designates the appropriate member
3955   // of the transparent union.
3956   InitListExpr *Initializer = new (C) InitListExpr(SourceLocation(),
3957                                                    &E, 1,
3958                                                    SourceLocation());
3959   Initializer->setType(UnionType);
3960   Initializer->setInitializedFieldInUnion(Field);
3961
3962   // Build a compound literal constructing a value of the transparent
3963   // union type from this initializer list.
3964   E = new (C) CompoundLiteralExpr(SourceLocation(), UnionType, Initializer,
3965                                   false);
3966 }
3967
3968 Sema::AssignConvertType
3969 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, Expr *&rExpr) {
3970   QualType FromType = rExpr->getType();
3971
3972   // If the ArgType is a Union type, we want to handle a potential
3973   // transparent_union GCC extension.
3974   const RecordType *UT = ArgType->getAsUnionType();
3975   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
3976     return Incompatible;
3977
3978   // The field to initialize within the transparent union.
3979   RecordDecl *UD = UT->getDecl();
3980   FieldDecl *InitField = 0;
3981   // It's compatible if the expression matches any of the fields.
3982   for (RecordDecl::field_iterator it = UD->field_begin(),
3983          itend = UD->field_end();
3984        it != itend; ++it) {
3985     if (it->getType()->isPointerType()) {
3986       // If the transparent union contains a pointer type, we allow:
3987       // 1) void pointer
3988       // 2) null pointer constant
3989       if (FromType->isPointerType())
3990         if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
3991           ImpCastExprToType(rExpr, it->getType(), CastExpr::CK_BitCast);
3992           InitField = *it;
3993           break;
3994         }
3995
3996       if (rExpr->isNullPointerConstant(Context, 
3997                                        Expr::NPC_ValueDependentIsNull)) {
3998         ImpCastExprToType(rExpr, it->getType(), CastExpr::CK_IntegralToPointer);
3999         InitField = *it;
4000         break;
4001       }
4002     }
4003
4004     if (CheckAssignmentConstraints(it->getType(), rExpr->getType())
4005           == Compatible) {
4006       InitField = *it;
4007       break;
4008     }
4009   }
4010
4011   if (!InitField)
4012     return Incompatible;
4013
4014   ConstructTransparentUnion(Context, rExpr, ArgType, InitField);
4015   return Compatible;
4016 }
4017
4018 Sema::AssignConvertType
4019 Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
4020   if (getLangOptions().CPlusPlus) {
4021     if (!lhsType->isRecordType()) {
4022       // C++ 5.17p3: If the left operand is not of class type, the
4023       // expression is implicitly converted (C++ 4) to the
4024       // cv-unqualified type of the left operand.
4025       if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
4026                                     "assigning"))
4027         return Incompatible;
4028       return Compatible;
4029     }
4030
4031     // FIXME: Currently, we fall through and treat C++ classes like C
4032     // structures.
4033   }
4034
4035   // C99 6.5.16.1p1: the left operand is a pointer and the right is
4036   // a null pointer constant.
4037   if ((lhsType->isPointerType() ||
4038        lhsType->isObjCObjectPointerType() ||
4039        lhsType->isBlockPointerType())
4040       && rExpr->isNullPointerConstant(Context, 
4041                                       Expr::NPC_ValueDependentIsNull)) {
4042     ImpCastExprToType(rExpr, lhsType, CastExpr::CK_Unknown);
4043     return Compatible;
4044   }
4045
4046   // This check seems unnatural, however it is necessary to ensure the proper
4047   // conversion of functions/arrays. If the conversion were done for all
4048   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
4049   // expressions that surpress this implicit conversion (&, sizeof).
4050   //
4051   // Suppress this for references: C++ 8.5.3p5.
4052   if (!lhsType->isReferenceType())
4053     DefaultFunctionArrayConversion(rExpr);
4054
4055   Sema::AssignConvertType result =
4056     CheckAssignmentConstraints(lhsType, rExpr->getType());
4057
4058   // C99 6.5.16.1p2: The value of the right operand is converted to the
4059   // type of the assignment expression.
4060   // CheckAssignmentConstraints allows the left-hand side to be a reference,
4061   // so that we can use references in built-in functions even in C.
4062   // The getNonReferenceType() call makes sure that the resulting expression
4063   // does not have reference type.
4064   if (result != Incompatible && rExpr->getType() != lhsType)
4065     ImpCastExprToType(rExpr, lhsType.getNonReferenceType(),
4066                       CastExpr::CK_Unknown);
4067   return result;
4068 }
4069
4070 QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
4071   Diag(Loc, diag::err_typecheck_invalid_operands)
4072     << lex->getType() << rex->getType()
4073     << lex->getSourceRange() << rex->getSourceRange();
4074   return QualType();
4075 }
4076
4077 inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
4078                                                               Expr *&rex) {
4079   // For conversion purposes, we ignore any qualifiers.
4080   // For example, "const float" and "float" are equivalent.
4081   QualType lhsType =
4082     Context.getCanonicalType(lex->getType()).getUnqualifiedType();
4083   QualType rhsType =
4084     Context.getCanonicalType(rex->getType()).getUnqualifiedType();
4085
4086   // If the vector types are identical, return.
4087   if (lhsType == rhsType)
4088     return lhsType;
4089
4090   // Handle the case of a vector & extvector type of the same size and element
4091   // type.  It would be nice if we only had one vector type someday.
4092   if (getLangOptions().LaxVectorConversions) {
4093     // FIXME: Should we warn here?
4094     if (const VectorType *LV = lhsType->getAs<VectorType>()) {
4095       if (const VectorType *RV = rhsType->getAs<VectorType>())
4096         if (LV->getElementType() == RV->getElementType() &&
4097             LV->getNumElements() == RV->getNumElements()) {
4098           return lhsType->isExtVectorType() ? lhsType : rhsType;
4099         }
4100     }
4101   }
4102
4103   // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
4104   // swap back (so that we don't reverse the inputs to a subtract, for instance.
4105   bool swapped = false;
4106   if (rhsType->isExtVectorType()) {
4107     swapped = true;
4108     std::swap(rex, lex);
4109     std::swap(rhsType, lhsType);
4110   }
4111
4112   // Handle the case of an ext vector and scalar.
4113   if (const ExtVectorType *LV = lhsType->getAs<ExtVectorType>()) {
4114     QualType EltTy = LV->getElementType();
4115     if (EltTy->isIntegralType() && rhsType->isIntegralType()) {
4116       if (Context.getIntegerTypeOrder(EltTy, rhsType) >= 0) {
4117         ImpCastExprToType(rex, lhsType, CastExpr::CK_IntegralCast);
4118         if (swapped) std::swap(rex, lex);
4119         return lhsType;
4120       }
4121     }
4122     if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
4123         rhsType->isRealFloatingType()) {
4124       if (Context.getFloatingTypeOrder(EltTy, rhsType) >= 0) {
4125         ImpCastExprToType(rex, lhsType, CastExpr::CK_FloatingCast);
4126         if (swapped) std::swap(rex, lex);
4127         return lhsType;
4128       }
4129     }
4130   }
4131
4132   // Vectors of different size or scalar and non-ext-vector are errors.
4133   Diag(Loc, diag::err_typecheck_vector_not_convertable)
4134     << lex->getType() << rex->getType()
4135     << lex->getSourceRange() << rex->getSourceRange();
4136   return QualType();
4137 }
4138
4139 inline QualType Sema::CheckMultiplyDivideOperands(
4140   Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
4141   if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
4142     return CheckVectorOperands(Loc, lex, rex);
4143
4144   QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
4145
4146   if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
4147     return compType;
4148   return InvalidOperands(Loc, lex, rex);
4149 }
4150
4151 inline QualType Sema::CheckRemainderOperands(
4152   Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
4153   if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4154     if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
4155       return CheckVectorOperands(Loc, lex, rex);
4156     return InvalidOperands(Loc, lex, rex);
4157   }
4158
4159   QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
4160
4161   if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
4162     return compType;
4163   return InvalidOperands(Loc, lex, rex);
4164 }
4165
4166 inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
4167   Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy) {
4168   if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4169     QualType compType = CheckVectorOperands(Loc, lex, rex);
4170     if (CompLHSTy) *CompLHSTy = compType;
4171     return compType;
4172   }
4173
4174   QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
4175
4176   // handle the common case first (both operands are arithmetic).
4177   if (lex->getType()->isArithmeticType() &&
4178       rex->getType()->isArithmeticType()) {
4179     if (CompLHSTy) *CompLHSTy = compType;
4180     return compType;
4181   }
4182
4183   // Put any potential pointer into PExp
4184   Expr* PExp = lex, *IExp = rex;
4185   if (IExp->getType()->isAnyPointerType())
4186     std::swap(PExp, IExp);
4187
4188   if (PExp->getType()->isAnyPointerType()) {
4189
4190     if (IExp->getType()->isIntegerType()) {
4191       QualType PointeeTy = PExp->getType()->getPointeeType();
4192
4193       // Check for arithmetic on pointers to incomplete types.
4194       if (PointeeTy->isVoidType()) {
4195         if (getLangOptions().CPlusPlus) {
4196           Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
4197             << lex->getSourceRange() << rex->getSourceRange();
4198           return QualType();
4199         }
4200
4201         // GNU extension: arithmetic on pointer to void
4202         Diag(Loc, diag::ext_gnu_void_ptr)
4203           << lex->getSourceRange() << rex->getSourceRange();
4204       } else if (PointeeTy->isFunctionType()) {
4205         if (getLangOptions().CPlusPlus) {
4206           Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
4207             << lex->getType() << lex->getSourceRange();
4208           return QualType();
4209         }
4210
4211         // GNU extension: arithmetic on pointer to function
4212         Diag(Loc, diag::ext_gnu_ptr_func_arith)
4213           << lex->getType() << lex->getSourceRange();
4214       } else {
4215         // Check if we require a complete type.
4216         if (((PExp->getType()->isPointerType() &&
4217               !PExp->getType()->isDependentType()) ||
4218               PExp->getType()->isObjCObjectPointerType()) &&
4219              RequireCompleteType(Loc, PointeeTy,
4220                            PDiag(diag::err_typecheck_arithmetic_incomplete_type)
4221                              << PExp->getSourceRange()
4222                              << PExp->getType()))
4223           return QualType();
4224       }
4225       // Diagnose bad cases where we step over interface counts.
4226       if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4227         Diag(Loc, diag::err_arithmetic_nonfragile_interface)
4228           << PointeeTy << PExp->getSourceRange();
4229         return QualType();
4230       }
4231
4232       if (CompLHSTy) {
4233         QualType LHSTy = Context.isPromotableBitField(lex);
4234         if (LHSTy.isNull()) {
4235           LHSTy = lex->getType();
4236           if (LHSTy->isPromotableIntegerType())
4237             LHSTy = Context.getPromotedIntegerType(LHSTy);
4238         }
4239         *CompLHSTy = LHSTy;
4240       }
4241       return PExp->getType();
4242     }
4243   }
4244
4245   return InvalidOperands(Loc, lex, rex);
4246 }
4247
4248 // C99 6.5.6
4249 QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
4250                                         SourceLocation Loc, QualType* CompLHSTy) {
4251   if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4252     QualType compType = CheckVectorOperands(Loc, lex, rex);
4253     if (CompLHSTy) *CompLHSTy = compType;
4254     return compType;
4255   }
4256
4257   QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
4258
4259   // Enforce type constraints: C99 6.5.6p3.
4260
4261   // Handle the common case first (both operands are arithmetic).
4262   if (lex->getType()->isArithmeticType()
4263       && rex->getType()->isArithmeticType()) {
4264     if (CompLHSTy) *CompLHSTy = compType;
4265     return compType;
4266   }
4267
4268   // Either ptr - int   or   ptr - ptr.
4269   if (lex->getType()->isAnyPointerType()) {
4270     QualType lpointee = lex->getType()->getPointeeType();
4271
4272     // The LHS must be an completely-defined object type.
4273
4274     bool ComplainAboutVoid = false;
4275     Expr *ComplainAboutFunc = 0;
4276     if (lpointee->isVoidType()) {
4277       if (getLangOptions().CPlusPlus) {
4278         Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
4279           << lex->getSourceRange() << rex->getSourceRange();
4280         return QualType();
4281       }
4282
4283       // GNU C extension: arithmetic on pointer to void
4284       ComplainAboutVoid = true;
4285     } else if (lpointee->isFunctionType()) {
4286       if (getLangOptions().CPlusPlus) {
4287         Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
4288           << lex->getType() << lex->getSourceRange();
4289         return QualType();
4290       }
4291
4292       // GNU C extension: arithmetic on pointer to function
4293       ComplainAboutFunc = lex;
4294     } else if (!lpointee->isDependentType() &&
4295                RequireCompleteType(Loc, lpointee,
4296                                    PDiag(diag::err_typecheck_sub_ptr_object)
4297                                      << lex->getSourceRange()
4298                                      << lex->getType()))
4299       return QualType();
4300
4301     // Diagnose bad cases where we step over interface counts.
4302     if (lpointee->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4303       Diag(Loc, diag::err_arithmetic_nonfragile_interface)
4304         << lpointee << lex->getSourceRange();
4305       return QualType();
4306     }
4307
4308     // The result type of a pointer-int computation is the pointer type.
4309     if (rex->getType()->isIntegerType()) {
4310       if (ComplainAboutVoid)
4311         Diag(Loc, diag::ext_gnu_void_ptr)
4312           << lex->getSourceRange() << rex->getSourceRange();
4313       if (ComplainAboutFunc)
4314         Diag(Loc, diag::ext_gnu_ptr_func_arith)
4315           << ComplainAboutFunc->getType()
4316           << ComplainAboutFunc->getSourceRange();
4317
4318       if (CompLHSTy) *CompLHSTy = lex->getType();
4319       return lex->getType();
4320     }
4321
4322     // Handle pointer-pointer subtractions.
4323     if (const PointerType *RHSPTy = rex->getType()->getAs<PointerType>()) {
4324       QualType rpointee = RHSPTy->getPointeeType();
4325
4326       // RHS must be a completely-type object type.
4327       // Handle the GNU void* extension.
4328       if (rpointee->isVoidType()) {
4329         if (getLangOptions().CPlusPlus) {
4330           Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
4331             << lex->getSourceRange() << rex->getSourceRange();
4332           return QualType();
4333         }
4334
4335         ComplainAboutVoid = true;
4336       } else if (rpointee->isFunctionType()) {
4337         if (getLangOptions().CPlusPlus) {
4338           Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
4339             << rex->getType() << rex->getSourceRange();
4340           return QualType();
4341         }
4342
4343         // GNU extension: arithmetic on pointer to function
4344         if (!ComplainAboutFunc)
4345           ComplainAboutFunc = rex;
4346       } else if (!rpointee->isDependentType() &&
4347                  RequireCompleteType(Loc, rpointee,
4348                                      PDiag(diag::err_typecheck_sub_ptr_object)
4349                                        << rex->getSourceRange()
4350                                        << rex->getType()))
4351         return QualType();
4352
4353       if (getLangOptions().CPlusPlus) {
4354         // Pointee types must be the same: C++ [expr.add]
4355         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
4356           Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
4357             << lex->getType() << rex->getType()
4358             << lex->getSourceRange() << rex->getSourceRange();
4359           return QualType();
4360         }
4361       } else {
4362         // Pointee types must be compatible C99 6.5.6p3
4363         if (!Context.typesAreCompatible(
4364                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
4365                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
4366           Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
4367             << lex->getType() << rex->getType()
4368             << lex->getSourceRange() << rex->getSourceRange();
4369           return QualType();
4370         }
4371       }
4372
4373       if (ComplainAboutVoid)
4374         Diag(Loc, diag::ext_gnu_void_ptr)
4375           << lex->getSourceRange() << rex->getSourceRange();
4376       if (ComplainAboutFunc)
4377         Diag(Loc, diag::ext_gnu_ptr_func_arith)
4378           << ComplainAboutFunc->getType()
4379           << ComplainAboutFunc->getSourceRange();
4380
4381       if (CompLHSTy) *CompLHSTy = lex->getType();
4382       return Context.getPointerDiffType();
4383     }
4384   }
4385
4386   return InvalidOperands(Loc, lex, rex);
4387 }
4388
4389 // C99 6.5.7
4390 QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
4391                                   bool isCompAssign) {
4392   // C99 6.5.7p2: Each of the operands shall have integer type.
4393   if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
4394     return InvalidOperands(Loc, lex, rex);
4395
4396   // Vector shifts promote their scalar inputs to vector type.
4397   if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
4398     return CheckVectorOperands(Loc, lex, rex);
4399
4400   // Shifts don't perform usual arithmetic conversions, they just do integer
4401   // promotions on each operand. C99 6.5.7p3
4402   QualType LHSTy = Context.isPromotableBitField(lex);
4403   if (LHSTy.isNull()) {
4404     LHSTy = lex->getType();
4405     if (LHSTy->isPromotableIntegerType())
4406       LHSTy = Context.getPromotedIntegerType(LHSTy);
4407   }
4408   if (!isCompAssign)
4409     ImpCastExprToType(lex, LHSTy, CastExpr::CK_IntegralCast);
4410
4411   UsualUnaryConversions(rex);
4412
4413   // Sanity-check shift operands
4414   llvm::APSInt Right;
4415   // Check right/shifter operand
4416   if (!rex->isValueDependent() &&
4417       rex->isIntegerConstantExpr(Right, Context)) {
4418     if (Right.isNegative())
4419       Diag(Loc, diag::warn_shift_negative) << rex->getSourceRange();
4420     else {
4421       llvm::APInt LeftBits(Right.getBitWidth(),
4422                           Context.getTypeSize(lex->getType()));
4423       if (Right.uge(LeftBits))
4424         Diag(Loc, diag::warn_shift_gt_typewidth) << rex->getSourceRange();
4425     }
4426   }
4427
4428   // "The type of the result is that of the promoted left operand."
4429   return LHSTy;
4430 }
4431
4432 /// Implements -Wsign-compare.
4433 void Sema::CheckSignCompare(Expr *lex, Expr *rex, SourceLocation OpLoc,
4434                             const PartialDiagnostic &PD) {
4435   QualType lt = lex->getType(), rt = rex->getType();
4436
4437   // Only warn if both operands are integral.
4438   if (!lt->isIntegerType() || !rt->isIntegerType())
4439     return;
4440
4441   // The rule is that the signed operand becomes unsigned, so isolate the
4442   // signed operand.
4443   Expr *signedOperand;
4444   if (lt->isSignedIntegerType()) {
4445     if (rt->isSignedIntegerType()) return;
4446     signedOperand = lex;
4447   } else {
4448     if (!rt->isSignedIntegerType()) return;
4449     signedOperand = rex;
4450   }
4451
4452   // If the value is a non-negative integer constant, then the
4453   // signed->unsigned conversion won't change it.
4454   llvm::APSInt value;
4455   if (signedOperand->isIntegerConstantExpr(value, Context)) {
4456     assert(value.isSigned() && "result of signed expression not signed");
4457
4458     if (value.isNonNegative())
4459       return;
4460   }
4461
4462   Diag(OpLoc, PD)
4463     << lex->getType() << rex->getType()
4464     << lex->getSourceRange() << rex->getSourceRange();
4465 }
4466
4467 // C99 6.5.8, C++ [expr.rel]
4468 QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
4469                                     unsigned OpaqueOpc, bool isRelational) {
4470   BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)OpaqueOpc;
4471
4472   if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
4473     return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
4474
4475   CheckSignCompare(lex, rex, Loc, diag::warn_mixed_sign_comparison);
4476
4477   // C99 6.5.8p3 / C99 6.5.9p4
4478   if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
4479     UsualArithmeticConversions(lex, rex);
4480   else {
4481     UsualUnaryConversions(lex);
4482     UsualUnaryConversions(rex);
4483   }
4484   QualType lType = lex->getType();
4485   QualType rType = rex->getType();
4486
4487   if (!lType->isFloatingType()
4488       && !(lType->isBlockPointerType() && isRelational)) {
4489     // For non-floating point types, check for self-comparisons of the form
4490     // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
4491     // often indicate logic errors in the program.
4492     // NOTE: Don't warn about comparisons of enum constants. These can arise
4493     //  from macro expansions, and are usually quite deliberate.
4494     Expr *LHSStripped = lex->IgnoreParens();
4495     Expr *RHSStripped = rex->IgnoreParens();
4496     if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped))
4497       if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped))
4498         if (DRL->getDecl() == DRR->getDecl() &&
4499             !isa<EnumConstantDecl>(DRL->getDecl()))
4500           Diag(Loc, diag::warn_selfcomparison);
4501
4502     if (isa<CastExpr>(LHSStripped))
4503       LHSStripped = LHSStripped->IgnoreParenCasts();
4504     if (isa<CastExpr>(RHSStripped))
4505       RHSStripped = RHSStripped->IgnoreParenCasts();
4506
4507     // Warn about comparisons against a string constant (unless the other
4508     // operand is null), the user probably wants strcmp.
4509     Expr *literalString = 0;
4510     Expr *literalStringStripped = 0;
4511     if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
4512         !RHSStripped->isNullPointerConstant(Context, 
4513                                             Expr::NPC_ValueDependentIsNull)) {
4514       literalString = lex;
4515       literalStringStripped = LHSStripped;
4516     } else if ((isa<StringLiteral>(RHSStripped) ||
4517                 isa<ObjCEncodeExpr>(RHSStripped)) &&
4518                !LHSStripped->isNullPointerConstant(Context, 
4519                                             Expr::NPC_ValueDependentIsNull)) {
4520       literalString = rex;
4521       literalStringStripped = RHSStripped;
4522     }
4523
4524     if (literalString) {
4525       std::string resultComparison;
4526       switch (Opc) {
4527       case BinaryOperator::LT: resultComparison = ") < 0"; break;
4528       case BinaryOperator::GT: resultComparison = ") > 0"; break;
4529       case BinaryOperator::LE: resultComparison = ") <= 0"; break;
4530       case BinaryOperator::GE: resultComparison = ") >= 0"; break;
4531       case BinaryOperator::EQ: resultComparison = ") == 0"; break;
4532       case BinaryOperator::NE: resultComparison = ") != 0"; break;
4533       default: assert(false && "Invalid comparison operator");
4534       }
4535       Diag(Loc, diag::warn_stringcompare)
4536         << isa<ObjCEncodeExpr>(literalStringStripped)
4537         << literalString->getSourceRange()
4538         << CodeModificationHint::CreateReplacement(SourceRange(Loc), ", ")
4539         << CodeModificationHint::CreateInsertion(lex->getLocStart(),
4540                                                  "strcmp(")
4541         << CodeModificationHint::CreateInsertion(
4542                                        PP.getLocForEndOfToken(rex->getLocEnd()),
4543                                        resultComparison);
4544     }
4545   }
4546
4547   // The result of comparisons is 'bool' in C++, 'int' in C.
4548   QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy :Context.IntTy;
4549
4550   if (isRelational) {
4551     if (lType->isRealType() && rType->isRealType())
4552       return ResultTy;
4553   } else {
4554     // Check for comparisons of floating point operands using != and ==.
4555     if (lType->isFloatingType()) {
4556       assert(rType->isFloatingType());
4557       CheckFloatComparison(Loc,lex,rex);
4558     }
4559
4560     if (lType->isArithmeticType() && rType->isArithmeticType())
4561       return ResultTy;
4562   }
4563
4564   bool LHSIsNull = lex->isNullPointerConstant(Context, 
4565                                               Expr::NPC_ValueDependentIsNull);
4566   bool RHSIsNull = rex->isNullPointerConstant(Context, 
4567                                               Expr::NPC_ValueDependentIsNull);
4568
4569   // All of the following pointer related warnings are GCC extensions, except
4570   // when handling null pointer constants. One day, we can consider making them
4571   // errors (when -pedantic-errors is enabled).
4572   if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
4573     QualType LCanPointeeTy =
4574       Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
4575     QualType RCanPointeeTy =
4576       Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
4577
4578     if (getLangOptions().CPlusPlus) {
4579       if (LCanPointeeTy == RCanPointeeTy)
4580         return ResultTy;
4581
4582       // C++ [expr.rel]p2:
4583       //   [...] Pointer conversions (4.10) and qualification
4584       //   conversions (4.4) are performed on pointer operands (or on
4585       //   a pointer operand and a null pointer constant) to bring
4586       //   them to their composite pointer type. [...]
4587       //
4588       // C++ [expr.eq]p1 uses the same notion for (in)equality
4589       // comparisons of pointers.
4590       QualType T = FindCompositePointerType(lex, rex);
4591       if (T.isNull()) {
4592         Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
4593           << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4594         return QualType();
4595       }
4596
4597       ImpCastExprToType(lex, T, CastExpr::CK_BitCast);
4598       ImpCastExprToType(rex, T, CastExpr::CK_BitCast);
4599       return ResultTy;
4600     }
4601     // C99 6.5.9p2 and C99 6.5.8p2
4602     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
4603                                    RCanPointeeTy.getUnqualifiedType())) {
4604       // Valid unless a relational comparison of function pointers
4605       if (isRelational && LCanPointeeTy->isFunctionType()) {
4606         Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
4607           << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4608       }
4609     } else if (!isRelational &&
4610                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
4611       // Valid unless comparison between non-null pointer and function pointer
4612       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
4613           && !LHSIsNull && !RHSIsNull) {
4614         Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
4615           << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4616       }
4617     } else {
4618       // Invalid
4619       Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
4620         << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4621     }
4622     if (LCanPointeeTy != RCanPointeeTy)
4623       ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
4624     return ResultTy;
4625   }
4626
4627   if (getLangOptions().CPlusPlus) {
4628     // Comparison of pointers with null pointer constants and equality
4629     // comparisons of member pointers to null pointer constants.
4630     if (RHSIsNull &&
4631         (lType->isPointerType() ||
4632          (!isRelational && lType->isMemberPointerType()))) {
4633       ImpCastExprToType(rex, lType, CastExpr::CK_NullToMemberPointer);
4634       return ResultTy;
4635     }
4636     if (LHSIsNull &&
4637         (rType->isPointerType() ||
4638          (!isRelational && rType->isMemberPointerType()))) {
4639       ImpCastExprToType(lex, rType, CastExpr::CK_NullToMemberPointer);
4640       return ResultTy;
4641     }
4642
4643     // Comparison of member pointers.
4644     if (!isRelational &&
4645         lType->isMemberPointerType() && rType->isMemberPointerType()) {
4646       // C++ [expr.eq]p2:
4647       //   In addition, pointers to members can be compared, or a pointer to
4648       //   member and a null pointer constant. Pointer to member conversions
4649       //   (4.11) and qualification conversions (4.4) are performed to bring
4650       //   them to a common type. If one operand is a null pointer constant,
4651       //   the common type is the type of the other operand. Otherwise, the
4652       //   common type is a pointer to member type similar (4.4) to the type
4653       //   of one of the operands, with a cv-qualification signature (4.4)
4654       //   that is the union of the cv-qualification signatures of the operand
4655       //   types.
4656       QualType T = FindCompositePointerType(lex, rex);
4657       if (T.isNull()) {
4658         Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
4659         << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4660         return QualType();
4661       }
4662
4663       ImpCastExprToType(lex, T, CastExpr::CK_BitCast);
4664       ImpCastExprToType(rex, T, CastExpr::CK_BitCast);
4665       return ResultTy;
4666     }
4667
4668     // Comparison of nullptr_t with itself.
4669     if (lType->isNullPtrType() && rType->isNullPtrType())
4670       return ResultTy;
4671   }
4672
4673   // Handle block pointer types.
4674   if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
4675     QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
4676     QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
4677
4678     if (!LHSIsNull && !RHSIsNull &&
4679         !Context.typesAreCompatible(lpointee, rpointee)) {
4680       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
4681         << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4682     }
4683     ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
4684     return ResultTy;
4685   }
4686   // Allow block pointers to be compared with null pointer constants.
4687   if (!isRelational
4688       && ((lType->isBlockPointerType() && rType->isPointerType())
4689           || (lType->isPointerType() && rType->isBlockPointerType()))) {
4690     if (!LHSIsNull && !RHSIsNull) {
4691       if (!((rType->isPointerType() && rType->getAs<PointerType>()
4692              ->getPointeeType()->isVoidType())
4693             || (lType->isPointerType() && lType->getAs<PointerType>()
4694                 ->getPointeeType()->isVoidType())))
4695         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
4696           << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4697     }
4698     ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
4699     return ResultTy;
4700   }
4701
4702   if ((lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType())) {
4703     if (lType->isPointerType() || rType->isPointerType()) {
4704       const PointerType *LPT = lType->getAs<PointerType>();
4705       const PointerType *RPT = rType->getAs<PointerType>();
4706       bool LPtrToVoid = LPT ?
4707         Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
4708       bool RPtrToVoid = RPT ?
4709         Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
4710
4711       if (!LPtrToVoid && !RPtrToVoid &&
4712           !Context.typesAreCompatible(lType, rType)) {
4713         Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
4714           << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4715       }
4716       ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
4717       return ResultTy;
4718     }
4719     if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
4720       if (!Context.areComparableObjCPointerTypes(lType, rType))
4721         Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
4722           << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4723       ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
4724       return ResultTy;
4725     }
4726   }
4727   if (lType->isAnyPointerType() && rType->isIntegerType()) {
4728     unsigned DiagID = 0;
4729     if (RHSIsNull) {
4730       if (isRelational)
4731         DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
4732     } else if (isRelational)
4733       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
4734     else
4735       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
4736
4737     if (DiagID) {
4738       Diag(Loc, DiagID)
4739         << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4740     }
4741     ImpCastExprToType(rex, lType, CastExpr::CK_IntegralToPointer);
4742     return ResultTy;
4743   }
4744   if (lType->isIntegerType() && rType->isAnyPointerType()) {
4745     unsigned DiagID = 0;
4746     if (LHSIsNull) {
4747       if (isRelational)
4748         DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
4749     } else if (isRelational)
4750       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
4751     else
4752       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
4753
4754     if (DiagID) {
4755       Diag(Loc, DiagID)
4756         << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4757     }
4758     ImpCastExprToType(lex, rType, CastExpr::CK_IntegralToPointer);
4759     return ResultTy;
4760   }
4761   // Handle block pointers.
4762   if (!isRelational && RHSIsNull
4763       && lType->isBlockPointerType() && rType->isIntegerType()) {
4764     ImpCastExprToType(rex, lType, CastExpr::CK_IntegralToPointer);
4765     return ResultTy;
4766   }
4767   if (!isRelational && LHSIsNull
4768       && lType->isIntegerType() && rType->isBlockPointerType()) {
4769     ImpCastExprToType(lex, rType, CastExpr::CK_IntegralToPointer);
4770     return ResultTy;
4771   }
4772   return InvalidOperands(Loc, lex, rex);
4773 }
4774
4775 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
4776 /// operates on extended vector types.  Instead of producing an IntTy result,
4777 /// like a scalar comparison, a vector comparison produces a vector of integer
4778 /// types.
4779 QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
4780                                           SourceLocation Loc,
4781                                           bool isRelational) {
4782   // Check to make sure we're operating on vectors of the same type and width,
4783   // Allowing one side to be a scalar of element type.
4784   QualType vType = CheckVectorOperands(Loc, lex, rex);
4785   if (vType.isNull())
4786     return vType;
4787
4788   QualType lType = lex->getType();
4789   QualType rType = rex->getType();
4790
4791   // For non-floating point types, check for self-comparisons of the form
4792   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
4793   // often indicate logic errors in the program.
4794   if (!lType->isFloatingType()) {
4795     if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
4796       if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
4797         if (DRL->getDecl() == DRR->getDecl())
4798           Diag(Loc, diag::warn_selfcomparison);
4799   }
4800
4801   // Check for comparisons of floating point operands using != and ==.
4802   if (!isRelational && lType->isFloatingType()) {
4803     assert (rType->isFloatingType());
4804     CheckFloatComparison(Loc,lex,rex);
4805   }
4806
4807   // Return the type for the comparison, which is the same as vector type for
4808   // integer vectors, or an integer type of identical size and number of
4809   // elements for floating point vectors.
4810   if (lType->isIntegerType())
4811     return lType;
4812
4813   const VectorType *VTy = lType->getAs<VectorType>();
4814   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
4815   if (TypeSize == Context.getTypeSize(Context.IntTy))
4816     return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
4817   if (TypeSize == Context.getTypeSize(Context.LongTy))
4818     return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
4819
4820   assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
4821          "Unhandled vector element size in vector compare");
4822   return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
4823 }
4824
4825 inline QualType Sema::CheckBitwiseOperands(
4826   Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
4827   if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
4828     return CheckVectorOperands(Loc, lex, rex);
4829
4830   QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
4831
4832   if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
4833     return compType;
4834   return InvalidOperands(Loc, lex, rex);
4835 }
4836
4837 inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
4838   Expr *&lex, Expr *&rex, SourceLocation Loc) {
4839   UsualUnaryConversions(lex);
4840   UsualUnaryConversions(rex);
4841
4842   if (!lex->getType()->isScalarType() || !rex->getType()->isScalarType())
4843     return InvalidOperands(Loc, lex, rex);
4844     
4845   if (Context.getLangOptions().CPlusPlus) {
4846     // C++ [expr.log.and]p2
4847     // C++ [expr.log.or]p2
4848     return Context.BoolTy;
4849   }
4850
4851   return Context.IntTy;
4852 }
4853
4854 /// IsReadonlyProperty - Verify that otherwise a valid l-value expression
4855 /// is a read-only property; return true if so. A readonly property expression
4856 /// depends on various declarations and thus must be treated specially.
4857 ///
4858 static bool IsReadonlyProperty(Expr *E, Sema &S) {
4859   if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
4860     const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
4861     if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
4862       QualType BaseType = PropExpr->getBase()->getType();
4863       if (const ObjCObjectPointerType *OPT =
4864             BaseType->getAsObjCInterfacePointerType())
4865         if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
4866           if (S.isPropertyReadonly(PDecl, IFace))
4867             return true;
4868     }
4869   }
4870   return false;
4871 }
4872
4873 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
4874 /// emit an error and return true.  If so, return false.
4875 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
4876   SourceLocation OrigLoc = Loc;
4877   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
4878                                                               &Loc);
4879   if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
4880     IsLV = Expr::MLV_ReadonlyProperty;
4881   if (IsLV == Expr::MLV_Valid)
4882     return false;
4883
4884   unsigned Diag = 0;
4885   bool NeedType = false;
4886   switch (IsLV) { // C99 6.5.16p2
4887   default: assert(0 && "Unknown result from isModifiableLvalue!");
4888   case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
4889   case Expr::MLV_ArrayType:
4890     Diag = diag::err_typecheck_array_not_modifiable_lvalue;
4891     NeedType = true;
4892     break;
4893   case Expr::MLV_NotObjectType:
4894     Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
4895     NeedType = true;
4896     break;
4897   case Expr::MLV_LValueCast:
4898     Diag = diag::err_typecheck_lvalue_casts_not_supported;
4899     break;
4900   case Expr::MLV_InvalidExpression:
4901     Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
4902     break;
4903   case Expr::MLV_IncompleteType:
4904   case Expr::MLV_IncompleteVoidType:
4905     return S.RequireCompleteType(Loc, E->getType(),
4906                 PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
4907                   << E->getSourceRange());
4908   case Expr::MLV_DuplicateVectorComponents:
4909     Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
4910     break;
4911   case Expr::MLV_NotBlockQualified:
4912     Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
4913     break;
4914   case Expr::MLV_ReadonlyProperty:
4915     Diag = diag::error_readonly_property_assignment;
4916     break;
4917   case Expr::MLV_NoSetterProperty:
4918     Diag = diag::error_nosetter_property_assignment;
4919     break;
4920   }
4921
4922   SourceRange Assign;
4923   if (Loc != OrigLoc)
4924     Assign = SourceRange(OrigLoc, OrigLoc);
4925   if (NeedType)
4926     S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
4927   else
4928     S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
4929   return true;
4930 }
4931
4932
4933
4934 // C99 6.5.16.1
4935 QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
4936                                        SourceLocation Loc,
4937                                        QualType CompoundType) {
4938   // Verify that LHS is a modifiable lvalue, and emit error if not.
4939   if (CheckForModifiableLvalue(LHS, Loc, *this))
4940     return QualType();
4941
4942   QualType LHSType = LHS->getType();
4943   QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
4944
4945   AssignConvertType ConvTy;
4946   if (CompoundType.isNull()) {
4947     // Simple assignment "x = y".
4948     ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
4949     // Special case of NSObject attributes on c-style pointer types.
4950     if (ConvTy == IncompatiblePointer &&
4951         ((Context.isObjCNSObjectType(LHSType) &&
4952           RHSType->isObjCObjectPointerType()) ||
4953          (Context.isObjCNSObjectType(RHSType) &&
4954           LHSType->isObjCObjectPointerType())))
4955       ConvTy = Compatible;
4956
4957     // If the RHS is a unary plus or minus, check to see if they = and + are
4958     // right next to each other.  If so, the user may have typo'd "x =+ 4"
4959     // instead of "x += 4".
4960     Expr *RHSCheck = RHS;
4961     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
4962       RHSCheck = ICE->getSubExpr();
4963     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
4964       if ((UO->getOpcode() == UnaryOperator::Plus ||
4965            UO->getOpcode() == UnaryOperator::Minus) &&
4966           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
4967           // Only if the two operators are exactly adjacent.
4968           Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
4969           // And there is a space or other character before the subexpr of the
4970           // unary +/-.  We don't want to warn on "x=-1".
4971           Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
4972           UO->getSubExpr()->getLocStart().isFileID()) {
4973         Diag(Loc, diag::warn_not_compound_assign)
4974           << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
4975           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
4976       }
4977     }
4978   } else {
4979     // Compound assignment "x += y"
4980     ConvTy = CheckAssignmentConstraints(LHSType, RHSType);
4981   }
4982
4983   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
4984                                RHS, "assigning"))
4985     return QualType();
4986
4987   // C99 6.5.16p3: The type of an assignment expression is the type of the
4988   // left operand unless the left operand has qualified type, in which case
4989   // it is the unqualified version of the type of the left operand.
4990   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
4991   // is converted to the type of the assignment expression (above).
4992   // C++ 5.17p1: the type of the assignment expression is that of its left
4993   // operand.
4994   return LHSType.getUnqualifiedType();
4995 }
4996
4997 // C99 6.5.17
4998 QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
4999   // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
5000   DefaultFunctionArrayConversion(RHS);
5001
5002   // FIXME: Check that RHS type is complete in C mode (it's legal for it to be
5003   // incomplete in C++).
5004
5005   return RHS->getType();
5006 }
5007
5008 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
5009 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
5010 QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
5011                                               bool isInc) {
5012   if (Op->isTypeDependent())
5013     return Context.DependentTy;
5014
5015   QualType ResType = Op->getType();
5016   assert(!ResType.isNull() && "no type for increment/decrement expression");
5017
5018   if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
5019     // Decrement of bool is not allowed.
5020     if (!isInc) {
5021       Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
5022       return QualType();
5023     }
5024     // Increment of bool sets it to true, but is deprecated.
5025     Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
5026   } else if (ResType->isRealType()) {
5027     // OK!
5028   } else if (ResType->isAnyPointerType()) {
5029     QualType PointeeTy = ResType->getPointeeType();
5030
5031     // C99 6.5.2.4p2, 6.5.6p2
5032     if (PointeeTy->isVoidType()) {
5033       if (getLangOptions().CPlusPlus) {
5034         Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
5035           << Op->getSourceRange();
5036         return QualType();
5037       }
5038
5039       // Pointer to void is a GNU extension in C.
5040       Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
5041     } else if (PointeeTy->isFunctionType()) {
5042       if (getLangOptions().CPlusPlus) {
5043         Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
5044           << Op->getType() << Op->getSourceRange();
5045         return QualType();
5046       }
5047
5048       Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
5049         << ResType << Op->getSourceRange();
5050     } else if (RequireCompleteType(OpLoc, PointeeTy,
5051                            PDiag(diag::err_typecheck_arithmetic_incomplete_type)
5052                              << Op->getSourceRange()
5053                              << ResType))
5054       return QualType();
5055     // Diagnose bad cases where we step over interface counts.
5056     else if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
5057       Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
5058         << PointeeTy << Op->getSourceRange();
5059       return QualType();
5060     }
5061   } else if (ResType->isComplexType()) {
5062     // C99 does not support ++/-- on complex types, we allow as an extension.
5063     Diag(OpLoc, diag::ext_integer_increment_complex)
5064       << ResType << Op->getSourceRange();
5065   } else {
5066     Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
5067       << ResType << Op->getSourceRange();
5068     return QualType();
5069   }
5070   // At this point, we know we have a real, complex or pointer type.
5071   // Now make sure the operand is a modifiable lvalue.
5072   if (CheckForModifiableLvalue(Op, OpLoc, *this))
5073     return QualType();
5074   return ResType;
5075 }
5076
5077 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
5078 /// This routine allows us to typecheck complex/recursive expressions
5079 /// where the declaration is needed for type checking. We only need to
5080 /// handle cases when the expression references a function designator
5081 /// or is an lvalue. Here are some examples:
5082 ///  - &(x) => x
5083 ///  - &*****f => f for f a function designator.
5084 ///  - &s.xx => s
5085 ///  - &s.zz[1].yy -> s, if zz is an array
5086 ///  - *(x + 1) -> x, if x is an array
5087 ///  - &"123"[2] -> 0
5088 ///  - & __real__ x -> x
5089 static NamedDecl *getPrimaryDecl(Expr *E) {
5090   switch (E->getStmtClass()) {
5091   case Stmt::DeclRefExprClass:
5092     return cast<DeclRefExpr>(E)->getDecl();
5093   case Stmt::MemberExprClass:
5094     // If this is an arrow operator, the address is an offset from
5095     // the base's value, so the object the base refers to is
5096     // irrelevant.
5097     if (cast<MemberExpr>(E)->isArrow())
5098       return 0;
5099     // Otherwise, the expression refers to a part of the base
5100     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
5101   case Stmt::ArraySubscriptExprClass: {
5102     // FIXME: This code shouldn't be necessary!  We should catch the implicit
5103     // promotion of register arrays earlier.
5104     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
5105     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
5106       if (ICE->getSubExpr()->getType()->isArrayType())
5107         return getPrimaryDecl(ICE->getSubExpr());
5108     }
5109     return 0;
5110   }
5111   case Stmt::UnaryOperatorClass: {
5112     UnaryOperator *UO = cast<UnaryOperator>(E);
5113
5114     switch(UO->getOpcode()) {
5115     case UnaryOperator::Real:
5116     case UnaryOperator::Imag:
5117     case UnaryOperator::Extension:
5118       return getPrimaryDecl(UO->getSubExpr());
5119     default:
5120       return 0;
5121     }
5122   }
5123   case Stmt::ParenExprClass:
5124     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
5125   case Stmt::ImplicitCastExprClass:
5126     // If the result of an implicit cast is an l-value, we care about
5127     // the sub-expression; otherwise, the result here doesn't matter.
5128     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
5129   default:
5130     return 0;
5131   }
5132 }
5133
5134 /// CheckAddressOfOperand - The operand of & must be either a function
5135 /// designator or an lvalue designating an object. If it is an lvalue, the
5136 /// object cannot be declared with storage class register or be a bit field.
5137 /// Note: The usual conversions are *not* applied to the operand of the &
5138 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
5139 /// In C++, the operand might be an overloaded function name, in which case
5140 /// we allow the '&' but retain the overloaded-function type.
5141 QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
5142   // Make sure to ignore parentheses in subsequent checks
5143   op = op->IgnoreParens();
5144
5145   if (op->isTypeDependent())
5146     return Context.DependentTy;
5147
5148   if (getLangOptions().C99) {
5149     // Implement C99-only parts of addressof rules.
5150     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
5151       if (uOp->getOpcode() == UnaryOperator::Deref)
5152         // Per C99 6.5.3.2, the address of a deref always returns a valid result
5153         // (assuming the deref expression is valid).
5154         return uOp->getSubExpr()->getType();
5155     }
5156     // Technically, there should be a check for array subscript
5157     // expressions here, but the result of one is always an lvalue anyway.
5158   }
5159   NamedDecl *dcl = getPrimaryDecl(op);
5160   Expr::isLvalueResult lval = op->isLvalue(Context);
5161
5162   if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
5163     // C99 6.5.3.2p1
5164     // The operand must be either an l-value or a function designator
5165     if (!op->getType()->isFunctionType()) {
5166       // FIXME: emit more specific diag...
5167       Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
5168         << op->getSourceRange();
5169       return QualType();
5170     }
5171   } else if (op->getBitField()) { // C99 6.5.3.2p1
5172     // The operand cannot be a bit-field
5173     Diag(OpLoc, diag::err_typecheck_address_of)
5174       << "bit-field" << op->getSourceRange();
5175         return QualType();
5176   } else if (isa<ExtVectorElementExpr>(op) || (isa<ArraySubscriptExpr>(op) &&
5177            cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType())){
5178     // The operand cannot be an element of a vector
5179     Diag(OpLoc, diag::err_typecheck_address_of)
5180       << "vector element" << op->getSourceRange();
5181     return QualType();
5182   } else if (isa<ObjCPropertyRefExpr>(op)) {
5183     // cannot take address of a property expression.
5184     Diag(OpLoc, diag::err_typecheck_address_of)
5185       << "property expression" << op->getSourceRange();
5186     return QualType();
5187   } else if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(op)) {
5188     // FIXME: Can LHS ever be null here?
5189     if (!CheckAddressOfOperand(CO->getTrueExpr(), OpLoc).isNull())
5190       return CheckAddressOfOperand(CO->getFalseExpr(), OpLoc);
5191   } else if (dcl) { // C99 6.5.3.2p1
5192     // We have an lvalue with a decl. Make sure the decl is not declared
5193     // with the register storage-class specifier.
5194     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
5195       if (vd->getStorageClass() == VarDecl::Register) {
5196         Diag(OpLoc, diag::err_typecheck_address_of)
5197           << "register variable" << op->getSourceRange();
5198         return QualType();
5199       }
5200     } else if (isa<OverloadedFunctionDecl>(dcl) ||
5201                isa<FunctionTemplateDecl>(dcl)) {
5202       return Context.OverloadTy;
5203     } else if (FieldDecl *FD = dyn_cast<FieldDecl>(dcl)) {
5204       // Okay: we can take the address of a field.
5205       // Could be a pointer to member, though, if there is an explicit
5206       // scope qualifier for the class.
5207       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
5208         DeclContext *Ctx = dcl->getDeclContext();
5209         if (Ctx && Ctx->isRecord()) {
5210           if (FD->getType()->isReferenceType()) {
5211             Diag(OpLoc,
5212                  diag::err_cannot_form_pointer_to_member_of_reference_type)
5213               << FD->getDeclName() << FD->getType();
5214             return QualType();
5215           }
5216
5217           return Context.getMemberPointerType(op->getType(),
5218                 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
5219         }
5220       }
5221     } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(dcl)) {
5222       // Okay: we can take the address of a function.
5223       // As above.
5224       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier() &&
5225           MD->isInstance())
5226         return Context.getMemberPointerType(op->getType(),
5227               Context.getTypeDeclType(MD->getParent()).getTypePtr());
5228     } else if (!isa<FunctionDecl>(dcl))
5229       assert(0 && "Unknown/unexpected decl type");
5230   }
5231
5232   if (lval == Expr::LV_IncompleteVoidType) {
5233     // Taking the address of a void variable is technically illegal, but we
5234     // allow it in cases which are otherwise valid.
5235     // Example: "extern void x; void* y = &x;".
5236     Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
5237   }
5238
5239   // If the operand has type "type", the result has type "pointer to type".
5240   return Context.getPointerType(op->getType());
5241 }
5242
5243 QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
5244   if (Op->isTypeDependent())
5245     return Context.DependentTy;
5246
5247   UsualUnaryConversions(Op);
5248   QualType Ty = Op->getType();
5249
5250   // Note that per both C89 and C99, this is always legal, even if ptype is an
5251   // incomplete type or void.  It would be possible to warn about dereferencing
5252   // a void pointer, but it's completely well-defined, and such a warning is
5253   // unlikely to catch any mistakes.
5254   if (const PointerType *PT = Ty->getAs<PointerType>())
5255     return PT->getPointeeType();
5256
5257   if (const ObjCObjectPointerType *OPT = Ty->getAs<ObjCObjectPointerType>())
5258     return OPT->getPointeeType();
5259
5260   Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
5261     << Ty << Op->getSourceRange();
5262   return QualType();
5263 }
5264
5265 static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
5266   tok::TokenKind Kind) {
5267   BinaryOperator::Opcode Opc;
5268   switch (Kind) {
5269   default: assert(0 && "Unknown binop!");
5270   case tok::periodstar:           Opc = BinaryOperator::PtrMemD; break;
5271   case tok::arrowstar:            Opc = BinaryOperator::PtrMemI; break;
5272   case tok::star:                 Opc = BinaryOperator::Mul; break;
5273   case tok::slash:                Opc = BinaryOperator::Div; break;
5274   case tok::percent:              Opc = BinaryOperator::Rem; break;
5275   case tok::plus:                 Opc = BinaryOperator::Add; break;
5276   case tok::minus:                Opc = BinaryOperator::Sub; break;
5277   case tok::lessless:             Opc = BinaryOperator::Shl; break;
5278   case tok::greatergreater:       Opc = BinaryOperator::Shr; break;
5279   case tok::lessequal:            Opc = BinaryOperator::LE; break;
5280   case tok::less:                 Opc = BinaryOperator::LT; break;
5281   case tok::greaterequal:         Opc = BinaryOperator::GE; break;
5282   case tok::greater:              Opc = BinaryOperator::GT; break;
5283   case tok::exclaimequal:         Opc = BinaryOperator::NE; break;
5284   case tok::equalequal:           Opc = BinaryOperator::EQ; break;
5285   case tok::amp:                  Opc = BinaryOperator::And; break;
5286   case tok::caret:                Opc = BinaryOperator::Xor; break;
5287   case tok::pipe:                 Opc = BinaryOperator::Or; break;
5288   case tok::ampamp:               Opc = BinaryOperator::LAnd; break;
5289   case tok::pipepipe:             Opc = BinaryOperator::LOr; break;
5290   case tok::equal:                Opc = BinaryOperator::Assign; break;
5291   case tok::starequal:            Opc = BinaryOperator::MulAssign; break;
5292   case tok::slashequal:           Opc = BinaryOperator::DivAssign; break;
5293   case tok::percentequal:         Opc = BinaryOperator::RemAssign; break;
5294   case tok::plusequal:            Opc = BinaryOperator::AddAssign; break;
5295   case tok::minusequal:           Opc = BinaryOperator::SubAssign; break;
5296   case tok::lesslessequal:        Opc = BinaryOperator::ShlAssign; break;
5297   case tok::greatergreaterequal:  Opc = BinaryOperator::ShrAssign; break;
5298   case tok::ampequal:             Opc = BinaryOperator::AndAssign; break;
5299   case tok::caretequal:           Opc = BinaryOperator::XorAssign; break;
5300   case tok::pipeequal:            Opc = BinaryOperator::OrAssign; break;
5301   case tok::comma:                Opc = BinaryOperator::Comma; break;
5302   }
5303   return Opc;
5304 }
5305
5306 static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
5307   tok::TokenKind Kind) {
5308   UnaryOperator::Opcode Opc;
5309   switch (Kind) {
5310   default: assert(0 && "Unknown unary op!");
5311   case tok::plusplus:     Opc = UnaryOperator::PreInc; break;
5312   case tok::minusminus:   Opc = UnaryOperator::PreDec; break;
5313   case tok::amp:          Opc = UnaryOperator::AddrOf; break;
5314   case tok::star:         Opc = UnaryOperator::Deref; break;
5315   case tok::plus:         Opc = UnaryOperator::Plus; break;
5316   case tok::minus:        Opc = UnaryOperator::Minus; break;
5317   case tok::tilde:        Opc = UnaryOperator::Not; break;
5318   case tok::exclaim:      Opc = UnaryOperator::LNot; break;
5319   case tok::kw___real:    Opc = UnaryOperator::Real; break;
5320   case tok::kw___imag:    Opc = UnaryOperator::Imag; break;
5321   case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
5322   }
5323   return Opc;
5324 }
5325
5326 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
5327 /// operator @p Opc at location @c TokLoc. This routine only supports
5328 /// built-in operations; ActOnBinOp handles overloaded operators.
5329 Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
5330                                                   unsigned Op,
5331                                                   Expr *lhs, Expr *rhs) {
5332   QualType ResultTy;     // Result type of the binary operator.
5333   BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
5334   // The following two variables are used for compound assignment operators
5335   QualType CompLHSTy;    // Type of LHS after promotions for computation
5336   QualType CompResultTy; // Type of computation result
5337
5338   switch (Opc) {
5339   case BinaryOperator::Assign:
5340     ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
5341     break;
5342   case BinaryOperator::PtrMemD:
5343   case BinaryOperator::PtrMemI:
5344     ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
5345                                             Opc == BinaryOperator::PtrMemI);
5346     break;
5347   case BinaryOperator::Mul:
5348   case BinaryOperator::Div:
5349     ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
5350     break;
5351   case BinaryOperator::Rem:
5352     ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
5353     break;
5354   case BinaryOperator::Add:
5355     ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
5356     break;
5357   case BinaryOperator::Sub:
5358     ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
5359     break;
5360   case BinaryOperator::Shl:
5361   case BinaryOperator::Shr:
5362     ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
5363     break;
5364   case BinaryOperator::LE:
5365   case BinaryOperator::LT:
5366   case BinaryOperator::GE:
5367   case BinaryOperator::GT:
5368     ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
5369     break;
5370   case BinaryOperator::EQ:
5371   case BinaryOperator::NE:
5372     ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
5373     break;
5374   case BinaryOperator::And:
5375   case BinaryOperator::Xor:
5376   case BinaryOperator::Or:
5377     ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
5378     break;
5379   case BinaryOperator::LAnd:
5380   case BinaryOperator::LOr:
5381     ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
5382     break;
5383   case BinaryOperator::MulAssign:
5384   case BinaryOperator::DivAssign:
5385     CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
5386     CompLHSTy = CompResultTy;
5387     if (!CompResultTy.isNull())
5388       ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
5389     break;
5390   case BinaryOperator::RemAssign:
5391     CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
5392     CompLHSTy = CompResultTy;
5393     if (!CompResultTy.isNull())
5394       ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
5395     break;
5396   case BinaryOperator::AddAssign:
5397     CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
5398     if (!CompResultTy.isNull())
5399       ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
5400     break;
5401   case BinaryOperator::SubAssign:
5402     CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
5403     if (!CompResultTy.isNull())
5404       ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
5405     break;
5406   case BinaryOperator::ShlAssign:
5407   case BinaryOperator::ShrAssign:
5408     CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
5409     CompLHSTy = CompResultTy;
5410     if (!CompResultTy.isNull())
5411       ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
5412     break;
5413   case BinaryOperator::AndAssign:
5414   case BinaryOperator::XorAssign:
5415   case BinaryOperator::OrAssign:
5416     CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
5417     CompLHSTy = CompResultTy;
5418     if (!CompResultTy.isNull())
5419       ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
5420     break;
5421   case BinaryOperator::Comma:
5422     ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
5423     break;
5424   }
5425   if (ResultTy.isNull())
5426     return ExprError();
5427   if (CompResultTy.isNull())
5428     return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
5429   else
5430     return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
5431                                                       CompLHSTy, CompResultTy,
5432                                                       OpLoc));
5433 }
5434
5435 /// SuggestParentheses - Emit a diagnostic together with a fixit hint that wraps
5436 /// ParenRange in parentheses.
5437 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
5438                                const PartialDiagnostic &PD,
5439                                SourceRange ParenRange)
5440 {
5441   SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
5442   if (!ParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
5443     // We can't display the parentheses, so just dig the
5444     // warning/error and return.
5445     Self.Diag(Loc, PD);
5446     return;
5447   }
5448
5449   Self.Diag(Loc, PD)
5450     << CodeModificationHint::CreateInsertion(ParenRange.getBegin(), "(")
5451     << CodeModificationHint::CreateInsertion(EndLoc, ")");
5452 }
5453
5454 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
5455 /// operators are mixed in a way that suggests that the programmer forgot that
5456 /// comparison operators have higher precedence. The most typical example of
5457 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
5458 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperator::Opcode Opc,
5459                                       SourceLocation OpLoc,Expr *lhs,Expr *rhs){
5460   typedef BinaryOperator BinOp;
5461   BinOp::Opcode lhsopc = static_cast<BinOp::Opcode>(-1),
5462                 rhsopc = static_cast<BinOp::Opcode>(-1);
5463   if (BinOp *BO = dyn_cast<BinOp>(lhs))
5464     lhsopc = BO->getOpcode();
5465   if (BinOp *BO = dyn_cast<BinOp>(rhs))
5466     rhsopc = BO->getOpcode();
5467
5468   // Subs are not binary operators.
5469   if (lhsopc == -1 && rhsopc == -1)
5470     return;
5471
5472   // Bitwise operations are sometimes used as eager logical ops.
5473   // Don't diagnose this.
5474   if ((BinOp::isComparisonOp(lhsopc) || BinOp::isBitwiseOp(lhsopc)) &&
5475       (BinOp::isComparisonOp(rhsopc) || BinOp::isBitwiseOp(rhsopc)))
5476     return;
5477
5478   if (BinOp::isComparisonOp(lhsopc))
5479     SuggestParentheses(Self, OpLoc,
5480       PDiag(diag::warn_precedence_bitwise_rel)
5481           << SourceRange(lhs->getLocStart(), OpLoc)
5482           << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(lhsopc),
5483       SourceRange(cast<BinOp>(lhs)->getRHS()->getLocStart(), rhs->getLocEnd()));
5484   else if (BinOp::isComparisonOp(rhsopc))
5485     SuggestParentheses(Self, OpLoc,
5486       PDiag(diag::warn_precedence_bitwise_rel)
5487           << SourceRange(OpLoc, rhs->getLocEnd())
5488           << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(rhsopc),
5489       SourceRange(lhs->getLocEnd(), cast<BinOp>(rhs)->getLHS()->getLocStart()));
5490 }
5491
5492 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
5493 /// precedence. This currently diagnoses only "arg1 'bitwise' arg2 'eq' arg3".
5494 /// But it could also warn about arg1 && arg2 || arg3, as GCC 4.3+ does.
5495 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperator::Opcode Opc,
5496                                     SourceLocation OpLoc, Expr *lhs, Expr *rhs){
5497   if (BinaryOperator::isBitwiseOp(Opc))
5498     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, lhs, rhs);
5499 }
5500
5501 // Binary Operators.  'Tok' is the token for the operator.
5502 Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
5503                                           tok::TokenKind Kind,
5504                                           ExprArg LHS, ExprArg RHS) {
5505   BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
5506   Expr *lhs = LHS.takeAs<Expr>(), *rhs = RHS.takeAs<Expr>();
5507
5508   assert((lhs != 0) && "ActOnBinOp(): missing left expression");
5509   assert((rhs != 0) && "ActOnBinOp(): missing right expression");
5510
5511   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
5512   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, lhs, rhs);
5513
5514   return BuildBinOp(S, TokLoc, Opc, lhs, rhs);
5515 }
5516
5517 Action::OwningExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
5518                                           BinaryOperator::Opcode Opc,
5519                                           Expr *lhs, Expr *rhs) {
5520   if (getLangOptions().CPlusPlus &&
5521       (lhs->getType()->isOverloadableType() ||
5522        rhs->getType()->isOverloadableType())) {
5523     // Find all of the overloaded operators visible from this
5524     // point. We perform both an operator-name lookup from the local
5525     // scope and an argument-dependent lookup based on the types of
5526     // the arguments.
5527     FunctionSet Functions;
5528     OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
5529     if (OverOp != OO_None) {
5530       if (S)
5531         LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
5532                                      Functions);
5533       Expr *Args[2] = { lhs, rhs };
5534       DeclarationName OpName
5535         = Context.DeclarationNames.getCXXOperatorName(OverOp);
5536       ArgumentDependentLookup(OpName, /*Operator*/true, Args, 2, Functions);
5537     }
5538     
5539     // Build the (potentially-overloaded, potentially-dependent)
5540     // binary operation.
5541     return CreateOverloadedBinOp(OpLoc, Opc, Functions, lhs, rhs);
5542   }
5543   
5544   // Build a built-in binary operation.
5545   return CreateBuiltinBinOp(OpLoc, Opc, lhs, rhs);
5546 }
5547
5548 Action::OwningExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
5549                                                     unsigned OpcIn,
5550                                                     ExprArg InputArg) {
5551   UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
5552
5553   // FIXME: Input is modified below, but InputArg is not updated appropriately.
5554   Expr *Input = (Expr *)InputArg.get();
5555   QualType resultType;
5556   switch (Opc) {
5557   case UnaryOperator::OffsetOf:
5558     assert(false && "Invalid unary operator");
5559     break;
5560
5561   case UnaryOperator::PreInc:
5562   case UnaryOperator::PreDec:
5563   case UnaryOperator::PostInc:
5564   case UnaryOperator::PostDec:
5565     resultType = CheckIncrementDecrementOperand(Input, OpLoc,
5566                                                 Opc == UnaryOperator::PreInc ||
5567                                                 Opc == UnaryOperator::PostInc);
5568     break;
5569   case UnaryOperator::AddrOf:
5570     resultType = CheckAddressOfOperand(Input, OpLoc);
5571     break;
5572   case UnaryOperator::Deref:
5573     DefaultFunctionArrayConversion(Input);
5574     resultType = CheckIndirectionOperand(Input, OpLoc);
5575     break;
5576   case UnaryOperator::Plus:
5577   case UnaryOperator::Minus:
5578     UsualUnaryConversions(Input);
5579     resultType = Input->getType();
5580     if (resultType->isDependentType())
5581       break;
5582     if (resultType->isArithmeticType()) // C99 6.5.3.3p1
5583       break;
5584     else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
5585              resultType->isEnumeralType())
5586       break;
5587     else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
5588              Opc == UnaryOperator::Plus &&
5589              resultType->isPointerType())
5590       break;
5591
5592     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
5593       << resultType << Input->getSourceRange());
5594   case UnaryOperator::Not: // bitwise complement
5595     UsualUnaryConversions(Input);
5596     resultType = Input->getType();
5597     if (resultType->isDependentType())
5598       break;
5599     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
5600     if (resultType->isComplexType() || resultType->isComplexIntegerType())
5601       // C99 does not support '~' for complex conjugation.
5602       Diag(OpLoc, diag::ext_integer_complement_complex)
5603         << resultType << Input->getSourceRange();
5604     else if (!resultType->isIntegerType())
5605       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
5606         << resultType << Input->getSourceRange());
5607     break;
5608   case UnaryOperator::LNot: // logical negation
5609     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
5610     DefaultFunctionArrayConversion(Input);
5611     resultType = Input->getType();
5612     if (resultType->isDependentType())
5613       break;
5614     if (!resultType->isScalarType()) // C99 6.5.3.3p1
5615       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
5616         << resultType << Input->getSourceRange());
5617     // LNot always has type int. C99 6.5.3.3p5.
5618     // In C++, it's bool. C++ 5.3.1p8
5619     resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
5620     break;
5621   case UnaryOperator::Real:
5622   case UnaryOperator::Imag:
5623     resultType = CheckRealImagOperand(Input, OpLoc, Opc == UnaryOperator::Real);
5624     break;
5625   case UnaryOperator::Extension:
5626     resultType = Input->getType();
5627     break;
5628   }
5629   if (resultType.isNull())
5630     return ExprError();
5631
5632   InputArg.release();
5633   return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
5634 }
5635
5636 Action::OwningExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
5637                                             UnaryOperator::Opcode Opc,
5638                                             ExprArg input) {
5639   Expr *Input = (Expr*)input.get();
5640   if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType()) {
5641     // Find all of the overloaded operators visible from this
5642     // point. We perform both an operator-name lookup from the local
5643     // scope and an argument-dependent lookup based on the types of
5644     // the arguments.
5645     FunctionSet Functions;
5646     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
5647     if (OverOp != OO_None) {
5648       if (S)
5649         LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
5650                                      Functions);
5651       DeclarationName OpName
5652         = Context.DeclarationNames.getCXXOperatorName(OverOp);
5653       ArgumentDependentLookup(OpName, /*Operator*/true, &Input, 1, Functions);
5654     }
5655     
5656     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, move(input));
5657   }
5658   
5659   return CreateBuiltinUnaryOp(OpLoc, Opc, move(input));
5660 }
5661
5662 // Unary Operators.  'Tok' is the token for the operator.
5663 Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
5664                                             tok::TokenKind Op, ExprArg input) {
5665   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), move(input));
5666 }
5667
5668 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
5669 Sema::OwningExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
5670                                             SourceLocation LabLoc,
5671                                             IdentifierInfo *LabelII) {
5672   // Look up the record for this label identifier.
5673   LabelStmt *&LabelDecl = getLabelMap()[LabelII];
5674
5675   // If we haven't seen this label yet, create a forward reference. It
5676   // will be validated and/or cleaned up in ActOnFinishFunctionBody.
5677   if (LabelDecl == 0)
5678     LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
5679
5680   // Create the AST node.  The address of a label always has type 'void*'.
5681   return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
5682                                        Context.getPointerType(Context.VoidTy)));
5683 }
5684
5685 Sema::OwningExprResult
5686 Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtArg substmt,
5687                     SourceLocation RPLoc) { // "({..})"
5688   Stmt *SubStmt = static_cast<Stmt*>(substmt.get());
5689   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
5690   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
5691
5692   bool isFileScope = getCurFunctionOrMethodDecl() == 0;
5693   if (isFileScope)
5694     return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
5695
5696   // FIXME: there are a variety of strange constraints to enforce here, for
5697   // example, it is not possible to goto into a stmt expression apparently.
5698   // More semantic analysis is needed.
5699
5700   // If there are sub stmts in the compound stmt, take the type of the last one
5701   // as the type of the stmtexpr.
5702   QualType Ty = Context.VoidTy;
5703
5704   if (!Compound->body_empty()) {
5705     Stmt *LastStmt = Compound->body_back();
5706     // If LastStmt is a label, skip down through into the body.
5707     while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
5708       LastStmt = Label->getSubStmt();
5709
5710     if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
5711       Ty = LastExpr->getType();
5712   }
5713
5714   // FIXME: Check that expression type is complete/non-abstract; statement
5715   // expressions are not lvalues.
5716
5717   substmt.release();
5718   return Owned(new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc));
5719 }
5720
5721 Sema::OwningExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
5722                                                   SourceLocation BuiltinLoc,
5723                                                   SourceLocation TypeLoc,
5724                                                   TypeTy *argty,
5725                                                   OffsetOfComponent *CompPtr,
5726                                                   unsigned NumComponents,
5727                                                   SourceLocation RPLoc) {
5728   // FIXME: This function leaks all expressions in the offset components on
5729   // error.
5730   // FIXME: Preserve type source info.
5731   QualType ArgTy = GetTypeFromParser(argty);
5732   assert(!ArgTy.isNull() && "Missing type argument!");
5733
5734   bool Dependent = ArgTy->isDependentType();
5735
5736   // We must have at least one component that refers to the type, and the first
5737   // one is known to be a field designator.  Verify that the ArgTy represents
5738   // a struct/union/class.
5739   if (!Dependent && !ArgTy->isRecordType())
5740     return ExprError(Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy);
5741
5742   // FIXME: Type must be complete per C99 7.17p3 because a declaring a variable
5743   // with an incomplete type would be illegal.
5744
5745   // Otherwise, create a null pointer as the base, and iteratively process
5746   // the offsetof designators.
5747   QualType ArgTyPtr = Context.getPointerType(ArgTy);
5748   Expr* Res = new (Context) ImplicitValueInitExpr(ArgTyPtr);
5749   Res = new (Context) UnaryOperator(Res, UnaryOperator::Deref,
5750                                     ArgTy, SourceLocation());
5751
5752   // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
5753   // GCC extension, diagnose them.
5754   // FIXME: This diagnostic isn't actually visible because the location is in
5755   // a system header!
5756   if (NumComponents != 1)
5757     Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
5758       << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
5759
5760   if (!Dependent) {
5761     bool DidWarnAboutNonPOD = false;
5762
5763     if (RequireCompleteType(TypeLoc, Res->getType(),
5764                             diag::err_offsetof_incomplete_type))
5765       return ExprError();
5766
5767     // FIXME: Dependent case loses a lot of information here. And probably
5768     // leaks like a sieve.
5769     for (unsigned i = 0; i != NumComponents; ++i) {
5770       const OffsetOfComponent &OC = CompPtr[i];
5771       if (OC.isBrackets) {
5772         // Offset of an array sub-field.  TODO: Should we allow vector elements?
5773         const ArrayType *AT = Context.getAsArrayType(Res->getType());
5774         if (!AT) {
5775           Res->Destroy(Context);
5776           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
5777             << Res->getType());
5778         }
5779
5780         // FIXME: C++: Verify that operator[] isn't overloaded.
5781
5782         // Promote the array so it looks more like a normal array subscript
5783         // expression.
5784         DefaultFunctionArrayConversion(Res);
5785
5786         // C99 6.5.2.1p1
5787         Expr *Idx = static_cast<Expr*>(OC.U.E);
5788         // FIXME: Leaks Res
5789         if (!Idx->isTypeDependent() && !Idx->getType()->isIntegerType())
5790           return ExprError(Diag(Idx->getLocStart(),
5791                                 diag::err_typecheck_subscript_not_integer)
5792             << Idx->getSourceRange());
5793
5794         Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
5795                                                OC.LocEnd);
5796         continue;
5797       }
5798
5799       const RecordType *RC = Res->getType()->getAs<RecordType>();
5800       if (!RC) {
5801         Res->Destroy(Context);
5802         return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
5803           << Res->getType());
5804       }
5805
5806       // Get the decl corresponding to this.
5807       RecordDecl *RD = RC->getDecl();
5808       if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
5809         if (!CRD->isPOD() && !DidWarnAboutNonPOD) {
5810           ExprError(Diag(BuiltinLoc, diag::warn_offsetof_non_pod_type)
5811             << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
5812             << Res->getType());
5813           DidWarnAboutNonPOD = true;
5814         }
5815       }
5816
5817       LookupResult R;
5818       LookupQualifiedName(R, RD, OC.U.IdentInfo, LookupMemberName);
5819
5820       FieldDecl *MemberDecl
5821         = dyn_cast_or_null<FieldDecl>(R.getAsSingleDecl(Context));
5822       // FIXME: Leaks Res
5823       if (!MemberDecl)
5824         return ExprError(Diag(BuiltinLoc, diag::err_no_member)
5825          << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, OC.LocEnd));
5826
5827       // FIXME: C++: Verify that MemberDecl isn't a static field.
5828       // FIXME: Verify that MemberDecl isn't a bitfield.
5829       if (cast<RecordDecl>(MemberDecl->getDeclContext())->isAnonymousStructOrUnion()) {
5830         Res = BuildAnonymousStructUnionMemberReference(
5831             SourceLocation(), MemberDecl, Res, SourceLocation()).takeAs<Expr>();
5832       } else {
5833         // MemberDecl->getType() doesn't get the right qualifiers, but it
5834         // doesn't matter here.
5835         Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
5836                 MemberDecl->getType().getNonReferenceType());
5837       }
5838     }
5839   }
5840
5841   return Owned(new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
5842                                            Context.getSizeType(), BuiltinLoc));
5843 }
5844
5845
5846 Sema::OwningExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
5847                                                       TypeTy *arg1,TypeTy *arg2,
5848                                                       SourceLocation RPLoc) {
5849   // FIXME: Preserve type source info.
5850   QualType argT1 = GetTypeFromParser(arg1);
5851   QualType argT2 = GetTypeFromParser(arg2);
5852
5853   assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
5854
5855   if (getLangOptions().CPlusPlus) {
5856     Diag(BuiltinLoc, diag::err_types_compatible_p_in_cplusplus)
5857       << SourceRange(BuiltinLoc, RPLoc);
5858     return ExprError();
5859   }
5860
5861   return Owned(new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc,
5862                                                  argT1, argT2, RPLoc));
5863 }
5864
5865 Sema::OwningExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
5866                                              ExprArg cond,
5867                                              ExprArg expr1, ExprArg expr2,
5868                                              SourceLocation RPLoc) {
5869   Expr *CondExpr = static_cast<Expr*>(cond.get());
5870   Expr *LHSExpr = static_cast<Expr*>(expr1.get());
5871   Expr *RHSExpr = static_cast<Expr*>(expr2.get());
5872
5873   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
5874
5875   QualType resType;
5876   bool ValueDependent = false;
5877   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
5878     resType = Context.DependentTy;
5879     ValueDependent = true;
5880   } else {
5881     // The conditional expression is required to be a constant expression.
5882     llvm::APSInt condEval(32);
5883     SourceLocation ExpLoc;
5884     if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
5885       return ExprError(Diag(ExpLoc,
5886                        diag::err_typecheck_choose_expr_requires_constant)
5887         << CondExpr->getSourceRange());
5888
5889     // If the condition is > zero, then the AST type is the same as the LSHExpr.
5890     resType = condEval.getZExtValue() ? LHSExpr->getType() : RHSExpr->getType();
5891     ValueDependent = condEval.getZExtValue() ? LHSExpr->isValueDependent()
5892                                              : RHSExpr->isValueDependent();
5893   }
5894
5895   cond.release(); expr1.release(); expr2.release();
5896   return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
5897                                         resType, RPLoc,
5898                                         resType->isDependentType(),
5899                                         ValueDependent));
5900 }
5901
5902 //===----------------------------------------------------------------------===//
5903 // Clang Extensions.
5904 //===----------------------------------------------------------------------===//
5905
5906 /// ActOnBlockStart - This callback is invoked when a block literal is started.
5907 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
5908   // Analyze block parameters.
5909   BlockSemaInfo *BSI = new BlockSemaInfo();
5910
5911   // Add BSI to CurBlock.
5912   BSI->PrevBlockInfo = CurBlock;
5913   CurBlock = BSI;
5914
5915   BSI->ReturnType = QualType();
5916   BSI->TheScope = BlockScope;
5917   BSI->hasBlockDeclRefExprs = false;
5918   BSI->hasPrototype = false;
5919   BSI->SavedFunctionNeedsScopeChecking = CurFunctionNeedsScopeChecking;
5920   CurFunctionNeedsScopeChecking = false;
5921
5922   BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
5923   PushDeclContext(BlockScope, BSI->TheDecl);
5924 }
5925
5926 void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
5927   assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
5928
5929   if (ParamInfo.getNumTypeObjects() == 0
5930       || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) {
5931     ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
5932     QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
5933
5934     if (T->isArrayType()) {
5935       Diag(ParamInfo.getSourceRange().getBegin(),
5936            diag::err_block_returns_array);
5937       return;
5938     }
5939
5940     // The parameter list is optional, if there was none, assume ().
5941     if (!T->isFunctionType())
5942       T = Context.getFunctionType(T, NULL, 0, 0, 0);
5943
5944     CurBlock->hasPrototype = true;
5945     CurBlock->isVariadic = false;
5946     // Check for a valid sentinel attribute on this block.
5947     if (CurBlock->TheDecl->getAttr<SentinelAttr>()) {
5948       Diag(ParamInfo.getAttributes()->getLoc(),
5949            diag::warn_attribute_sentinel_not_variadic) << 1;
5950       // FIXME: remove the attribute.
5951     }
5952     QualType RetTy = T.getTypePtr()->getAs<FunctionType>()->getResultType();
5953
5954     // Do not allow returning a objc interface by-value.
5955     if (RetTy->isObjCInterfaceType()) {
5956       Diag(ParamInfo.getSourceRange().getBegin(),
5957            diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
5958       return;
5959     }
5960     return;
5961   }
5962
5963   // Analyze arguments to block.
5964   assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
5965          "Not a function declarator!");
5966   DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
5967
5968   CurBlock->hasPrototype = FTI.hasPrototype;
5969   CurBlock->isVariadic = true;
5970
5971   // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
5972   // no arguments, not a function that takes a single void argument.
5973   if (FTI.hasPrototype &&
5974       FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
5975      (!FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType().getCVRQualifiers()&&
5976         FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType())) {
5977     // empty arg list, don't push any params.
5978     CurBlock->isVariadic = false;
5979   } else if (FTI.hasPrototype) {
5980     for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
5981       CurBlock->Params.push_back(FTI.ArgInfo[i].Param.getAs<ParmVarDecl>());
5982     CurBlock->isVariadic = FTI.isVariadic;
5983   }
5984   CurBlock->TheDecl->setParams(Context, CurBlock->Params.data(),
5985                                CurBlock->Params.size());
5986   CurBlock->TheDecl->setIsVariadic(CurBlock->isVariadic);
5987   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
5988   for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
5989        E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
5990     // If this has an identifier, add it to the scope stack.
5991     if ((*AI)->getIdentifier())
5992       PushOnScopeChains(*AI, CurBlock->TheScope);
5993
5994   // Check for a valid sentinel attribute on this block.
5995   if (!CurBlock->isVariadic &&
5996       CurBlock->TheDecl->getAttr<SentinelAttr>()) {
5997     Diag(ParamInfo.getAttributes()->getLoc(),
5998          diag::warn_attribute_sentinel_not_variadic) << 1;
5999     // FIXME: remove the attribute.
6000   }
6001
6002   // Analyze the return type.
6003   QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
6004   QualType RetTy = T->getAs<FunctionType>()->getResultType();
6005
6006   // Do not allow returning a objc interface by-value.
6007   if (RetTy->isObjCInterfaceType()) {
6008     Diag(ParamInfo.getSourceRange().getBegin(),
6009          diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
6010   } else if (!RetTy->isDependentType())
6011     CurBlock->ReturnType = RetTy;
6012 }
6013
6014 /// ActOnBlockError - If there is an error parsing a block, this callback
6015 /// is invoked to pop the information about the block from the action impl.
6016 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
6017   // Ensure that CurBlock is deleted.
6018   llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
6019
6020   CurFunctionNeedsScopeChecking = CurBlock->SavedFunctionNeedsScopeChecking;
6021
6022   // Pop off CurBlock, handle nested blocks.
6023   PopDeclContext();
6024   CurBlock = CurBlock->PrevBlockInfo;
6025   // FIXME: Delete the ParmVarDecl objects as well???
6026 }
6027
6028 /// ActOnBlockStmtExpr - This is called when the body of a block statement
6029 /// literal was successfully completed.  ^(int x){...}
6030 Sema::OwningExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
6031                                                 StmtArg body, Scope *CurScope) {
6032   // If blocks are disabled, emit an error.
6033   if (!LangOpts.Blocks)
6034     Diag(CaretLoc, diag::err_blocks_disable);
6035
6036   // Ensure that CurBlock is deleted.
6037   llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
6038
6039   PopDeclContext();
6040
6041   // Pop off CurBlock, handle nested blocks.
6042   CurBlock = CurBlock->PrevBlockInfo;
6043
6044   QualType RetTy = Context.VoidTy;
6045   if (!BSI->ReturnType.isNull())
6046     RetTy = BSI->ReturnType;
6047
6048   llvm::SmallVector<QualType, 8> ArgTypes;
6049   for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
6050     ArgTypes.push_back(BSI->Params[i]->getType());
6051
6052   bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
6053   QualType BlockTy;
6054   if (!BSI->hasPrototype)
6055     BlockTy = Context.getFunctionType(RetTy, 0, 0, false, 0, false, false, 0, 0,
6056                                       NoReturn);
6057   else
6058     BlockTy = Context.getFunctionType(RetTy, ArgTypes.data(), ArgTypes.size(),
6059                                       BSI->isVariadic, 0, false, false, 0, 0,
6060                                       NoReturn);
6061
6062   // FIXME: Check that return/parameter types are complete/non-abstract
6063   DiagnoseUnusedParameters(BSI->Params.begin(), BSI->Params.end());
6064   BlockTy = Context.getBlockPointerType(BlockTy);
6065
6066   // If needed, diagnose invalid gotos and switches in the block.
6067   if (CurFunctionNeedsScopeChecking)
6068     DiagnoseInvalidJumps(static_cast<CompoundStmt*>(body.get()));
6069   CurFunctionNeedsScopeChecking = BSI->SavedFunctionNeedsScopeChecking;
6070
6071   BSI->TheDecl->setBody(body.takeAs<CompoundStmt>());
6072   CheckFallThroughForBlock(BlockTy, BSI->TheDecl->getBody());
6073   return Owned(new (Context) BlockExpr(BSI->TheDecl, BlockTy,
6074                                        BSI->hasBlockDeclRefExprs));
6075 }
6076
6077 Sema::OwningExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
6078                                         ExprArg expr, TypeTy *type,
6079                                         SourceLocation RPLoc) {
6080   QualType T = GetTypeFromParser(type);
6081   Expr *E = static_cast<Expr*>(expr.get());
6082   Expr *OrigExpr = E;
6083
6084   InitBuiltinVaListType();
6085
6086   // Get the va_list type
6087   QualType VaListType = Context.getBuiltinVaListType();
6088   if (VaListType->isArrayType()) {
6089     // Deal with implicit array decay; for example, on x86-64,
6090     // va_list is an array, but it's supposed to decay to
6091     // a pointer for va_arg.
6092     VaListType = Context.getArrayDecayedType(VaListType);
6093     // Make sure the input expression also decays appropriately.
6094     UsualUnaryConversions(E);
6095   } else {
6096     // Otherwise, the va_list argument must be an l-value because
6097     // it is modified by va_arg.
6098     if (!E->isTypeDependent() &&
6099         CheckForModifiableLvalue(E, BuiltinLoc, *this))
6100       return ExprError();
6101   }
6102
6103   if (!E->isTypeDependent() &&
6104       !Context.hasSameType(VaListType, E->getType())) {
6105     return ExprError(Diag(E->getLocStart(),
6106                          diag::err_first_argument_to_va_arg_not_of_type_va_list)
6107       << OrigExpr->getType() << E->getSourceRange());
6108   }
6109
6110   // FIXME: Check that type is complete/non-abstract
6111   // FIXME: Warn if a non-POD type is passed in.
6112
6113   expr.release();
6114   return Owned(new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(),
6115                                        RPLoc));
6116 }
6117
6118 Sema::OwningExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
6119   // The type of __null will be int or long, depending on the size of
6120   // pointers on the target.
6121   QualType Ty;
6122   if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
6123     Ty = Context.IntTy;
6124   else
6125     Ty = Context.LongTy;
6126
6127   return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
6128 }
6129
6130 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
6131                                     SourceLocation Loc,
6132                                     QualType DstType, QualType SrcType,
6133                                     Expr *SrcExpr, const char *Flavor) {
6134   // Decode the result (notice that AST's are still created for extensions).
6135   bool isInvalid = false;
6136   unsigned DiagKind;
6137   switch (ConvTy) {
6138   default: assert(0 && "Unknown conversion type");
6139   case Compatible: return false;
6140   case PointerToInt:
6141     DiagKind = diag::ext_typecheck_convert_pointer_int;
6142     break;
6143   case IntToPointer:
6144     DiagKind = diag::ext_typecheck_convert_int_pointer;
6145     break;
6146   case IncompatiblePointer:
6147     DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
6148     break;
6149   case IncompatiblePointerSign:
6150     DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
6151     break;
6152   case FunctionVoidPointer:
6153     DiagKind = diag::ext_typecheck_convert_pointer_void_func;
6154     break;
6155   case CompatiblePointerDiscardsQualifiers:
6156     // If the qualifiers lost were because we were applying the
6157     // (deprecated) C++ conversion from a string literal to a char*
6158     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
6159     // Ideally, this check would be performed in
6160     // CheckPointerTypesForAssignment. However, that would require a
6161     // bit of refactoring (so that the second argument is an
6162     // expression, rather than a type), which should be done as part
6163     // of a larger effort to fix CheckPointerTypesForAssignment for
6164     // C++ semantics.
6165     if (getLangOptions().CPlusPlus &&
6166         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
6167       return false;
6168     DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
6169     break;
6170   case IntToBlockPointer:
6171     DiagKind = diag::err_int_to_block_pointer;
6172     break;
6173   case IncompatibleBlockPointer:
6174     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
6175     break;
6176   case IncompatibleObjCQualifiedId:
6177     // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
6178     // it can give a more specific diagnostic.
6179     DiagKind = diag::warn_incompatible_qualified_id;
6180     break;
6181   case IncompatibleVectors:
6182     DiagKind = diag::warn_incompatible_vectors;
6183     break;
6184   case Incompatible:
6185     DiagKind = diag::err_typecheck_convert_incompatible;
6186     isInvalid = true;
6187     break;
6188   }
6189
6190   Diag(Loc, DiagKind) << DstType << SrcType << Flavor
6191     << SrcExpr->getSourceRange();
6192   return isInvalid;
6193 }
6194
6195 bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
6196   llvm::APSInt ICEResult;
6197   if (E->isIntegerConstantExpr(ICEResult, Context)) {
6198     if (Result)
6199       *Result = ICEResult;
6200     return false;
6201   }
6202
6203   Expr::EvalResult EvalResult;
6204
6205   if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
6206       EvalResult.HasSideEffects) {
6207     Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
6208
6209     if (EvalResult.Diag) {
6210       // We only show the note if it's not the usual "invalid subexpression"
6211       // or if it's actually in a subexpression.
6212       if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
6213           E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
6214         Diag(EvalResult.DiagLoc, EvalResult.Diag);
6215     }
6216
6217     return true;
6218   }
6219
6220   Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
6221     E->getSourceRange();
6222
6223   if (EvalResult.Diag &&
6224       Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
6225     Diag(EvalResult.DiagLoc, EvalResult.Diag);
6226
6227   if (Result)
6228     *Result = EvalResult.Val.getInt();
6229   return false;
6230 }
6231
6232 Sema::ExpressionEvaluationContext
6233 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
6234   // Introduce a new set of potentially referenced declarations to the stack.
6235   if (NewContext == PotentiallyPotentiallyEvaluated)
6236     PotentiallyReferencedDeclStack.push_back(PotentiallyReferencedDecls());
6237
6238   std::swap(ExprEvalContext, NewContext);
6239   return NewContext;
6240 }
6241
6242 void
6243 Sema::PopExpressionEvaluationContext(ExpressionEvaluationContext OldContext,
6244                                      ExpressionEvaluationContext NewContext) {
6245   ExprEvalContext = NewContext;
6246
6247   if (OldContext == PotentiallyPotentiallyEvaluated) {
6248     // Mark any remaining declarations in the current position of the stack
6249     // as "referenced". If they were not meant to be referenced, semantic
6250     // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
6251     PotentiallyReferencedDecls RemainingDecls;
6252     RemainingDecls.swap(PotentiallyReferencedDeclStack.back());
6253     PotentiallyReferencedDeclStack.pop_back();
6254
6255     for (PotentiallyReferencedDecls::iterator I = RemainingDecls.begin(),
6256                                            IEnd = RemainingDecls.end();
6257          I != IEnd; ++I)
6258       MarkDeclarationReferenced(I->first, I->second);
6259   }
6260 }
6261
6262 /// \brief Note that the given declaration was referenced in the source code.
6263 ///
6264 /// This routine should be invoke whenever a given declaration is referenced
6265 /// in the source code, and where that reference occurred. If this declaration
6266 /// reference means that the the declaration is used (C++ [basic.def.odr]p2,
6267 /// C99 6.9p3), then the declaration will be marked as used.
6268 ///
6269 /// \param Loc the location where the declaration was referenced.
6270 ///
6271 /// \param D the declaration that has been referenced by the source code.
6272 void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
6273   assert(D && "No declaration?");
6274
6275   if (D->isUsed())
6276     return;
6277
6278   // Mark a parameter or variable declaration "used", regardless of whether we're in a
6279   // template or not. The reason for this is that unevaluated expressions
6280   // (e.g. (void)sizeof()) constitute a use for warning purposes (-Wunused-variables and
6281   // -Wunused-parameters)
6282   if (isa<ParmVarDecl>(D) || 
6283       (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod()))
6284     D->setUsed(true);
6285
6286   // Do not mark anything as "used" within a dependent context; wait for
6287   // an instantiation.
6288   if (CurContext->isDependentContext())
6289     return;
6290
6291   switch (ExprEvalContext) {
6292     case Unevaluated:
6293       // We are in an expression that is not potentially evaluated; do nothing.
6294       return;
6295
6296     case PotentiallyEvaluated:
6297       // We are in a potentially-evaluated expression, so this declaration is
6298       // "used"; handle this below.
6299       break;
6300
6301     case PotentiallyPotentiallyEvaluated:
6302       // We are in an expression that may be potentially evaluated; queue this
6303       // declaration reference until we know whether the expression is
6304       // potentially evaluated.
6305       PotentiallyReferencedDeclStack.back().push_back(std::make_pair(Loc, D));
6306       return;
6307   }
6308
6309   // Note that this declaration has been used.
6310   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
6311     unsigned TypeQuals;
6312     if (Constructor->isImplicit() && Constructor->isDefaultConstructor()) {
6313         if (!Constructor->isUsed())
6314           DefineImplicitDefaultConstructor(Loc, Constructor);
6315     } else if (Constructor->isImplicit() &&
6316                Constructor->isCopyConstructor(Context, TypeQuals)) {
6317       if (!Constructor->isUsed())
6318         DefineImplicitCopyConstructor(Loc, Constructor, TypeQuals);
6319     }
6320   } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
6321     if (Destructor->isImplicit() && !Destructor->isUsed())
6322       DefineImplicitDestructor(Loc, Destructor);
6323
6324   } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
6325     if (MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
6326         MethodDecl->getOverloadedOperator() == OO_Equal) {
6327       if (!MethodDecl->isUsed())
6328         DefineImplicitOverloadedAssign(Loc, MethodDecl);
6329     }
6330   }
6331   if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
6332     // Implicit instantiation of function templates and member functions of
6333     // class templates.
6334     if (!Function->getBody() && Function->isImplicitlyInstantiable()) {
6335       bool AlreadyInstantiated = false;
6336       if (FunctionTemplateSpecializationInfo *SpecInfo
6337                                 = Function->getTemplateSpecializationInfo()) {
6338         if (SpecInfo->getPointOfInstantiation().isInvalid())
6339           SpecInfo->setPointOfInstantiation(Loc);
6340         else if (SpecInfo->getTemplateSpecializationKind() 
6341                    == TSK_ImplicitInstantiation)
6342           AlreadyInstantiated = true;
6343       } else if (MemberSpecializationInfo *MSInfo 
6344                                   = Function->getMemberSpecializationInfo()) {
6345         if (MSInfo->getPointOfInstantiation().isInvalid())
6346           MSInfo->setPointOfInstantiation(Loc);
6347         else if (MSInfo->getTemplateSpecializationKind() 
6348                    == TSK_ImplicitInstantiation)
6349           AlreadyInstantiated = true;
6350       }
6351       
6352       if (!AlreadyInstantiated)
6353         PendingImplicitInstantiations.push_back(std::make_pair(Function, Loc));
6354     }
6355     
6356     // FIXME: keep track of references to static functions
6357     Function->setUsed(true);
6358     return;
6359   }
6360
6361   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
6362     // Implicit instantiation of static data members of class templates.
6363     if (Var->isStaticDataMember() &&
6364         Var->getInstantiatedFromStaticDataMember()) {
6365       MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
6366       assert(MSInfo && "Missing member specialization information?");
6367       if (MSInfo->getPointOfInstantiation().isInvalid() &&
6368           MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
6369         MSInfo->setPointOfInstantiation(Loc);
6370         PendingImplicitInstantiations.push_back(std::make_pair(Var, Loc));
6371       }
6372     }
6373
6374     // FIXME: keep track of references to static data?
6375
6376     D->setUsed(true);
6377     return;
6378   }
6379 }
6380
6381 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
6382                                CallExpr *CE, FunctionDecl *FD) {
6383   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
6384     return false;
6385
6386   PartialDiagnostic Note =
6387     FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
6388     << FD->getDeclName() : PDiag();
6389   SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
6390   
6391   if (RequireCompleteType(Loc, ReturnType,
6392                           FD ? 
6393                           PDiag(diag::err_call_function_incomplete_return)
6394                             << CE->getSourceRange() << FD->getDeclName() :
6395                           PDiag(diag::err_call_incomplete_return) 
6396                             << CE->getSourceRange(),
6397                           std::make_pair(NoteLoc, Note)))
6398     return true;
6399
6400   return false;
6401 }
6402
6403 // Diagnose the common s/=/==/ typo.  Note that adding parentheses
6404 // will prevent this condition from triggering, which is what we want.
6405 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
6406   SourceLocation Loc;
6407
6408   if (isa<BinaryOperator>(E)) {
6409     BinaryOperator *Op = cast<BinaryOperator>(E);
6410     if (Op->getOpcode() != BinaryOperator::Assign)
6411       return;
6412
6413     Loc = Op->getOperatorLoc();
6414   } else if (isa<CXXOperatorCallExpr>(E)) {
6415     CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(E);
6416     if (Op->getOperator() != OO_Equal)
6417       return;
6418
6419     Loc = Op->getOperatorLoc();
6420   } else {
6421     // Not an assignment.
6422     return;
6423   }
6424
6425   SourceLocation Open = E->getSourceRange().getBegin();
6426   SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
6427   
6428   Diag(Loc, diag::warn_condition_is_assignment)
6429     << E->getSourceRange()
6430     << CodeModificationHint::CreateInsertion(Open, "(")
6431     << CodeModificationHint::CreateInsertion(Close, ")");
6432 }
6433
6434 bool Sema::CheckBooleanCondition(Expr *&E, SourceLocation Loc) {
6435   DiagnoseAssignmentAsCondition(E);
6436
6437   if (!E->isTypeDependent()) {
6438     DefaultFunctionArrayConversion(E);
6439
6440     QualType T = E->getType();
6441
6442     if (getLangOptions().CPlusPlus) {
6443       if (CheckCXXBooleanCondition(E)) // C++ 6.4p4
6444         return true;
6445     } else if (!T->isScalarType()) { // C99 6.8.4.1p1
6446       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
6447         << T << E->getSourceRange();
6448       return true;
6449     }
6450   }
6451
6452   return false;
6453 }