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