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 "clang/Sema/SemaInternal.h"
15 #include "clang/Sema/DelayedDiagnostic.h"
16 #include "clang/Sema/Initialization.h"
17 #include "clang/Sema/Lookup.h"
18 #include "clang/Sema/ScopeInfo.h"
19 #include "clang/Sema/AnalysisBasedWarnings.h"
20 #include "clang/AST/ASTContext.h"
21 #include "clang/AST/ASTConsumer.h"
22 #include "clang/AST/ASTMutationListener.h"
23 #include "clang/AST/CXXInheritance.h"
24 #include "clang/AST/DeclObjC.h"
25 #include "clang/AST/DeclTemplate.h"
26 #include "clang/AST/EvaluatedExprVisitor.h"
27 #include "clang/AST/Expr.h"
28 #include "clang/AST/ExprCXX.h"
29 #include "clang/AST/ExprObjC.h"
30 #include "clang/AST/RecursiveASTVisitor.h"
31 #include "clang/AST/TypeLoc.h"
32 #include "clang/Basic/PartialDiagnostic.h"
33 #include "clang/Basic/SourceManager.h"
34 #include "clang/Basic/TargetInfo.h"
35 #include "clang/Lex/LiteralSupport.h"
36 #include "clang/Lex/Preprocessor.h"
37 #include "clang/Sema/DeclSpec.h"
38 #include "clang/Sema/Designator.h"
39 #include "clang/Sema/Scope.h"
40 #include "clang/Sema/ScopeInfo.h"
41 #include "clang/Sema/ParsedTemplate.h"
42 #include "clang/Sema/SemaFixItUtils.h"
43 #include "clang/Sema/Template.h"
44 #include "TreeTransform.h"
45 using namespace clang;
46 using namespace sema;
47 
48 /// \brief Determine whether the use of this declaration is valid, without
49 /// emitting diagnostics.
50 bool Sema::CanUseDecl(NamedDecl *D) {
51   // See if this is an auto-typed variable whose initializer we are parsing.
52   if (ParsingInitForAutoVars.count(D))
53     return false;
54 
55   // See if this is a deleted function.
56   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
57     if (FD->isDeleted())
58       return false;
59   }
60 
61   // See if this function is unavailable.
62   if (D->getAvailability() == AR_Unavailable &&
63       cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
64     return false;
65 
66   return true;
67 }
68 
69 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
70   // Warn if this is used but marked unused.
71   if (D->hasAttr<UnusedAttr>()) {
72     const Decl *DC = cast<Decl>(S.getCurObjCLexicalContext());
73     if (!DC->hasAttr<UnusedAttr>())
74       S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
75   }
76 }
77 
78 static AvailabilityResult DiagnoseAvailabilityOfDecl(Sema &S,
79                               NamedDecl *D, SourceLocation Loc,
80                               const ObjCInterfaceDecl *UnknownObjCClass) {
81   // See if this declaration is unavailable or deprecated.
82   std::string Message;
83   AvailabilityResult Result = D->getAvailability(&Message);
84   if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D))
85     if (Result == AR_Available) {
86       const DeclContext *DC = ECD->getDeclContext();
87       if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC))
88         Result = TheEnumDecl->getAvailability(&Message);
89     }
90 
91   switch (Result) {
92     case AR_Available:
93     case AR_NotYetIntroduced:
94       break;
95 
96     case AR_Deprecated:
97       S.EmitDeprecationWarning(D, Message, Loc, UnknownObjCClass);
98       break;
99 
100     case AR_Unavailable:
101       if (S.getCurContextAvailability() != AR_Unavailable) {
102         if (Message.empty()) {
103           if (!UnknownObjCClass)
104             S.Diag(Loc, diag::err_unavailable) << D->getDeclName();
105           else
106             S.Diag(Loc, diag::warn_unavailable_fwdclass_message)
107               << D->getDeclName();
108         }
109         else
110           S.Diag(Loc, diag::err_unavailable_message)
111             << D->getDeclName() << Message;
112           S.Diag(D->getLocation(), diag::note_unavailable_here)
113           << isa<FunctionDecl>(D) << false;
114       }
115       break;
116     }
117     return Result;
118 }
119 
120 /// \brief Emit a note explaining that this function is deleted or unavailable.
121 void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
122   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
123 
124   if (Method && Method->isDeleted() && !Method->isDeletedAsWritten()) {
125     // If the method was explicitly defaulted, point at that declaration.
126     if (!Method->isImplicit())
127       Diag(Decl->getLocation(), diag::note_implicitly_deleted);
128 
129     // Try to diagnose why this special member function was implicitly
130     // deleted. This might fail, if that reason no longer applies.
131     CXXSpecialMember CSM = getSpecialMember(Method);
132     if (CSM != CXXInvalid)
133       ShouldDeleteSpecialMember(Method, CSM, /*Diagnose=*/true);
134 
135     return;
136   }
137 
138   Diag(Decl->getLocation(), diag::note_unavailable_here)
139     << 1 << Decl->isDeleted();
140 }
141 
142 /// \brief Determine whether a FunctionDecl was ever declared with an
143 /// explicit storage class.
144 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
145   for (FunctionDecl::redecl_iterator I = D->redecls_begin(),
146                                      E = D->redecls_end();
147        I != E; ++I) {
148     if (I->getStorageClassAsWritten() != SC_None)
149       return true;
150   }
151   return false;
152 }
153 
154 /// \brief Check whether we're in an extern inline function and referring to a
155 /// variable or function with internal linkage (C11 6.7.4p3).
156 ///
157 /// This is only a warning because we used to silently accept this code, but
158 /// in many cases it will not behave correctly. This is not enabled in C++ mode
159 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
160 /// and so while there may still be user mistakes, most of the time we can't
161 /// prove that there are errors.
162 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
163                                                       const NamedDecl *D,
164                                                       SourceLocation Loc) {
165   // This is disabled under C++; there are too many ways for this to fire in
166   // contexts where the warning is a false positive, or where it is technically
167   // correct but benign.
168   if (S.getLangOpts().CPlusPlus)
169     return;
170 
171   // Check if this is an inlined function or method.
172   FunctionDecl *Current = S.getCurFunctionDecl();
173   if (!Current)
174     return;
175   if (!Current->isInlined())
176     return;
177   if (Current->getLinkage() != ExternalLinkage)
178     return;
179 
180   // Check if the decl has internal linkage.
181   if (D->getLinkage() != InternalLinkage)
182     return;
183 
184   // Downgrade from ExtWarn to Extension if
185   //  (1) the supposedly external inline function is in the main file,
186   //      and probably won't be included anywhere else.
187   //  (2) the thing we're referencing is a pure function.
188   //  (3) the thing we're referencing is another inline function.
189   // This last can give us false negatives, but it's better than warning on
190   // wrappers for simple C library functions.
191   const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
192   bool DowngradeWarning = S.getSourceManager().isFromMainFile(Loc);
193   if (!DowngradeWarning && UsedFn)
194     DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
195 
196   S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline
197                                : diag::warn_internal_in_extern_inline)
198     << /*IsVar=*/!UsedFn << D;
199 
200   // Suggest "static" on the inline function, if possible.
201   if (!hasAnyExplicitStorageClass(Current)) {
202     const FunctionDecl *FirstDecl = Current->getCanonicalDecl();
203     SourceLocation DeclBegin = FirstDecl->getSourceRange().getBegin();
204     S.Diag(DeclBegin, diag::note_convert_inline_to_static)
205       << Current << FixItHint::CreateInsertion(DeclBegin, "static ");
206   }
207 
208   S.Diag(D->getCanonicalDecl()->getLocation(),
209          diag::note_internal_decl_declared_here)
210     << D;
211 }
212 
213 /// \brief Determine whether the use of this declaration is valid, and
214 /// emit any corresponding diagnostics.
215 ///
216 /// This routine diagnoses various problems with referencing
217 /// declarations that can occur when using a declaration. For example,
218 /// it might warn if a deprecated or unavailable declaration is being
219 /// used, or produce an error (and return true) if a C++0x deleted
220 /// function is being used.
221 ///
222 /// \returns true if there was an error (this declaration cannot be
223 /// referenced), false otherwise.
224 ///
225 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
226                              const ObjCInterfaceDecl *UnknownObjCClass) {
227   if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
228     // If there were any diagnostics suppressed by template argument deduction,
229     // emit them now.
230     llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >::iterator
231       Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
232     if (Pos != SuppressedDiagnostics.end()) {
233       SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second;
234       for (unsigned I = 0, N = Suppressed.size(); I != N; ++I)
235         Diag(Suppressed[I].first, Suppressed[I].second);
236 
237       // Clear out the list of suppressed diagnostics, so that we don't emit
238       // them again for this specialization. However, we don't obsolete this
239       // entry from the table, because we want to avoid ever emitting these
240       // diagnostics again.
241       Suppressed.clear();
242     }
243   }
244 
245   // See if this is an auto-typed variable whose initializer we are parsing.
246   if (ParsingInitForAutoVars.count(D)) {
247     Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
248       << D->getDeclName();
249     return true;
250   }
251 
252   // See if this is a deleted function.
253   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
254     if (FD->isDeleted()) {
255       Diag(Loc, diag::err_deleted_function_use);
256       NoteDeletedFunction(FD);
257       return true;
258     }
259   }
260   DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass);
261 
262   DiagnoseUnusedOfDecl(*this, D, Loc);
263 
264   diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
265 
266   return false;
267 }
268 
269 /// \brief Retrieve the message suffix that should be added to a
270 /// diagnostic complaining about the given function being deleted or
271 /// unavailable.
272 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
273   // FIXME: C++0x implicitly-deleted special member functions could be
274   // detected here so that we could improve diagnostics to say, e.g.,
275   // "base class 'A' had a deleted copy constructor".
276   if (FD->isDeleted())
277     return std::string();
278 
279   std::string Message;
280   if (FD->getAvailability(&Message))
281     return ": " + Message;
282 
283   return std::string();
284 }
285 
286 /// DiagnoseSentinelCalls - This routine checks whether a call or
287 /// message-send is to a declaration with the sentinel attribute, and
288 /// if so, it checks that the requirements of the sentinel are
289 /// satisfied.
290 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
291                                  Expr **args, unsigned numArgs) {
292   const SentinelAttr *attr = D->getAttr<SentinelAttr>();
293   if (!attr)
294     return;
295 
296   // The number of formal parameters of the declaration.
297   unsigned numFormalParams;
298 
299   // The kind of declaration.  This is also an index into a %select in
300   // the diagnostic.
301   enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
302 
303   if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
304     numFormalParams = MD->param_size();
305     calleeType = CT_Method;
306   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
307     numFormalParams = FD->param_size();
308     calleeType = CT_Function;
309   } else if (isa<VarDecl>(D)) {
310     QualType type = cast<ValueDecl>(D)->getType();
311     const FunctionType *fn = 0;
312     if (const PointerType *ptr = type->getAs<PointerType>()) {
313       fn = ptr->getPointeeType()->getAs<FunctionType>();
314       if (!fn) return;
315       calleeType = CT_Function;
316     } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
317       fn = ptr->getPointeeType()->castAs<FunctionType>();
318       calleeType = CT_Block;
319     } else {
320       return;
321     }
322 
323     if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
324       numFormalParams = proto->getNumArgs();
325     } else {
326       numFormalParams = 0;
327     }
328   } else {
329     return;
330   }
331 
332   // "nullPos" is the number of formal parameters at the end which
333   // effectively count as part of the variadic arguments.  This is
334   // useful if you would prefer to not have *any* formal parameters,
335   // but the language forces you to have at least one.
336   unsigned nullPos = attr->getNullPos();
337   assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
338   numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
339 
340   // The number of arguments which should follow the sentinel.
341   unsigned numArgsAfterSentinel = attr->getSentinel();
342 
343   // If there aren't enough arguments for all the formal parameters,
344   // the sentinel, and the args after the sentinel, complain.
345   if (numArgs < numFormalParams + numArgsAfterSentinel + 1) {
346     Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
347     Diag(D->getLocation(), diag::note_sentinel_here) << calleeType;
348     return;
349   }
350 
351   // Otherwise, find the sentinel expression.
352   Expr *sentinelExpr = args[numArgs - numArgsAfterSentinel - 1];
353   if (!sentinelExpr) return;
354   if (sentinelExpr->isValueDependent()) return;
355   if (Context.isSentinelNullExpr(sentinelExpr)) return;
356 
357   // Pick a reasonable string to insert.  Optimistically use 'nil' or
358   // 'NULL' if those are actually defined in the context.  Only use
359   // 'nil' for ObjC methods, where it's much more likely that the
360   // variadic arguments form a list of object pointers.
361   SourceLocation MissingNilLoc
362     = PP.getLocForEndOfToken(sentinelExpr->getLocEnd());
363   std::string NullValue;
364   if (calleeType == CT_Method &&
365       PP.getIdentifierInfo("nil")->hasMacroDefinition())
366     NullValue = "nil";
367   else if (PP.getIdentifierInfo("NULL")->hasMacroDefinition())
368     NullValue = "NULL";
369   else
370     NullValue = "(void*) 0";
371 
372   if (MissingNilLoc.isInvalid())
373     Diag(Loc, diag::warn_missing_sentinel) << calleeType;
374   else
375     Diag(MissingNilLoc, diag::warn_missing_sentinel)
376       << calleeType
377       << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
378   Diag(D->getLocation(), diag::note_sentinel_here) << calleeType;
379 }
380 
381 SourceRange Sema::getExprRange(Expr *E) const {
382   return E ? E->getSourceRange() : SourceRange();
383 }
384 
385 //===----------------------------------------------------------------------===//
386 //  Standard Promotions and Conversions
387 //===----------------------------------------------------------------------===//
388 
389 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
390 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) {
391   // Handle any placeholder expressions which made it here.
392   if (E->getType()->isPlaceholderType()) {
393     ExprResult result = CheckPlaceholderExpr(E);
394     if (result.isInvalid()) return ExprError();
395     E = result.take();
396   }
397 
398   QualType Ty = E->getType();
399   assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
400 
401   if (Ty->isFunctionType())
402     E = ImpCastExprToType(E, Context.getPointerType(Ty),
403                           CK_FunctionToPointerDecay).take();
404   else if (Ty->isArrayType()) {
405     // In C90 mode, arrays only promote to pointers if the array expression is
406     // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
407     // type 'array of type' is converted to an expression that has type 'pointer
408     // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
409     // that has type 'array of type' ...".  The relevant change is "an lvalue"
410     // (C90) to "an expression" (C99).
411     //
412     // C++ 4.2p1:
413     // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
414     // T" can be converted to an rvalue of type "pointer to T".
415     //
416     if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
417       E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
418                             CK_ArrayToPointerDecay).take();
419   }
420   return Owned(E);
421 }
422 
423 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
424   // Check to see if we are dereferencing a null pointer.  If so,
425   // and if not volatile-qualified, this is undefined behavior that the
426   // optimizer will delete, so warn about it.  People sometimes try to use this
427   // to get a deterministic trap and are surprised by clang's behavior.  This
428   // only handles the pattern "*null", which is a very syntactic check.
429   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
430     if (UO->getOpcode() == UO_Deref &&
431         UO->getSubExpr()->IgnoreParenCasts()->
432           isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
433         !UO->getType().isVolatileQualified()) {
434     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
435                           S.PDiag(diag::warn_indirection_through_null)
436                             << UO->getSubExpr()->getSourceRange());
437     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
438                         S.PDiag(diag::note_indirection_through_null));
439   }
440 }
441 
442 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
443   // Handle any placeholder expressions which made it here.
444   if (E->getType()->isPlaceholderType()) {
445     ExprResult result = CheckPlaceholderExpr(E);
446     if (result.isInvalid()) return ExprError();
447     E = result.take();
448   }
449 
450   // C++ [conv.lval]p1:
451   //   A glvalue of a non-function, non-array type T can be
452   //   converted to a prvalue.
453   if (!E->isGLValue()) return Owned(E);
454 
455   QualType T = E->getType();
456   assert(!T.isNull() && "r-value conversion on typeless expression?");
457 
458   // We don't want to throw lvalue-to-rvalue casts on top of
459   // expressions of certain types in C++.
460   if (getLangOpts().CPlusPlus &&
461       (E->getType() == Context.OverloadTy ||
462        T->isDependentType() ||
463        T->isRecordType()))
464     return Owned(E);
465 
466   // The C standard is actually really unclear on this point, and
467   // DR106 tells us what the result should be but not why.  It's
468   // generally best to say that void types just doesn't undergo
469   // lvalue-to-rvalue at all.  Note that expressions of unqualified
470   // 'void' type are never l-values, but qualified void can be.
471   if (T->isVoidType())
472     return Owned(E);
473 
474   CheckForNullPointerDereference(*this, E);
475 
476   // C++ [conv.lval]p1:
477   //   [...] If T is a non-class type, the type of the prvalue is the
478   //   cv-unqualified version of T. Otherwise, the type of the
479   //   rvalue is T.
480   //
481   // C99 6.3.2.1p2:
482   //   If the lvalue has qualified type, the value has the unqualified
483   //   version of the type of the lvalue; otherwise, the value has the
484   //   type of the lvalue.
485   if (T.hasQualifiers())
486     T = T.getUnqualifiedType();
487 
488   UpdateMarkingForLValueToRValue(E);
489 
490   ExprResult Res = Owned(ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
491                                                   E, 0, VK_RValue));
492 
493   // C11 6.3.2.1p2:
494   //   ... if the lvalue has atomic type, the value has the non-atomic version
495   //   of the type of the lvalue ...
496   if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
497     T = Atomic->getValueType().getUnqualifiedType();
498     Res = Owned(ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic,
499                                          Res.get(), 0, VK_RValue));
500   }
501 
502   return Res;
503 }
504 
505 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) {
506   ExprResult Res = DefaultFunctionArrayConversion(E);
507   if (Res.isInvalid())
508     return ExprError();
509   Res = DefaultLvalueConversion(Res.take());
510   if (Res.isInvalid())
511     return ExprError();
512   return Res;
513 }
514 
515 
516 /// UsualUnaryConversions - Performs various conversions that are common to most
517 /// operators (C99 6.3). The conversions of array and function types are
518 /// sometimes suppressed. For example, the array->pointer conversion doesn't
519 /// apply if the array is an argument to the sizeof or address (&) operators.
520 /// In these instances, this routine should *not* be called.
521 ExprResult Sema::UsualUnaryConversions(Expr *E) {
522   // First, convert to an r-value.
523   ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
524   if (Res.isInvalid())
525     return Owned(E);
526   E = Res.take();
527 
528   QualType Ty = E->getType();
529   assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
530 
531   // Half FP is a bit different: it's a storage-only type, meaning that any
532   // "use" of it should be promoted to float.
533   if (Ty->isHalfType())
534     return ImpCastExprToType(Res.take(), Context.FloatTy, CK_FloatingCast);
535 
536   // Try to perform integral promotions if the object has a theoretically
537   // promotable type.
538   if (Ty->isIntegralOrUnscopedEnumerationType()) {
539     // C99 6.3.1.1p2:
540     //
541     //   The following may be used in an expression wherever an int or
542     //   unsigned int may be used:
543     //     - an object or expression with an integer type whose integer
544     //       conversion rank is less than or equal to the rank of int
545     //       and unsigned int.
546     //     - A bit-field of type _Bool, int, signed int, or unsigned int.
547     //
548     //   If an int can represent all values of the original type, the
549     //   value is converted to an int; otherwise, it is converted to an
550     //   unsigned int. These are called the integer promotions. All
551     //   other types are unchanged by the integer promotions.
552 
553     QualType PTy = Context.isPromotableBitField(E);
554     if (!PTy.isNull()) {
555       E = ImpCastExprToType(E, PTy, CK_IntegralCast).take();
556       return Owned(E);
557     }
558     if (Ty->isPromotableIntegerType()) {
559       QualType PT = Context.getPromotedIntegerType(Ty);
560       E = ImpCastExprToType(E, PT, CK_IntegralCast).take();
561       return Owned(E);
562     }
563   }
564   return Owned(E);
565 }
566 
567 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
568 /// do not have a prototype. Arguments that have type float are promoted to
569 /// double. All other argument types are converted by UsualUnaryConversions().
570 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
571   QualType Ty = E->getType();
572   assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
573 
574   ExprResult Res = UsualUnaryConversions(E);
575   if (Res.isInvalid())
576     return Owned(E);
577   E = Res.take();
578 
579   // If this is a 'float' (CVR qualified or typedef) promote to double.
580   if (Ty->isSpecificBuiltinType(BuiltinType::Float))
581     E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).take();
582 
583   // C++ performs lvalue-to-rvalue conversion as a default argument
584   // promotion, even on class types, but note:
585   //   C++11 [conv.lval]p2:
586   //     When an lvalue-to-rvalue conversion occurs in an unevaluated
587   //     operand or a subexpression thereof the value contained in the
588   //     referenced object is not accessed. Otherwise, if the glvalue
589   //     has a class type, the conversion copy-initializes a temporary
590   //     of type T from the glvalue and the result of the conversion
591   //     is a prvalue for the temporary.
592   // FIXME: add some way to gate this entire thing for correctness in
593   // potentially potentially evaluated contexts.
594   if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
595     ExprResult Temp = PerformCopyInitialization(
596                        InitializedEntity::InitializeTemporary(E->getType()),
597                                                 E->getExprLoc(),
598                                                 Owned(E));
599     if (Temp.isInvalid())
600       return ExprError();
601     E = Temp.get();
602   }
603 
604   return Owned(E);
605 }
606 
607 /// Determine the degree of POD-ness for an expression.
608 /// Incomplete types are considered POD, since this check can be performed
609 /// when we're in an unevaluated context.
610 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
611   if (Ty->isIncompleteType()) {
612     if (Ty->isObjCObjectType())
613       return VAK_Invalid;
614     return VAK_Valid;
615   }
616 
617   if (Ty.isCXX98PODType(Context))
618     return VAK_Valid;
619 
620   // C++0x [expr.call]p7:
621   //   Passing a potentially-evaluated argument of class type (Clause 9)
622   //   having a non-trivial copy constructor, a non-trivial move constructor,
623   //   or a non-trivial destructor, with no corresponding parameter,
624   //   is conditionally-supported with implementation-defined semantics.
625   if (getLangOpts().CPlusPlus0x && !Ty->isDependentType())
626     if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
627       if (Record->hasTrivialCopyConstructor() &&
628           Record->hasTrivialMoveConstructor() &&
629           Record->hasTrivialDestructor())
630         return VAK_ValidInCXX11;
631 
632   if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
633     return VAK_Valid;
634   return VAK_Invalid;
635 }
636 
637 bool Sema::variadicArgumentPODCheck(const Expr *E, VariadicCallType CT) {
638   // Don't allow one to pass an Objective-C interface to a vararg.
639   const QualType & Ty = E->getType();
640 
641   // Complain about passing non-POD types through varargs.
642   switch (isValidVarArgType(Ty)) {
643   case VAK_Valid:
644     break;
645   case VAK_ValidInCXX11:
646     DiagRuntimeBehavior(E->getLocStart(), 0,
647         PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
648         << E->getType() << CT);
649     break;
650   case VAK_Invalid: {
651     if (Ty->isObjCObjectType())
652       return DiagRuntimeBehavior(E->getLocStart(), 0,
653                           PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
654                             << Ty << CT);
655 
656     return DiagRuntimeBehavior(E->getLocStart(), 0,
657                    PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
658                    << getLangOpts().CPlusPlus0x << Ty << CT);
659   }
660   }
661   // c++ rules are enforced elsewhere.
662   return false;
663 }
664 
665 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
666 /// will create a trap if the resulting type is not a POD type.
667 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
668                                                   FunctionDecl *FDecl) {
669   if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
670     // Strip the unbridged-cast placeholder expression off, if applicable.
671     if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
672         (CT == VariadicMethod ||
673          (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
674       E = stripARCUnbridgedCast(E);
675 
676     // Otherwise, do normal placeholder checking.
677     } else {
678       ExprResult ExprRes = CheckPlaceholderExpr(E);
679       if (ExprRes.isInvalid())
680         return ExprError();
681       E = ExprRes.take();
682     }
683   }
684 
685   ExprResult ExprRes = DefaultArgumentPromotion(E);
686   if (ExprRes.isInvalid())
687     return ExprError();
688   E = ExprRes.take();
689 
690   // Diagnostics regarding non-POD argument types are
691   // emitted along with format string checking in Sema::CheckFunctionCall().
692   if (isValidVarArgType(E->getType()) == VAK_Invalid) {
693     // Turn this into a trap.
694     CXXScopeSpec SS;
695     SourceLocation TemplateKWLoc;
696     UnqualifiedId Name;
697     Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
698                        E->getLocStart());
699     ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
700                                           Name, true, false);
701     if (TrapFn.isInvalid())
702       return ExprError();
703 
704     ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(),
705                                     E->getLocStart(), MultiExprArg(),
706                                     E->getLocEnd());
707     if (Call.isInvalid())
708       return ExprError();
709 
710     ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
711                                   Call.get(), E);
712     if (Comma.isInvalid())
713       return ExprError();
714     return Comma.get();
715   }
716 
717   if (!getLangOpts().CPlusPlus &&
718       RequireCompleteType(E->getExprLoc(), E->getType(),
719                           diag::err_call_incomplete_argument))
720     return ExprError();
721 
722   return Owned(E);
723 }
724 
725 /// \brief Converts an integer to complex float type.  Helper function of
726 /// UsualArithmeticConversions()
727 ///
728 /// \return false if the integer expression is an integer type and is
729 /// successfully converted to the complex type.
730 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
731                                                   ExprResult &ComplexExpr,
732                                                   QualType IntTy,
733                                                   QualType ComplexTy,
734                                                   bool SkipCast) {
735   if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
736   if (SkipCast) return false;
737   if (IntTy->isIntegerType()) {
738     QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
739     IntExpr = S.ImpCastExprToType(IntExpr.take(), fpTy, CK_IntegralToFloating);
740     IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
741                                   CK_FloatingRealToComplex);
742   } else {
743     assert(IntTy->isComplexIntegerType());
744     IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
745                                   CK_IntegralComplexToFloatingComplex);
746   }
747   return false;
748 }
749 
750 /// \brief Takes two complex float types and converts them to the same type.
751 /// Helper function of UsualArithmeticConversions()
752 static QualType
753 handleComplexFloatToComplexFloatConverstion(Sema &S, ExprResult &LHS,
754                                             ExprResult &RHS, QualType LHSType,
755                                             QualType RHSType,
756                                             bool IsCompAssign) {
757   int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
758 
759   if (order < 0) {
760     // _Complex float -> _Complex double
761     if (!IsCompAssign)
762       LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingComplexCast);
763     return RHSType;
764   }
765   if (order > 0)
766     // _Complex float -> _Complex double
767     RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingComplexCast);
768   return LHSType;
769 }
770 
771 /// \brief Converts otherExpr to complex float and promotes complexExpr if
772 /// necessary.  Helper function of UsualArithmeticConversions()
773 static QualType handleOtherComplexFloatConversion(Sema &S,
774                                                   ExprResult &ComplexExpr,
775                                                   ExprResult &OtherExpr,
776                                                   QualType ComplexTy,
777                                                   QualType OtherTy,
778                                                   bool ConvertComplexExpr,
779                                                   bool ConvertOtherExpr) {
780   int order = S.Context.getFloatingTypeOrder(ComplexTy, OtherTy);
781 
782   // If just the complexExpr is complex, the otherExpr needs to be converted,
783   // and the complexExpr might need to be promoted.
784   if (order > 0) { // complexExpr is wider
785     // float -> _Complex double
786     if (ConvertOtherExpr) {
787       QualType fp = cast<ComplexType>(ComplexTy)->getElementType();
788       OtherExpr = S.ImpCastExprToType(OtherExpr.take(), fp, CK_FloatingCast);
789       OtherExpr = S.ImpCastExprToType(OtherExpr.take(), ComplexTy,
790                                       CK_FloatingRealToComplex);
791     }
792     return ComplexTy;
793   }
794 
795   // otherTy is at least as wide.  Find its corresponding complex type.
796   QualType result = (order == 0 ? ComplexTy :
797                                   S.Context.getComplexType(OtherTy));
798 
799   // double -> _Complex double
800   if (ConvertOtherExpr)
801     OtherExpr = S.ImpCastExprToType(OtherExpr.take(), result,
802                                     CK_FloatingRealToComplex);
803 
804   // _Complex float -> _Complex double
805   if (ConvertComplexExpr && order < 0)
806     ComplexExpr = S.ImpCastExprToType(ComplexExpr.take(), result,
807                                       CK_FloatingComplexCast);
808 
809   return result;
810 }
811 
812 /// \brief Handle arithmetic conversion with complex types.  Helper function of
813 /// UsualArithmeticConversions()
814 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
815                                              ExprResult &RHS, QualType LHSType,
816                                              QualType RHSType,
817                                              bool IsCompAssign) {
818   // if we have an integer operand, the result is the complex type.
819   if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
820                                              /*skipCast*/false))
821     return LHSType;
822   if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
823                                              /*skipCast*/IsCompAssign))
824     return RHSType;
825 
826   // This handles complex/complex, complex/float, or float/complex.
827   // When both operands are complex, the shorter operand is converted to the
828   // type of the longer, and that is the type of the result. This corresponds
829   // to what is done when combining two real floating-point operands.
830   // The fun begins when size promotion occur across type domains.
831   // From H&S 6.3.4: When one operand is complex and the other is a real
832   // floating-point type, the less precise type is converted, within it's
833   // real or complex domain, to the precision of the other type. For example,
834   // when combining a "long double" with a "double _Complex", the
835   // "double _Complex" is promoted to "long double _Complex".
836 
837   bool LHSComplexFloat = LHSType->isComplexType();
838   bool RHSComplexFloat = RHSType->isComplexType();
839 
840   // If both are complex, just cast to the more precise type.
841   if (LHSComplexFloat && RHSComplexFloat)
842     return handleComplexFloatToComplexFloatConverstion(S, LHS, RHS,
843                                                        LHSType, RHSType,
844                                                        IsCompAssign);
845 
846   // If only one operand is complex, promote it if necessary and convert the
847   // other operand to complex.
848   if (LHSComplexFloat)
849     return handleOtherComplexFloatConversion(
850         S, LHS, RHS, LHSType, RHSType, /*convertComplexExpr*/!IsCompAssign,
851         /*convertOtherExpr*/ true);
852 
853   assert(RHSComplexFloat);
854   return handleOtherComplexFloatConversion(
855       S, RHS, LHS, RHSType, LHSType, /*convertComplexExpr*/true,
856       /*convertOtherExpr*/ !IsCompAssign);
857 }
858 
859 /// \brief Hande arithmetic conversion from integer to float.  Helper function
860 /// of UsualArithmeticConversions()
861 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
862                                            ExprResult &IntExpr,
863                                            QualType FloatTy, QualType IntTy,
864                                            bool ConvertFloat, bool ConvertInt) {
865   if (IntTy->isIntegerType()) {
866     if (ConvertInt)
867       // Convert intExpr to the lhs floating point type.
868       IntExpr = S.ImpCastExprToType(IntExpr.take(), FloatTy,
869                                     CK_IntegralToFloating);
870     return FloatTy;
871   }
872 
873   // Convert both sides to the appropriate complex float.
874   assert(IntTy->isComplexIntegerType());
875   QualType result = S.Context.getComplexType(FloatTy);
876 
877   // _Complex int -> _Complex float
878   if (ConvertInt)
879     IntExpr = S.ImpCastExprToType(IntExpr.take(), result,
880                                   CK_IntegralComplexToFloatingComplex);
881 
882   // float -> _Complex float
883   if (ConvertFloat)
884     FloatExpr = S.ImpCastExprToType(FloatExpr.take(), result,
885                                     CK_FloatingRealToComplex);
886 
887   return result;
888 }
889 
890 /// \brief Handle arithmethic conversion with floating point types.  Helper
891 /// function of UsualArithmeticConversions()
892 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
893                                       ExprResult &RHS, QualType LHSType,
894                                       QualType RHSType, bool IsCompAssign) {
895   bool LHSFloat = LHSType->isRealFloatingType();
896   bool RHSFloat = RHSType->isRealFloatingType();
897 
898   // If we have two real floating types, convert the smaller operand
899   // to the bigger result.
900   if (LHSFloat && RHSFloat) {
901     int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
902     if (order > 0) {
903       RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingCast);
904       return LHSType;
905     }
906 
907     assert(order < 0 && "illegal float comparison");
908     if (!IsCompAssign)
909       LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingCast);
910     return RHSType;
911   }
912 
913   if (LHSFloat)
914     return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
915                                       /*convertFloat=*/!IsCompAssign,
916                                       /*convertInt=*/ true);
917   assert(RHSFloat);
918   return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
919                                     /*convertInt=*/ true,
920                                     /*convertFloat=*/!IsCompAssign);
921 }
922 
923 /// \brief Handle conversions with GCC complex int extension.  Helper function
924 /// of UsualArithmeticConversions()
925 // FIXME: if the operands are (int, _Complex long), we currently
926 // don't promote the complex.  Also, signedness?
927 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
928                                            ExprResult &RHS, QualType LHSType,
929                                            QualType RHSType,
930                                            bool IsCompAssign) {
931   const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
932   const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
933 
934   if (LHSComplexInt && RHSComplexInt) {
935     int order = S.Context.getIntegerTypeOrder(LHSComplexInt->getElementType(),
936                                               RHSComplexInt->getElementType());
937     assert(order && "inequal types with equal element ordering");
938     if (order > 0) {
939       // _Complex int -> _Complex long
940       RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralComplexCast);
941       return LHSType;
942     }
943 
944     if (!IsCompAssign)
945       LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralComplexCast);
946     return RHSType;
947   }
948 
949   if (LHSComplexInt) {
950     // int -> _Complex int
951     // FIXME: This needs to take integer ranks into account
952     RHS = S.ImpCastExprToType(RHS.take(), LHSComplexInt->getElementType(),
953                               CK_IntegralCast);
954     RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralRealToComplex);
955     return LHSType;
956   }
957 
958   assert(RHSComplexInt);
959   // int -> _Complex int
960   // FIXME: This needs to take integer ranks into account
961   if (!IsCompAssign) {
962     LHS = S.ImpCastExprToType(LHS.take(), RHSComplexInt->getElementType(),
963                               CK_IntegralCast);
964     LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralRealToComplex);
965   }
966   return RHSType;
967 }
968 
969 /// \brief Handle integer arithmetic conversions.  Helper function of
970 /// UsualArithmeticConversions()
971 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
972                                         ExprResult &RHS, QualType LHSType,
973                                         QualType RHSType, bool IsCompAssign) {
974   // The rules for this case are in C99 6.3.1.8
975   int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
976   bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
977   bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
978   if (LHSSigned == RHSSigned) {
979     // Same signedness; use the higher-ranked type
980     if (order >= 0) {
981       RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
982       return LHSType;
983     } else if (!IsCompAssign)
984       LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
985     return RHSType;
986   } else if (order != (LHSSigned ? 1 : -1)) {
987     // The unsigned type has greater than or equal rank to the
988     // signed type, so use the unsigned type
989     if (RHSSigned) {
990       RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
991       return LHSType;
992     } else if (!IsCompAssign)
993       LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
994     return RHSType;
995   } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
996     // The two types are different widths; if we are here, that
997     // means the signed type is larger than the unsigned type, so
998     // use the signed type.
999     if (LHSSigned) {
1000       RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
1001       return LHSType;
1002     } else if (!IsCompAssign)
1003       LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
1004     return RHSType;
1005   } else {
1006     // The signed type is higher-ranked than the unsigned type,
1007     // but isn't actually any bigger (like unsigned int and long
1008     // on most 32-bit systems).  Use the unsigned type corresponding
1009     // to the signed type.
1010     QualType result =
1011       S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1012     RHS = S.ImpCastExprToType(RHS.take(), result, CK_IntegralCast);
1013     if (!IsCompAssign)
1014       LHS = S.ImpCastExprToType(LHS.take(), result, CK_IntegralCast);
1015     return result;
1016   }
1017 }
1018 
1019 /// UsualArithmeticConversions - Performs various conversions that are common to
1020 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1021 /// routine returns the first non-arithmetic type found. The client is
1022 /// responsible for emitting appropriate error diagnostics.
1023 /// FIXME: verify the conversion rules for "complex int" are consistent with
1024 /// GCC.
1025 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1026                                           bool IsCompAssign) {
1027   if (!IsCompAssign) {
1028     LHS = UsualUnaryConversions(LHS.take());
1029     if (LHS.isInvalid())
1030       return QualType();
1031   }
1032 
1033   RHS = UsualUnaryConversions(RHS.take());
1034   if (RHS.isInvalid())
1035     return QualType();
1036 
1037   // For conversion purposes, we ignore any qualifiers.
1038   // For example, "const float" and "float" are equivalent.
1039   QualType LHSType =
1040     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1041   QualType RHSType =
1042     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1043 
1044   // For conversion purposes, we ignore any atomic qualifier on the LHS.
1045   if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1046     LHSType = AtomicLHS->getValueType();
1047 
1048   // If both types are identical, no conversion is needed.
1049   if (LHSType == RHSType)
1050     return LHSType;
1051 
1052   // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1053   // The caller can deal with this (e.g. pointer + int).
1054   if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1055     return QualType();
1056 
1057   // Apply unary and bitfield promotions to the LHS's type.
1058   QualType LHSUnpromotedType = LHSType;
1059   if (LHSType->isPromotableIntegerType())
1060     LHSType = Context.getPromotedIntegerType(LHSType);
1061   QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1062   if (!LHSBitfieldPromoteTy.isNull())
1063     LHSType = LHSBitfieldPromoteTy;
1064   if (LHSType != LHSUnpromotedType && !IsCompAssign)
1065     LHS = ImpCastExprToType(LHS.take(), LHSType, CK_IntegralCast);
1066 
1067   // If both types are identical, no conversion is needed.
1068   if (LHSType == RHSType)
1069     return LHSType;
1070 
1071   // At this point, we have two different arithmetic types.
1072 
1073   // Handle complex types first (C99 6.3.1.8p1).
1074   if (LHSType->isComplexType() || RHSType->isComplexType())
1075     return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1076                                         IsCompAssign);
1077 
1078   // Now handle "real" floating types (i.e. float, double, long double).
1079   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1080     return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1081                                  IsCompAssign);
1082 
1083   // Handle GCC complex int extension.
1084   if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1085     return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1086                                       IsCompAssign);
1087 
1088   // Finally, we have two differing integer types.
1089   return handleIntegerConversion(*this, LHS, RHS, LHSType, RHSType,
1090                                  IsCompAssign);
1091 }
1092 
1093 //===----------------------------------------------------------------------===//
1094 //  Semantic Analysis for various Expression Types
1095 //===----------------------------------------------------------------------===//
1096 
1097 
1098 ExprResult
1099 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1100                                 SourceLocation DefaultLoc,
1101                                 SourceLocation RParenLoc,
1102                                 Expr *ControllingExpr,
1103                                 MultiTypeArg ArgTypes,
1104                                 MultiExprArg ArgExprs) {
1105   unsigned NumAssocs = ArgTypes.size();
1106   assert(NumAssocs == ArgExprs.size());
1107 
1108   ParsedType *ParsedTypes = ArgTypes.data();
1109   Expr **Exprs = ArgExprs.data();
1110 
1111   TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1112   for (unsigned i = 0; i < NumAssocs; ++i) {
1113     if (ParsedTypes[i])
1114       (void) GetTypeFromParser(ParsedTypes[i], &Types[i]);
1115     else
1116       Types[i] = 0;
1117   }
1118 
1119   ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1120                                              ControllingExpr, Types, Exprs,
1121                                              NumAssocs);
1122   delete [] Types;
1123   return ER;
1124 }
1125 
1126 ExprResult
1127 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1128                                  SourceLocation DefaultLoc,
1129                                  SourceLocation RParenLoc,
1130                                  Expr *ControllingExpr,
1131                                  TypeSourceInfo **Types,
1132                                  Expr **Exprs,
1133                                  unsigned NumAssocs) {
1134   bool TypeErrorFound = false,
1135        IsResultDependent = ControllingExpr->isTypeDependent(),
1136        ContainsUnexpandedParameterPack
1137          = ControllingExpr->containsUnexpandedParameterPack();
1138 
1139   for (unsigned i = 0; i < NumAssocs; ++i) {
1140     if (Exprs[i]->containsUnexpandedParameterPack())
1141       ContainsUnexpandedParameterPack = true;
1142 
1143     if (Types[i]) {
1144       if (Types[i]->getType()->containsUnexpandedParameterPack())
1145         ContainsUnexpandedParameterPack = true;
1146 
1147       if (Types[i]->getType()->isDependentType()) {
1148         IsResultDependent = true;
1149       } else {
1150         // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1151         // complete object type other than a variably modified type."
1152         unsigned D = 0;
1153         if (Types[i]->getType()->isIncompleteType())
1154           D = diag::err_assoc_type_incomplete;
1155         else if (!Types[i]->getType()->isObjectType())
1156           D = diag::err_assoc_type_nonobject;
1157         else if (Types[i]->getType()->isVariablyModifiedType())
1158           D = diag::err_assoc_type_variably_modified;
1159 
1160         if (D != 0) {
1161           Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1162             << Types[i]->getTypeLoc().getSourceRange()
1163             << Types[i]->getType();
1164           TypeErrorFound = true;
1165         }
1166 
1167         // C11 6.5.1.1p2 "No two generic associations in the same generic
1168         // selection shall specify compatible types."
1169         for (unsigned j = i+1; j < NumAssocs; ++j)
1170           if (Types[j] && !Types[j]->getType()->isDependentType() &&
1171               Context.typesAreCompatible(Types[i]->getType(),
1172                                          Types[j]->getType())) {
1173             Diag(Types[j]->getTypeLoc().getBeginLoc(),
1174                  diag::err_assoc_compatible_types)
1175               << Types[j]->getTypeLoc().getSourceRange()
1176               << Types[j]->getType()
1177               << Types[i]->getType();
1178             Diag(Types[i]->getTypeLoc().getBeginLoc(),
1179                  diag::note_compat_assoc)
1180               << Types[i]->getTypeLoc().getSourceRange()
1181               << Types[i]->getType();
1182             TypeErrorFound = true;
1183           }
1184       }
1185     }
1186   }
1187   if (TypeErrorFound)
1188     return ExprError();
1189 
1190   // If we determined that the generic selection is result-dependent, don't
1191   // try to compute the result expression.
1192   if (IsResultDependent)
1193     return Owned(new (Context) GenericSelectionExpr(
1194                    Context, KeyLoc, ControllingExpr,
1195                    llvm::makeArrayRef(Types, NumAssocs),
1196                    llvm::makeArrayRef(Exprs, NumAssocs),
1197                    DefaultLoc, RParenLoc, ContainsUnexpandedParameterPack));
1198 
1199   SmallVector<unsigned, 1> CompatIndices;
1200   unsigned DefaultIndex = -1U;
1201   for (unsigned i = 0; i < NumAssocs; ++i) {
1202     if (!Types[i])
1203       DefaultIndex = i;
1204     else if (Context.typesAreCompatible(ControllingExpr->getType(),
1205                                         Types[i]->getType()))
1206       CompatIndices.push_back(i);
1207   }
1208 
1209   // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1210   // type compatible with at most one of the types named in its generic
1211   // association list."
1212   if (CompatIndices.size() > 1) {
1213     // We strip parens here because the controlling expression is typically
1214     // parenthesized in macro definitions.
1215     ControllingExpr = ControllingExpr->IgnoreParens();
1216     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1217       << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1218       << (unsigned) CompatIndices.size();
1219     for (SmallVector<unsigned, 1>::iterator I = CompatIndices.begin(),
1220          E = CompatIndices.end(); I != E; ++I) {
1221       Diag(Types[*I]->getTypeLoc().getBeginLoc(),
1222            diag::note_compat_assoc)
1223         << Types[*I]->getTypeLoc().getSourceRange()
1224         << Types[*I]->getType();
1225     }
1226     return ExprError();
1227   }
1228 
1229   // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1230   // its controlling expression shall have type compatible with exactly one of
1231   // the types named in its generic association list."
1232   if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1233     // We strip parens here because the controlling expression is typically
1234     // parenthesized in macro definitions.
1235     ControllingExpr = ControllingExpr->IgnoreParens();
1236     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1237       << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1238     return ExprError();
1239   }
1240 
1241   // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1242   // type name that is compatible with the type of the controlling expression,
1243   // then the result expression of the generic selection is the expression
1244   // in that generic association. Otherwise, the result expression of the
1245   // generic selection is the expression in the default generic association."
1246   unsigned ResultIndex =
1247     CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1248 
1249   return Owned(new (Context) GenericSelectionExpr(
1250                  Context, KeyLoc, ControllingExpr,
1251                  llvm::makeArrayRef(Types, NumAssocs),
1252                  llvm::makeArrayRef(Exprs, NumAssocs),
1253                  DefaultLoc, RParenLoc, ContainsUnexpandedParameterPack,
1254                  ResultIndex));
1255 }
1256 
1257 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1258 /// location of the token and the offset of the ud-suffix within it.
1259 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1260                                      unsigned Offset) {
1261   return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1262                                         S.getLangOpts());
1263 }
1264 
1265 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1266 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1267 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1268                                                  IdentifierInfo *UDSuffix,
1269                                                  SourceLocation UDSuffixLoc,
1270                                                  ArrayRef<Expr*> Args,
1271                                                  SourceLocation LitEndLoc) {
1272   assert(Args.size() <= 2 && "too many arguments for literal operator");
1273 
1274   QualType ArgTy[2];
1275   for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1276     ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1277     if (ArgTy[ArgIdx]->isArrayType())
1278       ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1279   }
1280 
1281   DeclarationName OpName =
1282     S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1283   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1284   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1285 
1286   LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1287   if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1288                               /*AllowRawAndTemplate*/false) == Sema::LOLR_Error)
1289     return ExprError();
1290 
1291   return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1292 }
1293 
1294 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1295 /// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
1296 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1297 /// multiple tokens.  However, the common case is that StringToks points to one
1298 /// string.
1299 ///
1300 ExprResult
1301 Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks,
1302                          Scope *UDLScope) {
1303   assert(NumStringToks && "Must have at least one string!");
1304 
1305   StringLiteralParser Literal(StringToks, NumStringToks, PP);
1306   if (Literal.hadError)
1307     return ExprError();
1308 
1309   SmallVector<SourceLocation, 4> StringTokLocs;
1310   for (unsigned i = 0; i != NumStringToks; ++i)
1311     StringTokLocs.push_back(StringToks[i].getLocation());
1312 
1313   QualType StrTy = Context.CharTy;
1314   if (Literal.isWide())
1315     StrTy = Context.getWCharType();
1316   else if (Literal.isUTF16())
1317     StrTy = Context.Char16Ty;
1318   else if (Literal.isUTF32())
1319     StrTy = Context.Char32Ty;
1320   else if (Literal.isPascal())
1321     StrTy = Context.UnsignedCharTy;
1322 
1323   StringLiteral::StringKind Kind = StringLiteral::Ascii;
1324   if (Literal.isWide())
1325     Kind = StringLiteral::Wide;
1326   else if (Literal.isUTF8())
1327     Kind = StringLiteral::UTF8;
1328   else if (Literal.isUTF16())
1329     Kind = StringLiteral::UTF16;
1330   else if (Literal.isUTF32())
1331     Kind = StringLiteral::UTF32;
1332 
1333   // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
1334   if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
1335     StrTy.addConst();
1336 
1337   // Get an array type for the string, according to C99 6.4.5.  This includes
1338   // the nul terminator character as well as the string length for pascal
1339   // strings.
1340   StrTy = Context.getConstantArrayType(StrTy,
1341                                  llvm::APInt(32, Literal.GetNumStringChars()+1),
1342                                        ArrayType::Normal, 0);
1343 
1344   // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1345   StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1346                                              Kind, Literal.Pascal, StrTy,
1347                                              &StringTokLocs[0],
1348                                              StringTokLocs.size());
1349   if (Literal.getUDSuffix().empty())
1350     return Owned(Lit);
1351 
1352   // We're building a user-defined literal.
1353   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1354   SourceLocation UDSuffixLoc =
1355     getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1356                    Literal.getUDSuffixOffset());
1357 
1358   // Make sure we're allowed user-defined literals here.
1359   if (!UDLScope)
1360     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1361 
1362   // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1363   //   operator "" X (str, len)
1364   QualType SizeType = Context.getSizeType();
1365   llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1366   IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1367                                                   StringTokLocs[0]);
1368   Expr *Args[] = { Lit, LenArg };
1369   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
1370                                         Args, StringTokLocs.back());
1371 }
1372 
1373 ExprResult
1374 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1375                        SourceLocation Loc,
1376                        const CXXScopeSpec *SS) {
1377   DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1378   return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1379 }
1380 
1381 /// BuildDeclRefExpr - Build an expression that references a
1382 /// declaration that does not require a closure capture.
1383 ExprResult
1384 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1385                        const DeclarationNameInfo &NameInfo,
1386                        const CXXScopeSpec *SS) {
1387   if (getLangOpts().CUDA)
1388     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
1389       if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) {
1390         CUDAFunctionTarget CallerTarget = IdentifyCUDATarget(Caller),
1391                            CalleeTarget = IdentifyCUDATarget(Callee);
1392         if (CheckCUDATarget(CallerTarget, CalleeTarget)) {
1393           Diag(NameInfo.getLoc(), diag::err_ref_bad_target)
1394             << CalleeTarget << D->getIdentifier() << CallerTarget;
1395           Diag(D->getLocation(), diag::note_previous_decl)
1396             << D->getIdentifier();
1397           return ExprError();
1398         }
1399       }
1400 
1401   bool refersToEnclosingScope =
1402     (CurContext != D->getDeclContext() &&
1403      D->getDeclContext()->isFunctionOrMethod());
1404 
1405   DeclRefExpr *E = DeclRefExpr::Create(Context,
1406                                        SS ? SS->getWithLocInContext(Context)
1407                                               : NestedNameSpecifierLoc(),
1408                                        SourceLocation(),
1409                                        D, refersToEnclosingScope,
1410                                        NameInfo, Ty, VK);
1411 
1412   MarkDeclRefReferenced(E);
1413 
1414   // Just in case we're building an illegal pointer-to-member.
1415   FieldDecl *FD = dyn_cast<FieldDecl>(D);
1416   if (FD && FD->isBitField())
1417     E->setObjectKind(OK_BitField);
1418 
1419   return Owned(E);
1420 }
1421 
1422 /// Decomposes the given name into a DeclarationNameInfo, its location, and
1423 /// possibly a list of template arguments.
1424 ///
1425 /// If this produces template arguments, it is permitted to call
1426 /// DecomposeTemplateName.
1427 ///
1428 /// This actually loses a lot of source location information for
1429 /// non-standard name kinds; we should consider preserving that in
1430 /// some way.
1431 void
1432 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1433                              TemplateArgumentListInfo &Buffer,
1434                              DeclarationNameInfo &NameInfo,
1435                              const TemplateArgumentListInfo *&TemplateArgs) {
1436   if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1437     Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1438     Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1439 
1440     ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
1441                                        Id.TemplateId->NumArgs);
1442     translateTemplateArguments(TemplateArgsPtr, Buffer);
1443 
1444     TemplateName TName = Id.TemplateId->Template.get();
1445     SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1446     NameInfo = Context.getNameForTemplate(TName, TNameLoc);
1447     TemplateArgs = &Buffer;
1448   } else {
1449     NameInfo = GetNameFromUnqualifiedId(Id);
1450     TemplateArgs = 0;
1451   }
1452 }
1453 
1454 /// Diagnose an empty lookup.
1455 ///
1456 /// \return false if new lookup candidates were found
1457 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1458                                CorrectionCandidateCallback &CCC,
1459                                TemplateArgumentListInfo *ExplicitTemplateArgs,
1460                                llvm::ArrayRef<Expr *> Args) {
1461   DeclarationName Name = R.getLookupName();
1462 
1463   unsigned diagnostic = diag::err_undeclared_var_use;
1464   unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
1465   if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1466       Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
1467       Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
1468     diagnostic = diag::err_undeclared_use;
1469     diagnostic_suggest = diag::err_undeclared_use_suggest;
1470   }
1471 
1472   // If the original lookup was an unqualified lookup, fake an
1473   // unqualified lookup.  This is useful when (for example) the
1474   // original lookup would not have found something because it was a
1475   // dependent name.
1476   DeclContext *DC = (SS.isEmpty() && !CallsUndergoingInstantiation.empty())
1477     ? CurContext : 0;
1478   while (DC) {
1479     if (isa<CXXRecordDecl>(DC)) {
1480       LookupQualifiedName(R, DC);
1481 
1482       if (!R.empty()) {
1483         // Don't give errors about ambiguities in this lookup.
1484         R.suppressDiagnostics();
1485 
1486         // During a default argument instantiation the CurContext points
1487         // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1488         // function parameter list, hence add an explicit check.
1489         bool isDefaultArgument = !ActiveTemplateInstantiations.empty() &&
1490                               ActiveTemplateInstantiations.back().Kind ==
1491             ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
1492         CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1493         bool isInstance = CurMethod &&
1494                           CurMethod->isInstance() &&
1495                           DC == CurMethod->getParent() && !isDefaultArgument;
1496 
1497 
1498         // Give a code modification hint to insert 'this->'.
1499         // TODO: fixit for inserting 'Base<T>::' in the other cases.
1500         // Actually quite difficult!
1501         if (getLangOpts().MicrosoftMode)
1502           diagnostic = diag::warn_found_via_dependent_bases_lookup;
1503         if (isInstance) {
1504           Diag(R.getNameLoc(), diagnostic) << Name
1505             << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1506           UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1507               CallsUndergoingInstantiation.back()->getCallee());
1508 
1509 
1510           CXXMethodDecl *DepMethod;
1511           if (CurMethod->getTemplatedKind() ==
1512               FunctionDecl::TK_FunctionTemplateSpecialization)
1513             DepMethod = cast<CXXMethodDecl>(CurMethod->getPrimaryTemplate()->
1514                 getInstantiatedFromMemberTemplate()->getTemplatedDecl());
1515           else
1516             DepMethod = cast<CXXMethodDecl>(
1517                 CurMethod->getInstantiatedFromMemberFunction());
1518           assert(DepMethod && "No template pattern found");
1519 
1520           QualType DepThisType = DepMethod->getThisType(Context);
1521           CheckCXXThisCapture(R.getNameLoc());
1522           CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1523                                      R.getNameLoc(), DepThisType, false);
1524           TemplateArgumentListInfo TList;
1525           if (ULE->hasExplicitTemplateArgs())
1526             ULE->copyTemplateArgumentsInto(TList);
1527 
1528           CXXScopeSpec SS;
1529           SS.Adopt(ULE->getQualifierLoc());
1530           CXXDependentScopeMemberExpr *DepExpr =
1531               CXXDependentScopeMemberExpr::Create(
1532                   Context, DepThis, DepThisType, true, SourceLocation(),
1533                   SS.getWithLocInContext(Context),
1534                   ULE->getTemplateKeywordLoc(), 0,
1535                   R.getLookupNameInfo(),
1536                   ULE->hasExplicitTemplateArgs() ? &TList : 0);
1537           CallsUndergoingInstantiation.back()->setCallee(DepExpr);
1538         } else {
1539           Diag(R.getNameLoc(), diagnostic) << Name;
1540         }
1541 
1542         // Do we really want to note all of these?
1543         for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1544           Diag((*I)->getLocation(), diag::note_dependent_var_use);
1545 
1546         // Return true if we are inside a default argument instantiation
1547         // and the found name refers to an instance member function, otherwise
1548         // the function calling DiagnoseEmptyLookup will try to create an
1549         // implicit member call and this is wrong for default argument.
1550         if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1551           Diag(R.getNameLoc(), diag::err_member_call_without_object);
1552           return true;
1553         }
1554 
1555         // Tell the callee to try to recover.
1556         return false;
1557       }
1558 
1559       R.clear();
1560     }
1561 
1562     // In Microsoft mode, if we are performing lookup from within a friend
1563     // function definition declared at class scope then we must set
1564     // DC to the lexical parent to be able to search into the parent
1565     // class.
1566     if (getLangOpts().MicrosoftMode && isa<FunctionDecl>(DC) &&
1567         cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1568         DC->getLexicalParent()->isRecord())
1569       DC = DC->getLexicalParent();
1570     else
1571       DC = DC->getParent();
1572   }
1573 
1574   // We didn't find anything, so try to correct for a typo.
1575   TypoCorrection Corrected;
1576   if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
1577                                     S, &SS, CCC))) {
1578     std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1579     std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOpts()));
1580     R.setLookupName(Corrected.getCorrection());
1581 
1582     if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
1583       if (Corrected.isOverloaded()) {
1584         OverloadCandidateSet OCS(R.getNameLoc());
1585         OverloadCandidateSet::iterator Best;
1586         for (TypoCorrection::decl_iterator CD = Corrected.begin(),
1587                                         CDEnd = Corrected.end();
1588              CD != CDEnd; ++CD) {
1589           if (FunctionTemplateDecl *FTD =
1590                    dyn_cast<FunctionTemplateDecl>(*CD))
1591             AddTemplateOverloadCandidate(
1592                 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
1593                 Args, OCS);
1594           else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
1595             if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1596               AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
1597                                    Args, OCS);
1598         }
1599         switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1600           case OR_Success:
1601             ND = Best->Function;
1602             break;
1603           default:
1604             break;
1605         }
1606       }
1607       R.addDecl(ND);
1608       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
1609         if (SS.isEmpty())
1610           Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr
1611             << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1612         else
1613           Diag(R.getNameLoc(), diag::err_no_member_suggest)
1614             << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
1615             << SS.getRange()
1616             << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1617         if (ND)
1618           Diag(ND->getLocation(), diag::note_previous_decl)
1619             << CorrectedQuotedStr;
1620 
1621         // Tell the callee to try to recover.
1622         return false;
1623       }
1624 
1625       if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) {
1626         // FIXME: If we ended up with a typo for a type name or
1627         // Objective-C class name, we're in trouble because the parser
1628         // is in the wrong place to recover. Suggest the typo
1629         // correction, but don't make it a fix-it since we're not going
1630         // to recover well anyway.
1631         if (SS.isEmpty())
1632           Diag(R.getNameLoc(), diagnostic_suggest)
1633             << Name << CorrectedQuotedStr;
1634         else
1635           Diag(R.getNameLoc(), diag::err_no_member_suggest)
1636             << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
1637             << SS.getRange();
1638 
1639         // Don't try to recover; it won't work.
1640         return true;
1641       }
1642     } else {
1643       // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
1644       // because we aren't able to recover.
1645       if (SS.isEmpty())
1646         Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr;
1647       else
1648         Diag(R.getNameLoc(), diag::err_no_member_suggest)
1649         << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
1650         << SS.getRange();
1651       return true;
1652     }
1653   }
1654   R.clear();
1655 
1656   // Emit a special diagnostic for failed member lookups.
1657   // FIXME: computing the declaration context might fail here (?)
1658   if (!SS.isEmpty()) {
1659     Diag(R.getNameLoc(), diag::err_no_member)
1660       << Name << computeDeclContext(SS, false)
1661       << SS.getRange();
1662     return true;
1663   }
1664 
1665   // Give up, we can't recover.
1666   Diag(R.getNameLoc(), diagnostic) << Name;
1667   return true;
1668 }
1669 
1670 ExprResult Sema::ActOnIdExpression(Scope *S,
1671                                    CXXScopeSpec &SS,
1672                                    SourceLocation TemplateKWLoc,
1673                                    UnqualifiedId &Id,
1674                                    bool HasTrailingLParen,
1675                                    bool IsAddressOfOperand,
1676                                    CorrectionCandidateCallback *CCC) {
1677   assert(!(IsAddressOfOperand && HasTrailingLParen) &&
1678          "cannot be direct & operand and have a trailing lparen");
1679 
1680   if (SS.isInvalid())
1681     return ExprError();
1682 
1683   TemplateArgumentListInfo TemplateArgsBuffer;
1684 
1685   // Decompose the UnqualifiedId into the following data.
1686   DeclarationNameInfo NameInfo;
1687   const TemplateArgumentListInfo *TemplateArgs;
1688   DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
1689 
1690   DeclarationName Name = NameInfo.getName();
1691   IdentifierInfo *II = Name.getAsIdentifierInfo();
1692   SourceLocation NameLoc = NameInfo.getLoc();
1693 
1694   // C++ [temp.dep.expr]p3:
1695   //   An id-expression is type-dependent if it contains:
1696   //     -- an identifier that was declared with a dependent type,
1697   //        (note: handled after lookup)
1698   //     -- a template-id that is dependent,
1699   //        (note: handled in BuildTemplateIdExpr)
1700   //     -- a conversion-function-id that specifies a dependent type,
1701   //     -- a nested-name-specifier that contains a class-name that
1702   //        names a dependent type.
1703   // Determine whether this is a member of an unknown specialization;
1704   // we need to handle these differently.
1705   bool DependentID = false;
1706   if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1707       Name.getCXXNameType()->isDependentType()) {
1708     DependentID = true;
1709   } else if (SS.isSet()) {
1710     if (DeclContext *DC = computeDeclContext(SS, false)) {
1711       if (RequireCompleteDeclContext(SS, DC))
1712         return ExprError();
1713     } else {
1714       DependentID = true;
1715     }
1716   }
1717 
1718   if (DependentID)
1719     return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1720                                       IsAddressOfOperand, TemplateArgs);
1721 
1722   // Perform the required lookup.
1723   LookupResult R(*this, NameInfo,
1724                  (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
1725                   ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
1726   if (TemplateArgs) {
1727     // Lookup the template name again to correctly establish the context in
1728     // which it was found. This is really unfortunate as we already did the
1729     // lookup to determine that it was a template name in the first place. If
1730     // this becomes a performance hit, we can work harder to preserve those
1731     // results until we get here but it's likely not worth it.
1732     bool MemberOfUnknownSpecialization;
1733     LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1734                        MemberOfUnknownSpecialization);
1735 
1736     if (MemberOfUnknownSpecialization ||
1737         (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
1738       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1739                                         IsAddressOfOperand, TemplateArgs);
1740   } else {
1741     bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
1742     LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
1743 
1744     // If the result might be in a dependent base class, this is a dependent
1745     // id-expression.
1746     if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
1747       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1748                                         IsAddressOfOperand, TemplateArgs);
1749 
1750     // If this reference is in an Objective-C method, then we need to do
1751     // some special Objective-C lookup, too.
1752     if (IvarLookupFollowUp) {
1753       ExprResult E(LookupInObjCMethod(R, S, II, true));
1754       if (E.isInvalid())
1755         return ExprError();
1756 
1757       if (Expr *Ex = E.takeAs<Expr>())
1758         return Owned(Ex);
1759     }
1760   }
1761 
1762   if (R.isAmbiguous())
1763     return ExprError();
1764 
1765   // Determine whether this name might be a candidate for
1766   // argument-dependent lookup.
1767   bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
1768 
1769   if (R.empty() && !ADL) {
1770     // Otherwise, this could be an implicitly declared function reference (legal
1771     // in C90, extension in C99, forbidden in C++).
1772     if (HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
1773       NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1774       if (D) R.addDecl(D);
1775     }
1776 
1777     // If this name wasn't predeclared and if this is not a function
1778     // call, diagnose the problem.
1779     if (R.empty()) {
1780 
1781       // In Microsoft mode, if we are inside a template class member function
1782       // and we can't resolve an identifier then assume the identifier is type
1783       // dependent. The goal is to postpone name lookup to instantiation time
1784       // to be able to search into type dependent base classes.
1785       if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
1786           isa<CXXMethodDecl>(CurContext))
1787         return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1788                                           IsAddressOfOperand, TemplateArgs);
1789 
1790       CorrectionCandidateCallback DefaultValidator;
1791       if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator))
1792         return ExprError();
1793 
1794       assert(!R.empty() &&
1795              "DiagnoseEmptyLookup returned false but added no results");
1796 
1797       // If we found an Objective-C instance variable, let
1798       // LookupInObjCMethod build the appropriate expression to
1799       // reference the ivar.
1800       if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1801         R.clear();
1802         ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
1803         // In a hopelessly buggy code, Objective-C instance variable
1804         // lookup fails and no expression will be built to reference it.
1805         if (!E.isInvalid() && !E.get())
1806           return ExprError();
1807         return E;
1808       }
1809     }
1810   }
1811 
1812   // This is guaranteed from this point on.
1813   assert(!R.empty() || ADL);
1814 
1815   // Check whether this might be a C++ implicit instance member access.
1816   // C++ [class.mfct.non-static]p3:
1817   //   When an id-expression that is not part of a class member access
1818   //   syntax and not used to form a pointer to member is used in the
1819   //   body of a non-static member function of class X, if name lookup
1820   //   resolves the name in the id-expression to a non-static non-type
1821   //   member of some class C, the id-expression is transformed into a
1822   //   class member access expression using (*this) as the
1823   //   postfix-expression to the left of the . operator.
1824   //
1825   // But we don't actually need to do this for '&' operands if R
1826   // resolved to a function or overloaded function set, because the
1827   // expression is ill-formed if it actually works out to be a
1828   // non-static member function:
1829   //
1830   // C++ [expr.ref]p4:
1831   //   Otherwise, if E1.E2 refers to a non-static member function. . .
1832   //   [t]he expression can be used only as the left-hand operand of a
1833   //   member function call.
1834   //
1835   // There are other safeguards against such uses, but it's important
1836   // to get this right here so that we don't end up making a
1837   // spuriously dependent expression if we're inside a dependent
1838   // instance method.
1839   if (!R.empty() && (*R.begin())->isCXXClassMember()) {
1840     bool MightBeImplicitMember;
1841     if (!IsAddressOfOperand)
1842       MightBeImplicitMember = true;
1843     else if (!SS.isEmpty())
1844       MightBeImplicitMember = false;
1845     else if (R.isOverloadedResult())
1846       MightBeImplicitMember = false;
1847     else if (R.isUnresolvableResult())
1848       MightBeImplicitMember = true;
1849     else
1850       MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
1851                               isa<IndirectFieldDecl>(R.getFoundDecl());
1852 
1853     if (MightBeImplicitMember)
1854       return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
1855                                              R, TemplateArgs);
1856   }
1857 
1858   if (TemplateArgs || TemplateKWLoc.isValid())
1859     return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
1860 
1861   return BuildDeclarationNameExpr(SS, R, ADL);
1862 }
1863 
1864 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1865 /// declaration name, generally during template instantiation.
1866 /// There's a large number of things which don't need to be done along
1867 /// this path.
1868 ExprResult
1869 Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
1870                                         const DeclarationNameInfo &NameInfo) {
1871   DeclContext *DC;
1872   if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
1873     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
1874                                      NameInfo, /*TemplateArgs=*/0);
1875 
1876   if (RequireCompleteDeclContext(SS, DC))
1877     return ExprError();
1878 
1879   LookupResult R(*this, NameInfo, LookupOrdinaryName);
1880   LookupQualifiedName(R, DC);
1881 
1882   if (R.isAmbiguous())
1883     return ExprError();
1884 
1885   if (R.empty()) {
1886     Diag(NameInfo.getLoc(), diag::err_no_member)
1887       << NameInfo.getName() << DC << SS.getRange();
1888     return ExprError();
1889   }
1890 
1891   return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1892 }
1893 
1894 /// LookupInObjCMethod - The parser has read a name in, and Sema has
1895 /// detected that we're currently inside an ObjC method.  Perform some
1896 /// additional lookup.
1897 ///
1898 /// Ideally, most of this would be done by lookup, but there's
1899 /// actually quite a lot of extra work involved.
1900 ///
1901 /// Returns a null sentinel to indicate trivial success.
1902 ExprResult
1903 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
1904                          IdentifierInfo *II, bool AllowBuiltinCreation) {
1905   SourceLocation Loc = Lookup.getNameLoc();
1906   ObjCMethodDecl *CurMethod = getCurMethodDecl();
1907 
1908   // There are two cases to handle here.  1) scoped lookup could have failed,
1909   // in which case we should look for an ivar.  2) scoped lookup could have
1910   // found a decl, but that decl is outside the current instance method (i.e.
1911   // a global variable).  In these two cases, we do a lookup for an ivar with
1912   // this name, if the lookup sucedes, we replace it our current decl.
1913 
1914   // If we're in a class method, we don't normally want to look for
1915   // ivars.  But if we don't find anything else, and there's an
1916   // ivar, that's an error.
1917   bool IsClassMethod = CurMethod->isClassMethod();
1918 
1919   bool LookForIvars;
1920   if (Lookup.empty())
1921     LookForIvars = true;
1922   else if (IsClassMethod)
1923     LookForIvars = false;
1924   else
1925     LookForIvars = (Lookup.isSingleResult() &&
1926                     Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
1927   ObjCInterfaceDecl *IFace = 0;
1928   if (LookForIvars) {
1929     IFace = CurMethod->getClassInterface();
1930     ObjCInterfaceDecl *ClassDeclared;
1931     ObjCIvarDecl *IV = 0;
1932     if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
1933       // Diagnose using an ivar in a class method.
1934       if (IsClassMethod)
1935         return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1936                          << IV->getDeclName());
1937 
1938       // If we're referencing an invalid decl, just return this as a silent
1939       // error node.  The error diagnostic was already emitted on the decl.
1940       if (IV->isInvalidDecl())
1941         return ExprError();
1942 
1943       // Check if referencing a field with __attribute__((deprecated)).
1944       if (DiagnoseUseOfDecl(IV, Loc))
1945         return ExprError();
1946 
1947       // Diagnose the use of an ivar outside of the declaring class.
1948       if (IV->getAccessControl() == ObjCIvarDecl::Private &&
1949           !declaresSameEntity(ClassDeclared, IFace) &&
1950           !getLangOpts().DebuggerSupport)
1951         Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1952 
1953       // FIXME: This should use a new expr for a direct reference, don't
1954       // turn this into Self->ivar, just return a BareIVarExpr or something.
1955       IdentifierInfo &II = Context.Idents.get("self");
1956       UnqualifiedId SelfName;
1957       SelfName.setIdentifier(&II, SourceLocation());
1958       SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
1959       CXXScopeSpec SelfScopeSpec;
1960       SourceLocation TemplateKWLoc;
1961       ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
1962                                               SelfName, false, false);
1963       if (SelfExpr.isInvalid())
1964         return ExprError();
1965 
1966       SelfExpr = DefaultLvalueConversion(SelfExpr.take());
1967       if (SelfExpr.isInvalid())
1968         return ExprError();
1969 
1970       MarkAnyDeclReferenced(Loc, IV);
1971 
1972       ObjCMethodFamily MF = CurMethod->getMethodFamily();
1973       if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize)
1974         Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
1975       return Owned(new (Context)
1976                    ObjCIvarRefExpr(IV, IV->getType(), Loc,
1977                                    SelfExpr.take(), true, true));
1978     }
1979   } else if (CurMethod->isInstanceMethod()) {
1980     // We should warn if a local variable hides an ivar.
1981     if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
1982       ObjCInterfaceDecl *ClassDeclared;
1983       if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1984         if (IV->getAccessControl() != ObjCIvarDecl::Private ||
1985             declaresSameEntity(IFace, ClassDeclared))
1986           Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
1987       }
1988     }
1989   } else if (Lookup.isSingleResult() &&
1990              Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
1991     // If accessing a stand-alone ivar in a class method, this is an error.
1992     if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
1993       return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1994                        << IV->getDeclName());
1995   }
1996 
1997   if (Lookup.empty() && II && AllowBuiltinCreation) {
1998     // FIXME. Consolidate this with similar code in LookupName.
1999     if (unsigned BuiltinID = II->getBuiltinID()) {
2000       if (!(getLangOpts().CPlusPlus &&
2001             Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2002         NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2003                                            S, Lookup.isForRedeclaration(),
2004                                            Lookup.getNameLoc());
2005         if (D) Lookup.addDecl(D);
2006       }
2007     }
2008   }
2009   // Sentinel value saying that we didn't do anything special.
2010   return Owned((Expr*) 0);
2011 }
2012 
2013 /// \brief Cast a base object to a member's actual type.
2014 ///
2015 /// Logically this happens in three phases:
2016 ///
2017 /// * First we cast from the base type to the naming class.
2018 ///   The naming class is the class into which we were looking
2019 ///   when we found the member;  it's the qualifier type if a
2020 ///   qualifier was provided, and otherwise it's the base type.
2021 ///
2022 /// * Next we cast from the naming class to the declaring class.
2023 ///   If the member we found was brought into a class's scope by
2024 ///   a using declaration, this is that class;  otherwise it's
2025 ///   the class declaring the member.
2026 ///
2027 /// * Finally we cast from the declaring class to the "true"
2028 ///   declaring class of the member.  This conversion does not
2029 ///   obey access control.
2030 ExprResult
2031 Sema::PerformObjectMemberConversion(Expr *From,
2032                                     NestedNameSpecifier *Qualifier,
2033                                     NamedDecl *FoundDecl,
2034                                     NamedDecl *Member) {
2035   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2036   if (!RD)
2037     return Owned(From);
2038 
2039   QualType DestRecordType;
2040   QualType DestType;
2041   QualType FromRecordType;
2042   QualType FromType = From->getType();
2043   bool PointerConversions = false;
2044   if (isa<FieldDecl>(Member)) {
2045     DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2046 
2047     if (FromType->getAs<PointerType>()) {
2048       DestType = Context.getPointerType(DestRecordType);
2049       FromRecordType = FromType->getPointeeType();
2050       PointerConversions = true;
2051     } else {
2052       DestType = DestRecordType;
2053       FromRecordType = FromType;
2054     }
2055   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2056     if (Method->isStatic())
2057       return Owned(From);
2058 
2059     DestType = Method->getThisType(Context);
2060     DestRecordType = DestType->getPointeeType();
2061 
2062     if (FromType->getAs<PointerType>()) {
2063       FromRecordType = FromType->getPointeeType();
2064       PointerConversions = true;
2065     } else {
2066       FromRecordType = FromType;
2067       DestType = DestRecordType;
2068     }
2069   } else {
2070     // No conversion necessary.
2071     return Owned(From);
2072   }
2073 
2074   if (DestType->isDependentType() || FromType->isDependentType())
2075     return Owned(From);
2076 
2077   // If the unqualified types are the same, no conversion is necessary.
2078   if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2079     return Owned(From);
2080 
2081   SourceRange FromRange = From->getSourceRange();
2082   SourceLocation FromLoc = FromRange.getBegin();
2083 
2084   ExprValueKind VK = From->getValueKind();
2085 
2086   // C++ [class.member.lookup]p8:
2087   //   [...] Ambiguities can often be resolved by qualifying a name with its
2088   //   class name.
2089   //
2090   // If the member was a qualified name and the qualified referred to a
2091   // specific base subobject type, we'll cast to that intermediate type
2092   // first and then to the object in which the member is declared. That allows
2093   // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2094   //
2095   //   class Base { public: int x; };
2096   //   class Derived1 : public Base { };
2097   //   class Derived2 : public Base { };
2098   //   class VeryDerived : public Derived1, public Derived2 { void f(); };
2099   //
2100   //   void VeryDerived::f() {
2101   //     x = 17; // error: ambiguous base subobjects
2102   //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
2103   //   }
2104   if (Qualifier) {
2105     QualType QType = QualType(Qualifier->getAsType(), 0);
2106     assert(!QType.isNull() && "lookup done with dependent qualifier?");
2107     assert(QType->isRecordType() && "lookup done with non-record type");
2108 
2109     QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2110 
2111     // In C++98, the qualifier type doesn't actually have to be a base
2112     // type of the object type, in which case we just ignore it.
2113     // Otherwise build the appropriate casts.
2114     if (IsDerivedFrom(FromRecordType, QRecordType)) {
2115       CXXCastPath BasePath;
2116       if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2117                                        FromLoc, FromRange, &BasePath))
2118         return ExprError();
2119 
2120       if (PointerConversions)
2121         QType = Context.getPointerType(QType);
2122       From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2123                                VK, &BasePath).take();
2124 
2125       FromType = QType;
2126       FromRecordType = QRecordType;
2127 
2128       // If the qualifier type was the same as the destination type,
2129       // we're done.
2130       if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2131         return Owned(From);
2132     }
2133   }
2134 
2135   bool IgnoreAccess = false;
2136 
2137   // If we actually found the member through a using declaration, cast
2138   // down to the using declaration's type.
2139   //
2140   // Pointer equality is fine here because only one declaration of a
2141   // class ever has member declarations.
2142   if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2143     assert(isa<UsingShadowDecl>(FoundDecl));
2144     QualType URecordType = Context.getTypeDeclType(
2145                            cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2146 
2147     // We only need to do this if the naming-class to declaring-class
2148     // conversion is non-trivial.
2149     if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2150       assert(IsDerivedFrom(FromRecordType, URecordType));
2151       CXXCastPath BasePath;
2152       if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2153                                        FromLoc, FromRange, &BasePath))
2154         return ExprError();
2155 
2156       QualType UType = URecordType;
2157       if (PointerConversions)
2158         UType = Context.getPointerType(UType);
2159       From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2160                                VK, &BasePath).take();
2161       FromType = UType;
2162       FromRecordType = URecordType;
2163     }
2164 
2165     // We don't do access control for the conversion from the
2166     // declaring class to the true declaring class.
2167     IgnoreAccess = true;
2168   }
2169 
2170   CXXCastPath BasePath;
2171   if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2172                                    FromLoc, FromRange, &BasePath,
2173                                    IgnoreAccess))
2174     return ExprError();
2175 
2176   return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2177                            VK, &BasePath);
2178 }
2179 
2180 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2181                                       const LookupResult &R,
2182                                       bool HasTrailingLParen) {
2183   // Only when used directly as the postfix-expression of a call.
2184   if (!HasTrailingLParen)
2185     return false;
2186 
2187   // Never if a scope specifier was provided.
2188   if (SS.isSet())
2189     return false;
2190 
2191   // Only in C++ or ObjC++.
2192   if (!getLangOpts().CPlusPlus)
2193     return false;
2194 
2195   // Turn off ADL when we find certain kinds of declarations during
2196   // normal lookup:
2197   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2198     NamedDecl *D = *I;
2199 
2200     // C++0x [basic.lookup.argdep]p3:
2201     //     -- a declaration of a class member
2202     // Since using decls preserve this property, we check this on the
2203     // original decl.
2204     if (D->isCXXClassMember())
2205       return false;
2206 
2207     // C++0x [basic.lookup.argdep]p3:
2208     //     -- a block-scope function declaration that is not a
2209     //        using-declaration
2210     // NOTE: we also trigger this for function templates (in fact, we
2211     // don't check the decl type at all, since all other decl types
2212     // turn off ADL anyway).
2213     if (isa<UsingShadowDecl>(D))
2214       D = cast<UsingShadowDecl>(D)->getTargetDecl();
2215     else if (D->getDeclContext()->isFunctionOrMethod())
2216       return false;
2217 
2218     // C++0x [basic.lookup.argdep]p3:
2219     //     -- a declaration that is neither a function or a function
2220     //        template
2221     // And also for builtin functions.
2222     if (isa<FunctionDecl>(D)) {
2223       FunctionDecl *FDecl = cast<FunctionDecl>(D);
2224 
2225       // But also builtin functions.
2226       if (FDecl->getBuiltinID() && FDecl->isImplicit())
2227         return false;
2228     } else if (!isa<FunctionTemplateDecl>(D))
2229       return false;
2230   }
2231 
2232   return true;
2233 }
2234 
2235 
2236 /// Diagnoses obvious problems with the use of the given declaration
2237 /// as an expression.  This is only actually called for lookups that
2238 /// were not overloaded, and it doesn't promise that the declaration
2239 /// will in fact be used.
2240 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2241   if (isa<TypedefNameDecl>(D)) {
2242     S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2243     return true;
2244   }
2245 
2246   if (isa<ObjCInterfaceDecl>(D)) {
2247     S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2248     return true;
2249   }
2250 
2251   if (isa<NamespaceDecl>(D)) {
2252     S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2253     return true;
2254   }
2255 
2256   return false;
2257 }
2258 
2259 ExprResult
2260 Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2261                                LookupResult &R,
2262                                bool NeedsADL) {
2263   // If this is a single, fully-resolved result and we don't need ADL,
2264   // just build an ordinary singleton decl ref.
2265   if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
2266     return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
2267                                     R.getFoundDecl());
2268 
2269   // We only need to check the declaration if there's exactly one
2270   // result, because in the overloaded case the results can only be
2271   // functions and function templates.
2272   if (R.isSingleResult() &&
2273       CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
2274     return ExprError();
2275 
2276   // Otherwise, just build an unresolved lookup expression.  Suppress
2277   // any lookup-related diagnostics; we'll hash these out later, when
2278   // we've picked a target.
2279   R.suppressDiagnostics();
2280 
2281   UnresolvedLookupExpr *ULE
2282     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2283                                    SS.getWithLocInContext(Context),
2284                                    R.getLookupNameInfo(),
2285                                    NeedsADL, R.isOverloadedResult(),
2286                                    R.begin(), R.end());
2287 
2288   return Owned(ULE);
2289 }
2290 
2291 /// \brief Complete semantic analysis for a reference to the given declaration.
2292 ExprResult
2293 Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2294                                const DeclarationNameInfo &NameInfo,
2295                                NamedDecl *D) {
2296   assert(D && "Cannot refer to a NULL declaration");
2297   assert(!isa<FunctionTemplateDecl>(D) &&
2298          "Cannot refer unambiguously to a function template");
2299 
2300   SourceLocation Loc = NameInfo.getLoc();
2301   if (CheckDeclInExpr(*this, Loc, D))
2302     return ExprError();
2303 
2304   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2305     // Specifically diagnose references to class templates that are missing
2306     // a template argument list.
2307     Diag(Loc, diag::err_template_decl_ref)
2308       << Template << SS.getRange();
2309     Diag(Template->getLocation(), diag::note_template_decl_here);
2310     return ExprError();
2311   }
2312 
2313   // Make sure that we're referring to a value.
2314   ValueDecl *VD = dyn_cast<ValueDecl>(D);
2315   if (!VD) {
2316     Diag(Loc, diag::err_ref_non_value)
2317       << D << SS.getRange();
2318     Diag(D->getLocation(), diag::note_declared_at);
2319     return ExprError();
2320   }
2321 
2322   // Check whether this declaration can be used. Note that we suppress
2323   // this check when we're going to perform argument-dependent lookup
2324   // on this function name, because this might not be the function
2325   // that overload resolution actually selects.
2326   if (DiagnoseUseOfDecl(VD, Loc))
2327     return ExprError();
2328 
2329   // Only create DeclRefExpr's for valid Decl's.
2330   if (VD->isInvalidDecl())
2331     return ExprError();
2332 
2333   // Handle members of anonymous structs and unions.  If we got here,
2334   // and the reference is to a class member indirect field, then this
2335   // must be the subject of a pointer-to-member expression.
2336   if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2337     if (!indirectField->isCXXClassMember())
2338       return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2339                                                       indirectField);
2340 
2341   {
2342     QualType type = VD->getType();
2343     ExprValueKind valueKind = VK_RValue;
2344 
2345     switch (D->getKind()) {
2346     // Ignore all the non-ValueDecl kinds.
2347 #define ABSTRACT_DECL(kind)
2348 #define VALUE(type, base)
2349 #define DECL(type, base) \
2350     case Decl::type:
2351 #include "clang/AST/DeclNodes.inc"
2352       llvm_unreachable("invalid value decl kind");
2353 
2354     // These shouldn't make it here.
2355     case Decl::ObjCAtDefsField:
2356     case Decl::ObjCIvar:
2357       llvm_unreachable("forming non-member reference to ivar?");
2358 
2359     // Enum constants are always r-values and never references.
2360     // Unresolved using declarations are dependent.
2361     case Decl::EnumConstant:
2362     case Decl::UnresolvedUsingValue:
2363       valueKind = VK_RValue;
2364       break;
2365 
2366     // Fields and indirect fields that got here must be for
2367     // pointer-to-member expressions; we just call them l-values for
2368     // internal consistency, because this subexpression doesn't really
2369     // exist in the high-level semantics.
2370     case Decl::Field:
2371     case Decl::IndirectField:
2372       assert(getLangOpts().CPlusPlus &&
2373              "building reference to field in C?");
2374 
2375       // These can't have reference type in well-formed programs, but
2376       // for internal consistency we do this anyway.
2377       type = type.getNonReferenceType();
2378       valueKind = VK_LValue;
2379       break;
2380 
2381     // Non-type template parameters are either l-values or r-values
2382     // depending on the type.
2383     case Decl::NonTypeTemplateParm: {
2384       if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2385         type = reftype->getPointeeType();
2386         valueKind = VK_LValue; // even if the parameter is an r-value reference
2387         break;
2388       }
2389 
2390       // For non-references, we need to strip qualifiers just in case
2391       // the template parameter was declared as 'const int' or whatever.
2392       valueKind = VK_RValue;
2393       type = type.getUnqualifiedType();
2394       break;
2395     }
2396 
2397     case Decl::Var:
2398       // In C, "extern void blah;" is valid and is an r-value.
2399       if (!getLangOpts().CPlusPlus &&
2400           !type.hasQualifiers() &&
2401           type->isVoidType()) {
2402         valueKind = VK_RValue;
2403         break;
2404       }
2405       // fallthrough
2406 
2407     case Decl::ImplicitParam:
2408     case Decl::ParmVar: {
2409       // These are always l-values.
2410       valueKind = VK_LValue;
2411       type = type.getNonReferenceType();
2412 
2413       // FIXME: Does the addition of const really only apply in
2414       // potentially-evaluated contexts? Since the variable isn't actually
2415       // captured in an unevaluated context, it seems that the answer is no.
2416       if (!isUnevaluatedContext()) {
2417         QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
2418         if (!CapturedType.isNull())
2419           type = CapturedType;
2420       }
2421 
2422       break;
2423     }
2424 
2425     case Decl::Function: {
2426       if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
2427         if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
2428           type = Context.BuiltinFnTy;
2429           valueKind = VK_RValue;
2430           break;
2431         }
2432       }
2433 
2434       const FunctionType *fty = type->castAs<FunctionType>();
2435 
2436       // If we're referring to a function with an __unknown_anytype
2437       // result type, make the entire expression __unknown_anytype.
2438       if (fty->getResultType() == Context.UnknownAnyTy) {
2439         type = Context.UnknownAnyTy;
2440         valueKind = VK_RValue;
2441         break;
2442       }
2443 
2444       // Functions are l-values in C++.
2445       if (getLangOpts().CPlusPlus) {
2446         valueKind = VK_LValue;
2447         break;
2448       }
2449 
2450       // C99 DR 316 says that, if a function type comes from a
2451       // function definition (without a prototype), that type is only
2452       // used for checking compatibility. Therefore, when referencing
2453       // the function, we pretend that we don't have the full function
2454       // type.
2455       if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2456           isa<FunctionProtoType>(fty))
2457         type = Context.getFunctionNoProtoType(fty->getResultType(),
2458                                               fty->getExtInfo());
2459 
2460       // Functions are r-values in C.
2461       valueKind = VK_RValue;
2462       break;
2463     }
2464 
2465     case Decl::CXXMethod:
2466       // If we're referring to a method with an __unknown_anytype
2467       // result type, make the entire expression __unknown_anytype.
2468       // This should only be possible with a type written directly.
2469       if (const FunctionProtoType *proto
2470             = dyn_cast<FunctionProtoType>(VD->getType()))
2471         if (proto->getResultType() == Context.UnknownAnyTy) {
2472           type = Context.UnknownAnyTy;
2473           valueKind = VK_RValue;
2474           break;
2475         }
2476 
2477       // C++ methods are l-values if static, r-values if non-static.
2478       if (cast<CXXMethodDecl>(VD)->isStatic()) {
2479         valueKind = VK_LValue;
2480         break;
2481       }
2482       // fallthrough
2483 
2484     case Decl::CXXConversion:
2485     case Decl::CXXDestructor:
2486     case Decl::CXXConstructor:
2487       valueKind = VK_RValue;
2488       break;
2489     }
2490 
2491     return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS);
2492   }
2493 }
2494 
2495 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
2496   PredefinedExpr::IdentType IT;
2497 
2498   switch (Kind) {
2499   default: llvm_unreachable("Unknown simple primary expr!");
2500   case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2501   case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
2502   case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break;
2503   case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
2504   }
2505 
2506   // Pre-defined identifiers are of type char[x], where x is the length of the
2507   // string.
2508 
2509   Decl *currentDecl = getCurFunctionOrMethodDecl();
2510   if (!currentDecl && getCurBlock())
2511     currentDecl = getCurBlock()->TheDecl;
2512   if (!currentDecl) {
2513     Diag(Loc, diag::ext_predef_outside_function);
2514     currentDecl = Context.getTranslationUnitDecl();
2515   }
2516 
2517   QualType ResTy;
2518   if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2519     ResTy = Context.DependentTy;
2520   } else {
2521     unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
2522 
2523     llvm::APInt LengthI(32, Length + 1);
2524     if (IT == PredefinedExpr::LFunction)
2525       ResTy = Context.WCharTy.withConst();
2526     else
2527       ResTy = Context.CharTy.withConst();
2528     ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2529   }
2530   return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
2531 }
2532 
2533 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
2534   SmallString<16> CharBuffer;
2535   bool Invalid = false;
2536   StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
2537   if (Invalid)
2538     return ExprError();
2539 
2540   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
2541                             PP, Tok.getKind());
2542   if (Literal.hadError())
2543     return ExprError();
2544 
2545   QualType Ty;
2546   if (Literal.isWide())
2547     Ty = Context.WCharTy; // L'x' -> wchar_t in C and C++.
2548   else if (Literal.isUTF16())
2549     Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
2550   else if (Literal.isUTF32())
2551     Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
2552   else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
2553     Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
2554   else
2555     Ty = Context.CharTy;  // 'x' -> char in C++
2556 
2557   CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
2558   if (Literal.isWide())
2559     Kind = CharacterLiteral::Wide;
2560   else if (Literal.isUTF16())
2561     Kind = CharacterLiteral::UTF16;
2562   else if (Literal.isUTF32())
2563     Kind = CharacterLiteral::UTF32;
2564 
2565   Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
2566                                              Tok.getLocation());
2567 
2568   if (Literal.getUDSuffix().empty())
2569     return Owned(Lit);
2570 
2571   // We're building a user-defined literal.
2572   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2573   SourceLocation UDSuffixLoc =
2574     getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
2575 
2576   // Make sure we're allowed user-defined literals here.
2577   if (!UDLScope)
2578     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
2579 
2580   // C++11 [lex.ext]p6: The literal L is treated as a call of the form
2581   //   operator "" X (ch)
2582   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
2583                                         llvm::makeArrayRef(&Lit, 1),
2584                                         Tok.getLocation());
2585 }
2586 
2587 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
2588   unsigned IntSize = Context.getTargetInfo().getIntWidth();
2589   return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
2590                                       Context.IntTy, Loc));
2591 }
2592 
2593 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
2594                                   QualType Ty, SourceLocation Loc) {
2595   const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
2596 
2597   using llvm::APFloat;
2598   APFloat Val(Format);
2599 
2600   APFloat::opStatus result = Literal.GetFloatValue(Val);
2601 
2602   // Overflow is always an error, but underflow is only an error if
2603   // we underflowed to zero (APFloat reports denormals as underflow).
2604   if ((result & APFloat::opOverflow) ||
2605       ((result & APFloat::opUnderflow) && Val.isZero())) {
2606     unsigned diagnostic;
2607     SmallString<20> buffer;
2608     if (result & APFloat::opOverflow) {
2609       diagnostic = diag::warn_float_overflow;
2610       APFloat::getLargest(Format).toString(buffer);
2611     } else {
2612       diagnostic = diag::warn_float_underflow;
2613       APFloat::getSmallest(Format).toString(buffer);
2614     }
2615 
2616     S.Diag(Loc, diagnostic)
2617       << Ty
2618       << StringRef(buffer.data(), buffer.size());
2619   }
2620 
2621   bool isExact = (result == APFloat::opOK);
2622   return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
2623 }
2624 
2625 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
2626   // Fast path for a single digit (which is quite common).  A single digit
2627   // cannot have a trigraph, escaped newline, radix prefix, or suffix.
2628   if (Tok.getLength() == 1) {
2629     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
2630     return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
2631   }
2632 
2633   SmallString<512> IntegerBuffer;
2634   // Add padding so that NumericLiteralParser can overread by one character.
2635   IntegerBuffer.resize(Tok.getLength()+1);
2636   const char *ThisTokBegin = &IntegerBuffer[0];
2637 
2638   // Get the spelling of the token, which eliminates trigraphs, etc.
2639   bool Invalid = false;
2640   unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
2641   if (Invalid)
2642     return ExprError();
2643 
2644   NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
2645                                Tok.getLocation(), PP);
2646   if (Literal.hadError)
2647     return ExprError();
2648 
2649   if (Literal.hasUDSuffix()) {
2650     // We're building a user-defined literal.
2651     IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2652     SourceLocation UDSuffixLoc =
2653       getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
2654 
2655     // Make sure we're allowed user-defined literals here.
2656     if (!UDLScope)
2657       return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
2658 
2659     QualType CookedTy;
2660     if (Literal.isFloatingLiteral()) {
2661       // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
2662       // long double, the literal is treated as a call of the form
2663       //   operator "" X (f L)
2664       CookedTy = Context.LongDoubleTy;
2665     } else {
2666       // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
2667       // unsigned long long, the literal is treated as a call of the form
2668       //   operator "" X (n ULL)
2669       CookedTy = Context.UnsignedLongLongTy;
2670     }
2671 
2672     DeclarationName OpName =
2673       Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
2674     DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
2675     OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
2676 
2677     // Perform literal operator lookup to determine if we're building a raw
2678     // literal or a cooked one.
2679     LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
2680     switch (LookupLiteralOperator(UDLScope, R, llvm::makeArrayRef(&CookedTy, 1),
2681                                   /*AllowRawAndTemplate*/true)) {
2682     case LOLR_Error:
2683       return ExprError();
2684 
2685     case LOLR_Cooked: {
2686       Expr *Lit;
2687       if (Literal.isFloatingLiteral()) {
2688         Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
2689       } else {
2690         llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
2691         if (Literal.GetIntegerValue(ResultVal))
2692           Diag(Tok.getLocation(), diag::warn_integer_too_large);
2693         Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
2694                                      Tok.getLocation());
2695       }
2696       return BuildLiteralOperatorCall(R, OpNameInfo,
2697                                       llvm::makeArrayRef(&Lit, 1),
2698                                       Tok.getLocation());
2699     }
2700 
2701     case LOLR_Raw: {
2702       // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
2703       // literal is treated as a call of the form
2704       //   operator "" X ("n")
2705       SourceLocation TokLoc = Tok.getLocation();
2706       unsigned Length = Literal.getUDSuffixOffset();
2707       QualType StrTy = Context.getConstantArrayType(
2708           Context.CharTy, llvm::APInt(32, Length + 1),
2709           ArrayType::Normal, 0);
2710       Expr *Lit = StringLiteral::Create(
2711           Context, StringRef(ThisTokBegin, Length), StringLiteral::Ascii,
2712           /*Pascal*/false, StrTy, &TokLoc, 1);
2713       return BuildLiteralOperatorCall(R, OpNameInfo,
2714                                       llvm::makeArrayRef(&Lit, 1), TokLoc);
2715     }
2716 
2717     case LOLR_Template:
2718       // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
2719       // template), L is treated as a call fo the form
2720       //   operator "" X <'c1', 'c2', ... 'ck'>()
2721       // where n is the source character sequence c1 c2 ... ck.
2722       TemplateArgumentListInfo ExplicitArgs;
2723       unsigned CharBits = Context.getIntWidth(Context.CharTy);
2724       bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
2725       llvm::APSInt Value(CharBits, CharIsUnsigned);
2726       for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
2727         Value = ThisTokBegin[I];
2728         TemplateArgument Arg(Context, Value, Context.CharTy);
2729         TemplateArgumentLocInfo ArgInfo;
2730         ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
2731       }
2732       return BuildLiteralOperatorCall(R, OpNameInfo, ArrayRef<Expr*>(),
2733                                       Tok.getLocation(), &ExplicitArgs);
2734     }
2735 
2736     llvm_unreachable("unexpected literal operator lookup result");
2737   }
2738 
2739   Expr *Res;
2740 
2741   if (Literal.isFloatingLiteral()) {
2742     QualType Ty;
2743     if (Literal.isFloat)
2744       Ty = Context.FloatTy;
2745     else if (!Literal.isLong)
2746       Ty = Context.DoubleTy;
2747     else
2748       Ty = Context.LongDoubleTy;
2749 
2750     Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
2751 
2752     if (Ty == Context.DoubleTy) {
2753       if (getLangOpts().SinglePrecisionConstants) {
2754         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
2755       } else if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
2756         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
2757         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
2758       }
2759     }
2760   } else if (!Literal.isIntegerLiteral()) {
2761     return ExprError();
2762   } else {
2763     QualType Ty;
2764 
2765     // long long is a C99 feature.
2766     if (!getLangOpts().C99 && Literal.isLongLong)
2767       Diag(Tok.getLocation(),
2768            getLangOpts().CPlusPlus0x ?
2769              diag::warn_cxx98_compat_longlong : diag::ext_longlong);
2770 
2771     // Get the value in the widest-possible width.
2772     unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
2773     // The microsoft literal suffix extensions support 128-bit literals, which
2774     // may be wider than [u]intmax_t.
2775     if (Literal.isMicrosoftInteger && MaxWidth < 128)
2776       MaxWidth = 128;
2777     llvm::APInt ResultVal(MaxWidth, 0);
2778 
2779     if (Literal.GetIntegerValue(ResultVal)) {
2780       // If this value didn't fit into uintmax_t, warn and force to ull.
2781       Diag(Tok.getLocation(), diag::warn_integer_too_large);
2782       Ty = Context.UnsignedLongLongTy;
2783       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
2784              "long long is not intmax_t?");
2785     } else {
2786       // If this value fits into a ULL, try to figure out what else it fits into
2787       // according to the rules of C99 6.4.4.1p5.
2788 
2789       // Octal, Hexadecimal, and integers with a U suffix are allowed to
2790       // be an unsigned int.
2791       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2792 
2793       // Check from smallest to largest, picking the smallest type we can.
2794       unsigned Width = 0;
2795       if (!Literal.isLong && !Literal.isLongLong) {
2796         // Are int/unsigned possibilities?
2797         unsigned IntSize = Context.getTargetInfo().getIntWidth();
2798 
2799         // Does it fit in a unsigned int?
2800         if (ResultVal.isIntN(IntSize)) {
2801           // Does it fit in a signed int?
2802           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
2803             Ty = Context.IntTy;
2804           else if (AllowUnsigned)
2805             Ty = Context.UnsignedIntTy;
2806           Width = IntSize;
2807         }
2808       }
2809 
2810       // Are long/unsigned long possibilities?
2811       if (Ty.isNull() && !Literal.isLongLong) {
2812         unsigned LongSize = Context.getTargetInfo().getLongWidth();
2813 
2814         // Does it fit in a unsigned long?
2815         if (ResultVal.isIntN(LongSize)) {
2816           // Does it fit in a signed long?
2817           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
2818             Ty = Context.LongTy;
2819           else if (AllowUnsigned)
2820             Ty = Context.UnsignedLongTy;
2821           Width = LongSize;
2822         }
2823       }
2824 
2825       // Check long long if needed.
2826       if (Ty.isNull()) {
2827         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
2828 
2829         // Does it fit in a unsigned long long?
2830         if (ResultVal.isIntN(LongLongSize)) {
2831           // Does it fit in a signed long long?
2832           // To be compatible with MSVC, hex integer literals ending with the
2833           // LL or i64 suffix are always signed in Microsoft mode.
2834           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
2835               (getLangOpts().MicrosoftExt && Literal.isLongLong)))
2836             Ty = Context.LongLongTy;
2837           else if (AllowUnsigned)
2838             Ty = Context.UnsignedLongLongTy;
2839           Width = LongLongSize;
2840         }
2841       }
2842 
2843       // If it doesn't fit in unsigned long long, and we're using Microsoft
2844       // extensions, then its a 128-bit integer literal.
2845       if (Ty.isNull() && Literal.isMicrosoftInteger) {
2846         if (Literal.isUnsigned)
2847           Ty = Context.UnsignedInt128Ty;
2848         else
2849           Ty = Context.Int128Ty;
2850         Width = 128;
2851       }
2852 
2853       // If we still couldn't decide a type, we probably have something that
2854       // does not fit in a signed long long, but has no U suffix.
2855       if (Ty.isNull()) {
2856         Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
2857         Ty = Context.UnsignedLongLongTy;
2858         Width = Context.getTargetInfo().getLongLongWidth();
2859       }
2860 
2861       if (ResultVal.getBitWidth() != Width)
2862         ResultVal = ResultVal.trunc(Width);
2863     }
2864     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
2865   }
2866 
2867   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
2868   if (Literal.isImaginary)
2869     Res = new (Context) ImaginaryLiteral(Res,
2870                                         Context.getComplexType(Res->getType()));
2871 
2872   return Owned(Res);
2873 }
2874 
2875 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
2876   assert((E != 0) && "ActOnParenExpr() missing expr");
2877   return Owned(new (Context) ParenExpr(L, R, E));
2878 }
2879 
2880 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
2881                                          SourceLocation Loc,
2882                                          SourceRange ArgRange) {
2883   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
2884   // scalar or vector data type argument..."
2885   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
2886   // type (C99 6.2.5p18) or void.
2887   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
2888     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
2889       << T << ArgRange;
2890     return true;
2891   }
2892 
2893   assert((T->isVoidType() || !T->isIncompleteType()) &&
2894          "Scalar types should always be complete");
2895   return false;
2896 }
2897 
2898 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
2899                                            SourceLocation Loc,
2900                                            SourceRange ArgRange,
2901                                            UnaryExprOrTypeTrait TraitKind) {
2902   // C99 6.5.3.4p1:
2903   if (T->isFunctionType()) {
2904     // alignof(function) is allowed as an extension.
2905     if (TraitKind == UETT_SizeOf)
2906       S.Diag(Loc, diag::ext_sizeof_function_type) << ArgRange;
2907     return false;
2908   }
2909 
2910   // Allow sizeof(void)/alignof(void) as an extension.
2911   if (T->isVoidType()) {
2912     S.Diag(Loc, diag::ext_sizeof_void_type) << TraitKind << ArgRange;
2913     return false;
2914   }
2915 
2916   return true;
2917 }
2918 
2919 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
2920                                              SourceLocation Loc,
2921                                              SourceRange ArgRange,
2922                                              UnaryExprOrTypeTrait TraitKind) {
2923   // Reject sizeof(interface) and sizeof(interface<proto>) if the
2924   // runtime doesn't allow it.
2925   if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
2926     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
2927       << T << (TraitKind == UETT_SizeOf)
2928       << ArgRange;
2929     return true;
2930   }
2931 
2932   return false;
2933 }
2934 
2935 /// \brief Check the constrains on expression operands to unary type expression
2936 /// and type traits.
2937 ///
2938 /// Completes any types necessary and validates the constraints on the operand
2939 /// expression. The logic mostly mirrors the type-based overload, but may modify
2940 /// the expression as it completes the type for that expression through template
2941 /// instantiation, etc.
2942 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
2943                                             UnaryExprOrTypeTrait ExprKind) {
2944   QualType ExprTy = E->getType();
2945 
2946   // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2947   //   the result is the size of the referenced type."
2948   // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2949   //   result shall be the alignment of the referenced type."
2950   if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2951     ExprTy = Ref->getPointeeType();
2952 
2953   if (ExprKind == UETT_VecStep)
2954     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
2955                                         E->getSourceRange());
2956 
2957   // Whitelist some types as extensions
2958   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
2959                                       E->getSourceRange(), ExprKind))
2960     return false;
2961 
2962   if (RequireCompleteExprType(E,
2963                               diag::err_sizeof_alignof_incomplete_type,
2964                               ExprKind, E->getSourceRange()))
2965     return true;
2966 
2967   // Completeing the expression's type may have changed it.
2968   ExprTy = E->getType();
2969   if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2970     ExprTy = Ref->getPointeeType();
2971 
2972   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
2973                                        E->getSourceRange(), ExprKind))
2974     return true;
2975 
2976   if (ExprKind == UETT_SizeOf) {
2977     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
2978       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
2979         QualType OType = PVD->getOriginalType();
2980         QualType Type = PVD->getType();
2981         if (Type->isPointerType() && OType->isArrayType()) {
2982           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
2983             << Type << OType;
2984           Diag(PVD->getLocation(), diag::note_declared_at);
2985         }
2986       }
2987     }
2988   }
2989 
2990   return false;
2991 }
2992 
2993 /// \brief Check the constraints on operands to unary expression and type
2994 /// traits.
2995 ///
2996 /// This will complete any types necessary, and validate the various constraints
2997 /// on those operands.
2998 ///
2999 /// The UsualUnaryConversions() function is *not* called by this routine.
3000 /// C99 6.3.2.1p[2-4] all state:
3001 ///   Except when it is the operand of the sizeof operator ...
3002 ///
3003 /// C++ [expr.sizeof]p4
3004 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3005 ///   standard conversions are not applied to the operand of sizeof.
3006 ///
3007 /// This policy is followed for all of the unary trait expressions.
3008 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
3009                                             SourceLocation OpLoc,
3010                                             SourceRange ExprRange,
3011                                             UnaryExprOrTypeTrait ExprKind) {
3012   if (ExprType->isDependentType())
3013     return false;
3014 
3015   // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
3016   //   the result is the size of the referenced type."
3017   // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
3018   //   result shall be the alignment of the referenced type."
3019   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3020     ExprType = Ref->getPointeeType();
3021 
3022   if (ExprKind == UETT_VecStep)
3023     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
3024 
3025   // Whitelist some types as extensions
3026   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
3027                                       ExprKind))
3028     return false;
3029 
3030   if (RequireCompleteType(OpLoc, ExprType,
3031                           diag::err_sizeof_alignof_incomplete_type,
3032                           ExprKind, ExprRange))
3033     return true;
3034 
3035   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
3036                                        ExprKind))
3037     return true;
3038 
3039   return false;
3040 }
3041 
3042 static bool CheckAlignOfExpr(Sema &S, Expr *E) {
3043   E = E->IgnoreParens();
3044 
3045   // alignof decl is always ok.
3046   if (isa<DeclRefExpr>(E))
3047     return false;
3048 
3049   // Cannot know anything else if the expression is dependent.
3050   if (E->isTypeDependent())
3051     return false;
3052 
3053   if (E->getBitField()) {
3054     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield)
3055        << 1 << E->getSourceRange();
3056     return true;
3057   }
3058 
3059   // Alignment of a field access is always okay, so long as it isn't a
3060   // bit-field.
3061   if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
3062     if (isa<FieldDecl>(ME->getMemberDecl()))
3063       return false;
3064 
3065   return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
3066 }
3067 
3068 bool Sema::CheckVecStepExpr(Expr *E) {
3069   E = E->IgnoreParens();
3070 
3071   // Cannot know anything else if the expression is dependent.
3072   if (E->isTypeDependent())
3073     return false;
3074 
3075   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
3076 }
3077 
3078 /// \brief Build a sizeof or alignof expression given a type operand.
3079 ExprResult
3080 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3081                                      SourceLocation OpLoc,
3082                                      UnaryExprOrTypeTrait ExprKind,
3083                                      SourceRange R) {
3084   if (!TInfo)
3085     return ExprError();
3086 
3087   QualType T = TInfo->getType();
3088 
3089   if (!T->isDependentType() &&
3090       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
3091     return ExprError();
3092 
3093   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
3094   return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo,
3095                                                       Context.getSizeType(),
3096                                                       OpLoc, R.getEnd()));
3097 }
3098 
3099 /// \brief Build a sizeof or alignof expression given an expression
3100 /// operand.
3101 ExprResult
3102 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
3103                                      UnaryExprOrTypeTrait ExprKind) {
3104   ExprResult PE = CheckPlaceholderExpr(E);
3105   if (PE.isInvalid())
3106     return ExprError();
3107 
3108   E = PE.get();
3109 
3110   // Verify that the operand is valid.
3111   bool isInvalid = false;
3112   if (E->isTypeDependent()) {
3113     // Delay type-checking for type-dependent expressions.
3114   } else if (ExprKind == UETT_AlignOf) {
3115     isInvalid = CheckAlignOfExpr(*this, E);
3116   } else if (ExprKind == UETT_VecStep) {
3117     isInvalid = CheckVecStepExpr(E);
3118   } else if (E->getBitField()) {  // C99 6.5.3.4p1.
3119     Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0;
3120     isInvalid = true;
3121   } else {
3122     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
3123   }
3124 
3125   if (isInvalid)
3126     return ExprError();
3127 
3128   if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
3129     PE = TranformToPotentiallyEvaluated(E);
3130     if (PE.isInvalid()) return ExprError();
3131     E = PE.take();
3132   }
3133 
3134   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
3135   return Owned(new (Context) UnaryExprOrTypeTraitExpr(
3136       ExprKind, E, Context.getSizeType(), OpLoc,
3137       E->getSourceRange().getEnd()));
3138 }
3139 
3140 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
3141 /// expr and the same for @c alignof and @c __alignof
3142 /// Note that the ArgRange is invalid if isType is false.
3143 ExprResult
3144 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
3145                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
3146                                     void *TyOrEx, const SourceRange &ArgRange) {
3147   // If error parsing type, ignore.
3148   if (TyOrEx == 0) return ExprError();
3149 
3150   if (IsType) {
3151     TypeSourceInfo *TInfo;
3152     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
3153     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
3154   }
3155 
3156   Expr *ArgEx = (Expr *)TyOrEx;
3157   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
3158   return Result;
3159 }
3160 
3161 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
3162                                      bool IsReal) {
3163   if (V.get()->isTypeDependent())
3164     return S.Context.DependentTy;
3165 
3166   // _Real and _Imag are only l-values for normal l-values.
3167   if (V.get()->getObjectKind() != OK_Ordinary) {
3168     V = S.DefaultLvalueConversion(V.take());
3169     if (V.isInvalid())
3170       return QualType();
3171   }
3172 
3173   // These operators return the element type of a complex type.
3174   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
3175     return CT->getElementType();
3176 
3177   // Otherwise they pass through real integer and floating point types here.
3178   if (V.get()->getType()->isArithmeticType())
3179     return V.get()->getType();
3180 
3181   // Test for placeholders.
3182   ExprResult PR = S.CheckPlaceholderExpr(V.get());
3183   if (PR.isInvalid()) return QualType();
3184   if (PR.get() != V.get()) {
3185     V = PR;
3186     return CheckRealImagOperand(S, V, Loc, IsReal);
3187   }
3188 
3189   // Reject anything else.
3190   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
3191     << (IsReal ? "__real" : "__imag");
3192   return QualType();
3193 }
3194 
3195 
3196 
3197 ExprResult
3198 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
3199                           tok::TokenKind Kind, Expr *Input) {
3200   UnaryOperatorKind Opc;
3201   switch (Kind) {
3202   default: llvm_unreachable("Unknown unary op!");
3203   case tok::plusplus:   Opc = UO_PostInc; break;
3204   case tok::minusminus: Opc = UO_PostDec; break;
3205   }
3206 
3207   // Since this might is a postfix expression, get rid of ParenListExprs.
3208   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
3209   if (Result.isInvalid()) return ExprError();
3210   Input = Result.take();
3211 
3212   return BuildUnaryOp(S, OpLoc, Opc, Input);
3213 }
3214 
3215 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal.
3216 ///
3217 /// \return true on error
3218 static bool checkArithmeticOnObjCPointer(Sema &S,
3219                                          SourceLocation opLoc,
3220                                          Expr *op) {
3221   assert(op->getType()->isObjCObjectPointerType());
3222   if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic())
3223     return false;
3224 
3225   S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
3226     << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
3227     << op->getSourceRange();
3228   return true;
3229 }
3230 
3231 ExprResult
3232 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
3233                               Expr *Idx, SourceLocation RLoc) {
3234   // Since this might be a postfix expression, get rid of ParenListExprs.
3235   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
3236   if (Result.isInvalid()) return ExprError();
3237   Base = Result.take();
3238 
3239   Expr *LHSExp = Base, *RHSExp = Idx;
3240 
3241   if (getLangOpts().CPlusPlus &&
3242       (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
3243     return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
3244                                                   Context.DependentTy,
3245                                                   VK_LValue, OK_Ordinary,
3246                                                   RLoc));
3247   }
3248 
3249   if (getLangOpts().CPlusPlus &&
3250       (LHSExp->getType()->isRecordType() ||
3251        LHSExp->getType()->isEnumeralType() ||
3252        RHSExp->getType()->isRecordType() ||
3253        RHSExp->getType()->isEnumeralType()) &&
3254       !LHSExp->getType()->isObjCObjectPointerType()) {
3255     return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
3256   }
3257 
3258   return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
3259 }
3260 
3261 ExprResult
3262 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
3263                                       Expr *Idx, SourceLocation RLoc) {
3264   Expr *LHSExp = Base;
3265   Expr *RHSExp = Idx;
3266 
3267   // Perform default conversions.
3268   if (!LHSExp->getType()->getAs<VectorType>()) {
3269     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
3270     if (Result.isInvalid())
3271       return ExprError();
3272     LHSExp = Result.take();
3273   }
3274   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
3275   if (Result.isInvalid())
3276     return ExprError();
3277   RHSExp = Result.take();
3278 
3279   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
3280   ExprValueKind VK = VK_LValue;
3281   ExprObjectKind OK = OK_Ordinary;
3282 
3283   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
3284   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
3285   // in the subscript position. As a result, we need to derive the array base
3286   // and index from the expression types.
3287   Expr *BaseExpr, *IndexExpr;
3288   QualType ResultType;
3289   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3290     BaseExpr = LHSExp;
3291     IndexExpr = RHSExp;
3292     ResultType = Context.DependentTy;
3293   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
3294     BaseExpr = LHSExp;
3295     IndexExpr = RHSExp;
3296     ResultType = PTy->getPointeeType();
3297   } else if (const ObjCObjectPointerType *PTy =
3298                LHSTy->getAs<ObjCObjectPointerType>()) {
3299     BaseExpr = LHSExp;
3300     IndexExpr = RHSExp;
3301 
3302     // Use custom logic if this should be the pseudo-object subscript
3303     // expression.
3304     if (!LangOpts.ObjCRuntime.isSubscriptPointerArithmetic())
3305       return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, 0, 0);
3306 
3307     ResultType = PTy->getPointeeType();
3308     if (!LangOpts.ObjCRuntime.allowsPointerArithmetic()) {
3309       Diag(LLoc, diag::err_subscript_nonfragile_interface)
3310         << ResultType << BaseExpr->getSourceRange();
3311       return ExprError();
3312     }
3313   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
3314      // Handle the uncommon case of "123[Ptr]".
3315     BaseExpr = RHSExp;
3316     IndexExpr = LHSExp;
3317     ResultType = PTy->getPointeeType();
3318   } else if (const ObjCObjectPointerType *PTy =
3319                RHSTy->getAs<ObjCObjectPointerType>()) {
3320      // Handle the uncommon case of "123[Ptr]".
3321     BaseExpr = RHSExp;
3322     IndexExpr = LHSExp;
3323     ResultType = PTy->getPointeeType();
3324     if (!LangOpts.ObjCRuntime.allowsPointerArithmetic()) {
3325       Diag(LLoc, diag::err_subscript_nonfragile_interface)
3326         << ResultType << BaseExpr->getSourceRange();
3327       return ExprError();
3328     }
3329   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
3330     BaseExpr = LHSExp;    // vectors: V[123]
3331     IndexExpr = RHSExp;
3332     VK = LHSExp->getValueKind();
3333     if (VK != VK_RValue)
3334       OK = OK_VectorComponent;
3335 
3336     // FIXME: need to deal with const...
3337     ResultType = VTy->getElementType();
3338   } else if (LHSTy->isArrayType()) {
3339     // If we see an array that wasn't promoted by
3340     // DefaultFunctionArrayLvalueConversion, it must be an array that
3341     // wasn't promoted because of the C90 rule that doesn't
3342     // allow promoting non-lvalue arrays.  Warn, then
3343     // force the promotion here.
3344     Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3345         LHSExp->getSourceRange();
3346     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
3347                                CK_ArrayToPointerDecay).take();
3348     LHSTy = LHSExp->getType();
3349 
3350     BaseExpr = LHSExp;
3351     IndexExpr = RHSExp;
3352     ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
3353   } else if (RHSTy->isArrayType()) {
3354     // Same as previous, except for 123[f().a] case
3355     Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3356         RHSExp->getSourceRange();
3357     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
3358                                CK_ArrayToPointerDecay).take();
3359     RHSTy = RHSExp->getType();
3360 
3361     BaseExpr = RHSExp;
3362     IndexExpr = LHSExp;
3363     ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
3364   } else {
3365     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3366        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
3367   }
3368   // C99 6.5.2.1p1
3369   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
3370     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3371                      << IndexExpr->getSourceRange());
3372 
3373   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
3374        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3375          && !IndexExpr->isTypeDependent())
3376     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3377 
3378   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
3379   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3380   // type. Note that Functions are not objects, and that (in C99 parlance)
3381   // incomplete types are not object types.
3382   if (ResultType->isFunctionType()) {
3383     Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3384       << ResultType << BaseExpr->getSourceRange();
3385     return ExprError();
3386   }
3387 
3388   if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
3389     // GNU extension: subscripting on pointer to void
3390     Diag(LLoc, diag::ext_gnu_subscript_void_type)
3391       << BaseExpr->getSourceRange();
3392 
3393     // C forbids expressions of unqualified void type from being l-values.
3394     // See IsCForbiddenLValueType.
3395     if (!ResultType.hasQualifiers()) VK = VK_RValue;
3396   } else if (!ResultType->isDependentType() &&
3397       RequireCompleteType(LLoc, ResultType,
3398                           diag::err_subscript_incomplete_type, BaseExpr))
3399     return ExprError();
3400 
3401   assert(VK == VK_RValue || LangOpts.CPlusPlus ||
3402          !ResultType.isCForbiddenLValueType());
3403 
3404   return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
3405                                                 ResultType, VK, OK, RLoc));
3406 }
3407 
3408 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
3409                                         FunctionDecl *FD,
3410                                         ParmVarDecl *Param) {
3411   if (Param->hasUnparsedDefaultArg()) {
3412     Diag(CallLoc,
3413          diag::err_use_of_default_argument_to_function_declared_later) <<
3414       FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
3415     Diag(UnparsedDefaultArgLocs[Param],
3416          diag::note_default_argument_declared_here);
3417     return ExprError();
3418   }
3419 
3420   if (Param->hasUninstantiatedDefaultArg()) {
3421     Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
3422 
3423     EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated,
3424                                                  Param);
3425 
3426     // Instantiate the expression.
3427     MultiLevelTemplateArgumentList ArgList
3428       = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
3429 
3430     std::pair<const TemplateArgument *, unsigned> Innermost
3431       = ArgList.getInnermost();
3432     InstantiatingTemplate Inst(*this, CallLoc, Param,
3433                                ArrayRef<TemplateArgument>(Innermost.first,
3434                                                           Innermost.second));
3435     if (Inst)
3436       return ExprError();
3437 
3438     ExprResult Result;
3439     {
3440       // C++ [dcl.fct.default]p5:
3441       //   The names in the [default argument] expression are bound, and
3442       //   the semantic constraints are checked, at the point where the
3443       //   default argument expression appears.
3444       ContextRAII SavedContext(*this, FD);
3445       LocalInstantiationScope Local(*this);
3446       Result = SubstExpr(UninstExpr, ArgList);
3447     }
3448     if (Result.isInvalid())
3449       return ExprError();
3450 
3451     // Check the expression as an initializer for the parameter.
3452     InitializedEntity Entity
3453       = InitializedEntity::InitializeParameter(Context, Param);
3454     InitializationKind Kind
3455       = InitializationKind::CreateCopy(Param->getLocation(),
3456              /*FIXME:EqualLoc*/UninstExpr->getLocStart());
3457     Expr *ResultE = Result.takeAs<Expr>();
3458 
3459     InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
3460     Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
3461     if (Result.isInvalid())
3462       return ExprError();
3463 
3464     Expr *Arg = Result.takeAs<Expr>();
3465     CheckImplicitConversions(Arg, Param->getOuterLocStart());
3466     // Build the default argument expression.
3467     return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param, Arg));
3468   }
3469 
3470   // If the default expression creates temporaries, we need to
3471   // push them to the current stack of expression temporaries so they'll
3472   // be properly destroyed.
3473   // FIXME: We should really be rebuilding the default argument with new
3474   // bound temporaries; see the comment in PR5810.
3475   // We don't need to do that with block decls, though, because
3476   // blocks in default argument expression can never capture anything.
3477   if (isa<ExprWithCleanups>(Param->getInit())) {
3478     // Set the "needs cleanups" bit regardless of whether there are
3479     // any explicit objects.
3480     ExprNeedsCleanups = true;
3481 
3482     // Append all the objects to the cleanup list.  Right now, this
3483     // should always be a no-op, because blocks in default argument
3484     // expressions should never be able to capture anything.
3485     assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() &&
3486            "default argument expression has capturing blocks?");
3487   }
3488 
3489   // We already type-checked the argument, so we know it works.
3490   // Just mark all of the declarations in this potentially-evaluated expression
3491   // as being "referenced".
3492   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
3493                                    /*SkipLocalVariables=*/true);
3494   return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
3495 }
3496 
3497 
3498 Sema::VariadicCallType
3499 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
3500                           Expr *Fn) {
3501   if (Proto && Proto->isVariadic()) {
3502     if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
3503       return VariadicConstructor;
3504     else if (Fn && Fn->getType()->isBlockPointerType())
3505       return VariadicBlock;
3506     else if (FDecl) {
3507       if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3508         if (Method->isInstance())
3509           return VariadicMethod;
3510     }
3511     return VariadicFunction;
3512   }
3513   return VariadicDoesNotApply;
3514 }
3515 
3516 /// ConvertArgumentsForCall - Converts the arguments specified in
3517 /// Args/NumArgs to the parameter types of the function FDecl with
3518 /// function prototype Proto. Call is the call expression itself, and
3519 /// Fn is the function expression. For a C++ member function, this
3520 /// routine does not attempt to convert the object argument. Returns
3521 /// true if the call is ill-formed.
3522 bool
3523 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
3524                               FunctionDecl *FDecl,
3525                               const FunctionProtoType *Proto,
3526                               Expr **Args, unsigned NumArgs,
3527                               SourceLocation RParenLoc,
3528                               bool IsExecConfig) {
3529   // Bail out early if calling a builtin with custom typechecking.
3530   // We don't need to do this in the
3531   if (FDecl)
3532     if (unsigned ID = FDecl->getBuiltinID())
3533       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
3534         return false;
3535 
3536   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
3537   // assignment, to the types of the corresponding parameter, ...
3538   unsigned NumArgsInProto = Proto->getNumArgs();
3539   bool Invalid = false;
3540   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumArgsInProto;
3541   unsigned FnKind = Fn->getType()->isBlockPointerType()
3542                        ? 1 /* block */
3543                        : (IsExecConfig ? 3 /* kernel function (exec config) */
3544                                        : 0 /* function */);
3545 
3546   // If too few arguments are available (and we don't have default
3547   // arguments for the remaining parameters), don't make the call.
3548   if (NumArgs < NumArgsInProto) {
3549     if (NumArgs < MinArgs) {
3550       if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
3551         Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic()
3552                           ? diag::err_typecheck_call_too_few_args_one
3553                           : diag::err_typecheck_call_too_few_args_at_least_one)
3554           << FnKind
3555           << FDecl->getParamDecl(0) << Fn->getSourceRange();
3556       else
3557         Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic()
3558                           ? diag::err_typecheck_call_too_few_args
3559                           : diag::err_typecheck_call_too_few_args_at_least)
3560           << FnKind
3561           << MinArgs << NumArgs << Fn->getSourceRange();
3562 
3563       // Emit the location of the prototype.
3564       if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
3565         Diag(FDecl->getLocStart(), diag::note_callee_decl)
3566           << FDecl;
3567 
3568       return true;
3569     }
3570     Call->setNumArgs(Context, NumArgsInProto);
3571   }
3572 
3573   // If too many are passed and not variadic, error on the extras and drop
3574   // them.
3575   if (NumArgs > NumArgsInProto) {
3576     if (!Proto->isVariadic()) {
3577       if (NumArgsInProto == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
3578         Diag(Args[NumArgsInProto]->getLocStart(),
3579              MinArgs == NumArgsInProto
3580                ? diag::err_typecheck_call_too_many_args_one
3581                : diag::err_typecheck_call_too_many_args_at_most_one)
3582           << FnKind
3583           << FDecl->getParamDecl(0) << NumArgs << Fn->getSourceRange()
3584           << SourceRange(Args[NumArgsInProto]->getLocStart(),
3585                          Args[NumArgs-1]->getLocEnd());
3586       else
3587         Diag(Args[NumArgsInProto]->getLocStart(),
3588              MinArgs == NumArgsInProto
3589                ? diag::err_typecheck_call_too_many_args
3590                : diag::err_typecheck_call_too_many_args_at_most)
3591           << FnKind
3592           << NumArgsInProto << NumArgs << Fn->getSourceRange()
3593           << SourceRange(Args[NumArgsInProto]->getLocStart(),
3594                          Args[NumArgs-1]->getLocEnd());
3595 
3596       // Emit the location of the prototype.
3597       if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
3598         Diag(FDecl->getLocStart(), diag::note_callee_decl)
3599           << FDecl;
3600 
3601       // This deletes the extra arguments.
3602       Call->setNumArgs(Context, NumArgsInProto);
3603       return true;
3604     }
3605   }
3606   SmallVector<Expr *, 8> AllArgs;
3607   VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
3608 
3609   Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
3610                                    Proto, 0, Args, NumArgs, AllArgs, CallType);
3611   if (Invalid)
3612     return true;
3613   unsigned TotalNumArgs = AllArgs.size();
3614   for (unsigned i = 0; i < TotalNumArgs; ++i)
3615     Call->setArg(i, AllArgs[i]);
3616 
3617   return false;
3618 }
3619 
3620 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
3621                                   FunctionDecl *FDecl,
3622                                   const FunctionProtoType *Proto,
3623                                   unsigned FirstProtoArg,
3624                                   Expr **Args, unsigned NumArgs,
3625                                   SmallVector<Expr *, 8> &AllArgs,
3626                                   VariadicCallType CallType,
3627                                   bool AllowExplicit) {
3628   unsigned NumArgsInProto = Proto->getNumArgs();
3629   unsigned NumArgsToCheck = NumArgs;
3630   bool Invalid = false;
3631   if (NumArgs != NumArgsInProto)
3632     // Use default arguments for missing arguments
3633     NumArgsToCheck = NumArgsInProto;
3634   unsigned ArgIx = 0;
3635   // Continue to check argument types (even if we have too few/many args).
3636   for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
3637     QualType ProtoArgType = Proto->getArgType(i);
3638 
3639     Expr *Arg;
3640     ParmVarDecl *Param;
3641     if (ArgIx < NumArgs) {
3642       Arg = Args[ArgIx++];
3643 
3644       if (RequireCompleteType(Arg->getLocStart(),
3645                               ProtoArgType,
3646                               diag::err_call_incomplete_argument, Arg))
3647         return true;
3648 
3649       // Pass the argument
3650       Param = 0;
3651       if (FDecl && i < FDecl->getNumParams())
3652         Param = FDecl->getParamDecl(i);
3653 
3654       // Strip the unbridged-cast placeholder expression off, if applicable.
3655       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
3656           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
3657           (!Param || !Param->hasAttr<CFConsumedAttr>()))
3658         Arg = stripARCUnbridgedCast(Arg);
3659 
3660       InitializedEntity Entity =
3661         Param? InitializedEntity::InitializeParameter(Context, Param)
3662              : InitializedEntity::InitializeParameter(Context, ProtoArgType,
3663                                                       Proto->isArgConsumed(i));
3664       ExprResult ArgE = PerformCopyInitialization(Entity,
3665                                                   SourceLocation(),
3666                                                   Owned(Arg),
3667                                                   /*TopLevelOfInitList=*/false,
3668                                                   AllowExplicit);
3669       if (ArgE.isInvalid())
3670         return true;
3671 
3672       Arg = ArgE.takeAs<Expr>();
3673     } else {
3674       Param = FDecl->getParamDecl(i);
3675 
3676       ExprResult ArgExpr =
3677         BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
3678       if (ArgExpr.isInvalid())
3679         return true;
3680 
3681       Arg = ArgExpr.takeAs<Expr>();
3682     }
3683 
3684     // Check for array bounds violations for each argument to the call. This
3685     // check only triggers warnings when the argument isn't a more complex Expr
3686     // with its own checking, such as a BinaryOperator.
3687     CheckArrayAccess(Arg);
3688 
3689     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
3690     CheckStaticArrayArgument(CallLoc, Param, Arg);
3691 
3692     AllArgs.push_back(Arg);
3693   }
3694 
3695   // If this is a variadic call, handle args passed through "...".
3696   if (CallType != VariadicDoesNotApply) {
3697     // Assume that extern "C" functions with variadic arguments that
3698     // return __unknown_anytype aren't *really* variadic.
3699     if (Proto->getResultType() == Context.UnknownAnyTy &&
3700         FDecl && FDecl->isExternC()) {
3701       for (unsigned i = ArgIx; i != NumArgs; ++i) {
3702         ExprResult arg;
3703         if (isa<ExplicitCastExpr>(Args[i]->IgnoreParens()))
3704           arg = DefaultFunctionArrayLvalueConversion(Args[i]);
3705         else
3706           arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl);
3707         Invalid |= arg.isInvalid();
3708         AllArgs.push_back(arg.take());
3709       }
3710 
3711     // Otherwise do argument promotion, (C99 6.5.2.2p7).
3712     } else {
3713       for (unsigned i = ArgIx; i != NumArgs; ++i) {
3714         ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType,
3715                                                           FDecl);
3716         Invalid |= Arg.isInvalid();
3717         AllArgs.push_back(Arg.take());
3718       }
3719     }
3720 
3721     // Check for array bounds violations.
3722     for (unsigned i = ArgIx; i != NumArgs; ++i)
3723       CheckArrayAccess(Args[i]);
3724   }
3725   return Invalid;
3726 }
3727 
3728 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
3729   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
3730   if (ArrayTypeLoc *ATL = dyn_cast<ArrayTypeLoc>(&TL))
3731     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
3732       << ATL->getLocalSourceRange();
3733 }
3734 
3735 /// CheckStaticArrayArgument - If the given argument corresponds to a static
3736 /// array parameter, check that it is non-null, and that if it is formed by
3737 /// array-to-pointer decay, the underlying array is sufficiently large.
3738 ///
3739 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
3740 /// array type derivation, then for each call to the function, the value of the
3741 /// corresponding actual argument shall provide access to the first element of
3742 /// an array with at least as many elements as specified by the size expression.
3743 void
3744 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
3745                                ParmVarDecl *Param,
3746                                const Expr *ArgExpr) {
3747   // Static array parameters are not supported in C++.
3748   if (!Param || getLangOpts().CPlusPlus)
3749     return;
3750 
3751   QualType OrigTy = Param->getOriginalType();
3752 
3753   const ArrayType *AT = Context.getAsArrayType(OrigTy);
3754   if (!AT || AT->getSizeModifier() != ArrayType::Static)
3755     return;
3756 
3757   if (ArgExpr->isNullPointerConstant(Context,
3758                                      Expr::NPC_NeverValueDependent)) {
3759     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
3760     DiagnoseCalleeStaticArrayParam(*this, Param);
3761     return;
3762   }
3763 
3764   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
3765   if (!CAT)
3766     return;
3767 
3768   const ConstantArrayType *ArgCAT =
3769     Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
3770   if (!ArgCAT)
3771     return;
3772 
3773   if (ArgCAT->getSize().ult(CAT->getSize())) {
3774     Diag(CallLoc, diag::warn_static_array_too_small)
3775       << ArgExpr->getSourceRange()
3776       << (unsigned) ArgCAT->getSize().getZExtValue()
3777       << (unsigned) CAT->getSize().getZExtValue();
3778     DiagnoseCalleeStaticArrayParam(*this, Param);
3779   }
3780 }
3781 
3782 /// Given a function expression of unknown-any type, try to rebuild it
3783 /// to have a function type.
3784 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
3785 
3786 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
3787 /// This provides the location of the left/right parens and a list of comma
3788 /// locations.
3789 ExprResult
3790 Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
3791                     MultiExprArg ArgExprs, SourceLocation RParenLoc,
3792                     Expr *ExecConfig, bool IsExecConfig) {
3793   // Since this might be a postfix expression, get rid of ParenListExprs.
3794   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
3795   if (Result.isInvalid()) return ExprError();
3796   Fn = Result.take();
3797 
3798   if (getLangOpts().CPlusPlus) {
3799     // If this is a pseudo-destructor expression, build the call immediately.
3800     if (isa<CXXPseudoDestructorExpr>(Fn)) {
3801       if (!ArgExprs.empty()) {
3802         // Pseudo-destructor calls should not have any arguments.
3803         Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
3804           << FixItHint::CreateRemoval(
3805                                     SourceRange(ArgExprs[0]->getLocStart(),
3806                                                 ArgExprs.back()->getLocEnd()));
3807       }
3808 
3809       return Owned(new (Context) CallExpr(Context, Fn, MultiExprArg(),
3810                                           Context.VoidTy, VK_RValue,
3811                                           RParenLoc));
3812     }
3813 
3814     // Determine whether this is a dependent call inside a C++ template,
3815     // in which case we won't do any semantic analysis now.
3816     // FIXME: Will need to cache the results of name lookup (including ADL) in
3817     // Fn.
3818     bool Dependent = false;
3819     if (Fn->isTypeDependent())
3820       Dependent = true;
3821     else if (Expr::hasAnyTypeDependentArguments(ArgExprs))
3822       Dependent = true;
3823 
3824     if (Dependent) {
3825       if (ExecConfig) {
3826         return Owned(new (Context) CUDAKernelCallExpr(
3827             Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
3828             Context.DependentTy, VK_RValue, RParenLoc));
3829       } else {
3830         return Owned(new (Context) CallExpr(Context, Fn, ArgExprs,
3831                                             Context.DependentTy, VK_RValue,
3832                                             RParenLoc));
3833       }
3834     }
3835 
3836     // Determine whether this is a call to an object (C++ [over.call.object]).
3837     if (Fn->getType()->isRecordType())
3838       return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc,
3839                                                 ArgExprs.data(),
3840                                                 ArgExprs.size(), RParenLoc));
3841 
3842     if (Fn->getType() == Context.UnknownAnyTy) {
3843       ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
3844       if (result.isInvalid()) return ExprError();
3845       Fn = result.take();
3846     }
3847 
3848     if (Fn->getType() == Context.BoundMemberTy) {
3849       return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs.data(),
3850                                        ArgExprs.size(), RParenLoc);
3851     }
3852   }
3853 
3854   // Check for overloaded calls.  This can happen even in C due to extensions.
3855   if (Fn->getType() == Context.OverloadTy) {
3856     OverloadExpr::FindResult find = OverloadExpr::find(Fn);
3857 
3858     // We aren't supposed to apply this logic for if there's an '&' involved.
3859     if (!find.HasFormOfMemberPointer) {
3860       OverloadExpr *ovl = find.Expression;
3861       if (isa<UnresolvedLookupExpr>(ovl)) {
3862         UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
3863         return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, ArgExprs.data(),
3864                                        ArgExprs.size(), RParenLoc, ExecConfig);
3865       } else {
3866         return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs.data(),
3867                                          ArgExprs.size(), RParenLoc);
3868       }
3869     }
3870   }
3871 
3872   // If we're directly calling a function, get the appropriate declaration.
3873   if (Fn->getType() == Context.UnknownAnyTy) {
3874     ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
3875     if (result.isInvalid()) return ExprError();
3876     Fn = result.take();
3877   }
3878 
3879   Expr *NakedFn = Fn->IgnoreParens();
3880 
3881   NamedDecl *NDecl = 0;
3882   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
3883     if (UnOp->getOpcode() == UO_AddrOf)
3884       NakedFn = UnOp->getSubExpr()->IgnoreParens();
3885 
3886   if (isa<DeclRefExpr>(NakedFn))
3887     NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
3888   else if (isa<MemberExpr>(NakedFn))
3889     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
3890 
3891   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs.data(),
3892                                ArgExprs.size(), RParenLoc, ExecConfig,
3893                                IsExecConfig);
3894 }
3895 
3896 ExprResult
3897 Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
3898                               MultiExprArg ExecConfig, SourceLocation GGGLoc) {
3899   FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
3900   if (!ConfigDecl)
3901     return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
3902                           << "cudaConfigureCall");
3903   QualType ConfigQTy = ConfigDecl->getType();
3904 
3905   DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
3906       ConfigDecl, false, ConfigQTy, VK_LValue, LLLLoc);
3907   MarkFunctionReferenced(LLLLoc, ConfigDecl);
3908 
3909   return ActOnCallExpr(S, ConfigDR, LLLLoc, ExecConfig, GGGLoc, 0,
3910                        /*IsExecConfig=*/true);
3911 }
3912 
3913 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
3914 ///
3915 /// __builtin_astype( value, dst type )
3916 ///
3917 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
3918                                  SourceLocation BuiltinLoc,
3919                                  SourceLocation RParenLoc) {
3920   ExprValueKind VK = VK_RValue;
3921   ExprObjectKind OK = OK_Ordinary;
3922   QualType DstTy = GetTypeFromParser(ParsedDestTy);
3923   QualType SrcTy = E->getType();
3924   if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
3925     return ExprError(Diag(BuiltinLoc,
3926                           diag::err_invalid_astype_of_different_size)
3927                      << DstTy
3928                      << SrcTy
3929                      << E->getSourceRange());
3930   return Owned(new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc,
3931                RParenLoc));
3932 }
3933 
3934 /// BuildResolvedCallExpr - Build a call to a resolved expression,
3935 /// i.e. an expression not of \p OverloadTy.  The expression should
3936 /// unary-convert to an expression of function-pointer or
3937 /// block-pointer type.
3938 ///
3939 /// \param NDecl the declaration being called, if available
3940 ExprResult
3941 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
3942                             SourceLocation LParenLoc,
3943                             Expr **Args, unsigned NumArgs,
3944                             SourceLocation RParenLoc,
3945                             Expr *Config, bool IsExecConfig) {
3946   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
3947   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
3948 
3949   // Promote the function operand.
3950   // We special-case function promotion here because we only allow promoting
3951   // builtin functions to function pointers in the callee of a call.
3952   ExprResult Result;
3953   if (BuiltinID &&
3954       Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
3955     Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()),
3956                                CK_BuiltinFnToFnPtr).take();
3957   } else {
3958     Result = UsualUnaryConversions(Fn);
3959   }
3960   if (Result.isInvalid())
3961     return ExprError();
3962   Fn = Result.take();
3963 
3964   // Make the call expr early, before semantic checks.  This guarantees cleanup
3965   // of arguments and function on error.
3966   CallExpr *TheCall;
3967   if (Config)
3968     TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
3969                                                cast<CallExpr>(Config),
3970                                                llvm::makeArrayRef(Args,NumArgs),
3971                                                Context.BoolTy,
3972                                                VK_RValue,
3973                                                RParenLoc);
3974   else
3975     TheCall = new (Context) CallExpr(Context, Fn,
3976                                      llvm::makeArrayRef(Args, NumArgs),
3977                                      Context.BoolTy,
3978                                      VK_RValue,
3979                                      RParenLoc);
3980 
3981   // Bail out early if calling a builtin with custom typechecking.
3982   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
3983     return CheckBuiltinFunctionCall(BuiltinID, TheCall);
3984 
3985  retry:
3986   const FunctionType *FuncT;
3987   if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
3988     // C99 6.5.2.2p1 - "The expression that denotes the called function shall
3989     // have type pointer to function".
3990     FuncT = PT->getPointeeType()->getAs<FunctionType>();
3991     if (FuncT == 0)
3992       return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3993                          << Fn->getType() << Fn->getSourceRange());
3994   } else if (const BlockPointerType *BPT =
3995                Fn->getType()->getAs<BlockPointerType>()) {
3996     FuncT = BPT->getPointeeType()->castAs<FunctionType>();
3997   } else {
3998     // Handle calls to expressions of unknown-any type.
3999     if (Fn->getType() == Context.UnknownAnyTy) {
4000       ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
4001       if (rewrite.isInvalid()) return ExprError();
4002       Fn = rewrite.take();
4003       TheCall->setCallee(Fn);
4004       goto retry;
4005     }
4006 
4007     return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4008       << Fn->getType() << Fn->getSourceRange());
4009   }
4010 
4011   if (getLangOpts().CUDA) {
4012     if (Config) {
4013       // CUDA: Kernel calls must be to global functions
4014       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
4015         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
4016             << FDecl->getName() << Fn->getSourceRange());
4017 
4018       // CUDA: Kernel function must have 'void' return type
4019       if (!FuncT->getResultType()->isVoidType())
4020         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
4021             << Fn->getType() << Fn->getSourceRange());
4022     } else {
4023       // CUDA: Calls to global functions must be configured
4024       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
4025         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
4026             << FDecl->getName() << Fn->getSourceRange());
4027     }
4028   }
4029 
4030   // Check for a valid return type
4031   if (CheckCallReturnType(FuncT->getResultType(),
4032                           Fn->getLocStart(), TheCall,
4033                           FDecl))
4034     return ExprError();
4035 
4036   // We know the result type of the call, set it.
4037   TheCall->setType(FuncT->getCallResultType(Context));
4038   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
4039 
4040   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
4041   if (Proto) {
4042     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
4043                                 RParenLoc, IsExecConfig))
4044       return ExprError();
4045   } else {
4046     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
4047 
4048     if (FDecl) {
4049       // Check if we have too few/too many template arguments, based
4050       // on our knowledge of the function definition.
4051       const FunctionDecl *Def = 0;
4052       if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
4053         Proto = Def->getType()->getAs<FunctionProtoType>();
4054         if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
4055           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
4056             << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
4057       }
4058 
4059       // If the function we're calling isn't a function prototype, but we have
4060       // a function prototype from a prior declaratiom, use that prototype.
4061       if (!FDecl->hasPrototype())
4062         Proto = FDecl->getType()->getAs<FunctionProtoType>();
4063     }
4064 
4065     // Promote the arguments (C99 6.5.2.2p6).
4066     for (unsigned i = 0; i != NumArgs; i++) {
4067       Expr *Arg = Args[i];
4068 
4069       if (Proto && i < Proto->getNumArgs()) {
4070         InitializedEntity Entity
4071           = InitializedEntity::InitializeParameter(Context,
4072                                                    Proto->getArgType(i),
4073                                                    Proto->isArgConsumed(i));
4074         ExprResult ArgE = PerformCopyInitialization(Entity,
4075                                                     SourceLocation(),
4076                                                     Owned(Arg));
4077         if (ArgE.isInvalid())
4078           return true;
4079 
4080         Arg = ArgE.takeAs<Expr>();
4081 
4082       } else {
4083         ExprResult ArgE = DefaultArgumentPromotion(Arg);
4084 
4085         if (ArgE.isInvalid())
4086           return true;
4087 
4088         Arg = ArgE.takeAs<Expr>();
4089       }
4090 
4091       if (RequireCompleteType(Arg->getLocStart(),
4092                               Arg->getType(),
4093                               diag::err_call_incomplete_argument, Arg))
4094         return ExprError();
4095 
4096       TheCall->setArg(i, Arg);
4097     }
4098   }
4099 
4100   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4101     if (!Method->isStatic())
4102       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
4103         << Fn->getSourceRange());
4104 
4105   // Check for sentinels
4106   if (NDecl)
4107     DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
4108 
4109   // Do special checking on direct calls to functions.
4110   if (FDecl) {
4111     if (CheckFunctionCall(FDecl, TheCall, Proto))
4112       return ExprError();
4113 
4114     if (BuiltinID)
4115       return CheckBuiltinFunctionCall(BuiltinID, TheCall);
4116   } else if (NDecl) {
4117     if (CheckBlockCall(NDecl, TheCall, Proto))
4118       return ExprError();
4119   }
4120 
4121   return MaybeBindToTemporary(TheCall);
4122 }
4123 
4124 ExprResult
4125 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
4126                            SourceLocation RParenLoc, Expr *InitExpr) {
4127   assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
4128   // FIXME: put back this assert when initializers are worked out.
4129   //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
4130 
4131   TypeSourceInfo *TInfo;
4132   QualType literalType = GetTypeFromParser(Ty, &TInfo);
4133   if (!TInfo)
4134     TInfo = Context.getTrivialTypeSourceInfo(literalType);
4135 
4136   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
4137 }
4138 
4139 ExprResult
4140 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
4141                                SourceLocation RParenLoc, Expr *LiteralExpr) {
4142   QualType literalType = TInfo->getType();
4143 
4144   if (literalType->isArrayType()) {
4145     if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
4146           diag::err_illegal_decl_array_incomplete_type,
4147           SourceRange(LParenLoc,
4148                       LiteralExpr->getSourceRange().getEnd())))
4149       return ExprError();
4150     if (literalType->isVariableArrayType())
4151       return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
4152         << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
4153   } else if (!literalType->isDependentType() &&
4154              RequireCompleteType(LParenLoc, literalType,
4155                diag::err_typecheck_decl_incomplete_type,
4156                SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
4157     return ExprError();
4158 
4159   InitializedEntity Entity
4160     = InitializedEntity::InitializeTemporary(literalType);
4161   InitializationKind Kind
4162     = InitializationKind::CreateCStyleCast(LParenLoc,
4163                                            SourceRange(LParenLoc, RParenLoc),
4164                                            /*InitList=*/true);
4165   InitializationSequence InitSeq(*this, Entity, Kind, &LiteralExpr, 1);
4166   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
4167                                       &literalType);
4168   if (Result.isInvalid())
4169     return ExprError();
4170   LiteralExpr = Result.get();
4171 
4172   bool isFileScope = getCurFunctionOrMethodDecl() == 0;
4173   if (isFileScope) { // 6.5.2.5p3
4174     if (CheckForConstantInitializer(LiteralExpr, literalType))
4175       return ExprError();
4176   }
4177 
4178   // In C, compound literals are l-values for some reason.
4179   ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue;
4180 
4181   return MaybeBindToTemporary(
4182            new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
4183                                              VK, LiteralExpr, isFileScope));
4184 }
4185 
4186 ExprResult
4187 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
4188                     SourceLocation RBraceLoc) {
4189   // Immediately handle non-overload placeholders.  Overloads can be
4190   // resolved contextually, but everything else here can't.
4191   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
4192     if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
4193       ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
4194 
4195       // Ignore failures; dropping the entire initializer list because
4196       // of one failure would be terrible for indexing/etc.
4197       if (result.isInvalid()) continue;
4198 
4199       InitArgList[I] = result.take();
4200     }
4201   }
4202 
4203   // Semantic analysis for initializers is done by ActOnDeclarator() and
4204   // CheckInitializer() - it requires knowledge of the object being intialized.
4205 
4206   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
4207                                                RBraceLoc);
4208   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
4209   return Owned(E);
4210 }
4211 
4212 /// Do an explicit extend of the given block pointer if we're in ARC.
4213 static void maybeExtendBlockObject(Sema &S, ExprResult &E) {
4214   assert(E.get()->getType()->isBlockPointerType());
4215   assert(E.get()->isRValue());
4216 
4217   // Only do this in an r-value context.
4218   if (!S.getLangOpts().ObjCAutoRefCount) return;
4219 
4220   E = ImplicitCastExpr::Create(S.Context, E.get()->getType(),
4221                                CK_ARCExtendBlockObject, E.get(),
4222                                /*base path*/ 0, VK_RValue);
4223   S.ExprNeedsCleanups = true;
4224 }
4225 
4226 /// Prepare a conversion of the given expression to an ObjC object
4227 /// pointer type.
4228 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
4229   QualType type = E.get()->getType();
4230   if (type->isObjCObjectPointerType()) {
4231     return CK_BitCast;
4232   } else if (type->isBlockPointerType()) {
4233     maybeExtendBlockObject(*this, E);
4234     return CK_BlockPointerToObjCPointerCast;
4235   } else {
4236     assert(type->isPointerType());
4237     return CK_CPointerToObjCPointerCast;
4238   }
4239 }
4240 
4241 /// Prepares for a scalar cast, performing all the necessary stages
4242 /// except the final cast and returning the kind required.
4243 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
4244   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
4245   // Also, callers should have filtered out the invalid cases with
4246   // pointers.  Everything else should be possible.
4247 
4248   QualType SrcTy = Src.get()->getType();
4249   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
4250     return CK_NoOp;
4251 
4252   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
4253   case Type::STK_MemberPointer:
4254     llvm_unreachable("member pointer type in C");
4255 
4256   case Type::STK_CPointer:
4257   case Type::STK_BlockPointer:
4258   case Type::STK_ObjCObjectPointer:
4259     switch (DestTy->getScalarTypeKind()) {
4260     case Type::STK_CPointer:
4261       return CK_BitCast;
4262     case Type::STK_BlockPointer:
4263       return (SrcKind == Type::STK_BlockPointer
4264                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
4265     case Type::STK_ObjCObjectPointer:
4266       if (SrcKind == Type::STK_ObjCObjectPointer)
4267         return CK_BitCast;
4268       if (SrcKind == Type::STK_CPointer)
4269         return CK_CPointerToObjCPointerCast;
4270       maybeExtendBlockObject(*this, Src);
4271       return CK_BlockPointerToObjCPointerCast;
4272     case Type::STK_Bool:
4273       return CK_PointerToBoolean;
4274     case Type::STK_Integral:
4275       return CK_PointerToIntegral;
4276     case Type::STK_Floating:
4277     case Type::STK_FloatingComplex:
4278     case Type::STK_IntegralComplex:
4279     case Type::STK_MemberPointer:
4280       llvm_unreachable("illegal cast from pointer");
4281     }
4282     llvm_unreachable("Should have returned before this");
4283 
4284   case Type::STK_Bool: // casting from bool is like casting from an integer
4285   case Type::STK_Integral:
4286     switch (DestTy->getScalarTypeKind()) {
4287     case Type::STK_CPointer:
4288     case Type::STK_ObjCObjectPointer:
4289     case Type::STK_BlockPointer:
4290       if (Src.get()->isNullPointerConstant(Context,
4291                                            Expr::NPC_ValueDependentIsNull))
4292         return CK_NullToPointer;
4293       return CK_IntegralToPointer;
4294     case Type::STK_Bool:
4295       return CK_IntegralToBoolean;
4296     case Type::STK_Integral:
4297       return CK_IntegralCast;
4298     case Type::STK_Floating:
4299       return CK_IntegralToFloating;
4300     case Type::STK_IntegralComplex:
4301       Src = ImpCastExprToType(Src.take(),
4302                               DestTy->castAs<ComplexType>()->getElementType(),
4303                               CK_IntegralCast);
4304       return CK_IntegralRealToComplex;
4305     case Type::STK_FloatingComplex:
4306       Src = ImpCastExprToType(Src.take(),
4307                               DestTy->castAs<ComplexType>()->getElementType(),
4308                               CK_IntegralToFloating);
4309       return CK_FloatingRealToComplex;
4310     case Type::STK_MemberPointer:
4311       llvm_unreachable("member pointer type in C");
4312     }
4313     llvm_unreachable("Should have returned before this");
4314 
4315   case Type::STK_Floating:
4316     switch (DestTy->getScalarTypeKind()) {
4317     case Type::STK_Floating:
4318       return CK_FloatingCast;
4319     case Type::STK_Bool:
4320       return CK_FloatingToBoolean;
4321     case Type::STK_Integral:
4322       return CK_FloatingToIntegral;
4323     case Type::STK_FloatingComplex:
4324       Src = ImpCastExprToType(Src.take(),
4325                               DestTy->castAs<ComplexType>()->getElementType(),
4326                               CK_FloatingCast);
4327       return CK_FloatingRealToComplex;
4328     case Type::STK_IntegralComplex:
4329       Src = ImpCastExprToType(Src.take(),
4330                               DestTy->castAs<ComplexType>()->getElementType(),
4331                               CK_FloatingToIntegral);
4332       return CK_IntegralRealToComplex;
4333     case Type::STK_CPointer:
4334     case Type::STK_ObjCObjectPointer:
4335     case Type::STK_BlockPointer:
4336       llvm_unreachable("valid float->pointer cast?");
4337     case Type::STK_MemberPointer:
4338       llvm_unreachable("member pointer type in C");
4339     }
4340     llvm_unreachable("Should have returned before this");
4341 
4342   case Type::STK_FloatingComplex:
4343     switch (DestTy->getScalarTypeKind()) {
4344     case Type::STK_FloatingComplex:
4345       return CK_FloatingComplexCast;
4346     case Type::STK_IntegralComplex:
4347       return CK_FloatingComplexToIntegralComplex;
4348     case Type::STK_Floating: {
4349       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
4350       if (Context.hasSameType(ET, DestTy))
4351         return CK_FloatingComplexToReal;
4352       Src = ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal);
4353       return CK_FloatingCast;
4354     }
4355     case Type::STK_Bool:
4356       return CK_FloatingComplexToBoolean;
4357     case Type::STK_Integral:
4358       Src = ImpCastExprToType(Src.take(),
4359                               SrcTy->castAs<ComplexType>()->getElementType(),
4360                               CK_FloatingComplexToReal);
4361       return CK_FloatingToIntegral;
4362     case Type::STK_CPointer:
4363     case Type::STK_ObjCObjectPointer:
4364     case Type::STK_BlockPointer:
4365       llvm_unreachable("valid complex float->pointer cast?");
4366     case Type::STK_MemberPointer:
4367       llvm_unreachable("member pointer type in C");
4368     }
4369     llvm_unreachable("Should have returned before this");
4370 
4371   case Type::STK_IntegralComplex:
4372     switch (DestTy->getScalarTypeKind()) {
4373     case Type::STK_FloatingComplex:
4374       return CK_IntegralComplexToFloatingComplex;
4375     case Type::STK_IntegralComplex:
4376       return CK_IntegralComplexCast;
4377     case Type::STK_Integral: {
4378       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
4379       if (Context.hasSameType(ET, DestTy))
4380         return CK_IntegralComplexToReal;
4381       Src = ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal);
4382       return CK_IntegralCast;
4383     }
4384     case Type::STK_Bool:
4385       return CK_IntegralComplexToBoolean;
4386     case Type::STK_Floating:
4387       Src = ImpCastExprToType(Src.take(),
4388                               SrcTy->castAs<ComplexType>()->getElementType(),
4389                               CK_IntegralComplexToReal);
4390       return CK_IntegralToFloating;
4391     case Type::STK_CPointer:
4392     case Type::STK_ObjCObjectPointer:
4393     case Type::STK_BlockPointer:
4394       llvm_unreachable("valid complex int->pointer cast?");
4395     case Type::STK_MemberPointer:
4396       llvm_unreachable("member pointer type in C");
4397     }
4398     llvm_unreachable("Should have returned before this");
4399   }
4400 
4401   llvm_unreachable("Unhandled scalar cast");
4402 }
4403 
4404 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
4405                            CastKind &Kind) {
4406   assert(VectorTy->isVectorType() && "Not a vector type!");
4407 
4408   if (Ty->isVectorType() || Ty->isIntegerType()) {
4409     if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
4410       return Diag(R.getBegin(),
4411                   Ty->isVectorType() ?
4412                   diag::err_invalid_conversion_between_vectors :
4413                   diag::err_invalid_conversion_between_vector_and_integer)
4414         << VectorTy << Ty << R;
4415   } else
4416     return Diag(R.getBegin(),
4417                 diag::err_invalid_conversion_between_vector_and_scalar)
4418       << VectorTy << Ty << R;
4419 
4420   Kind = CK_BitCast;
4421   return false;
4422 }
4423 
4424 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
4425                                     Expr *CastExpr, CastKind &Kind) {
4426   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
4427 
4428   QualType SrcTy = CastExpr->getType();
4429 
4430   // If SrcTy is a VectorType, the total size must match to explicitly cast to
4431   // an ExtVectorType.
4432   // In OpenCL, casts between vectors of different types are not allowed.
4433   // (See OpenCL 6.2).
4434   if (SrcTy->isVectorType()) {
4435     if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)
4436         || (getLangOpts().OpenCL &&
4437             (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
4438       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
4439         << DestTy << SrcTy << R;
4440       return ExprError();
4441     }
4442     Kind = CK_BitCast;
4443     return Owned(CastExpr);
4444   }
4445 
4446   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
4447   // conversion will take place first from scalar to elt type, and then
4448   // splat from elt type to vector.
4449   if (SrcTy->isPointerType())
4450     return Diag(R.getBegin(),
4451                 diag::err_invalid_conversion_between_vector_and_scalar)
4452       << DestTy << SrcTy << R;
4453 
4454   QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
4455   ExprResult CastExprRes = Owned(CastExpr);
4456   CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy);
4457   if (CastExprRes.isInvalid())
4458     return ExprError();
4459   CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take();
4460 
4461   Kind = CK_VectorSplat;
4462   return Owned(CastExpr);
4463 }
4464 
4465 ExprResult
4466 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
4467                     Declarator &D, ParsedType &Ty,
4468                     SourceLocation RParenLoc, Expr *CastExpr) {
4469   assert(!D.isInvalidType() && (CastExpr != 0) &&
4470          "ActOnCastExpr(): missing type or expr");
4471 
4472   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
4473   if (D.isInvalidType())
4474     return ExprError();
4475 
4476   if (getLangOpts().CPlusPlus) {
4477     // Check that there are no default arguments (C++ only).
4478     CheckExtraCXXDefaultArguments(D);
4479   }
4480 
4481   checkUnusedDeclAttributes(D);
4482 
4483   QualType castType = castTInfo->getType();
4484   Ty = CreateParsedType(castType, castTInfo);
4485 
4486   bool isVectorLiteral = false;
4487 
4488   // Check for an altivec or OpenCL literal,
4489   // i.e. all the elements are integer constants.
4490   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
4491   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
4492   if ((getLangOpts().AltiVec || getLangOpts().OpenCL)
4493        && castType->isVectorType() && (PE || PLE)) {
4494     if (PLE && PLE->getNumExprs() == 0) {
4495       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
4496       return ExprError();
4497     }
4498     if (PE || PLE->getNumExprs() == 1) {
4499       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
4500       if (!E->getType()->isVectorType())
4501         isVectorLiteral = true;
4502     }
4503     else
4504       isVectorLiteral = true;
4505   }
4506 
4507   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
4508   // then handle it as such.
4509   if (isVectorLiteral)
4510     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
4511 
4512   // If the Expr being casted is a ParenListExpr, handle it specially.
4513   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
4514   // sequence of BinOp comma operators.
4515   if (isa<ParenListExpr>(CastExpr)) {
4516     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
4517     if (Result.isInvalid()) return ExprError();
4518     CastExpr = Result.take();
4519   }
4520 
4521   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
4522 }
4523 
4524 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
4525                                     SourceLocation RParenLoc, Expr *E,
4526                                     TypeSourceInfo *TInfo) {
4527   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
4528          "Expected paren or paren list expression");
4529 
4530   Expr **exprs;
4531   unsigned numExprs;
4532   Expr *subExpr;
4533   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
4534     exprs = PE->getExprs();
4535     numExprs = PE->getNumExprs();
4536   } else {
4537     subExpr = cast<ParenExpr>(E)->getSubExpr();
4538     exprs = &subExpr;
4539     numExprs = 1;
4540   }
4541 
4542   QualType Ty = TInfo->getType();
4543   assert(Ty->isVectorType() && "Expected vector type");
4544 
4545   SmallVector<Expr *, 8> initExprs;
4546   const VectorType *VTy = Ty->getAs<VectorType>();
4547   unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
4548 
4549   // '(...)' form of vector initialization in AltiVec: the number of
4550   // initializers must be one or must match the size of the vector.
4551   // If a single value is specified in the initializer then it will be
4552   // replicated to all the components of the vector
4553   if (VTy->getVectorKind() == VectorType::AltiVecVector) {
4554     // The number of initializers must be one or must match the size of the
4555     // vector. If a single value is specified in the initializer then it will
4556     // be replicated to all the components of the vector
4557     if (numExprs == 1) {
4558       QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
4559       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
4560       if (Literal.isInvalid())
4561         return ExprError();
4562       Literal = ImpCastExprToType(Literal.take(), ElemTy,
4563                                   PrepareScalarCast(Literal, ElemTy));
4564       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4565     }
4566     else if (numExprs < numElems) {
4567       Diag(E->getExprLoc(),
4568            diag::err_incorrect_number_of_vector_initializers);
4569       return ExprError();
4570     }
4571     else
4572       initExprs.append(exprs, exprs + numExprs);
4573   }
4574   else {
4575     // For OpenCL, when the number of initializers is a single value,
4576     // it will be replicated to all components of the vector.
4577     if (getLangOpts().OpenCL &&
4578         VTy->getVectorKind() == VectorType::GenericVector &&
4579         numExprs == 1) {
4580         QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
4581         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
4582         if (Literal.isInvalid())
4583           return ExprError();
4584         Literal = ImpCastExprToType(Literal.take(), ElemTy,
4585                                     PrepareScalarCast(Literal, ElemTy));
4586         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4587     }
4588 
4589     initExprs.append(exprs, exprs + numExprs);
4590   }
4591   // FIXME: This means that pretty-printing the final AST will produce curly
4592   // braces instead of the original commas.
4593   InitListExpr *initE = new (Context) InitListExpr(Context, LParenLoc,
4594                                                    initExprs, RParenLoc);
4595   initE->setType(Ty);
4596   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
4597 }
4598 
4599 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
4600 /// the ParenListExpr into a sequence of comma binary operators.
4601 ExprResult
4602 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
4603   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
4604   if (!E)
4605     return Owned(OrigExpr);
4606 
4607   ExprResult Result(E->getExpr(0));
4608 
4609   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
4610     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
4611                         E->getExpr(i));
4612 
4613   if (Result.isInvalid()) return ExprError();
4614 
4615   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
4616 }
4617 
4618 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
4619                                     SourceLocation R,
4620                                     MultiExprArg Val) {
4621   assert(Val.data() != 0 && "ActOnParenOrParenListExpr() missing expr list");
4622   Expr *expr = new (Context) ParenListExpr(Context, L, Val, R);
4623   return Owned(expr);
4624 }
4625 
4626 /// \brief Emit a specialized diagnostic when one expression is a null pointer
4627 /// constant and the other is not a pointer.  Returns true if a diagnostic is
4628 /// emitted.
4629 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
4630                                       SourceLocation QuestionLoc) {
4631   Expr *NullExpr = LHSExpr;
4632   Expr *NonPointerExpr = RHSExpr;
4633   Expr::NullPointerConstantKind NullKind =
4634       NullExpr->isNullPointerConstant(Context,
4635                                       Expr::NPC_ValueDependentIsNotNull);
4636 
4637   if (NullKind == Expr::NPCK_NotNull) {
4638     NullExpr = RHSExpr;
4639     NonPointerExpr = LHSExpr;
4640     NullKind =
4641         NullExpr->isNullPointerConstant(Context,
4642                                         Expr::NPC_ValueDependentIsNotNull);
4643   }
4644 
4645   if (NullKind == Expr::NPCK_NotNull)
4646     return false;
4647 
4648   if (NullKind == Expr::NPCK_ZeroExpression)
4649     return false;
4650 
4651   if (NullKind == Expr::NPCK_ZeroLiteral) {
4652     // In this case, check to make sure that we got here from a "NULL"
4653     // string in the source code.
4654     NullExpr = NullExpr->IgnoreParenImpCasts();
4655     SourceLocation loc = NullExpr->getExprLoc();
4656     if (!findMacroSpelling(loc, "NULL"))
4657       return false;
4658   }
4659 
4660   int DiagType = (NullKind == Expr::NPCK_CXX0X_nullptr);
4661   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
4662       << NonPointerExpr->getType() << DiagType
4663       << NonPointerExpr->getSourceRange();
4664   return true;
4665 }
4666 
4667 /// \brief Return false if the condition expression is valid, true otherwise.
4668 static bool checkCondition(Sema &S, Expr *Cond) {
4669   QualType CondTy = Cond->getType();
4670 
4671   // C99 6.5.15p2
4672   if (CondTy->isScalarType()) return false;
4673 
4674   // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
4675   if (S.getLangOpts().OpenCL && CondTy->isVectorType())
4676     return false;
4677 
4678   // Emit the proper error message.
4679   S.Diag(Cond->getLocStart(), S.getLangOpts().OpenCL ?
4680                               diag::err_typecheck_cond_expect_scalar :
4681                               diag::err_typecheck_cond_expect_scalar_or_vector)
4682     << CondTy;
4683   return true;
4684 }
4685 
4686 /// \brief Return false if the two expressions can be converted to a vector,
4687 /// true otherwise
4688 static bool checkConditionalConvertScalarsToVectors(Sema &S, ExprResult &LHS,
4689                                                     ExprResult &RHS,
4690                                                     QualType CondTy) {
4691   // Both operands should be of scalar type.
4692   if (!LHS.get()->getType()->isScalarType()) {
4693     S.Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4694       << CondTy;
4695     return true;
4696   }
4697   if (!RHS.get()->getType()->isScalarType()) {
4698     S.Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4699       << CondTy;
4700     return true;
4701   }
4702 
4703   // Implicity convert these scalars to the type of the condition.
4704   LHS = S.ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast);
4705   RHS = S.ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast);
4706   return false;
4707 }
4708 
4709 /// \brief Handle when one or both operands are void type.
4710 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
4711                                          ExprResult &RHS) {
4712     Expr *LHSExpr = LHS.get();
4713     Expr *RHSExpr = RHS.get();
4714 
4715     if (!LHSExpr->getType()->isVoidType())
4716       S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4717         << RHSExpr->getSourceRange();
4718     if (!RHSExpr->getType()->isVoidType())
4719       S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4720         << LHSExpr->getSourceRange();
4721     LHS = S.ImpCastExprToType(LHS.take(), S.Context.VoidTy, CK_ToVoid);
4722     RHS = S.ImpCastExprToType(RHS.take(), S.Context.VoidTy, CK_ToVoid);
4723     return S.Context.VoidTy;
4724 }
4725 
4726 /// \brief Return false if the NullExpr can be promoted to PointerTy,
4727 /// true otherwise.
4728 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
4729                                         QualType PointerTy) {
4730   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
4731       !NullExpr.get()->isNullPointerConstant(S.Context,
4732                                             Expr::NPC_ValueDependentIsNull))
4733     return true;
4734 
4735   NullExpr = S.ImpCastExprToType(NullExpr.take(), PointerTy, CK_NullToPointer);
4736   return false;
4737 }
4738 
4739 /// \brief Checks compatibility between two pointers and return the resulting
4740 /// type.
4741 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
4742                                                      ExprResult &RHS,
4743                                                      SourceLocation Loc) {
4744   QualType LHSTy = LHS.get()->getType();
4745   QualType RHSTy = RHS.get()->getType();
4746 
4747   if (S.Context.hasSameType(LHSTy, RHSTy)) {
4748     // Two identical pointers types are always compatible.
4749     return LHSTy;
4750   }
4751 
4752   QualType lhptee, rhptee;
4753 
4754   // Get the pointee types.
4755   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
4756     lhptee = LHSBTy->getPointeeType();
4757     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
4758   } else {
4759     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
4760     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
4761   }
4762 
4763   // C99 6.5.15p6: If both operands are pointers to compatible types or to
4764   // differently qualified versions of compatible types, the result type is
4765   // a pointer to an appropriately qualified version of the composite
4766   // type.
4767 
4768   // Only CVR-qualifiers exist in the standard, and the differently-qualified
4769   // clause doesn't make sense for our extensions. E.g. address space 2 should
4770   // be incompatible with address space 3: they may live on different devices or
4771   // anything.
4772   Qualifiers lhQual = lhptee.getQualifiers();
4773   Qualifiers rhQual = rhptee.getQualifiers();
4774 
4775   unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
4776   lhQual.removeCVRQualifiers();
4777   rhQual.removeCVRQualifiers();
4778 
4779   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
4780   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
4781 
4782   QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
4783 
4784   if (CompositeTy.isNull()) {
4785     S.Diag(Loc, diag::warn_typecheck_cond_incompatible_pointers)
4786       << LHSTy << RHSTy << LHS.get()->getSourceRange()
4787       << RHS.get()->getSourceRange();
4788     // In this situation, we assume void* type. No especially good
4789     // reason, but this is what gcc does, and we do have to pick
4790     // to get a consistent AST.
4791     QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy);
4792     LHS = S.ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4793     RHS = S.ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
4794     return incompatTy;
4795   }
4796 
4797   // The pointer types are compatible.
4798   QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual);
4799   ResultTy = S.Context.getPointerType(ResultTy);
4800 
4801   LHS = S.ImpCastExprToType(LHS.take(), ResultTy, CK_BitCast);
4802   RHS = S.ImpCastExprToType(RHS.take(), ResultTy, CK_BitCast);
4803   return ResultTy;
4804 }
4805 
4806 /// \brief Return the resulting type when the operands are both block pointers.
4807 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
4808                                                           ExprResult &LHS,
4809                                                           ExprResult &RHS,
4810                                                           SourceLocation Loc) {
4811   QualType LHSTy = LHS.get()->getType();
4812   QualType RHSTy = RHS.get()->getType();
4813 
4814   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
4815     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
4816       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
4817       LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4818       RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4819       return destType;
4820     }
4821     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
4822       << LHSTy << RHSTy << LHS.get()->getSourceRange()
4823       << RHS.get()->getSourceRange();
4824     return QualType();
4825   }
4826 
4827   // We have 2 block pointer types.
4828   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
4829 }
4830 
4831 /// \brief Return the resulting type when the operands are both pointers.
4832 static QualType
4833 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
4834                                             ExprResult &RHS,
4835                                             SourceLocation Loc) {
4836   // get the pointer types
4837   QualType LHSTy = LHS.get()->getType();
4838   QualType RHSTy = RHS.get()->getType();
4839 
4840   // get the "pointed to" types
4841   QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4842   QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4843 
4844   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
4845   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
4846     // Figure out necessary qualifiers (C99 6.5.15p6)
4847     QualType destPointee
4848       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4849     QualType destType = S.Context.getPointerType(destPointee);
4850     // Add qualifiers if necessary.
4851     LHS = S.ImpCastExprToType(LHS.take(), destType, CK_NoOp);
4852     // Promote to void*.
4853     RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4854     return destType;
4855   }
4856   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
4857     QualType destPointee
4858       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4859     QualType destType = S.Context.getPointerType(destPointee);
4860     // Add qualifiers if necessary.
4861     RHS = S.ImpCastExprToType(RHS.take(), destType, CK_NoOp);
4862     // Promote to void*.
4863     LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4864     return destType;
4865   }
4866 
4867   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
4868 }
4869 
4870 /// \brief Return false if the first expression is not an integer and the second
4871 /// expression is not a pointer, true otherwise.
4872 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
4873                                         Expr* PointerExpr, SourceLocation Loc,
4874                                         bool IsIntFirstExpr) {
4875   if (!PointerExpr->getType()->isPointerType() ||
4876       !Int.get()->getType()->isIntegerType())
4877     return false;
4878 
4879   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
4880   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
4881 
4882   S.Diag(Loc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4883     << Expr1->getType() << Expr2->getType()
4884     << Expr1->getSourceRange() << Expr2->getSourceRange();
4885   Int = S.ImpCastExprToType(Int.take(), PointerExpr->getType(),
4886                             CK_IntegralToPointer);
4887   return true;
4888 }
4889 
4890 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
4891 /// In that case, LHS = cond.
4892 /// C99 6.5.15
4893 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
4894                                         ExprResult &RHS, ExprValueKind &VK,
4895                                         ExprObjectKind &OK,
4896                                         SourceLocation QuestionLoc) {
4897 
4898   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
4899   if (!LHSResult.isUsable()) return QualType();
4900   LHS = LHSResult;
4901 
4902   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
4903   if (!RHSResult.isUsable()) return QualType();
4904   RHS = RHSResult;
4905 
4906   // C++ is sufficiently different to merit its own checker.
4907   if (getLangOpts().CPlusPlus)
4908     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
4909 
4910   VK = VK_RValue;
4911   OK = OK_Ordinary;
4912 
4913   Cond = UsualUnaryConversions(Cond.take());
4914   if (Cond.isInvalid())
4915     return QualType();
4916   LHS = UsualUnaryConversions(LHS.take());
4917   if (LHS.isInvalid())
4918     return QualType();
4919   RHS = UsualUnaryConversions(RHS.take());
4920   if (RHS.isInvalid())
4921     return QualType();
4922 
4923   QualType CondTy = Cond.get()->getType();
4924   QualType LHSTy = LHS.get()->getType();
4925   QualType RHSTy = RHS.get()->getType();
4926 
4927   // first, check the condition.
4928   if (checkCondition(*this, Cond.get()))
4929     return QualType();
4930 
4931   // Now check the two expressions.
4932   if (LHSTy->isVectorType() || RHSTy->isVectorType())
4933     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
4934 
4935   // OpenCL: If the condition is a vector, and both operands are scalar,
4936   // attempt to implicity convert them to the vector type to act like the
4937   // built in select.
4938   if (getLangOpts().OpenCL && CondTy->isVectorType())
4939     if (checkConditionalConvertScalarsToVectors(*this, LHS, RHS, CondTy))
4940       return QualType();
4941 
4942   // If both operands have arithmetic type, do the usual arithmetic conversions
4943   // to find a common type: C99 6.5.15p3,5.
4944   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
4945     UsualArithmeticConversions(LHS, RHS);
4946     if (LHS.isInvalid() || RHS.isInvalid())
4947       return QualType();
4948     return LHS.get()->getType();
4949   }
4950 
4951   // If both operands are the same structure or union type, the result is that
4952   // type.
4953   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
4954     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
4955       if (LHSRT->getDecl() == RHSRT->getDecl())
4956         // "If both the operands have structure or union type, the result has
4957         // that type."  This implies that CV qualifiers are dropped.
4958         return LHSTy.getUnqualifiedType();
4959     // FIXME: Type of conditional expression must be complete in C mode.
4960   }
4961 
4962   // C99 6.5.15p5: "If both operands have void type, the result has void type."
4963   // The following || allows only one side to be void (a GCC-ism).
4964   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
4965     return checkConditionalVoidType(*this, LHS, RHS);
4966   }
4967 
4968   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
4969   // the type of the other operand."
4970   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
4971   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
4972 
4973   // All objective-c pointer type analysis is done here.
4974   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
4975                                                         QuestionLoc);
4976   if (LHS.isInvalid() || RHS.isInvalid())
4977     return QualType();
4978   if (!compositeType.isNull())
4979     return compositeType;
4980 
4981 
4982   // Handle block pointer types.
4983   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
4984     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
4985                                                      QuestionLoc);
4986 
4987   // Check constraints for C object pointers types (C99 6.5.15p3,6).
4988   if (LHSTy->isPointerType() && RHSTy->isPointerType())
4989     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
4990                                                        QuestionLoc);
4991 
4992   // GCC compatibility: soften pointer/integer mismatch.  Note that
4993   // null pointers have been filtered out by this point.
4994   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
4995       /*isIntFirstExpr=*/true))
4996     return RHSTy;
4997   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
4998       /*isIntFirstExpr=*/false))
4999     return LHSTy;
5000 
5001   // Emit a better diagnostic if one of the expressions is a null pointer
5002   // constant and the other is not a pointer type. In this case, the user most
5003   // likely forgot to take the address of the other expression.
5004   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
5005     return QualType();
5006 
5007   // Otherwise, the operands are not compatible.
5008   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
5009     << LHSTy << RHSTy << LHS.get()->getSourceRange()
5010     << RHS.get()->getSourceRange();
5011   return QualType();
5012 }
5013 
5014 /// FindCompositeObjCPointerType - Helper method to find composite type of
5015 /// two objective-c pointer types of the two input expressions.
5016 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
5017                                             SourceLocation QuestionLoc) {
5018   QualType LHSTy = LHS.get()->getType();
5019   QualType RHSTy = RHS.get()->getType();
5020 
5021   // Handle things like Class and struct objc_class*.  Here we case the result
5022   // to the pseudo-builtin, because that will be implicitly cast back to the
5023   // redefinition type if an attempt is made to access its fields.
5024   if (LHSTy->isObjCClassType() &&
5025       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
5026     RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
5027     return LHSTy;
5028   }
5029   if (RHSTy->isObjCClassType() &&
5030       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
5031     LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
5032     return RHSTy;
5033   }
5034   // And the same for struct objc_object* / id
5035   if (LHSTy->isObjCIdType() &&
5036       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
5037     RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
5038     return LHSTy;
5039   }
5040   if (RHSTy->isObjCIdType() &&
5041       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
5042     LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
5043     return RHSTy;
5044   }
5045   // And the same for struct objc_selector* / SEL
5046   if (Context.isObjCSelType(LHSTy) &&
5047       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
5048     RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
5049     return LHSTy;
5050   }
5051   if (Context.isObjCSelType(RHSTy) &&
5052       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
5053     LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
5054     return RHSTy;
5055   }
5056   // Check constraints for Objective-C object pointers types.
5057   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
5058 
5059     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5060       // Two identical object pointer types are always compatible.
5061       return LHSTy;
5062     }
5063     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
5064     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
5065     QualType compositeType = LHSTy;
5066 
5067     // If both operands are interfaces and either operand can be
5068     // assigned to the other, use that type as the composite
5069     // type. This allows
5070     //   xxx ? (A*) a : (B*) b
5071     // where B is a subclass of A.
5072     //
5073     // Additionally, as for assignment, if either type is 'id'
5074     // allow silent coercion. Finally, if the types are
5075     // incompatible then make sure to use 'id' as the composite
5076     // type so the result is acceptable for sending messages to.
5077 
5078     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
5079     // It could return the composite type.
5080     if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
5081       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
5082     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
5083       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
5084     } else if ((LHSTy->isObjCQualifiedIdType() ||
5085                 RHSTy->isObjCQualifiedIdType()) &&
5086                Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
5087       // Need to handle "id<xx>" explicitly.
5088       // GCC allows qualified id and any Objective-C type to devolve to
5089       // id. Currently localizing to here until clear this should be
5090       // part of ObjCQualifiedIdTypesAreCompatible.
5091       compositeType = Context.getObjCIdType();
5092     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
5093       compositeType = Context.getObjCIdType();
5094     } else if (!(compositeType =
5095                  Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
5096       ;
5097     else {
5098       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
5099       << LHSTy << RHSTy
5100       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5101       QualType incompatTy = Context.getObjCIdType();
5102       LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
5103       RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
5104       return incompatTy;
5105     }
5106     // The object pointer types are compatible.
5107     LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast);
5108     RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast);
5109     return compositeType;
5110   }
5111   // Check Objective-C object pointer types and 'void *'
5112   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
5113     if (getLangOpts().ObjCAutoRefCount) {
5114       // ARC forbids the implicit conversion of object pointers to 'void *',
5115       // so these types are not compatible.
5116       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
5117           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5118       LHS = RHS = true;
5119       return QualType();
5120     }
5121     QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5122     QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5123     QualType destPointee
5124     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
5125     QualType destType = Context.getPointerType(destPointee);
5126     // Add qualifiers if necessary.
5127     LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
5128     // Promote to void*.
5129     RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
5130     return destType;
5131   }
5132   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
5133     if (getLangOpts().ObjCAutoRefCount) {
5134       // ARC forbids the implicit conversion of object pointers to 'void *',
5135       // so these types are not compatible.
5136       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
5137           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5138       LHS = RHS = true;
5139       return QualType();
5140     }
5141     QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5142     QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
5143     QualType destPointee
5144     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
5145     QualType destType = Context.getPointerType(destPointee);
5146     // Add qualifiers if necessary.
5147     RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
5148     // Promote to void*.
5149     LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
5150     return destType;
5151   }
5152   return QualType();
5153 }
5154 
5155 /// SuggestParentheses - Emit a note with a fixit hint that wraps
5156 /// ParenRange in parentheses.
5157 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
5158                                const PartialDiagnostic &Note,
5159                                SourceRange ParenRange) {
5160   SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
5161   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
5162       EndLoc.isValid()) {
5163     Self.Diag(Loc, Note)
5164       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
5165       << FixItHint::CreateInsertion(EndLoc, ")");
5166   } else {
5167     // We can't display the parentheses, so just show the bare note.
5168     Self.Diag(Loc, Note) << ParenRange;
5169   }
5170 }
5171 
5172 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
5173   return Opc >= BO_Mul && Opc <= BO_Shr;
5174 }
5175 
5176 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
5177 /// expression, either using a built-in or overloaded operator,
5178 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
5179 /// expression.
5180 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
5181                                    Expr **RHSExprs) {
5182   // Don't strip parenthesis: we should not warn if E is in parenthesis.
5183   E = E->IgnoreImpCasts();
5184   E = E->IgnoreConversionOperator();
5185   E = E->IgnoreImpCasts();
5186 
5187   // Built-in binary operator.
5188   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
5189     if (IsArithmeticOp(OP->getOpcode())) {
5190       *Opcode = OP->getOpcode();
5191       *RHSExprs = OP->getRHS();
5192       return true;
5193     }
5194   }
5195 
5196   // Overloaded operator.
5197   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
5198     if (Call->getNumArgs() != 2)
5199       return false;
5200 
5201     // Make sure this is really a binary operator that is safe to pass into
5202     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
5203     OverloadedOperatorKind OO = Call->getOperator();
5204     if (OO < OO_Plus || OO > OO_Arrow)
5205       return false;
5206 
5207     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
5208     if (IsArithmeticOp(OpKind)) {
5209       *Opcode = OpKind;
5210       *RHSExprs = Call->getArg(1);
5211       return true;
5212     }
5213   }
5214 
5215   return false;
5216 }
5217 
5218 static bool IsLogicOp(BinaryOperatorKind Opc) {
5219   return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
5220 }
5221 
5222 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
5223 /// or is a logical expression such as (x==y) which has int type, but is
5224 /// commonly interpreted as boolean.
5225 static bool ExprLooksBoolean(Expr *E) {
5226   E = E->IgnoreParenImpCasts();
5227 
5228   if (E->getType()->isBooleanType())
5229     return true;
5230   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
5231     return IsLogicOp(OP->getOpcode());
5232   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
5233     return OP->getOpcode() == UO_LNot;
5234 
5235   return false;
5236 }
5237 
5238 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
5239 /// and binary operator are mixed in a way that suggests the programmer assumed
5240 /// the conditional operator has higher precedence, for example:
5241 /// "int x = a + someBinaryCondition ? 1 : 2".
5242 static void DiagnoseConditionalPrecedence(Sema &Self,
5243                                           SourceLocation OpLoc,
5244                                           Expr *Condition,
5245                                           Expr *LHSExpr,
5246                                           Expr *RHSExpr) {
5247   BinaryOperatorKind CondOpcode;
5248   Expr *CondRHS;
5249 
5250   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
5251     return;
5252   if (!ExprLooksBoolean(CondRHS))
5253     return;
5254 
5255   // The condition is an arithmetic binary expression, with a right-
5256   // hand side that looks boolean, so warn.
5257 
5258   Self.Diag(OpLoc, diag::warn_precedence_conditional)
5259       << Condition->getSourceRange()
5260       << BinaryOperator::getOpcodeStr(CondOpcode);
5261 
5262   SuggestParentheses(Self, OpLoc,
5263     Self.PDiag(diag::note_precedence_conditional_silence)
5264       << BinaryOperator::getOpcodeStr(CondOpcode),
5265     SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
5266 
5267   SuggestParentheses(Self, OpLoc,
5268     Self.PDiag(diag::note_precedence_conditional_first),
5269     SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
5270 }
5271 
5272 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
5273 /// in the case of a the GNU conditional expr extension.
5274 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
5275                                     SourceLocation ColonLoc,
5276                                     Expr *CondExpr, Expr *LHSExpr,
5277                                     Expr *RHSExpr) {
5278   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
5279   // was the condition.
5280   OpaqueValueExpr *opaqueValue = 0;
5281   Expr *commonExpr = 0;
5282   if (LHSExpr == 0) {
5283     commonExpr = CondExpr;
5284 
5285     // We usually want to apply unary conversions *before* saving, except
5286     // in the special case of a C++ l-value conditional.
5287     if (!(getLangOpts().CPlusPlus
5288           && !commonExpr->isTypeDependent()
5289           && commonExpr->getValueKind() == RHSExpr->getValueKind()
5290           && commonExpr->isGLValue()
5291           && commonExpr->isOrdinaryOrBitFieldObject()
5292           && RHSExpr->isOrdinaryOrBitFieldObject()
5293           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
5294       ExprResult commonRes = UsualUnaryConversions(commonExpr);
5295       if (commonRes.isInvalid())
5296         return ExprError();
5297       commonExpr = commonRes.take();
5298     }
5299 
5300     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
5301                                                 commonExpr->getType(),
5302                                                 commonExpr->getValueKind(),
5303                                                 commonExpr->getObjectKind(),
5304                                                 commonExpr);
5305     LHSExpr = CondExpr = opaqueValue;
5306   }
5307 
5308   ExprValueKind VK = VK_RValue;
5309   ExprObjectKind OK = OK_Ordinary;
5310   ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
5311   QualType result = CheckConditionalOperands(Cond, LHS, RHS,
5312                                              VK, OK, QuestionLoc);
5313   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
5314       RHS.isInvalid())
5315     return ExprError();
5316 
5317   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
5318                                 RHS.get());
5319 
5320   if (!commonExpr)
5321     return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc,
5322                                                    LHS.take(), ColonLoc,
5323                                                    RHS.take(), result, VK, OK));
5324 
5325   return Owned(new (Context)
5326     BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(),
5327                               RHS.take(), QuestionLoc, ColonLoc, result, VK,
5328                               OK));
5329 }
5330 
5331 // checkPointerTypesForAssignment - This is a very tricky routine (despite
5332 // being closely modeled after the C99 spec:-). The odd characteristic of this
5333 // routine is it effectively iqnores the qualifiers on the top level pointee.
5334 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
5335 // FIXME: add a couple examples in this comment.
5336 static Sema::AssignConvertType
5337 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
5338   assert(LHSType.isCanonical() && "LHS not canonicalized!");
5339   assert(RHSType.isCanonical() && "RHS not canonicalized!");
5340 
5341   // get the "pointed to" type (ignoring qualifiers at the top level)
5342   const Type *lhptee, *rhptee;
5343   Qualifiers lhq, rhq;
5344   llvm::tie(lhptee, lhq) = cast<PointerType>(LHSType)->getPointeeType().split();
5345   llvm::tie(rhptee, rhq) = cast<PointerType>(RHSType)->getPointeeType().split();
5346 
5347   Sema::AssignConvertType ConvTy = Sema::Compatible;
5348 
5349   // C99 6.5.16.1p1: This following citation is common to constraints
5350   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
5351   // qualifiers of the type *pointed to* by the right;
5352   Qualifiers lq;
5353 
5354   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
5355   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
5356       lhq.compatiblyIncludesObjCLifetime(rhq)) {
5357     // Ignore lifetime for further calculation.
5358     lhq.removeObjCLifetime();
5359     rhq.removeObjCLifetime();
5360   }
5361 
5362   if (!lhq.compatiblyIncludes(rhq)) {
5363     // Treat address-space mismatches as fatal.  TODO: address subspaces
5364     if (lhq.getAddressSpace() != rhq.getAddressSpace())
5365       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5366 
5367     // It's okay to add or remove GC or lifetime qualifiers when converting to
5368     // and from void*.
5369     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
5370                         .compatiblyIncludes(
5371                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
5372              && (lhptee->isVoidType() || rhptee->isVoidType()))
5373       ; // keep old
5374 
5375     // Treat lifetime mismatches as fatal.
5376     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
5377       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5378 
5379     // For GCC compatibility, other qualifier mismatches are treated
5380     // as still compatible in C.
5381     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
5382   }
5383 
5384   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
5385   // incomplete type and the other is a pointer to a qualified or unqualified
5386   // version of void...
5387   if (lhptee->isVoidType()) {
5388     if (rhptee->isIncompleteOrObjectType())
5389       return ConvTy;
5390 
5391     // As an extension, we allow cast to/from void* to function pointer.
5392     assert(rhptee->isFunctionType());
5393     return Sema::FunctionVoidPointer;
5394   }
5395 
5396   if (rhptee->isVoidType()) {
5397     if (lhptee->isIncompleteOrObjectType())
5398       return ConvTy;
5399 
5400     // As an extension, we allow cast to/from void* to function pointer.
5401     assert(lhptee->isFunctionType());
5402     return Sema::FunctionVoidPointer;
5403   }
5404 
5405   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
5406   // unqualified versions of compatible types, ...
5407   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
5408   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
5409     // Check if the pointee types are compatible ignoring the sign.
5410     // We explicitly check for char so that we catch "char" vs
5411     // "unsigned char" on systems where "char" is unsigned.
5412     if (lhptee->isCharType())
5413       ltrans = S.Context.UnsignedCharTy;
5414     else if (lhptee->hasSignedIntegerRepresentation())
5415       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
5416 
5417     if (rhptee->isCharType())
5418       rtrans = S.Context.UnsignedCharTy;
5419     else if (rhptee->hasSignedIntegerRepresentation())
5420       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
5421 
5422     if (ltrans == rtrans) {
5423       // Types are compatible ignoring the sign. Qualifier incompatibility
5424       // takes priority over sign incompatibility because the sign
5425       // warning can be disabled.
5426       if (ConvTy != Sema::Compatible)
5427         return ConvTy;
5428 
5429       return Sema::IncompatiblePointerSign;
5430     }
5431 
5432     // If we are a multi-level pointer, it's possible that our issue is simply
5433     // one of qualification - e.g. char ** -> const char ** is not allowed. If
5434     // the eventual target type is the same and the pointers have the same
5435     // level of indirection, this must be the issue.
5436     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
5437       do {
5438         lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
5439         rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
5440       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
5441 
5442       if (lhptee == rhptee)
5443         return Sema::IncompatibleNestedPointerQualifiers;
5444     }
5445 
5446     // General pointer incompatibility takes priority over qualifiers.
5447     return Sema::IncompatiblePointer;
5448   }
5449   if (!S.getLangOpts().CPlusPlus &&
5450       S.IsNoReturnConversion(ltrans, rtrans, ltrans))
5451     return Sema::IncompatiblePointer;
5452   return ConvTy;
5453 }
5454 
5455 /// checkBlockPointerTypesForAssignment - This routine determines whether two
5456 /// block pointer types are compatible or whether a block and normal pointer
5457 /// are compatible. It is more restrict than comparing two function pointer
5458 // types.
5459 static Sema::AssignConvertType
5460 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
5461                                     QualType RHSType) {
5462   assert(LHSType.isCanonical() && "LHS not canonicalized!");
5463   assert(RHSType.isCanonical() && "RHS not canonicalized!");
5464 
5465   QualType lhptee, rhptee;
5466 
5467   // get the "pointed to" type (ignoring qualifiers at the top level)
5468   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
5469   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
5470 
5471   // In C++, the types have to match exactly.
5472   if (S.getLangOpts().CPlusPlus)
5473     return Sema::IncompatibleBlockPointer;
5474 
5475   Sema::AssignConvertType ConvTy = Sema::Compatible;
5476 
5477   // For blocks we enforce that qualifiers are identical.
5478   if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
5479     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
5480 
5481   if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
5482     return Sema::IncompatibleBlockPointer;
5483 
5484   return ConvTy;
5485 }
5486 
5487 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
5488 /// for assignment compatibility.
5489 static Sema::AssignConvertType
5490 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
5491                                    QualType RHSType) {
5492   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
5493   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
5494 
5495   if (LHSType->isObjCBuiltinType()) {
5496     // Class is not compatible with ObjC object pointers.
5497     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
5498         !RHSType->isObjCQualifiedClassType())
5499       return Sema::IncompatiblePointer;
5500     return Sema::Compatible;
5501   }
5502   if (RHSType->isObjCBuiltinType()) {
5503     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
5504         !LHSType->isObjCQualifiedClassType())
5505       return Sema::IncompatiblePointer;
5506     return Sema::Compatible;
5507   }
5508   QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
5509   QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
5510 
5511   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
5512       // make an exception for id<P>
5513       !LHSType->isObjCQualifiedIdType())
5514     return Sema::CompatiblePointerDiscardsQualifiers;
5515 
5516   if (S.Context.typesAreCompatible(LHSType, RHSType))
5517     return Sema::Compatible;
5518   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
5519     return Sema::IncompatibleObjCQualifiedId;
5520   return Sema::IncompatiblePointer;
5521 }
5522 
5523 Sema::AssignConvertType
5524 Sema::CheckAssignmentConstraints(SourceLocation Loc,
5525                                  QualType LHSType, QualType RHSType) {
5526   // Fake up an opaque expression.  We don't actually care about what
5527   // cast operations are required, so if CheckAssignmentConstraints
5528   // adds casts to this they'll be wasted, but fortunately that doesn't
5529   // usually happen on valid code.
5530   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
5531   ExprResult RHSPtr = &RHSExpr;
5532   CastKind K = CK_Invalid;
5533 
5534   return CheckAssignmentConstraints(LHSType, RHSPtr, K);
5535 }
5536 
5537 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
5538 /// has code to accommodate several GCC extensions when type checking
5539 /// pointers. Here are some objectionable examples that GCC considers warnings:
5540 ///
5541 ///  int a, *pint;
5542 ///  short *pshort;
5543 ///  struct foo *pfoo;
5544 ///
5545 ///  pint = pshort; // warning: assignment from incompatible pointer type
5546 ///  a = pint; // warning: assignment makes integer from pointer without a cast
5547 ///  pint = a; // warning: assignment makes pointer from integer without a cast
5548 ///  pint = pfoo; // warning: assignment from incompatible pointer type
5549 ///
5550 /// As a result, the code for dealing with pointers is more complex than the
5551 /// C99 spec dictates.
5552 ///
5553 /// Sets 'Kind' for any result kind except Incompatible.
5554 Sema::AssignConvertType
5555 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
5556                                  CastKind &Kind) {
5557   QualType RHSType = RHS.get()->getType();
5558   QualType OrigLHSType = LHSType;
5559 
5560   // Get canonical types.  We're not formatting these types, just comparing
5561   // them.
5562   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
5563   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
5564 
5565 
5566   // Common case: no conversion required.
5567   if (LHSType == RHSType) {
5568     Kind = CK_NoOp;
5569     return Compatible;
5570   }
5571 
5572   // If we have an atomic type, try a non-atomic assignment, then just add an
5573   // atomic qualification step.
5574   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
5575     Sema::AssignConvertType result =
5576       CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
5577     if (result != Compatible)
5578       return result;
5579     if (Kind != CK_NoOp)
5580       RHS = ImpCastExprToType(RHS.take(), AtomicTy->getValueType(), Kind);
5581     Kind = CK_NonAtomicToAtomic;
5582     return Compatible;
5583   }
5584 
5585   // If the left-hand side is a reference type, then we are in a
5586   // (rare!) case where we've allowed the use of references in C,
5587   // e.g., as a parameter type in a built-in function. In this case,
5588   // just make sure that the type referenced is compatible with the
5589   // right-hand side type. The caller is responsible for adjusting
5590   // LHSType so that the resulting expression does not have reference
5591   // type.
5592   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
5593     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
5594       Kind = CK_LValueBitCast;
5595       return Compatible;
5596     }
5597     return Incompatible;
5598   }
5599 
5600   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
5601   // to the same ExtVector type.
5602   if (LHSType->isExtVectorType()) {
5603     if (RHSType->isExtVectorType())
5604       return Incompatible;
5605     if (RHSType->isArithmeticType()) {
5606       // CK_VectorSplat does T -> vector T, so first cast to the
5607       // element type.
5608       QualType elType = cast<ExtVectorType>(LHSType)->getElementType();
5609       if (elType != RHSType) {
5610         Kind = PrepareScalarCast(RHS, elType);
5611         RHS = ImpCastExprToType(RHS.take(), elType, Kind);
5612       }
5613       Kind = CK_VectorSplat;
5614       return Compatible;
5615     }
5616   }
5617 
5618   // Conversions to or from vector type.
5619   if (LHSType->isVectorType() || RHSType->isVectorType()) {
5620     if (LHSType->isVectorType() && RHSType->isVectorType()) {
5621       // Allow assignments of an AltiVec vector type to an equivalent GCC
5622       // vector type and vice versa
5623       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
5624         Kind = CK_BitCast;
5625         return Compatible;
5626       }
5627 
5628       // If we are allowing lax vector conversions, and LHS and RHS are both
5629       // vectors, the total size only needs to be the same. This is a bitcast;
5630       // no bits are changed but the result type is different.
5631       if (getLangOpts().LaxVectorConversions &&
5632           (Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType))) {
5633         Kind = CK_BitCast;
5634         return IncompatibleVectors;
5635       }
5636     }
5637     return Incompatible;
5638   }
5639 
5640   // Arithmetic conversions.
5641   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
5642       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
5643     Kind = PrepareScalarCast(RHS, LHSType);
5644     return Compatible;
5645   }
5646 
5647   // Conversions to normal pointers.
5648   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
5649     // U* -> T*
5650     if (isa<PointerType>(RHSType)) {
5651       Kind = CK_BitCast;
5652       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
5653     }
5654 
5655     // int -> T*
5656     if (RHSType->isIntegerType()) {
5657       Kind = CK_IntegralToPointer; // FIXME: null?
5658       return IntToPointer;
5659     }
5660 
5661     // C pointers are not compatible with ObjC object pointers,
5662     // with two exceptions:
5663     if (isa<ObjCObjectPointerType>(RHSType)) {
5664       //  - conversions to void*
5665       if (LHSPointer->getPointeeType()->isVoidType()) {
5666         Kind = CK_BitCast;
5667         return Compatible;
5668       }
5669 
5670       //  - conversions from 'Class' to the redefinition type
5671       if (RHSType->isObjCClassType() &&
5672           Context.hasSameType(LHSType,
5673                               Context.getObjCClassRedefinitionType())) {
5674         Kind = CK_BitCast;
5675         return Compatible;
5676       }
5677 
5678       Kind = CK_BitCast;
5679       return IncompatiblePointer;
5680     }
5681 
5682     // U^ -> void*
5683     if (RHSType->getAs<BlockPointerType>()) {
5684       if (LHSPointer->getPointeeType()->isVoidType()) {
5685         Kind = CK_BitCast;
5686         return Compatible;
5687       }
5688     }
5689 
5690     return Incompatible;
5691   }
5692 
5693   // Conversions to block pointers.
5694   if (isa<BlockPointerType>(LHSType)) {
5695     // U^ -> T^
5696     if (RHSType->isBlockPointerType()) {
5697       Kind = CK_BitCast;
5698       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
5699     }
5700 
5701     // int or null -> T^
5702     if (RHSType->isIntegerType()) {
5703       Kind = CK_IntegralToPointer; // FIXME: null
5704       return IntToBlockPointer;
5705     }
5706 
5707     // id -> T^
5708     if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
5709       Kind = CK_AnyPointerToBlockPointerCast;
5710       return Compatible;
5711     }
5712 
5713     // void* -> T^
5714     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
5715       if (RHSPT->getPointeeType()->isVoidType()) {
5716         Kind = CK_AnyPointerToBlockPointerCast;
5717         return Compatible;
5718       }
5719 
5720     return Incompatible;
5721   }
5722 
5723   // Conversions to Objective-C pointers.
5724   if (isa<ObjCObjectPointerType>(LHSType)) {
5725     // A* -> B*
5726     if (RHSType->isObjCObjectPointerType()) {
5727       Kind = CK_BitCast;
5728       Sema::AssignConvertType result =
5729         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
5730       if (getLangOpts().ObjCAutoRefCount &&
5731           result == Compatible &&
5732           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
5733         result = IncompatibleObjCWeakRef;
5734       return result;
5735     }
5736 
5737     // int or null -> A*
5738     if (RHSType->isIntegerType()) {
5739       Kind = CK_IntegralToPointer; // FIXME: null
5740       return IntToPointer;
5741     }
5742 
5743     // In general, C pointers are not compatible with ObjC object pointers,
5744     // with two exceptions:
5745     if (isa<PointerType>(RHSType)) {
5746       Kind = CK_CPointerToObjCPointerCast;
5747 
5748       //  - conversions from 'void*'
5749       if (RHSType->isVoidPointerType()) {
5750         return Compatible;
5751       }
5752 
5753       //  - conversions to 'Class' from its redefinition type
5754       if (LHSType->isObjCClassType() &&
5755           Context.hasSameType(RHSType,
5756                               Context.getObjCClassRedefinitionType())) {
5757         return Compatible;
5758       }
5759 
5760       return IncompatiblePointer;
5761     }
5762 
5763     // T^ -> A*
5764     if (RHSType->isBlockPointerType()) {
5765       maybeExtendBlockObject(*this, RHS);
5766       Kind = CK_BlockPointerToObjCPointerCast;
5767       return Compatible;
5768     }
5769 
5770     return Incompatible;
5771   }
5772 
5773   // Conversions from pointers that are not covered by the above.
5774   if (isa<PointerType>(RHSType)) {
5775     // T* -> _Bool
5776     if (LHSType == Context.BoolTy) {
5777       Kind = CK_PointerToBoolean;
5778       return Compatible;
5779     }
5780 
5781     // T* -> int
5782     if (LHSType->isIntegerType()) {
5783       Kind = CK_PointerToIntegral;
5784       return PointerToInt;
5785     }
5786 
5787     return Incompatible;
5788   }
5789 
5790   // Conversions from Objective-C pointers that are not covered by the above.
5791   if (isa<ObjCObjectPointerType>(RHSType)) {
5792     // T* -> _Bool
5793     if (LHSType == Context.BoolTy) {
5794       Kind = CK_PointerToBoolean;
5795       return Compatible;
5796     }
5797 
5798     // T* -> int
5799     if (LHSType->isIntegerType()) {
5800       Kind = CK_PointerToIntegral;
5801       return PointerToInt;
5802     }
5803 
5804     return Incompatible;
5805   }
5806 
5807   // struct A -> struct B
5808   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
5809     if (Context.typesAreCompatible(LHSType, RHSType)) {
5810       Kind = CK_NoOp;
5811       return Compatible;
5812     }
5813   }
5814 
5815   return Incompatible;
5816 }
5817 
5818 /// \brief Constructs a transparent union from an expression that is
5819 /// used to initialize the transparent union.
5820 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
5821                                       ExprResult &EResult, QualType UnionType,
5822                                       FieldDecl *Field) {
5823   // Build an initializer list that designates the appropriate member
5824   // of the transparent union.
5825   Expr *E = EResult.take();
5826   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
5827                                                    E, SourceLocation());
5828   Initializer->setType(UnionType);
5829   Initializer->setInitializedFieldInUnion(Field);
5830 
5831   // Build a compound literal constructing a value of the transparent
5832   // union type from this initializer list.
5833   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
5834   EResult = S.Owned(
5835     new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
5836                                 VK_RValue, Initializer, false));
5837 }
5838 
5839 Sema::AssignConvertType
5840 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
5841                                                ExprResult &RHS) {
5842   QualType RHSType = RHS.get()->getType();
5843 
5844   // If the ArgType is a Union type, we want to handle a potential
5845   // transparent_union GCC extension.
5846   const RecordType *UT = ArgType->getAsUnionType();
5847   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
5848     return Incompatible;
5849 
5850   // The field to initialize within the transparent union.
5851   RecordDecl *UD = UT->getDecl();
5852   FieldDecl *InitField = 0;
5853   // It's compatible if the expression matches any of the fields.
5854   for (RecordDecl::field_iterator it = UD->field_begin(),
5855          itend = UD->field_end();
5856        it != itend; ++it) {
5857     if (it->getType()->isPointerType()) {
5858       // If the transparent union contains a pointer type, we allow:
5859       // 1) void pointer
5860       // 2) null pointer constant
5861       if (RHSType->isPointerType())
5862         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
5863           RHS = ImpCastExprToType(RHS.take(), it->getType(), CK_BitCast);
5864           InitField = *it;
5865           break;
5866         }
5867 
5868       if (RHS.get()->isNullPointerConstant(Context,
5869                                            Expr::NPC_ValueDependentIsNull)) {
5870         RHS = ImpCastExprToType(RHS.take(), it->getType(),
5871                                 CK_NullToPointer);
5872         InitField = *it;
5873         break;
5874       }
5875     }
5876 
5877     CastKind Kind = CK_Invalid;
5878     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
5879           == Compatible) {
5880       RHS = ImpCastExprToType(RHS.take(), it->getType(), Kind);
5881       InitField = *it;
5882       break;
5883     }
5884   }
5885 
5886   if (!InitField)
5887     return Incompatible;
5888 
5889   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
5890   return Compatible;
5891 }
5892 
5893 Sema::AssignConvertType
5894 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS,
5895                                        bool Diagnose) {
5896   if (getLangOpts().CPlusPlus) {
5897     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
5898       // C++ 5.17p3: If the left operand is not of class type, the
5899       // expression is implicitly converted (C++ 4) to the
5900       // cv-unqualified type of the left operand.
5901       ExprResult Res;
5902       if (Diagnose) {
5903         Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5904                                         AA_Assigning);
5905       } else {
5906         ImplicitConversionSequence ICS =
5907             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5908                                   /*SuppressUserConversions=*/false,
5909                                   /*AllowExplicit=*/false,
5910                                   /*InOverloadResolution=*/false,
5911                                   /*CStyle=*/false,
5912                                   /*AllowObjCWritebackConversion=*/false);
5913         if (ICS.isFailure())
5914           return Incompatible;
5915         Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5916                                         ICS, AA_Assigning);
5917       }
5918       if (Res.isInvalid())
5919         return Incompatible;
5920       Sema::AssignConvertType result = Compatible;
5921       if (getLangOpts().ObjCAutoRefCount &&
5922           !CheckObjCARCUnavailableWeakConversion(LHSType,
5923                                                  RHS.get()->getType()))
5924         result = IncompatibleObjCWeakRef;
5925       RHS = Res;
5926       return result;
5927     }
5928 
5929     // FIXME: Currently, we fall through and treat C++ classes like C
5930     // structures.
5931     // FIXME: We also fall through for atomics; not sure what should
5932     // happen there, though.
5933   }
5934 
5935   // C99 6.5.16.1p1: the left operand is a pointer and the right is
5936   // a null pointer constant.
5937   if ((LHSType->isPointerType() ||
5938        LHSType->isObjCObjectPointerType() ||
5939        LHSType->isBlockPointerType())
5940       && RHS.get()->isNullPointerConstant(Context,
5941                                           Expr::NPC_ValueDependentIsNull)) {
5942     RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
5943     return Compatible;
5944   }
5945 
5946   // This check seems unnatural, however it is necessary to ensure the proper
5947   // conversion of functions/arrays. If the conversion were done for all
5948   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
5949   // expressions that suppress this implicit conversion (&, sizeof).
5950   //
5951   // Suppress this for references: C++ 8.5.3p5.
5952   if (!LHSType->isReferenceType()) {
5953     RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
5954     if (RHS.isInvalid())
5955       return Incompatible;
5956   }
5957 
5958   CastKind Kind = CK_Invalid;
5959   Sema::AssignConvertType result =
5960     CheckAssignmentConstraints(LHSType, RHS, Kind);
5961 
5962   // C99 6.5.16.1p2: The value of the right operand is converted to the
5963   // type of the assignment expression.
5964   // CheckAssignmentConstraints allows the left-hand side to be a reference,
5965   // so that we can use references in built-in functions even in C.
5966   // The getNonReferenceType() call makes sure that the resulting expression
5967   // does not have reference type.
5968   if (result != Incompatible && RHS.get()->getType() != LHSType)
5969     RHS = ImpCastExprToType(RHS.take(),
5970                             LHSType.getNonLValueExprType(Context), Kind);
5971   return result;
5972 }
5973 
5974 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
5975                                ExprResult &RHS) {
5976   Diag(Loc, diag::err_typecheck_invalid_operands)
5977     << LHS.get()->getType() << RHS.get()->getType()
5978     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5979   return QualType();
5980 }
5981 
5982 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
5983                                    SourceLocation Loc, bool IsCompAssign) {
5984   if (!IsCompAssign) {
5985     LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
5986     if (LHS.isInvalid())
5987       return QualType();
5988   }
5989   RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
5990   if (RHS.isInvalid())
5991     return QualType();
5992 
5993   // For conversion purposes, we ignore any qualifiers.
5994   // For example, "const float" and "float" are equivalent.
5995   QualType LHSType =
5996     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
5997   QualType RHSType =
5998     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
5999 
6000   // If the vector types are identical, return.
6001   if (LHSType == RHSType)
6002     return LHSType;
6003 
6004   // Handle the case of equivalent AltiVec and GCC vector types
6005   if (LHSType->isVectorType() && RHSType->isVectorType() &&
6006       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
6007     if (LHSType->isExtVectorType()) {
6008       RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
6009       return LHSType;
6010     }
6011 
6012     if (!IsCompAssign)
6013       LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
6014     return RHSType;
6015   }
6016 
6017   if (getLangOpts().LaxVectorConversions &&
6018       Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType)) {
6019     // If we are allowing lax vector conversions, and LHS and RHS are both
6020     // vectors, the total size only needs to be the same. This is a
6021     // bitcast; no bits are changed but the result type is different.
6022     // FIXME: Should we really be allowing this?
6023     RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
6024     return LHSType;
6025   }
6026 
6027   // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
6028   // swap back (so that we don't reverse the inputs to a subtract, for instance.
6029   bool swapped = false;
6030   if (RHSType->isExtVectorType() && !IsCompAssign) {
6031     swapped = true;
6032     std::swap(RHS, LHS);
6033     std::swap(RHSType, LHSType);
6034   }
6035 
6036   // Handle the case of an ext vector and scalar.
6037   if (const ExtVectorType *LV = LHSType->getAs<ExtVectorType>()) {
6038     QualType EltTy = LV->getElementType();
6039     if (EltTy->isIntegralType(Context) && RHSType->isIntegralType(Context)) {
6040       int order = Context.getIntegerTypeOrder(EltTy, RHSType);
6041       if (order > 0)
6042         RHS = ImpCastExprToType(RHS.take(), EltTy, CK_IntegralCast);
6043       if (order >= 0) {
6044         RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
6045         if (swapped) std::swap(RHS, LHS);
6046         return LHSType;
6047       }
6048     }
6049     if (EltTy->isRealFloatingType() && RHSType->isScalarType() &&
6050         RHSType->isRealFloatingType()) {
6051       int order = Context.getFloatingTypeOrder(EltTy, RHSType);
6052       if (order > 0)
6053         RHS = ImpCastExprToType(RHS.take(), EltTy, CK_FloatingCast);
6054       if (order >= 0) {
6055         RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
6056         if (swapped) std::swap(RHS, LHS);
6057         return LHSType;
6058       }
6059     }
6060   }
6061 
6062   // Vectors of different size or scalar and non-ext-vector are errors.
6063   if (swapped) std::swap(RHS, LHS);
6064   Diag(Loc, diag::err_typecheck_vector_not_convertable)
6065     << LHS.get()->getType() << RHS.get()->getType()
6066     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6067   return QualType();
6068 }
6069 
6070 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
6071 // expression.  These are mainly cases where the null pointer is used as an
6072 // integer instead of a pointer.
6073 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
6074                                 SourceLocation Loc, bool IsCompare) {
6075   // The canonical way to check for a GNU null is with isNullPointerConstant,
6076   // but we use a bit of a hack here for speed; this is a relatively
6077   // hot path, and isNullPointerConstant is slow.
6078   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
6079   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
6080 
6081   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
6082 
6083   // Avoid analyzing cases where the result will either be invalid (and
6084   // diagnosed as such) or entirely valid and not something to warn about.
6085   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
6086       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
6087     return;
6088 
6089   // Comparison operations would not make sense with a null pointer no matter
6090   // what the other expression is.
6091   if (!IsCompare) {
6092     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
6093         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
6094         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
6095     return;
6096   }
6097 
6098   // The rest of the operations only make sense with a null pointer
6099   // if the other expression is a pointer.
6100   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
6101       NonNullType->canDecayToPointerType())
6102     return;
6103 
6104   S.Diag(Loc, diag::warn_null_in_comparison_operation)
6105       << LHSNull /* LHS is NULL */ << NonNullType
6106       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6107 }
6108 
6109 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
6110                                            SourceLocation Loc,
6111                                            bool IsCompAssign, bool IsDiv) {
6112   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6113 
6114   if (LHS.get()->getType()->isVectorType() ||
6115       RHS.get()->getType()->isVectorType())
6116     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
6117 
6118   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
6119   if (LHS.isInvalid() || RHS.isInvalid())
6120     return QualType();
6121 
6122 
6123   if (compType.isNull() || !compType->isArithmeticType())
6124     return InvalidOperands(Loc, LHS, RHS);
6125 
6126   // Check for division by zero.
6127   if (IsDiv &&
6128       RHS.get()->isNullPointerConstant(Context,
6129                                        Expr::NPC_ValueDependentIsNotNull))
6130     DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_division_by_zero)
6131                                           << RHS.get()->getSourceRange());
6132 
6133   return compType;
6134 }
6135 
6136 QualType Sema::CheckRemainderOperands(
6137   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
6138   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6139 
6140   if (LHS.get()->getType()->isVectorType() ||
6141       RHS.get()->getType()->isVectorType()) {
6142     if (LHS.get()->getType()->hasIntegerRepresentation() &&
6143         RHS.get()->getType()->hasIntegerRepresentation())
6144       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
6145     return InvalidOperands(Loc, LHS, RHS);
6146   }
6147 
6148   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
6149   if (LHS.isInvalid() || RHS.isInvalid())
6150     return QualType();
6151 
6152   if (compType.isNull() || !compType->isIntegerType())
6153     return InvalidOperands(Loc, LHS, RHS);
6154 
6155   // Check for remainder by zero.
6156   if (RHS.get()->isNullPointerConstant(Context,
6157                                        Expr::NPC_ValueDependentIsNotNull))
6158     DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_remainder_by_zero)
6159                                  << RHS.get()->getSourceRange());
6160 
6161   return compType;
6162 }
6163 
6164 /// \brief Diagnose invalid arithmetic on two void pointers.
6165 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
6166                                                 Expr *LHSExpr, Expr *RHSExpr) {
6167   S.Diag(Loc, S.getLangOpts().CPlusPlus
6168                 ? diag::err_typecheck_pointer_arith_void_type
6169                 : diag::ext_gnu_void_ptr)
6170     << 1 /* two pointers */ << LHSExpr->getSourceRange()
6171                             << RHSExpr->getSourceRange();
6172 }
6173 
6174 /// \brief Diagnose invalid arithmetic on a void pointer.
6175 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
6176                                             Expr *Pointer) {
6177   S.Diag(Loc, S.getLangOpts().CPlusPlus
6178                 ? diag::err_typecheck_pointer_arith_void_type
6179                 : diag::ext_gnu_void_ptr)
6180     << 0 /* one pointer */ << Pointer->getSourceRange();
6181 }
6182 
6183 /// \brief Diagnose invalid arithmetic on two function pointers.
6184 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
6185                                                     Expr *LHS, Expr *RHS) {
6186   assert(LHS->getType()->isAnyPointerType());
6187   assert(RHS->getType()->isAnyPointerType());
6188   S.Diag(Loc, S.getLangOpts().CPlusPlus
6189                 ? diag::err_typecheck_pointer_arith_function_type
6190                 : diag::ext_gnu_ptr_func_arith)
6191     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
6192     // We only show the second type if it differs from the first.
6193     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
6194                                                    RHS->getType())
6195     << RHS->getType()->getPointeeType()
6196     << LHS->getSourceRange() << RHS->getSourceRange();
6197 }
6198 
6199 /// \brief Diagnose invalid arithmetic on a function pointer.
6200 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
6201                                                 Expr *Pointer) {
6202   assert(Pointer->getType()->isAnyPointerType());
6203   S.Diag(Loc, S.getLangOpts().CPlusPlus
6204                 ? diag::err_typecheck_pointer_arith_function_type
6205                 : diag::ext_gnu_ptr_func_arith)
6206     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
6207     << 0 /* one pointer, so only one type */
6208     << Pointer->getSourceRange();
6209 }
6210 
6211 /// \brief Emit error if Operand is incomplete pointer type
6212 ///
6213 /// \returns True if pointer has incomplete type
6214 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
6215                                                  Expr *Operand) {
6216   assert(Operand->getType()->isAnyPointerType() &&
6217          !Operand->getType()->isDependentType());
6218   QualType PointeeTy = Operand->getType()->getPointeeType();
6219   return S.RequireCompleteType(Loc, PointeeTy,
6220                                diag::err_typecheck_arithmetic_incomplete_type,
6221                                PointeeTy, Operand->getSourceRange());
6222 }
6223 
6224 /// \brief Check the validity of an arithmetic pointer operand.
6225 ///
6226 /// If the operand has pointer type, this code will check for pointer types
6227 /// which are invalid in arithmetic operations. These will be diagnosed
6228 /// appropriately, including whether or not the use is supported as an
6229 /// extension.
6230 ///
6231 /// \returns True when the operand is valid to use (even if as an extension).
6232 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
6233                                             Expr *Operand) {
6234   if (!Operand->getType()->isAnyPointerType()) return true;
6235 
6236   QualType PointeeTy = Operand->getType()->getPointeeType();
6237   if (PointeeTy->isVoidType()) {
6238     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
6239     return !S.getLangOpts().CPlusPlus;
6240   }
6241   if (PointeeTy->isFunctionType()) {
6242     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
6243     return !S.getLangOpts().CPlusPlus;
6244   }
6245 
6246   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
6247 
6248   return true;
6249 }
6250 
6251 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
6252 /// operands.
6253 ///
6254 /// This routine will diagnose any invalid arithmetic on pointer operands much
6255 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
6256 /// for emitting a single diagnostic even for operations where both LHS and RHS
6257 /// are (potentially problematic) pointers.
6258 ///
6259 /// \returns True when the operand is valid to use (even if as an extension).
6260 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
6261                                                 Expr *LHSExpr, Expr *RHSExpr) {
6262   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
6263   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
6264   if (!isLHSPointer && !isRHSPointer) return true;
6265 
6266   QualType LHSPointeeTy, RHSPointeeTy;
6267   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
6268   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
6269 
6270   // Check for arithmetic on pointers to incomplete types.
6271   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
6272   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
6273   if (isLHSVoidPtr || isRHSVoidPtr) {
6274     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
6275     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
6276     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
6277 
6278     return !S.getLangOpts().CPlusPlus;
6279   }
6280 
6281   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
6282   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
6283   if (isLHSFuncPtr || isRHSFuncPtr) {
6284     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
6285     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
6286                                                                 RHSExpr);
6287     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
6288 
6289     return !S.getLangOpts().CPlusPlus;
6290   }
6291 
6292   if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
6293     return false;
6294   if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
6295     return false;
6296 
6297   return true;
6298 }
6299 
6300 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
6301 /// literal.
6302 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
6303                                   Expr *LHSExpr, Expr *RHSExpr) {
6304   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
6305   Expr* IndexExpr = RHSExpr;
6306   if (!StrExpr) {
6307     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
6308     IndexExpr = LHSExpr;
6309   }
6310 
6311   bool IsStringPlusInt = StrExpr &&
6312       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
6313   if (!IsStringPlusInt)
6314     return;
6315 
6316   llvm::APSInt index;
6317   if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
6318     unsigned StrLenWithNull = StrExpr->getLength() + 1;
6319     if (index.isNonNegative() &&
6320         index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
6321                               index.isUnsigned()))
6322       return;
6323   }
6324 
6325   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
6326   Self.Diag(OpLoc, diag::warn_string_plus_int)
6327       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
6328 
6329   // Only print a fixit for "str" + int, not for int + "str".
6330   if (IndexExpr == RHSExpr) {
6331     SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd());
6332     Self.Diag(OpLoc, diag::note_string_plus_int_silence)
6333         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
6334         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
6335         << FixItHint::CreateInsertion(EndLoc, "]");
6336   } else
6337     Self.Diag(OpLoc, diag::note_string_plus_int_silence);
6338 }
6339 
6340 /// \brief Emit error when two pointers are incompatible.
6341 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
6342                                            Expr *LHSExpr, Expr *RHSExpr) {
6343   assert(LHSExpr->getType()->isAnyPointerType());
6344   assert(RHSExpr->getType()->isAnyPointerType());
6345   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
6346     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
6347     << RHSExpr->getSourceRange();
6348 }
6349 
6350 QualType Sema::CheckAdditionOperands( // C99 6.5.6
6351     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc,
6352     QualType* CompLHSTy) {
6353   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6354 
6355   if (LHS.get()->getType()->isVectorType() ||
6356       RHS.get()->getType()->isVectorType()) {
6357     QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
6358     if (CompLHSTy) *CompLHSTy = compType;
6359     return compType;
6360   }
6361 
6362   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6363   if (LHS.isInvalid() || RHS.isInvalid())
6364     return QualType();
6365 
6366   // Diagnose "string literal" '+' int.
6367   if (Opc == BO_Add)
6368     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
6369 
6370   // handle the common case first (both operands are arithmetic).
6371   if (!compType.isNull() && compType->isArithmeticType()) {
6372     if (CompLHSTy) *CompLHSTy = compType;
6373     return compType;
6374   }
6375 
6376   // Type-checking.  Ultimately the pointer's going to be in PExp;
6377   // note that we bias towards the LHS being the pointer.
6378   Expr *PExp = LHS.get(), *IExp = RHS.get();
6379 
6380   bool isObjCPointer;
6381   if (PExp->getType()->isPointerType()) {
6382     isObjCPointer = false;
6383   } else if (PExp->getType()->isObjCObjectPointerType()) {
6384     isObjCPointer = true;
6385   } else {
6386     std::swap(PExp, IExp);
6387     if (PExp->getType()->isPointerType()) {
6388       isObjCPointer = false;
6389     } else if (PExp->getType()->isObjCObjectPointerType()) {
6390       isObjCPointer = true;
6391     } else {
6392       return InvalidOperands(Loc, LHS, RHS);
6393     }
6394   }
6395   assert(PExp->getType()->isAnyPointerType());
6396 
6397   if (!IExp->getType()->isIntegerType())
6398     return InvalidOperands(Loc, LHS, RHS);
6399 
6400   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
6401     return QualType();
6402 
6403   if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
6404     return QualType();
6405 
6406   // Check array bounds for pointer arithemtic
6407   CheckArrayAccess(PExp, IExp);
6408 
6409   if (CompLHSTy) {
6410     QualType LHSTy = Context.isPromotableBitField(LHS.get());
6411     if (LHSTy.isNull()) {
6412       LHSTy = LHS.get()->getType();
6413       if (LHSTy->isPromotableIntegerType())
6414         LHSTy = Context.getPromotedIntegerType(LHSTy);
6415     }
6416     *CompLHSTy = LHSTy;
6417   }
6418 
6419   return PExp->getType();
6420 }
6421 
6422 // C99 6.5.6
6423 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
6424                                         SourceLocation Loc,
6425                                         QualType* CompLHSTy) {
6426   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6427 
6428   if (LHS.get()->getType()->isVectorType() ||
6429       RHS.get()->getType()->isVectorType()) {
6430     QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
6431     if (CompLHSTy) *CompLHSTy = compType;
6432     return compType;
6433   }
6434 
6435   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6436   if (LHS.isInvalid() || RHS.isInvalid())
6437     return QualType();
6438 
6439   // Enforce type constraints: C99 6.5.6p3.
6440 
6441   // Handle the common case first (both operands are arithmetic).
6442   if (!compType.isNull() && compType->isArithmeticType()) {
6443     if (CompLHSTy) *CompLHSTy = compType;
6444     return compType;
6445   }
6446 
6447   // Either ptr - int   or   ptr - ptr.
6448   if (LHS.get()->getType()->isAnyPointerType()) {
6449     QualType lpointee = LHS.get()->getType()->getPointeeType();
6450 
6451     // Diagnose bad cases where we step over interface counts.
6452     if (LHS.get()->getType()->isObjCObjectPointerType() &&
6453         checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
6454       return QualType();
6455 
6456     // The result type of a pointer-int computation is the pointer type.
6457     if (RHS.get()->getType()->isIntegerType()) {
6458       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
6459         return QualType();
6460 
6461       // Check array bounds for pointer arithemtic
6462       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/0,
6463                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
6464 
6465       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
6466       return LHS.get()->getType();
6467     }
6468 
6469     // Handle pointer-pointer subtractions.
6470     if (const PointerType *RHSPTy
6471           = RHS.get()->getType()->getAs<PointerType>()) {
6472       QualType rpointee = RHSPTy->getPointeeType();
6473 
6474       if (getLangOpts().CPlusPlus) {
6475         // Pointee types must be the same: C++ [expr.add]
6476         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
6477           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
6478         }
6479       } else {
6480         // Pointee types must be compatible C99 6.5.6p3
6481         if (!Context.typesAreCompatible(
6482                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
6483                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
6484           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
6485           return QualType();
6486         }
6487       }
6488 
6489       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
6490                                                LHS.get(), RHS.get()))
6491         return QualType();
6492 
6493       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
6494       return Context.getPointerDiffType();
6495     }
6496   }
6497 
6498   return InvalidOperands(Loc, LHS, RHS);
6499 }
6500 
6501 static bool isScopedEnumerationType(QualType T) {
6502   if (const EnumType *ET = dyn_cast<EnumType>(T))
6503     return ET->getDecl()->isScoped();
6504   return false;
6505 }
6506 
6507 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
6508                                    SourceLocation Loc, unsigned Opc,
6509                                    QualType LHSType) {
6510   llvm::APSInt Right;
6511   // Check right/shifter operand
6512   if (RHS.get()->isValueDependent() ||
6513       !RHS.get()->isIntegerConstantExpr(Right, S.Context))
6514     return;
6515 
6516   if (Right.isNegative()) {
6517     S.DiagRuntimeBehavior(Loc, RHS.get(),
6518                           S.PDiag(diag::warn_shift_negative)
6519                             << RHS.get()->getSourceRange());
6520     return;
6521   }
6522   llvm::APInt LeftBits(Right.getBitWidth(),
6523                        S.Context.getTypeSize(LHS.get()->getType()));
6524   if (Right.uge(LeftBits)) {
6525     S.DiagRuntimeBehavior(Loc, RHS.get(),
6526                           S.PDiag(diag::warn_shift_gt_typewidth)
6527                             << RHS.get()->getSourceRange());
6528     return;
6529   }
6530   if (Opc != BO_Shl)
6531     return;
6532 
6533   // When left shifting an ICE which is signed, we can check for overflow which
6534   // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
6535   // integers have defined behavior modulo one more than the maximum value
6536   // representable in the result type, so never warn for those.
6537   llvm::APSInt Left;
6538   if (LHS.get()->isValueDependent() ||
6539       !LHS.get()->isIntegerConstantExpr(Left, S.Context) ||
6540       LHSType->hasUnsignedIntegerRepresentation())
6541     return;
6542   llvm::APInt ResultBits =
6543       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
6544   if (LeftBits.uge(ResultBits))
6545     return;
6546   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
6547   Result = Result.shl(Right);
6548 
6549   // Print the bit representation of the signed integer as an unsigned
6550   // hexadecimal number.
6551   SmallString<40> HexResult;
6552   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
6553 
6554   // If we are only missing a sign bit, this is less likely to result in actual
6555   // bugs -- if the result is cast back to an unsigned type, it will have the
6556   // expected value. Thus we place this behind a different warning that can be
6557   // turned off separately if needed.
6558   if (LeftBits == ResultBits - 1) {
6559     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
6560         << HexResult.str() << LHSType
6561         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6562     return;
6563   }
6564 
6565   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
6566     << HexResult.str() << Result.getMinSignedBits() << LHSType
6567     << Left.getBitWidth() << LHS.get()->getSourceRange()
6568     << RHS.get()->getSourceRange();
6569 }
6570 
6571 // C99 6.5.7
6572 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
6573                                   SourceLocation Loc, unsigned Opc,
6574                                   bool IsCompAssign) {
6575   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6576 
6577   // C99 6.5.7p2: Each of the operands shall have integer type.
6578   if (!LHS.get()->getType()->hasIntegerRepresentation() ||
6579       !RHS.get()->getType()->hasIntegerRepresentation())
6580     return InvalidOperands(Loc, LHS, RHS);
6581 
6582   // C++0x: Don't allow scoped enums. FIXME: Use something better than
6583   // hasIntegerRepresentation() above instead of this.
6584   if (isScopedEnumerationType(LHS.get()->getType()) ||
6585       isScopedEnumerationType(RHS.get()->getType())) {
6586     return InvalidOperands(Loc, LHS, RHS);
6587   }
6588 
6589   // Vector shifts promote their scalar inputs to vector type.
6590   if (LHS.get()->getType()->isVectorType() ||
6591       RHS.get()->getType()->isVectorType())
6592     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
6593 
6594   // Shifts don't perform usual arithmetic conversions, they just do integer
6595   // promotions on each operand. C99 6.5.7p3
6596 
6597   // For the LHS, do usual unary conversions, but then reset them away
6598   // if this is a compound assignment.
6599   ExprResult OldLHS = LHS;
6600   LHS = UsualUnaryConversions(LHS.take());
6601   if (LHS.isInvalid())
6602     return QualType();
6603   QualType LHSType = LHS.get()->getType();
6604   if (IsCompAssign) LHS = OldLHS;
6605 
6606   // The RHS is simpler.
6607   RHS = UsualUnaryConversions(RHS.take());
6608   if (RHS.isInvalid())
6609     return QualType();
6610 
6611   // Sanity-check shift operands
6612   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
6613 
6614   // "The type of the result is that of the promoted left operand."
6615   return LHSType;
6616 }
6617 
6618 static bool IsWithinTemplateSpecialization(Decl *D) {
6619   if (DeclContext *DC = D->getDeclContext()) {
6620     if (isa<ClassTemplateSpecializationDecl>(DC))
6621       return true;
6622     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
6623       return FD->isFunctionTemplateSpecialization();
6624   }
6625   return false;
6626 }
6627 
6628 /// If two different enums are compared, raise a warning.
6629 static void checkEnumComparison(Sema &S, SourceLocation Loc, ExprResult &LHS,
6630                                 ExprResult &RHS) {
6631   QualType LHSStrippedType = LHS.get()->IgnoreParenImpCasts()->getType();
6632   QualType RHSStrippedType = RHS.get()->IgnoreParenImpCasts()->getType();
6633 
6634   const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
6635   if (!LHSEnumType)
6636     return;
6637   const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
6638   if (!RHSEnumType)
6639     return;
6640 
6641   // Ignore anonymous enums.
6642   if (!LHSEnumType->getDecl()->getIdentifier())
6643     return;
6644   if (!RHSEnumType->getDecl()->getIdentifier())
6645     return;
6646 
6647   if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
6648     return;
6649 
6650   S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
6651       << LHSStrippedType << RHSStrippedType
6652       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6653 }
6654 
6655 /// \brief Diagnose bad pointer comparisons.
6656 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
6657                                               ExprResult &LHS, ExprResult &RHS,
6658                                               bool IsError) {
6659   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
6660                       : diag::ext_typecheck_comparison_of_distinct_pointers)
6661     << LHS.get()->getType() << RHS.get()->getType()
6662     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6663 }
6664 
6665 /// \brief Returns false if the pointers are converted to a composite type,
6666 /// true otherwise.
6667 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
6668                                            ExprResult &LHS, ExprResult &RHS) {
6669   // C++ [expr.rel]p2:
6670   //   [...] Pointer conversions (4.10) and qualification
6671   //   conversions (4.4) are performed on pointer operands (or on
6672   //   a pointer operand and a null pointer constant) to bring
6673   //   them to their composite pointer type. [...]
6674   //
6675   // C++ [expr.eq]p1 uses the same notion for (in)equality
6676   // comparisons of pointers.
6677 
6678   // C++ [expr.eq]p2:
6679   //   In addition, pointers to members can be compared, or a pointer to
6680   //   member and a null pointer constant. Pointer to member conversions
6681   //   (4.11) and qualification conversions (4.4) are performed to bring
6682   //   them to a common type. If one operand is a null pointer constant,
6683   //   the common type is the type of the other operand. Otherwise, the
6684   //   common type is a pointer to member type similar (4.4) to the type
6685   //   of one of the operands, with a cv-qualification signature (4.4)
6686   //   that is the union of the cv-qualification signatures of the operand
6687   //   types.
6688 
6689   QualType LHSType = LHS.get()->getType();
6690   QualType RHSType = RHS.get()->getType();
6691   assert((LHSType->isPointerType() && RHSType->isPointerType()) ||
6692          (LHSType->isMemberPointerType() && RHSType->isMemberPointerType()));
6693 
6694   bool NonStandardCompositeType = false;
6695   bool *BoolPtr = S.isSFINAEContext() ? 0 : &NonStandardCompositeType;
6696   QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr);
6697   if (T.isNull()) {
6698     diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
6699     return true;
6700   }
6701 
6702   if (NonStandardCompositeType)
6703     S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
6704       << LHSType << RHSType << T << LHS.get()->getSourceRange()
6705       << RHS.get()->getSourceRange();
6706 
6707   LHS = S.ImpCastExprToType(LHS.take(), T, CK_BitCast);
6708   RHS = S.ImpCastExprToType(RHS.take(), T, CK_BitCast);
6709   return false;
6710 }
6711 
6712 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
6713                                                     ExprResult &LHS,
6714                                                     ExprResult &RHS,
6715                                                     bool IsError) {
6716   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
6717                       : diag::ext_typecheck_comparison_of_fptr_to_void)
6718     << LHS.get()->getType() << RHS.get()->getType()
6719     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6720 }
6721 
6722 static bool isObjCObjectLiteral(ExprResult &E) {
6723   switch (E.get()->getStmtClass()) {
6724   case Stmt::ObjCArrayLiteralClass:
6725   case Stmt::ObjCDictionaryLiteralClass:
6726   case Stmt::ObjCStringLiteralClass:
6727   case Stmt::ObjCBoxedExprClass:
6728     return true;
6729   default:
6730     // Note that ObjCBoolLiteral is NOT an object literal!
6731     return false;
6732   }
6733 }
6734 
6735 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
6736   // Get the LHS object's interface type.
6737   QualType Type = LHS->getType();
6738   QualType InterfaceType;
6739   if (const ObjCObjectPointerType *PTy = Type->getAs<ObjCObjectPointerType>()) {
6740     InterfaceType = PTy->getPointeeType();
6741     if (const ObjCObjectType *iQFaceTy =
6742         InterfaceType->getAsObjCQualifiedInterfaceType())
6743       InterfaceType = iQFaceTy->getBaseType();
6744   } else {
6745     // If this is not actually an Objective-C object, bail out.
6746     return false;
6747   }
6748 
6749   // If the RHS isn't an Objective-C object, bail out.
6750   if (!RHS->getType()->isObjCObjectPointerType())
6751     return false;
6752 
6753   // Try to find the -isEqual: method.
6754   Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
6755   ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
6756                                                       InterfaceType,
6757                                                       /*instance=*/true);
6758   if (!Method) {
6759     if (Type->isObjCIdType()) {
6760       // For 'id', just check the global pool.
6761       Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
6762                                                   /*receiverId=*/true,
6763                                                   /*warn=*/false);
6764     } else {
6765       // Check protocols.
6766       Method = S.LookupMethodInQualifiedType(IsEqualSel,
6767                                              cast<ObjCObjectPointerType>(Type),
6768                                              /*instance=*/true);
6769     }
6770   }
6771 
6772   if (!Method)
6773     return false;
6774 
6775   QualType T = Method->param_begin()[0]->getType();
6776   if (!T->isObjCObjectPointerType())
6777     return false;
6778 
6779   QualType R = Method->getResultType();
6780   if (!R->isScalarType())
6781     return false;
6782 
6783   return true;
6784 }
6785 
6786 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
6787                                           ExprResult &LHS, ExprResult &RHS,
6788                                           BinaryOperator::Opcode Opc){
6789   Expr *Literal;
6790   Expr *Other;
6791   if (isObjCObjectLiteral(LHS)) {
6792     Literal = LHS.get();
6793     Other = RHS.get();
6794   } else {
6795     Literal = RHS.get();
6796     Other = LHS.get();
6797   }
6798 
6799   // Don't warn on comparisons against nil.
6800   Other = Other->IgnoreParenCasts();
6801   if (Other->isNullPointerConstant(S.getASTContext(),
6802                                    Expr::NPC_ValueDependentIsNotNull))
6803     return;
6804 
6805   // This should be kept in sync with warn_objc_literal_comparison.
6806   // LK_String should always be last, since it has its own warning flag.
6807   enum {
6808     LK_Array,
6809     LK_Dictionary,
6810     LK_Numeric,
6811     LK_Boxed,
6812     LK_String
6813   } LiteralKind;
6814 
6815   switch (Literal->getStmtClass()) {
6816   case Stmt::ObjCStringLiteralClass:
6817     // "string literal"
6818     LiteralKind = LK_String;
6819     break;
6820   case Stmt::ObjCArrayLiteralClass:
6821     // "array literal"
6822     LiteralKind = LK_Array;
6823     break;
6824   case Stmt::ObjCDictionaryLiteralClass:
6825     // "dictionary literal"
6826     LiteralKind = LK_Dictionary;
6827     break;
6828   case Stmt::ObjCBoxedExprClass: {
6829     Expr *Inner = cast<ObjCBoxedExpr>(Literal)->getSubExpr();
6830     switch (Inner->getStmtClass()) {
6831     case Stmt::IntegerLiteralClass:
6832     case Stmt::FloatingLiteralClass:
6833     case Stmt::CharacterLiteralClass:
6834     case Stmt::ObjCBoolLiteralExprClass:
6835     case Stmt::CXXBoolLiteralExprClass:
6836       // "numeric literal"
6837       LiteralKind = LK_Numeric;
6838       break;
6839     case Stmt::ImplicitCastExprClass: {
6840       CastKind CK = cast<CastExpr>(Inner)->getCastKind();
6841       // Boolean literals can be represented by implicit casts.
6842       if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) {
6843         LiteralKind = LK_Numeric;
6844         break;
6845       }
6846       // FALLTHROUGH
6847     }
6848     default:
6849       // "boxed expression"
6850       LiteralKind = LK_Boxed;
6851       break;
6852     }
6853     break;
6854   }
6855   default:
6856     llvm_unreachable("Unknown Objective-C object literal kind");
6857   }
6858 
6859   if (LiteralKind == LK_String)
6860     S.Diag(Loc, diag::warn_objc_string_literal_comparison)
6861       << Literal->getSourceRange();
6862   else
6863     S.Diag(Loc, diag::warn_objc_literal_comparison)
6864       << LiteralKind << Literal->getSourceRange();
6865 
6866   if (BinaryOperator::isEqualityOp(Opc) &&
6867       hasIsEqualMethod(S, LHS.get(), RHS.get())) {
6868     SourceLocation Start = LHS.get()->getLocStart();
6869     SourceLocation End = S.PP.getLocForEndOfToken(RHS.get()->getLocEnd());
6870     SourceRange OpRange(Loc, S.PP.getLocForEndOfToken(Loc));
6871 
6872     S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
6873       << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
6874       << FixItHint::CreateReplacement(OpRange, "isEqual:")
6875       << FixItHint::CreateInsertion(End, "]");
6876   }
6877 }
6878 
6879 // C99 6.5.8, C++ [expr.rel]
6880 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
6881                                     SourceLocation Loc, unsigned OpaqueOpc,
6882                                     bool IsRelational) {
6883   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
6884 
6885   BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
6886 
6887   // Handle vector comparisons separately.
6888   if (LHS.get()->getType()->isVectorType() ||
6889       RHS.get()->getType()->isVectorType())
6890     return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
6891 
6892   QualType LHSType = LHS.get()->getType();
6893   QualType RHSType = RHS.get()->getType();
6894 
6895   Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
6896   Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
6897 
6898   checkEnumComparison(*this, Loc, LHS, RHS);
6899 
6900   if (!LHSType->hasFloatingRepresentation() &&
6901       !(LHSType->isBlockPointerType() && IsRelational) &&
6902       !LHS.get()->getLocStart().isMacroID() &&
6903       !RHS.get()->getLocStart().isMacroID()) {
6904     // For non-floating point types, check for self-comparisons of the form
6905     // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
6906     // often indicate logic errors in the program.
6907     //
6908     // NOTE: Don't warn about comparison expressions resulting from macro
6909     // expansion. Also don't warn about comparisons which are only self
6910     // comparisons within a template specialization. The warnings should catch
6911     // obvious cases in the definition of the template anyways. The idea is to
6912     // warn when the typed comparison operator will always evaluate to the same
6913     // result.
6914     if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
6915       if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
6916         if (DRL->getDecl() == DRR->getDecl() &&
6917             !IsWithinTemplateSpecialization(DRL->getDecl())) {
6918           DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
6919                               << 0 // self-
6920                               << (Opc == BO_EQ
6921                                   || Opc == BO_LE
6922                                   || Opc == BO_GE));
6923         } else if (LHSType->isArrayType() && RHSType->isArrayType() &&
6924                    !DRL->getDecl()->getType()->isReferenceType() &&
6925                    !DRR->getDecl()->getType()->isReferenceType()) {
6926             // what is it always going to eval to?
6927             char always_evals_to;
6928             switch(Opc) {
6929             case BO_EQ: // e.g. array1 == array2
6930               always_evals_to = 0; // false
6931               break;
6932             case BO_NE: // e.g. array1 != array2
6933               always_evals_to = 1; // true
6934               break;
6935             default:
6936               // best we can say is 'a constant'
6937               always_evals_to = 2; // e.g. array1 <= array2
6938               break;
6939             }
6940             DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
6941                                 << 1 // array
6942                                 << always_evals_to);
6943         }
6944       }
6945     }
6946 
6947     if (isa<CastExpr>(LHSStripped))
6948       LHSStripped = LHSStripped->IgnoreParenCasts();
6949     if (isa<CastExpr>(RHSStripped))
6950       RHSStripped = RHSStripped->IgnoreParenCasts();
6951 
6952     // Warn about comparisons against a string constant (unless the other
6953     // operand is null), the user probably wants strcmp.
6954     Expr *literalString = 0;
6955     Expr *literalStringStripped = 0;
6956     if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
6957         !RHSStripped->isNullPointerConstant(Context,
6958                                             Expr::NPC_ValueDependentIsNull)) {
6959       literalString = LHS.get();
6960       literalStringStripped = LHSStripped;
6961     } else if ((isa<StringLiteral>(RHSStripped) ||
6962                 isa<ObjCEncodeExpr>(RHSStripped)) &&
6963                !LHSStripped->isNullPointerConstant(Context,
6964                                             Expr::NPC_ValueDependentIsNull)) {
6965       literalString = RHS.get();
6966       literalStringStripped = RHSStripped;
6967     }
6968 
6969     if (literalString) {
6970       std::string resultComparison;
6971       switch (Opc) {
6972       case BO_LT: resultComparison = ") < 0"; break;
6973       case BO_GT: resultComparison = ") > 0"; break;
6974       case BO_LE: resultComparison = ") <= 0"; break;
6975       case BO_GE: resultComparison = ") >= 0"; break;
6976       case BO_EQ: resultComparison = ") == 0"; break;
6977       case BO_NE: resultComparison = ") != 0"; break;
6978       default: llvm_unreachable("Invalid comparison operator");
6979       }
6980 
6981       DiagRuntimeBehavior(Loc, 0,
6982         PDiag(diag::warn_stringcompare)
6983           << isa<ObjCEncodeExpr>(literalStringStripped)
6984           << literalString->getSourceRange());
6985     }
6986   }
6987 
6988   // C99 6.5.8p3 / C99 6.5.9p4
6989   if (LHS.get()->getType()->isArithmeticType() &&
6990       RHS.get()->getType()->isArithmeticType()) {
6991     UsualArithmeticConversions(LHS, RHS);
6992     if (LHS.isInvalid() || RHS.isInvalid())
6993       return QualType();
6994   }
6995   else {
6996     LHS = UsualUnaryConversions(LHS.take());
6997     if (LHS.isInvalid())
6998       return QualType();
6999 
7000     RHS = UsualUnaryConversions(RHS.take());
7001     if (RHS.isInvalid())
7002       return QualType();
7003   }
7004 
7005   LHSType = LHS.get()->getType();
7006   RHSType = RHS.get()->getType();
7007 
7008   // The result of comparisons is 'bool' in C++, 'int' in C.
7009   QualType ResultTy = Context.getLogicalOperationType();
7010 
7011   if (IsRelational) {
7012     if (LHSType->isRealType() && RHSType->isRealType())
7013       return ResultTy;
7014   } else {
7015     // Check for comparisons of floating point operands using != and ==.
7016     if (LHSType->hasFloatingRepresentation())
7017       CheckFloatComparison(Loc, LHS.get(), RHS.get());
7018 
7019     if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
7020       return ResultTy;
7021   }
7022 
7023   bool LHSIsNull = LHS.get()->isNullPointerConstant(Context,
7024                                               Expr::NPC_ValueDependentIsNull);
7025   bool RHSIsNull = RHS.get()->isNullPointerConstant(Context,
7026                                               Expr::NPC_ValueDependentIsNull);
7027 
7028   // All of the following pointer-related warnings are GCC extensions, except
7029   // when handling null pointer constants.
7030   if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2
7031     QualType LCanPointeeTy =
7032       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
7033     QualType RCanPointeeTy =
7034       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
7035 
7036     if (getLangOpts().CPlusPlus) {
7037       if (LCanPointeeTy == RCanPointeeTy)
7038         return ResultTy;
7039       if (!IsRelational &&
7040           (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7041         // Valid unless comparison between non-null pointer and function pointer
7042         // This is a gcc extension compatibility comparison.
7043         // In a SFINAE context, we treat this as a hard error to maintain
7044         // conformance with the C++ standard.
7045         if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
7046             && !LHSIsNull && !RHSIsNull) {
7047           diagnoseFunctionPointerToVoidComparison(
7048               *this, Loc, LHS, RHS, /*isError*/ isSFINAEContext());
7049 
7050           if (isSFINAEContext())
7051             return QualType();
7052 
7053           RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
7054           return ResultTy;
7055         }
7056       }
7057 
7058       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
7059         return QualType();
7060       else
7061         return ResultTy;
7062     }
7063     // C99 6.5.9p2 and C99 6.5.8p2
7064     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
7065                                    RCanPointeeTy.getUnqualifiedType())) {
7066       // Valid unless a relational comparison of function pointers
7067       if (IsRelational && LCanPointeeTy->isFunctionType()) {
7068         Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
7069           << LHSType << RHSType << LHS.get()->getSourceRange()
7070           << RHS.get()->getSourceRange();
7071       }
7072     } else if (!IsRelational &&
7073                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7074       // Valid unless comparison between non-null pointer and function pointer
7075       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
7076           && !LHSIsNull && !RHSIsNull)
7077         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
7078                                                 /*isError*/false);
7079     } else {
7080       // Invalid
7081       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
7082     }
7083     if (LCanPointeeTy != RCanPointeeTy) {
7084       if (LHSIsNull && !RHSIsNull)
7085         LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
7086       else
7087         RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
7088     }
7089     return ResultTy;
7090   }
7091 
7092   if (getLangOpts().CPlusPlus) {
7093     // Comparison of nullptr_t with itself.
7094     if (LHSType->isNullPtrType() && RHSType->isNullPtrType())
7095       return ResultTy;
7096 
7097     // Comparison of pointers with null pointer constants and equality
7098     // comparisons of member pointers to null pointer constants.
7099     if (RHSIsNull &&
7100         ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) ||
7101          (!IsRelational &&
7102           (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) {
7103       RHS = ImpCastExprToType(RHS.take(), LHSType,
7104                         LHSType->isMemberPointerType()
7105                           ? CK_NullToMemberPointer
7106                           : CK_NullToPointer);
7107       return ResultTy;
7108     }
7109     if (LHSIsNull &&
7110         ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) ||
7111          (!IsRelational &&
7112           (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) {
7113       LHS = ImpCastExprToType(LHS.take(), RHSType,
7114                         RHSType->isMemberPointerType()
7115                           ? CK_NullToMemberPointer
7116                           : CK_NullToPointer);
7117       return ResultTy;
7118     }
7119 
7120     // Comparison of member pointers.
7121     if (!IsRelational &&
7122         LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) {
7123       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
7124         return QualType();
7125       else
7126         return ResultTy;
7127     }
7128 
7129     // Handle scoped enumeration types specifically, since they don't promote
7130     // to integers.
7131     if (LHS.get()->getType()->isEnumeralType() &&
7132         Context.hasSameUnqualifiedType(LHS.get()->getType(),
7133                                        RHS.get()->getType()))
7134       return ResultTy;
7135   }
7136 
7137   // Handle block pointer types.
7138   if (!IsRelational && LHSType->isBlockPointerType() &&
7139       RHSType->isBlockPointerType()) {
7140     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
7141     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
7142 
7143     if (!LHSIsNull && !RHSIsNull &&
7144         !Context.typesAreCompatible(lpointee, rpointee)) {
7145       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
7146         << LHSType << RHSType << LHS.get()->getSourceRange()
7147         << RHS.get()->getSourceRange();
7148     }
7149     RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
7150     return ResultTy;
7151   }
7152 
7153   // Allow block pointers to be compared with null pointer constants.
7154   if (!IsRelational
7155       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
7156           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
7157     if (!LHSIsNull && !RHSIsNull) {
7158       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
7159              ->getPointeeType()->isVoidType())
7160             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
7161                 ->getPointeeType()->isVoidType())))
7162         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
7163           << LHSType << RHSType << LHS.get()->getSourceRange()
7164           << RHS.get()->getSourceRange();
7165     }
7166     if (LHSIsNull && !RHSIsNull)
7167       LHS = ImpCastExprToType(LHS.take(), RHSType,
7168                               RHSType->isPointerType() ? CK_BitCast
7169                                 : CK_AnyPointerToBlockPointerCast);
7170     else
7171       RHS = ImpCastExprToType(RHS.take(), LHSType,
7172                               LHSType->isPointerType() ? CK_BitCast
7173                                 : CK_AnyPointerToBlockPointerCast);
7174     return ResultTy;
7175   }
7176 
7177   if (LHSType->isObjCObjectPointerType() ||
7178       RHSType->isObjCObjectPointerType()) {
7179     const PointerType *LPT = LHSType->getAs<PointerType>();
7180     const PointerType *RPT = RHSType->getAs<PointerType>();
7181     if (LPT || RPT) {
7182       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
7183       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
7184 
7185       if (!LPtrToVoid && !RPtrToVoid &&
7186           !Context.typesAreCompatible(LHSType, RHSType)) {
7187         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
7188                                           /*isError*/false);
7189       }
7190       if (LHSIsNull && !RHSIsNull)
7191         LHS = ImpCastExprToType(LHS.take(), RHSType,
7192                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
7193       else
7194         RHS = ImpCastExprToType(RHS.take(), LHSType,
7195                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
7196       return ResultTy;
7197     }
7198     if (LHSType->isObjCObjectPointerType() &&
7199         RHSType->isObjCObjectPointerType()) {
7200       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
7201         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
7202                                           /*isError*/false);
7203       if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
7204         diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
7205 
7206       if (LHSIsNull && !RHSIsNull)
7207         LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
7208       else
7209         RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
7210       return ResultTy;
7211     }
7212   }
7213   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
7214       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
7215     unsigned DiagID = 0;
7216     bool isError = false;
7217     if (LangOpts.DebuggerSupport) {
7218       // Under a debugger, allow the comparison of pointers to integers,
7219       // since users tend to want to compare addresses.
7220     } else if ((LHSIsNull && LHSType->isIntegerType()) ||
7221         (RHSIsNull && RHSType->isIntegerType())) {
7222       if (IsRelational && !getLangOpts().CPlusPlus)
7223         DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
7224     } else if (IsRelational && !getLangOpts().CPlusPlus)
7225       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
7226     else if (getLangOpts().CPlusPlus) {
7227       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
7228       isError = true;
7229     } else
7230       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
7231 
7232     if (DiagID) {
7233       Diag(Loc, DiagID)
7234         << LHSType << RHSType << LHS.get()->getSourceRange()
7235         << RHS.get()->getSourceRange();
7236       if (isError)
7237         return QualType();
7238     }
7239 
7240     if (LHSType->isIntegerType())
7241       LHS = ImpCastExprToType(LHS.take(), RHSType,
7242                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
7243     else
7244       RHS = ImpCastExprToType(RHS.take(), LHSType,
7245                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
7246     return ResultTy;
7247   }
7248 
7249   // Handle block pointers.
7250   if (!IsRelational && RHSIsNull
7251       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
7252     RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
7253     return ResultTy;
7254   }
7255   if (!IsRelational && LHSIsNull
7256       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
7257     LHS = ImpCastExprToType(LHS.take(), RHSType, CK_NullToPointer);
7258     return ResultTy;
7259   }
7260 
7261   return InvalidOperands(Loc, LHS, RHS);
7262 }
7263 
7264 
7265 // Return a signed type that is of identical size and number of elements.
7266 // For floating point vectors, return an integer type of identical size
7267 // and number of elements.
7268 QualType Sema::GetSignedVectorType(QualType V) {
7269   const VectorType *VTy = V->getAs<VectorType>();
7270   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
7271   if (TypeSize == Context.getTypeSize(Context.CharTy))
7272     return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
7273   else if (TypeSize == Context.getTypeSize(Context.ShortTy))
7274     return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
7275   else if (TypeSize == Context.getTypeSize(Context.IntTy))
7276     return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
7277   else if (TypeSize == Context.getTypeSize(Context.LongTy))
7278     return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
7279   assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
7280          "Unhandled vector element size in vector compare");
7281   return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
7282 }
7283 
7284 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
7285 /// operates on extended vector types.  Instead of producing an IntTy result,
7286 /// like a scalar comparison, a vector comparison produces a vector of integer
7287 /// types.
7288 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
7289                                           SourceLocation Loc,
7290                                           bool IsRelational) {
7291   // Check to make sure we're operating on vectors of the same type and width,
7292   // Allowing one side to be a scalar of element type.
7293   QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false);
7294   if (vType.isNull())
7295     return vType;
7296 
7297   QualType LHSType = LHS.get()->getType();
7298 
7299   // If AltiVec, the comparison results in a numeric type, i.e.
7300   // bool for C++, int for C
7301   if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
7302     return Context.getLogicalOperationType();
7303 
7304   // For non-floating point types, check for self-comparisons of the form
7305   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
7306   // often indicate logic errors in the program.
7307   if (!LHSType->hasFloatingRepresentation()) {
7308     if (DeclRefExpr* DRL
7309           = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
7310       if (DeclRefExpr* DRR
7311             = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
7312         if (DRL->getDecl() == DRR->getDecl())
7313           DiagRuntimeBehavior(Loc, 0,
7314                               PDiag(diag::warn_comparison_always)
7315                                 << 0 // self-
7316                                 << 2 // "a constant"
7317                               );
7318   }
7319 
7320   // Check for comparisons of floating point operands using != and ==.
7321   if (!IsRelational && LHSType->hasFloatingRepresentation()) {
7322     assert (RHS.get()->getType()->hasFloatingRepresentation());
7323     CheckFloatComparison(Loc, LHS.get(), RHS.get());
7324   }
7325 
7326   // Return a signed type for the vector.
7327   return GetSignedVectorType(LHSType);
7328 }
7329 
7330 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
7331                                           SourceLocation Loc) {
7332   // Ensure that either both operands are of the same vector type, or
7333   // one operand is of a vector type and the other is of its element type.
7334   QualType vType = CheckVectorOperands(LHS, RHS, Loc, false);
7335   if (vType.isNull() || vType->isFloatingType())
7336     return InvalidOperands(Loc, LHS, RHS);
7337 
7338   return GetSignedVectorType(LHS.get()->getType());
7339 }
7340 
7341 inline QualType Sema::CheckBitwiseOperands(
7342   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
7343   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7344 
7345   if (LHS.get()->getType()->isVectorType() ||
7346       RHS.get()->getType()->isVectorType()) {
7347     if (LHS.get()->getType()->hasIntegerRepresentation() &&
7348         RHS.get()->getType()->hasIntegerRepresentation())
7349       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
7350 
7351     return InvalidOperands(Loc, LHS, RHS);
7352   }
7353 
7354   ExprResult LHSResult = Owned(LHS), RHSResult = Owned(RHS);
7355   QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
7356                                                  IsCompAssign);
7357   if (LHSResult.isInvalid() || RHSResult.isInvalid())
7358     return QualType();
7359   LHS = LHSResult.take();
7360   RHS = RHSResult.take();
7361 
7362   if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
7363     return compType;
7364   return InvalidOperands(Loc, LHS, RHS);
7365 }
7366 
7367 inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
7368   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) {
7369 
7370   // Check vector operands differently.
7371   if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
7372     return CheckVectorLogicalOperands(LHS, RHS, Loc);
7373 
7374   // Diagnose cases where the user write a logical and/or but probably meant a
7375   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
7376   // is a constant.
7377   if (LHS.get()->getType()->isIntegerType() &&
7378       !LHS.get()->getType()->isBooleanType() &&
7379       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
7380       // Don't warn in macros or template instantiations.
7381       !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
7382     // If the RHS can be constant folded, and if it constant folds to something
7383     // that isn't 0 or 1 (which indicate a potential logical operation that
7384     // happened to fold to true/false) then warn.
7385     // Parens on the RHS are ignored.
7386     llvm::APSInt Result;
7387     if (RHS.get()->EvaluateAsInt(Result, Context))
7388       if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType()) ||
7389           (Result != 0 && Result != 1)) {
7390         Diag(Loc, diag::warn_logical_instead_of_bitwise)
7391           << RHS.get()->getSourceRange()
7392           << (Opc == BO_LAnd ? "&&" : "||");
7393         // Suggest replacing the logical operator with the bitwise version
7394         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
7395             << (Opc == BO_LAnd ? "&" : "|")
7396             << FixItHint::CreateReplacement(SourceRange(
7397                 Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(),
7398                                                 getLangOpts())),
7399                                             Opc == BO_LAnd ? "&" : "|");
7400         if (Opc == BO_LAnd)
7401           // Suggest replacing "Foo() && kNonZero" with "Foo()"
7402           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
7403               << FixItHint::CreateRemoval(
7404                   SourceRange(
7405                       Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(),
7406                                                  0, getSourceManager(),
7407                                                  getLangOpts()),
7408                       RHS.get()->getLocEnd()));
7409       }
7410   }
7411 
7412   if (!Context.getLangOpts().CPlusPlus) {
7413     LHS = UsualUnaryConversions(LHS.take());
7414     if (LHS.isInvalid())
7415       return QualType();
7416 
7417     RHS = UsualUnaryConversions(RHS.take());
7418     if (RHS.isInvalid())
7419       return QualType();
7420 
7421     if (!LHS.get()->getType()->isScalarType() ||
7422         !RHS.get()->getType()->isScalarType())
7423       return InvalidOperands(Loc, LHS, RHS);
7424 
7425     return Context.IntTy;
7426   }
7427 
7428   // The following is safe because we only use this method for
7429   // non-overloadable operands.
7430 
7431   // C++ [expr.log.and]p1
7432   // C++ [expr.log.or]p1
7433   // The operands are both contextually converted to type bool.
7434   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
7435   if (LHSRes.isInvalid())
7436     return InvalidOperands(Loc, LHS, RHS);
7437   LHS = LHSRes;
7438 
7439   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
7440   if (RHSRes.isInvalid())
7441     return InvalidOperands(Loc, LHS, RHS);
7442   RHS = RHSRes;
7443 
7444   // C++ [expr.log.and]p2
7445   // C++ [expr.log.or]p2
7446   // The result is a bool.
7447   return Context.BoolTy;
7448 }
7449 
7450 /// IsReadonlyProperty - Verify that otherwise a valid l-value expression
7451 /// is a read-only property; return true if so. A readonly property expression
7452 /// depends on various declarations and thus must be treated specially.
7453 ///
7454 static bool IsReadonlyProperty(Expr *E, Sema &S) {
7455   const ObjCPropertyRefExpr *PropExpr = dyn_cast<ObjCPropertyRefExpr>(E);
7456   if (!PropExpr) return false;
7457   if (PropExpr->isImplicitProperty()) return false;
7458 
7459   ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
7460   QualType BaseType = PropExpr->isSuperReceiver() ?
7461                             PropExpr->getSuperReceiverType() :
7462                             PropExpr->getBase()->getType();
7463 
7464   if (const ObjCObjectPointerType *OPT =
7465       BaseType->getAsObjCInterfacePointerType())
7466     if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
7467       if (S.isPropertyReadonly(PDecl, IFace))
7468         return true;
7469   return false;
7470 }
7471 
7472 static bool IsReadonlyMessage(Expr *E, Sema &S) {
7473   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
7474   if (!ME) return false;
7475   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
7476   ObjCMessageExpr *Base =
7477     dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts());
7478   if (!Base) return false;
7479   return Base->getMethodDecl() != 0;
7480 }
7481 
7482 /// Is the given expression (which must be 'const') a reference to a
7483 /// variable which was originally non-const, but which has become
7484 /// 'const' due to being captured within a block?
7485 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
7486 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
7487   assert(E->isLValue() && E->getType().isConstQualified());
7488   E = E->IgnoreParens();
7489 
7490   // Must be a reference to a declaration from an enclosing scope.
7491   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
7492   if (!DRE) return NCCK_None;
7493   if (!DRE->refersToEnclosingLocal()) return NCCK_None;
7494 
7495   // The declaration must be a variable which is not declared 'const'.
7496   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
7497   if (!var) return NCCK_None;
7498   if (var->getType().isConstQualified()) return NCCK_None;
7499   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
7500 
7501   // Decide whether the first capture was for a block or a lambda.
7502   DeclContext *DC = S.CurContext;
7503   while (DC->getParent() != var->getDeclContext())
7504     DC = DC->getParent();
7505   return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
7506 }
7507 
7508 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
7509 /// emit an error and return true.  If so, return false.
7510 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
7511   assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
7512   SourceLocation OrigLoc = Loc;
7513   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
7514                                                               &Loc);
7515   if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
7516     IsLV = Expr::MLV_ReadonlyProperty;
7517   else if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
7518     IsLV = Expr::MLV_InvalidMessageExpression;
7519   if (IsLV == Expr::MLV_Valid)
7520     return false;
7521 
7522   unsigned Diag = 0;
7523   bool NeedType = false;
7524   switch (IsLV) { // C99 6.5.16p2
7525   case Expr::MLV_ConstQualified:
7526     Diag = diag::err_typecheck_assign_const;
7527 
7528     // Use a specialized diagnostic when we're assigning to an object
7529     // from an enclosing function or block.
7530     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
7531       if (NCCK == NCCK_Block)
7532         Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
7533       else
7534         Diag = diag::err_lambda_decl_ref_not_modifiable_lvalue;
7535       break;
7536     }
7537 
7538     // In ARC, use some specialized diagnostics for occasions where we
7539     // infer 'const'.  These are always pseudo-strong variables.
7540     if (S.getLangOpts().ObjCAutoRefCount) {
7541       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
7542       if (declRef && isa<VarDecl>(declRef->getDecl())) {
7543         VarDecl *var = cast<VarDecl>(declRef->getDecl());
7544 
7545         // Use the normal diagnostic if it's pseudo-__strong but the
7546         // user actually wrote 'const'.
7547         if (var->isARCPseudoStrong() &&
7548             (!var->getTypeSourceInfo() ||
7549              !var->getTypeSourceInfo()->getType().isConstQualified())) {
7550           // There are two pseudo-strong cases:
7551           //  - self
7552           ObjCMethodDecl *method = S.getCurMethodDecl();
7553           if (method && var == method->getSelfDecl())
7554             Diag = method->isClassMethod()
7555               ? diag::err_typecheck_arc_assign_self_class_method
7556               : diag::err_typecheck_arc_assign_self;
7557 
7558           //  - fast enumeration variables
7559           else
7560             Diag = diag::err_typecheck_arr_assign_enumeration;
7561 
7562           SourceRange Assign;
7563           if (Loc != OrigLoc)
7564             Assign = SourceRange(OrigLoc, OrigLoc);
7565           S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
7566           // We need to preserve the AST regardless, so migration tool
7567           // can do its job.
7568           return false;
7569         }
7570       }
7571     }
7572 
7573     break;
7574   case Expr::MLV_ArrayType:
7575   case Expr::MLV_ArrayTemporary:
7576     Diag = diag::err_typecheck_array_not_modifiable_lvalue;
7577     NeedType = true;
7578     break;
7579   case Expr::MLV_NotObjectType:
7580     Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
7581     NeedType = true;
7582     break;
7583   case Expr::MLV_LValueCast:
7584     Diag = diag::err_typecheck_lvalue_casts_not_supported;
7585     break;
7586   case Expr::MLV_Valid:
7587     llvm_unreachable("did not take early return for MLV_Valid");
7588   case Expr::MLV_InvalidExpression:
7589   case Expr::MLV_MemberFunction:
7590   case Expr::MLV_ClassTemporary:
7591     Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
7592     break;
7593   case Expr::MLV_IncompleteType:
7594   case Expr::MLV_IncompleteVoidType:
7595     return S.RequireCompleteType(Loc, E->getType(),
7596              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
7597   case Expr::MLV_DuplicateVectorComponents:
7598     Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
7599     break;
7600   case Expr::MLV_ReadonlyProperty:
7601   case Expr::MLV_NoSetterProperty:
7602     llvm_unreachable("readonly properties should be processed differently");
7603   case Expr::MLV_InvalidMessageExpression:
7604     Diag = diag::error_readonly_message_assignment;
7605     break;
7606   case Expr::MLV_SubObjCPropertySetting:
7607     Diag = diag::error_no_subobject_property_setting;
7608     break;
7609   }
7610 
7611   SourceRange Assign;
7612   if (Loc != OrigLoc)
7613     Assign = SourceRange(OrigLoc, OrigLoc);
7614   if (NeedType)
7615     S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
7616   else
7617     S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
7618   return true;
7619 }
7620 
7621 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
7622                                          SourceLocation Loc,
7623                                          Sema &Sema) {
7624   // C / C++ fields
7625   MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
7626   MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
7627   if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) {
7628     if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))
7629       Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
7630   }
7631 
7632   // Objective-C instance variables
7633   ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
7634   ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
7635   if (OL && OR && OL->getDecl() == OR->getDecl()) {
7636     DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
7637     DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
7638     if (RL && RR && RL->getDecl() == RR->getDecl())
7639       Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
7640   }
7641 }
7642 
7643 // C99 6.5.16.1
7644 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
7645                                        SourceLocation Loc,
7646                                        QualType CompoundType) {
7647   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
7648 
7649   // Verify that LHS is a modifiable lvalue, and emit error if not.
7650   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
7651     return QualType();
7652 
7653   QualType LHSType = LHSExpr->getType();
7654   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
7655                                              CompoundType;
7656   AssignConvertType ConvTy;
7657   if (CompoundType.isNull()) {
7658     Expr *RHSCheck = RHS.get();
7659 
7660     CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
7661 
7662     QualType LHSTy(LHSType);
7663     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
7664     if (RHS.isInvalid())
7665       return QualType();
7666     // Special case of NSObject attributes on c-style pointer types.
7667     if (ConvTy == IncompatiblePointer &&
7668         ((Context.isObjCNSObjectType(LHSType) &&
7669           RHSType->isObjCObjectPointerType()) ||
7670          (Context.isObjCNSObjectType(RHSType) &&
7671           LHSType->isObjCObjectPointerType())))
7672       ConvTy = Compatible;
7673 
7674     if (ConvTy == Compatible &&
7675         LHSType->isObjCObjectType())
7676         Diag(Loc, diag::err_objc_object_assignment)
7677           << LHSType;
7678 
7679     // If the RHS is a unary plus or minus, check to see if they = and + are
7680     // right next to each other.  If so, the user may have typo'd "x =+ 4"
7681     // instead of "x += 4".
7682     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
7683       RHSCheck = ICE->getSubExpr();
7684     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
7685       if ((UO->getOpcode() == UO_Plus ||
7686            UO->getOpcode() == UO_Minus) &&
7687           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
7688           // Only if the two operators are exactly adjacent.
7689           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
7690           // And there is a space or other character before the subexpr of the
7691           // unary +/-.  We don't want to warn on "x=-1".
7692           Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
7693           UO->getSubExpr()->getLocStart().isFileID()) {
7694         Diag(Loc, diag::warn_not_compound_assign)
7695           << (UO->getOpcode() == UO_Plus ? "+" : "-")
7696           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
7697       }
7698     }
7699 
7700     if (ConvTy == Compatible) {
7701       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong)
7702         checkRetainCycles(LHSExpr, RHS.get());
7703       else if (getLangOpts().ObjCAutoRefCount)
7704         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
7705     }
7706   } else {
7707     // Compound assignment "x += y"
7708     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
7709   }
7710 
7711   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
7712                                RHS.get(), AA_Assigning))
7713     return QualType();
7714 
7715   CheckForNullPointerDereference(*this, LHSExpr);
7716 
7717   // C99 6.5.16p3: The type of an assignment expression is the type of the
7718   // left operand unless the left operand has qualified type, in which case
7719   // it is the unqualified version of the type of the left operand.
7720   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
7721   // is converted to the type of the assignment expression (above).
7722   // C++ 5.17p1: the type of the assignment expression is that of its left
7723   // operand.
7724   return (getLangOpts().CPlusPlus
7725           ? LHSType : LHSType.getUnqualifiedType());
7726 }
7727 
7728 // C99 6.5.17
7729 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
7730                                    SourceLocation Loc) {
7731   LHS = S.CheckPlaceholderExpr(LHS.take());
7732   RHS = S.CheckPlaceholderExpr(RHS.take());
7733   if (LHS.isInvalid() || RHS.isInvalid())
7734     return QualType();
7735 
7736   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
7737   // operands, but not unary promotions.
7738   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
7739 
7740   // So we treat the LHS as a ignored value, and in C++ we allow the
7741   // containing site to determine what should be done with the RHS.
7742   LHS = S.IgnoredValueConversions(LHS.take());
7743   if (LHS.isInvalid())
7744     return QualType();
7745 
7746   S.DiagnoseUnusedExprResult(LHS.get());
7747 
7748   if (!S.getLangOpts().CPlusPlus) {
7749     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take());
7750     if (RHS.isInvalid())
7751       return QualType();
7752     if (!RHS.get()->getType()->isVoidType())
7753       S.RequireCompleteType(Loc, RHS.get()->getType(),
7754                             diag::err_incomplete_type);
7755   }
7756 
7757   return RHS.get()->getType();
7758 }
7759 
7760 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
7761 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
7762 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
7763                                                ExprValueKind &VK,
7764                                                SourceLocation OpLoc,
7765                                                bool IsInc, bool IsPrefix) {
7766   if (Op->isTypeDependent())
7767     return S.Context.DependentTy;
7768 
7769   QualType ResType = Op->getType();
7770   // Atomic types can be used for increment / decrement where the non-atomic
7771   // versions can, so ignore the _Atomic() specifier for the purpose of
7772   // checking.
7773   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
7774     ResType = ResAtomicType->getValueType();
7775 
7776   assert(!ResType.isNull() && "no type for increment/decrement expression");
7777 
7778   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
7779     // Decrement of bool is not allowed.
7780     if (!IsInc) {
7781       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
7782       return QualType();
7783     }
7784     // Increment of bool sets it to true, but is deprecated.
7785     S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
7786   } else if (ResType->isRealType()) {
7787     // OK!
7788   } else if (ResType->isPointerType()) {
7789     // C99 6.5.2.4p2, 6.5.6p2
7790     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
7791       return QualType();
7792   } else if (ResType->isObjCObjectPointerType()) {
7793     // On modern runtimes, ObjC pointer arithmetic is forbidden.
7794     // Otherwise, we just need a complete type.
7795     if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
7796         checkArithmeticOnObjCPointer(S, OpLoc, Op))
7797       return QualType();
7798   } else if (ResType->isAnyComplexType()) {
7799     // C99 does not support ++/-- on complex types, we allow as an extension.
7800     S.Diag(OpLoc, diag::ext_integer_increment_complex)
7801       << ResType << Op->getSourceRange();
7802   } else if (ResType->isPlaceholderType()) {
7803     ExprResult PR = S.CheckPlaceholderExpr(Op);
7804     if (PR.isInvalid()) return QualType();
7805     return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
7806                                           IsInc, IsPrefix);
7807   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
7808     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
7809   } else {
7810     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
7811       << ResType << int(IsInc) << Op->getSourceRange();
7812     return QualType();
7813   }
7814   // At this point, we know we have a real, complex or pointer type.
7815   // Now make sure the operand is a modifiable lvalue.
7816   if (CheckForModifiableLvalue(Op, OpLoc, S))
7817     return QualType();
7818   // In C++, a prefix increment is the same type as the operand. Otherwise
7819   // (in C or with postfix), the increment is the unqualified type of the
7820   // operand.
7821   if (IsPrefix && S.getLangOpts().CPlusPlus) {
7822     VK = VK_LValue;
7823     return ResType;
7824   } else {
7825     VK = VK_RValue;
7826     return ResType.getUnqualifiedType();
7827   }
7828 }
7829 
7830 
7831 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
7832 /// This routine allows us to typecheck complex/recursive expressions
7833 /// where the declaration is needed for type checking. We only need to
7834 /// handle cases when the expression references a function designator
7835 /// or is an lvalue. Here are some examples:
7836 ///  - &(x) => x
7837 ///  - &*****f => f for f a function designator.
7838 ///  - &s.xx => s
7839 ///  - &s.zz[1].yy -> s, if zz is an array
7840 ///  - *(x + 1) -> x, if x is an array
7841 ///  - &"123"[2] -> 0
7842 ///  - & __real__ x -> x
7843 static ValueDecl *getPrimaryDecl(Expr *E) {
7844   switch (E->getStmtClass()) {
7845   case Stmt::DeclRefExprClass:
7846     return cast<DeclRefExpr>(E)->getDecl();
7847   case Stmt::MemberExprClass:
7848     // If this is an arrow operator, the address is an offset from
7849     // the base's value, so the object the base refers to is
7850     // irrelevant.
7851     if (cast<MemberExpr>(E)->isArrow())
7852       return 0;
7853     // Otherwise, the expression refers to a part of the base
7854     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
7855   case Stmt::ArraySubscriptExprClass: {
7856     // FIXME: This code shouldn't be necessary!  We should catch the implicit
7857     // promotion of register arrays earlier.
7858     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
7859     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
7860       if (ICE->getSubExpr()->getType()->isArrayType())
7861         return getPrimaryDecl(ICE->getSubExpr());
7862     }
7863     return 0;
7864   }
7865   case Stmt::UnaryOperatorClass: {
7866     UnaryOperator *UO = cast<UnaryOperator>(E);
7867 
7868     switch(UO->getOpcode()) {
7869     case UO_Real:
7870     case UO_Imag:
7871     case UO_Extension:
7872       return getPrimaryDecl(UO->getSubExpr());
7873     default:
7874       return 0;
7875     }
7876   }
7877   case Stmt::ParenExprClass:
7878     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
7879   case Stmt::ImplicitCastExprClass:
7880     // If the result of an implicit cast is an l-value, we care about
7881     // the sub-expression; otherwise, the result here doesn't matter.
7882     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
7883   default:
7884     return 0;
7885   }
7886 }
7887 
7888 namespace {
7889   enum {
7890     AO_Bit_Field = 0,
7891     AO_Vector_Element = 1,
7892     AO_Property_Expansion = 2,
7893     AO_Register_Variable = 3,
7894     AO_No_Error = 4
7895   };
7896 }
7897 /// \brief Diagnose invalid operand for address of operations.
7898 ///
7899 /// \param Type The type of operand which cannot have its address taken.
7900 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
7901                                          Expr *E, unsigned Type) {
7902   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
7903 }
7904 
7905 /// CheckAddressOfOperand - The operand of & must be either a function
7906 /// designator or an lvalue designating an object. If it is an lvalue, the
7907 /// object cannot be declared with storage class register or be a bit field.
7908 /// Note: The usual conversions are *not* applied to the operand of the &
7909 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
7910 /// In C++, the operand might be an overloaded function name, in which case
7911 /// we allow the '&' but retain the overloaded-function type.
7912 static QualType CheckAddressOfOperand(Sema &S, ExprResult &OrigOp,
7913                                       SourceLocation OpLoc) {
7914   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
7915     if (PTy->getKind() == BuiltinType::Overload) {
7916       if (!isa<OverloadExpr>(OrigOp.get()->IgnoreParens())) {
7917         S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
7918           << OrigOp.get()->getSourceRange();
7919         return QualType();
7920       }
7921 
7922       return S.Context.OverloadTy;
7923     }
7924 
7925     if (PTy->getKind() == BuiltinType::UnknownAny)
7926       return S.Context.UnknownAnyTy;
7927 
7928     if (PTy->getKind() == BuiltinType::BoundMember) {
7929       S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
7930         << OrigOp.get()->getSourceRange();
7931       return QualType();
7932     }
7933 
7934     OrigOp = S.CheckPlaceholderExpr(OrigOp.take());
7935     if (OrigOp.isInvalid()) return QualType();
7936   }
7937 
7938   if (OrigOp.get()->isTypeDependent())
7939     return S.Context.DependentTy;
7940 
7941   assert(!OrigOp.get()->getType()->isPlaceholderType());
7942 
7943   // Make sure to ignore parentheses in subsequent checks
7944   Expr *op = OrigOp.get()->IgnoreParens();
7945 
7946   if (S.getLangOpts().C99) {
7947     // Implement C99-only parts of addressof rules.
7948     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
7949       if (uOp->getOpcode() == UO_Deref)
7950         // Per C99 6.5.3.2, the address of a deref always returns a valid result
7951         // (assuming the deref expression is valid).
7952         return uOp->getSubExpr()->getType();
7953     }
7954     // Technically, there should be a check for array subscript
7955     // expressions here, but the result of one is always an lvalue anyway.
7956   }
7957   ValueDecl *dcl = getPrimaryDecl(op);
7958   Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
7959   unsigned AddressOfError = AO_No_Error;
7960 
7961   if (lval == Expr::LV_ClassTemporary) {
7962     bool sfinae = S.isSFINAEContext();
7963     S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
7964                          : diag::ext_typecheck_addrof_class_temporary)
7965       << op->getType() << op->getSourceRange();
7966     if (sfinae)
7967       return QualType();
7968   } else if (isa<ObjCSelectorExpr>(op)) {
7969     return S.Context.getPointerType(op->getType());
7970   } else if (lval == Expr::LV_MemberFunction) {
7971     // If it's an instance method, make a member pointer.
7972     // The expression must have exactly the form &A::foo.
7973 
7974     // If the underlying expression isn't a decl ref, give up.
7975     if (!isa<DeclRefExpr>(op)) {
7976       S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
7977         << OrigOp.get()->getSourceRange();
7978       return QualType();
7979     }
7980     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
7981     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
7982 
7983     // The id-expression was parenthesized.
7984     if (OrigOp.get() != DRE) {
7985       S.Diag(OpLoc, diag::err_parens_pointer_member_function)
7986         << OrigOp.get()->getSourceRange();
7987 
7988     // The method was named without a qualifier.
7989     } else if (!DRE->getQualifier()) {
7990       S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
7991         << op->getSourceRange();
7992     }
7993 
7994     return S.Context.getMemberPointerType(op->getType(),
7995               S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
7996   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
7997     // C99 6.5.3.2p1
7998     // The operand must be either an l-value or a function designator
7999     if (!op->getType()->isFunctionType()) {
8000       // Use a special diagnostic for loads from property references.
8001       if (isa<PseudoObjectExpr>(op)) {
8002         AddressOfError = AO_Property_Expansion;
8003       } else {
8004         // FIXME: emit more specific diag...
8005         S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
8006           << op->getSourceRange();
8007         return QualType();
8008       }
8009     }
8010   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
8011     // The operand cannot be a bit-field
8012     AddressOfError = AO_Bit_Field;
8013   } else if (op->getObjectKind() == OK_VectorComponent) {
8014     // The operand cannot be an element of a vector
8015     AddressOfError = AO_Vector_Element;
8016   } else if (dcl) { // C99 6.5.3.2p1
8017     // We have an lvalue with a decl. Make sure the decl is not declared
8018     // with the register storage-class specifier.
8019     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
8020       // in C++ it is not error to take address of a register
8021       // variable (c++03 7.1.1P3)
8022       if (vd->getStorageClass() == SC_Register &&
8023           !S.getLangOpts().CPlusPlus) {
8024         AddressOfError = AO_Register_Variable;
8025       }
8026     } else if (isa<FunctionTemplateDecl>(dcl)) {
8027       return S.Context.OverloadTy;
8028     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
8029       // Okay: we can take the address of a field.
8030       // Could be a pointer to member, though, if there is an explicit
8031       // scope qualifier for the class.
8032       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
8033         DeclContext *Ctx = dcl->getDeclContext();
8034         if (Ctx && Ctx->isRecord()) {
8035           if (dcl->getType()->isReferenceType()) {
8036             S.Diag(OpLoc,
8037                    diag::err_cannot_form_pointer_to_member_of_reference_type)
8038               << dcl->getDeclName() << dcl->getType();
8039             return QualType();
8040           }
8041 
8042           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
8043             Ctx = Ctx->getParent();
8044           return S.Context.getMemberPointerType(op->getType(),
8045                 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
8046         }
8047       }
8048     } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl))
8049       llvm_unreachable("Unknown/unexpected decl type");
8050   }
8051 
8052   if (AddressOfError != AO_No_Error) {
8053     diagnoseAddressOfInvalidType(S, OpLoc, op, AddressOfError);
8054     return QualType();
8055   }
8056 
8057   if (lval == Expr::LV_IncompleteVoidType) {
8058     // Taking the address of a void variable is technically illegal, but we
8059     // allow it in cases which are otherwise valid.
8060     // Example: "extern void x; void* y = &x;".
8061     S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
8062   }
8063 
8064   // If the operand has type "type", the result has type "pointer to type".
8065   if (op->getType()->isObjCObjectType())
8066     return S.Context.getObjCObjectPointerType(op->getType());
8067   return S.Context.getPointerType(op->getType());
8068 }
8069 
8070 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
8071 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
8072                                         SourceLocation OpLoc) {
8073   if (Op->isTypeDependent())
8074     return S.Context.DependentTy;
8075 
8076   ExprResult ConvResult = S.UsualUnaryConversions(Op);
8077   if (ConvResult.isInvalid())
8078     return QualType();
8079   Op = ConvResult.take();
8080   QualType OpTy = Op->getType();
8081   QualType Result;
8082 
8083   if (isa<CXXReinterpretCastExpr>(Op)) {
8084     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
8085     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
8086                                      Op->getSourceRange());
8087   }
8088 
8089   // Note that per both C89 and C99, indirection is always legal, even if OpTy
8090   // is an incomplete type or void.  It would be possible to warn about
8091   // dereferencing a void pointer, but it's completely well-defined, and such a
8092   // warning is unlikely to catch any mistakes.
8093   if (const PointerType *PT = OpTy->getAs<PointerType>())
8094     Result = PT->getPointeeType();
8095   else if (const ObjCObjectPointerType *OPT =
8096              OpTy->getAs<ObjCObjectPointerType>())
8097     Result = OPT->getPointeeType();
8098   else {
8099     ExprResult PR = S.CheckPlaceholderExpr(Op);
8100     if (PR.isInvalid()) return QualType();
8101     if (PR.take() != Op)
8102       return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
8103   }
8104 
8105   if (Result.isNull()) {
8106     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
8107       << OpTy << Op->getSourceRange();
8108     return QualType();
8109   }
8110 
8111   // Dereferences are usually l-values...
8112   VK = VK_LValue;
8113 
8114   // ...except that certain expressions are never l-values in C.
8115   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
8116     VK = VK_RValue;
8117 
8118   return Result;
8119 }
8120 
8121 static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
8122   tok::TokenKind Kind) {
8123   BinaryOperatorKind Opc;
8124   switch (Kind) {
8125   default: llvm_unreachable("Unknown binop!");
8126   case tok::periodstar:           Opc = BO_PtrMemD; break;
8127   case tok::arrowstar:            Opc = BO_PtrMemI; break;
8128   case tok::star:                 Opc = BO_Mul; break;
8129   case tok::slash:                Opc = BO_Div; break;
8130   case tok::percent:              Opc = BO_Rem; break;
8131   case tok::plus:                 Opc = BO_Add; break;
8132   case tok::minus:                Opc = BO_Sub; break;
8133   case tok::lessless:             Opc = BO_Shl; break;
8134   case tok::greatergreater:       Opc = BO_Shr; break;
8135   case tok::lessequal:            Opc = BO_LE; break;
8136   case tok::less:                 Opc = BO_LT; break;
8137   case tok::greaterequal:         Opc = BO_GE; break;
8138   case tok::greater:              Opc = BO_GT; break;
8139   case tok::exclaimequal:         Opc = BO_NE; break;
8140   case tok::equalequal:           Opc = BO_EQ; break;
8141   case tok::amp:                  Opc = BO_And; break;
8142   case tok::caret:                Opc = BO_Xor; break;
8143   case tok::pipe:                 Opc = BO_Or; break;
8144   case tok::ampamp:               Opc = BO_LAnd; break;
8145   case tok::pipepipe:             Opc = BO_LOr; break;
8146   case tok::equal:                Opc = BO_Assign; break;
8147   case tok::starequal:            Opc = BO_MulAssign; break;
8148   case tok::slashequal:           Opc = BO_DivAssign; break;
8149   case tok::percentequal:         Opc = BO_RemAssign; break;
8150   case tok::plusequal:            Opc = BO_AddAssign; break;
8151   case tok::minusequal:           Opc = BO_SubAssign; break;
8152   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
8153   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
8154   case tok::ampequal:             Opc = BO_AndAssign; break;
8155   case tok::caretequal:           Opc = BO_XorAssign; break;
8156   case tok::pipeequal:            Opc = BO_OrAssign; break;
8157   case tok::comma:                Opc = BO_Comma; break;
8158   }
8159   return Opc;
8160 }
8161 
8162 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
8163   tok::TokenKind Kind) {
8164   UnaryOperatorKind Opc;
8165   switch (Kind) {
8166   default: llvm_unreachable("Unknown unary op!");
8167   case tok::plusplus:     Opc = UO_PreInc; break;
8168   case tok::minusminus:   Opc = UO_PreDec; break;
8169   case tok::amp:          Opc = UO_AddrOf; break;
8170   case tok::star:         Opc = UO_Deref; break;
8171   case tok::plus:         Opc = UO_Plus; break;
8172   case tok::minus:        Opc = UO_Minus; break;
8173   case tok::tilde:        Opc = UO_Not; break;
8174   case tok::exclaim:      Opc = UO_LNot; break;
8175   case tok::kw___real:    Opc = UO_Real; break;
8176   case tok::kw___imag:    Opc = UO_Imag; break;
8177   case tok::kw___extension__: Opc = UO_Extension; break;
8178   }
8179   return Opc;
8180 }
8181 
8182 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
8183 /// This warning is only emitted for builtin assignment operations. It is also
8184 /// suppressed in the event of macro expansions.
8185 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
8186                                    SourceLocation OpLoc) {
8187   if (!S.ActiveTemplateInstantiations.empty())
8188     return;
8189   if (OpLoc.isInvalid() || OpLoc.isMacroID())
8190     return;
8191   LHSExpr = LHSExpr->IgnoreParenImpCasts();
8192   RHSExpr = RHSExpr->IgnoreParenImpCasts();
8193   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
8194   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
8195   if (!LHSDeclRef || !RHSDeclRef ||
8196       LHSDeclRef->getLocation().isMacroID() ||
8197       RHSDeclRef->getLocation().isMacroID())
8198     return;
8199   const ValueDecl *LHSDecl =
8200     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
8201   const ValueDecl *RHSDecl =
8202     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
8203   if (LHSDecl != RHSDecl)
8204     return;
8205   if (LHSDecl->getType().isVolatileQualified())
8206     return;
8207   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
8208     if (RefTy->getPointeeType().isVolatileQualified())
8209       return;
8210 
8211   S.Diag(OpLoc, diag::warn_self_assignment)
8212       << LHSDeclRef->getType()
8213       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
8214 }
8215 
8216 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
8217 /// operator @p Opc at location @c TokLoc. This routine only supports
8218 /// built-in operations; ActOnBinOp handles overloaded operators.
8219 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
8220                                     BinaryOperatorKind Opc,
8221                                     Expr *LHSExpr, Expr *RHSExpr) {
8222   if (getLangOpts().CPlusPlus0x && isa<InitListExpr>(RHSExpr)) {
8223     // The syntax only allows initializer lists on the RHS of assignment,
8224     // so we don't need to worry about accepting invalid code for
8225     // non-assignment operators.
8226     // C++11 5.17p9:
8227     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
8228     //   of x = {} is x = T().
8229     InitializationKind Kind =
8230         InitializationKind::CreateDirectList(RHSExpr->getLocStart());
8231     InitializedEntity Entity =
8232         InitializedEntity::InitializeTemporary(LHSExpr->getType());
8233     InitializationSequence InitSeq(*this, Entity, Kind, &RHSExpr, 1);
8234     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
8235     if (Init.isInvalid())
8236       return Init;
8237     RHSExpr = Init.take();
8238   }
8239 
8240   ExprResult LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
8241   QualType ResultTy;     // Result type of the binary operator.
8242   // The following two variables are used for compound assignment operators
8243   QualType CompLHSTy;    // Type of LHS after promotions for computation
8244   QualType CompResultTy; // Type of computation result
8245   ExprValueKind VK = VK_RValue;
8246   ExprObjectKind OK = OK_Ordinary;
8247 
8248   switch (Opc) {
8249   case BO_Assign:
8250     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
8251     if (getLangOpts().CPlusPlus &&
8252         LHS.get()->getObjectKind() != OK_ObjCProperty) {
8253       VK = LHS.get()->getValueKind();
8254       OK = LHS.get()->getObjectKind();
8255     }
8256     if (!ResultTy.isNull())
8257       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
8258     break;
8259   case BO_PtrMemD:
8260   case BO_PtrMemI:
8261     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
8262                                             Opc == BO_PtrMemI);
8263     break;
8264   case BO_Mul:
8265   case BO_Div:
8266     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
8267                                            Opc == BO_Div);
8268     break;
8269   case BO_Rem:
8270     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
8271     break;
8272   case BO_Add:
8273     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
8274     break;
8275   case BO_Sub:
8276     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
8277     break;
8278   case BO_Shl:
8279   case BO_Shr:
8280     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
8281     break;
8282   case BO_LE:
8283   case BO_LT:
8284   case BO_GE:
8285   case BO_GT:
8286     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
8287     break;
8288   case BO_EQ:
8289   case BO_NE:
8290     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
8291     break;
8292   case BO_And:
8293   case BO_Xor:
8294   case BO_Or:
8295     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc);
8296     break;
8297   case BO_LAnd:
8298   case BO_LOr:
8299     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
8300     break;
8301   case BO_MulAssign:
8302   case BO_DivAssign:
8303     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
8304                                                Opc == BO_DivAssign);
8305     CompLHSTy = CompResultTy;
8306     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8307       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
8308     break;
8309   case BO_RemAssign:
8310     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
8311     CompLHSTy = CompResultTy;
8312     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8313       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
8314     break;
8315   case BO_AddAssign:
8316     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
8317     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8318       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
8319     break;
8320   case BO_SubAssign:
8321     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
8322     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8323       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
8324     break;
8325   case BO_ShlAssign:
8326   case BO_ShrAssign:
8327     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
8328     CompLHSTy = CompResultTy;
8329     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8330       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
8331     break;
8332   case BO_AndAssign:
8333   case BO_XorAssign:
8334   case BO_OrAssign:
8335     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true);
8336     CompLHSTy = CompResultTy;
8337     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8338       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
8339     break;
8340   case BO_Comma:
8341     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
8342     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
8343       VK = RHS.get()->getValueKind();
8344       OK = RHS.get()->getObjectKind();
8345     }
8346     break;
8347   }
8348   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
8349     return ExprError();
8350 
8351   // Check for array bounds violations for both sides of the BinaryOperator
8352   CheckArrayAccess(LHS.get());
8353   CheckArrayAccess(RHS.get());
8354 
8355   if (CompResultTy.isNull())
8356     return Owned(new (Context) BinaryOperator(LHS.take(), RHS.take(), Opc,
8357                                               ResultTy, VK, OK, OpLoc));
8358   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
8359       OK_ObjCProperty) {
8360     VK = VK_LValue;
8361     OK = LHS.get()->getObjectKind();
8362   }
8363   return Owned(new (Context) CompoundAssignOperator(LHS.take(), RHS.take(), Opc,
8364                                                     ResultTy, VK, OK, CompLHSTy,
8365                                                     CompResultTy, OpLoc));
8366 }
8367 
8368 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
8369 /// operators are mixed in a way that suggests that the programmer forgot that
8370 /// comparison operators have higher precedence. The most typical example of
8371 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
8372 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
8373                                       SourceLocation OpLoc, Expr *LHSExpr,
8374                                       Expr *RHSExpr) {
8375   typedef BinaryOperator BinOp;
8376   BinOp::Opcode LHSopc = static_cast<BinOp::Opcode>(-1),
8377                 RHSopc = static_cast<BinOp::Opcode>(-1);
8378   if (BinOp *BO = dyn_cast<BinOp>(LHSExpr))
8379     LHSopc = BO->getOpcode();
8380   if (BinOp *BO = dyn_cast<BinOp>(RHSExpr))
8381     RHSopc = BO->getOpcode();
8382 
8383   // Subs are not binary operators.
8384   if (LHSopc == -1 && RHSopc == -1)
8385     return;
8386 
8387   // Bitwise operations are sometimes used as eager logical ops.
8388   // Don't diagnose this.
8389   if ((BinOp::isComparisonOp(LHSopc) || BinOp::isBitwiseOp(LHSopc)) &&
8390       (BinOp::isComparisonOp(RHSopc) || BinOp::isBitwiseOp(RHSopc)))
8391     return;
8392 
8393   bool isLeftComp = BinOp::isComparisonOp(LHSopc);
8394   bool isRightComp = BinOp::isComparisonOp(RHSopc);
8395   if (!isLeftComp && !isRightComp) return;
8396 
8397   SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
8398                                                    OpLoc)
8399                                      : SourceRange(OpLoc, RHSExpr->getLocEnd());
8400   std::string OpStr = isLeftComp ? BinOp::getOpcodeStr(LHSopc)
8401                                  : BinOp::getOpcodeStr(RHSopc);
8402   SourceRange ParensRange = isLeftComp ?
8403       SourceRange(cast<BinOp>(LHSExpr)->getRHS()->getLocStart(),
8404                   RHSExpr->getLocEnd())
8405     : SourceRange(LHSExpr->getLocStart(),
8406                   cast<BinOp>(RHSExpr)->getLHS()->getLocStart());
8407 
8408   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
8409     << DiagRange << BinOp::getOpcodeStr(Opc) << OpStr;
8410   SuggestParentheses(Self, OpLoc,
8411     Self.PDiag(diag::note_precedence_bitwise_silence) << OpStr,
8412     (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
8413   SuggestParentheses(Self, OpLoc,
8414     Self.PDiag(diag::note_precedence_bitwise_first) << BinOp::getOpcodeStr(Opc),
8415     ParensRange);
8416 }
8417 
8418 /// \brief It accepts a '&' expr that is inside a '|' one.
8419 /// Emit a diagnostic together with a fixit hint that wraps the '&' expression
8420 /// in parentheses.
8421 static void
8422 EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc,
8423                                        BinaryOperator *Bop) {
8424   assert(Bop->getOpcode() == BO_And);
8425   Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or)
8426       << Bop->getSourceRange() << OpLoc;
8427   SuggestParentheses(Self, Bop->getOperatorLoc(),
8428     Self.PDiag(diag::note_bitwise_and_in_bitwise_or_silence),
8429     Bop->getSourceRange());
8430 }
8431 
8432 /// \brief It accepts a '&&' expr that is inside a '||' one.
8433 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
8434 /// in parentheses.
8435 static void
8436 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
8437                                        BinaryOperator *Bop) {
8438   assert(Bop->getOpcode() == BO_LAnd);
8439   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
8440       << Bop->getSourceRange() << OpLoc;
8441   SuggestParentheses(Self, Bop->getOperatorLoc(),
8442     Self.PDiag(diag::note_logical_and_in_logical_or_silence),
8443     Bop->getSourceRange());
8444 }
8445 
8446 /// \brief Returns true if the given expression can be evaluated as a constant
8447 /// 'true'.
8448 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
8449   bool Res;
8450   return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
8451 }
8452 
8453 /// \brief Returns true if the given expression can be evaluated as a constant
8454 /// 'false'.
8455 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
8456   bool Res;
8457   return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
8458 }
8459 
8460 /// \brief Look for '&&' in the left hand of a '||' expr.
8461 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
8462                                              Expr *LHSExpr, Expr *RHSExpr) {
8463   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
8464     if (Bop->getOpcode() == BO_LAnd) {
8465       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
8466       if (EvaluatesAsFalse(S, RHSExpr))
8467         return;
8468       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
8469       if (!EvaluatesAsTrue(S, Bop->getLHS()))
8470         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
8471     } else if (Bop->getOpcode() == BO_LOr) {
8472       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
8473         // If it's "a || b && 1 || c" we didn't warn earlier for
8474         // "a || b && 1", but warn now.
8475         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
8476           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
8477       }
8478     }
8479   }
8480 }
8481 
8482 /// \brief Look for '&&' in the right hand of a '||' expr.
8483 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
8484                                              Expr *LHSExpr, Expr *RHSExpr) {
8485   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
8486     if (Bop->getOpcode() == BO_LAnd) {
8487       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
8488       if (EvaluatesAsFalse(S, LHSExpr))
8489         return;
8490       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
8491       if (!EvaluatesAsTrue(S, Bop->getRHS()))
8492         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
8493     }
8494   }
8495 }
8496 
8497 /// \brief Look for '&' in the left or right hand of a '|' expr.
8498 static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc,
8499                                              Expr *OrArg) {
8500   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) {
8501     if (Bop->getOpcode() == BO_And)
8502       return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop);
8503   }
8504 }
8505 
8506 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
8507 /// precedence.
8508 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
8509                                     SourceLocation OpLoc, Expr *LHSExpr,
8510                                     Expr *RHSExpr){
8511   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
8512   if (BinaryOperator::isBitwiseOp(Opc))
8513     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
8514 
8515   // Diagnose "arg1 & arg2 | arg3"
8516   if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) {
8517     DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr);
8518     DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr);
8519   }
8520 
8521   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
8522   // We don't warn for 'assert(a || b && "bad")' since this is safe.
8523   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
8524     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
8525     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
8526   }
8527 }
8528 
8529 // Binary Operators.  'Tok' is the token for the operator.
8530 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
8531                             tok::TokenKind Kind,
8532                             Expr *LHSExpr, Expr *RHSExpr) {
8533   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
8534   assert((LHSExpr != 0) && "ActOnBinOp(): missing left expression");
8535   assert((RHSExpr != 0) && "ActOnBinOp(): missing right expression");
8536 
8537   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
8538   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
8539 
8540   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
8541 }
8542 
8543 /// Build an overloaded binary operator expression in the given scope.
8544 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
8545                                        BinaryOperatorKind Opc,
8546                                        Expr *LHS, Expr *RHS) {
8547   // Find all of the overloaded operators visible from this
8548   // point. We perform both an operator-name lookup from the local
8549   // scope and an argument-dependent lookup based on the types of
8550   // the arguments.
8551   UnresolvedSet<16> Functions;
8552   OverloadedOperatorKind OverOp
8553     = BinaryOperator::getOverloadedOperator(Opc);
8554   if (Sc && OverOp != OO_None)
8555     S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
8556                                    RHS->getType(), Functions);
8557 
8558   // Build the (potentially-overloaded, potentially-dependent)
8559   // binary operation.
8560   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
8561 }
8562 
8563 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
8564                             BinaryOperatorKind Opc,
8565                             Expr *LHSExpr, Expr *RHSExpr) {
8566   // We want to end up calling one of checkPseudoObjectAssignment
8567   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
8568   // both expressions are overloadable or either is type-dependent),
8569   // or CreateBuiltinBinOp (in any other case).  We also want to get
8570   // any placeholder types out of the way.
8571 
8572   // Handle pseudo-objects in the LHS.
8573   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
8574     // Assignments with a pseudo-object l-value need special analysis.
8575     if (pty->getKind() == BuiltinType::PseudoObject &&
8576         BinaryOperator::isAssignmentOp(Opc))
8577       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
8578 
8579     // Don't resolve overloads if the other type is overloadable.
8580     if (pty->getKind() == BuiltinType::Overload) {
8581       // We can't actually test that if we still have a placeholder,
8582       // though.  Fortunately, none of the exceptions we see in that
8583       // code below are valid when the LHS is an overload set.  Note
8584       // that an overload set can be dependently-typed, but it never
8585       // instantiates to having an overloadable type.
8586       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
8587       if (resolvedRHS.isInvalid()) return ExprError();
8588       RHSExpr = resolvedRHS.take();
8589 
8590       if (RHSExpr->isTypeDependent() ||
8591           RHSExpr->getType()->isOverloadableType())
8592         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8593     }
8594 
8595     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
8596     if (LHS.isInvalid()) return ExprError();
8597     LHSExpr = LHS.take();
8598   }
8599 
8600   // Handle pseudo-objects in the RHS.
8601   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
8602     // An overload in the RHS can potentially be resolved by the type
8603     // being assigned to.
8604     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
8605       if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
8606         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8607 
8608       if (LHSExpr->getType()->isOverloadableType())
8609         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8610 
8611       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
8612     }
8613 
8614     // Don't resolve overloads if the other type is overloadable.
8615     if (pty->getKind() == BuiltinType::Overload &&
8616         LHSExpr->getType()->isOverloadableType())
8617       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8618 
8619     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
8620     if (!resolvedRHS.isUsable()) return ExprError();
8621     RHSExpr = resolvedRHS.take();
8622   }
8623 
8624   if (getLangOpts().CPlusPlus) {
8625     // If either expression is type-dependent, always build an
8626     // overloaded op.
8627     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
8628       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8629 
8630     // Otherwise, build an overloaded op if either expression has an
8631     // overloadable type.
8632     if (LHSExpr->getType()->isOverloadableType() ||
8633         RHSExpr->getType()->isOverloadableType())
8634       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8635   }
8636 
8637   // Build a built-in binary operation.
8638   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
8639 }
8640 
8641 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
8642                                       UnaryOperatorKind Opc,
8643                                       Expr *InputExpr) {
8644   ExprResult Input = Owned(InputExpr);
8645   ExprValueKind VK = VK_RValue;
8646   ExprObjectKind OK = OK_Ordinary;
8647   QualType resultType;
8648   switch (Opc) {
8649   case UO_PreInc:
8650   case UO_PreDec:
8651   case UO_PostInc:
8652   case UO_PostDec:
8653     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc,
8654                                                 Opc == UO_PreInc ||
8655                                                 Opc == UO_PostInc,
8656                                                 Opc == UO_PreInc ||
8657                                                 Opc == UO_PreDec);
8658     break;
8659   case UO_AddrOf:
8660     resultType = CheckAddressOfOperand(*this, Input, OpLoc);
8661     break;
8662   case UO_Deref: {
8663     Input = DefaultFunctionArrayLvalueConversion(Input.take());
8664     if (Input.isInvalid()) return ExprError();
8665     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
8666     break;
8667   }
8668   case UO_Plus:
8669   case UO_Minus:
8670     Input = UsualUnaryConversions(Input.take());
8671     if (Input.isInvalid()) return ExprError();
8672     resultType = Input.get()->getType();
8673     if (resultType->isDependentType())
8674       break;
8675     if (resultType->isArithmeticType() || // C99 6.5.3.3p1
8676         resultType->isVectorType())
8677       break;
8678     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6-7
8679              resultType->isEnumeralType())
8680       break;
8681     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
8682              Opc == UO_Plus &&
8683              resultType->isPointerType())
8684       break;
8685 
8686     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
8687       << resultType << Input.get()->getSourceRange());
8688 
8689   case UO_Not: // bitwise complement
8690     Input = UsualUnaryConversions(Input.take());
8691     if (Input.isInvalid()) return ExprError();
8692     resultType = Input.get()->getType();
8693     if (resultType->isDependentType())
8694       break;
8695     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
8696     if (resultType->isComplexType() || resultType->isComplexIntegerType())
8697       // C99 does not support '~' for complex conjugation.
8698       Diag(OpLoc, diag::ext_integer_complement_complex)
8699         << resultType << Input.get()->getSourceRange();
8700     else if (resultType->hasIntegerRepresentation())
8701       break;
8702     else {
8703       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
8704         << resultType << Input.get()->getSourceRange());
8705     }
8706     break;
8707 
8708   case UO_LNot: // logical negation
8709     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
8710     Input = DefaultFunctionArrayLvalueConversion(Input.take());
8711     if (Input.isInvalid()) return ExprError();
8712     resultType = Input.get()->getType();
8713 
8714     // Though we still have to promote half FP to float...
8715     if (resultType->isHalfType()) {
8716       Input = ImpCastExprToType(Input.take(), Context.FloatTy, CK_FloatingCast).take();
8717       resultType = Context.FloatTy;
8718     }
8719 
8720     if (resultType->isDependentType())
8721       break;
8722     if (resultType->isScalarType()) {
8723       // C99 6.5.3.3p1: ok, fallthrough;
8724       if (Context.getLangOpts().CPlusPlus) {
8725         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
8726         // operand contextually converted to bool.
8727         Input = ImpCastExprToType(Input.take(), Context.BoolTy,
8728                                   ScalarTypeToBooleanCastKind(resultType));
8729       }
8730     } else if (resultType->isExtVectorType()) {
8731       // Vector logical not returns the signed variant of the operand type.
8732       resultType = GetSignedVectorType(resultType);
8733       break;
8734     } else {
8735       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
8736         << resultType << Input.get()->getSourceRange());
8737     }
8738 
8739     // LNot always has type int. C99 6.5.3.3p5.
8740     // In C++, it's bool. C++ 5.3.1p8
8741     resultType = Context.getLogicalOperationType();
8742     break;
8743   case UO_Real:
8744   case UO_Imag:
8745     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
8746     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
8747     // complex l-values to ordinary l-values and all other values to r-values.
8748     if (Input.isInvalid()) return ExprError();
8749     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
8750       if (Input.get()->getValueKind() != VK_RValue &&
8751           Input.get()->getObjectKind() == OK_Ordinary)
8752         VK = Input.get()->getValueKind();
8753     } else if (!getLangOpts().CPlusPlus) {
8754       // In C, a volatile scalar is read by __imag. In C++, it is not.
8755       Input = DefaultLvalueConversion(Input.take());
8756     }
8757     break;
8758   case UO_Extension:
8759     resultType = Input.get()->getType();
8760     VK = Input.get()->getValueKind();
8761     OK = Input.get()->getObjectKind();
8762     break;
8763   }
8764   if (resultType.isNull() || Input.isInvalid())
8765     return ExprError();
8766 
8767   // Check for array bounds violations in the operand of the UnaryOperator,
8768   // except for the '*' and '&' operators that have to be handled specially
8769   // by CheckArrayAccess (as there are special cases like &array[arraysize]
8770   // that are explicitly defined as valid by the standard).
8771   if (Opc != UO_AddrOf && Opc != UO_Deref)
8772     CheckArrayAccess(Input.get());
8773 
8774   return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType,
8775                                            VK, OK, OpLoc));
8776 }
8777 
8778 /// \brief Determine whether the given expression is a qualified member
8779 /// access expression, of a form that could be turned into a pointer to member
8780 /// with the address-of operator.
8781 static bool isQualifiedMemberAccess(Expr *E) {
8782   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
8783     if (!DRE->getQualifier())
8784       return false;
8785 
8786     ValueDecl *VD = DRE->getDecl();
8787     if (!VD->isCXXClassMember())
8788       return false;
8789 
8790     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
8791       return true;
8792     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
8793       return Method->isInstance();
8794 
8795     return false;
8796   }
8797 
8798   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
8799     if (!ULE->getQualifier())
8800       return false;
8801 
8802     for (UnresolvedLookupExpr::decls_iterator D = ULE->decls_begin(),
8803                                            DEnd = ULE->decls_end();
8804          D != DEnd; ++D) {
8805       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*D)) {
8806         if (Method->isInstance())
8807           return true;
8808       } else {
8809         // Overload set does not contain methods.
8810         break;
8811       }
8812     }
8813 
8814     return false;
8815   }
8816 
8817   return false;
8818 }
8819 
8820 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
8821                               UnaryOperatorKind Opc, Expr *Input) {
8822   // First things first: handle placeholders so that the
8823   // overloaded-operator check considers the right type.
8824   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
8825     // Increment and decrement of pseudo-object references.
8826     if (pty->getKind() == BuiltinType::PseudoObject &&
8827         UnaryOperator::isIncrementDecrementOp(Opc))
8828       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
8829 
8830     // extension is always a builtin operator.
8831     if (Opc == UO_Extension)
8832       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
8833 
8834     // & gets special logic for several kinds of placeholder.
8835     // The builtin code knows what to do.
8836     if (Opc == UO_AddrOf &&
8837         (pty->getKind() == BuiltinType::Overload ||
8838          pty->getKind() == BuiltinType::UnknownAny ||
8839          pty->getKind() == BuiltinType::BoundMember))
8840       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
8841 
8842     // Anything else needs to be handled now.
8843     ExprResult Result = CheckPlaceholderExpr(Input);
8844     if (Result.isInvalid()) return ExprError();
8845     Input = Result.take();
8846   }
8847 
8848   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
8849       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
8850       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
8851     // Find all of the overloaded operators visible from this
8852     // point. We perform both an operator-name lookup from the local
8853     // scope and an argument-dependent lookup based on the types of
8854     // the arguments.
8855     UnresolvedSet<16> Functions;
8856     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
8857     if (S && OverOp != OO_None)
8858       LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
8859                                    Functions);
8860 
8861     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
8862   }
8863 
8864   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
8865 }
8866 
8867 // Unary Operators.  'Tok' is the token for the operator.
8868 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
8869                               tok::TokenKind Op, Expr *Input) {
8870   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
8871 }
8872 
8873 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
8874 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
8875                                 LabelDecl *TheDecl) {
8876   TheDecl->setUsed();
8877   // Create the AST node.  The address of a label always has type 'void*'.
8878   return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
8879                                        Context.getPointerType(Context.VoidTy)));
8880 }
8881 
8882 /// Given the last statement in a statement-expression, check whether
8883 /// the result is a producing expression (like a call to an
8884 /// ns_returns_retained function) and, if so, rebuild it to hoist the
8885 /// release out of the full-expression.  Otherwise, return null.
8886 /// Cannot fail.
8887 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
8888   // Should always be wrapped with one of these.
8889   ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
8890   if (!cleanups) return 0;
8891 
8892   ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
8893   if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
8894     return 0;
8895 
8896   // Splice out the cast.  This shouldn't modify any interesting
8897   // features of the statement.
8898   Expr *producer = cast->getSubExpr();
8899   assert(producer->getType() == cast->getType());
8900   assert(producer->getValueKind() == cast->getValueKind());
8901   cleanups->setSubExpr(producer);
8902   return cleanups;
8903 }
8904 
8905 void Sema::ActOnStartStmtExpr() {
8906   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
8907 }
8908 
8909 void Sema::ActOnStmtExprError() {
8910   // Note that function is also called by TreeTransform when leaving a
8911   // StmtExpr scope without rebuilding anything.
8912 
8913   DiscardCleanupsInEvaluationContext();
8914   PopExpressionEvaluationContext();
8915 }
8916 
8917 ExprResult
8918 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
8919                     SourceLocation RPLoc) { // "({..})"
8920   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
8921   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
8922 
8923   if (hasAnyUnrecoverableErrorsInThisFunction())
8924     DiscardCleanupsInEvaluationContext();
8925   assert(!ExprNeedsCleanups && "cleanups within StmtExpr not correctly bound!");
8926   PopExpressionEvaluationContext();
8927 
8928   bool isFileScope
8929     = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
8930   if (isFileScope)
8931     return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
8932 
8933   // FIXME: there are a variety of strange constraints to enforce here, for
8934   // example, it is not possible to goto into a stmt expression apparently.
8935   // More semantic analysis is needed.
8936 
8937   // If there are sub stmts in the compound stmt, take the type of the last one
8938   // as the type of the stmtexpr.
8939   QualType Ty = Context.VoidTy;
8940   bool StmtExprMayBindToTemp = false;
8941   if (!Compound->body_empty()) {
8942     Stmt *LastStmt = Compound->body_back();
8943     LabelStmt *LastLabelStmt = 0;
8944     // If LastStmt is a label, skip down through into the body.
8945     while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
8946       LastLabelStmt = Label;
8947       LastStmt = Label->getSubStmt();
8948     }
8949 
8950     if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
8951       // Do function/array conversion on the last expression, but not
8952       // lvalue-to-rvalue.  However, initialize an unqualified type.
8953       ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
8954       if (LastExpr.isInvalid())
8955         return ExprError();
8956       Ty = LastExpr.get()->getType().getUnqualifiedType();
8957 
8958       if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
8959         // In ARC, if the final expression ends in a consume, splice
8960         // the consume out and bind it later.  In the alternate case
8961         // (when dealing with a retainable type), the result
8962         // initialization will create a produce.  In both cases the
8963         // result will be +1, and we'll need to balance that out with
8964         // a bind.
8965         if (Expr *rebuiltLastStmt
8966               = maybeRebuildARCConsumingStmt(LastExpr.get())) {
8967           LastExpr = rebuiltLastStmt;
8968         } else {
8969           LastExpr = PerformCopyInitialization(
8970                             InitializedEntity::InitializeResult(LPLoc,
8971                                                                 Ty,
8972                                                                 false),
8973                                                    SourceLocation(),
8974                                                LastExpr);
8975         }
8976 
8977         if (LastExpr.isInvalid())
8978           return ExprError();
8979         if (LastExpr.get() != 0) {
8980           if (!LastLabelStmt)
8981             Compound->setLastStmt(LastExpr.take());
8982           else
8983             LastLabelStmt->setSubStmt(LastExpr.take());
8984           StmtExprMayBindToTemp = true;
8985         }
8986       }
8987     }
8988   }
8989 
8990   // FIXME: Check that expression type is complete/non-abstract; statement
8991   // expressions are not lvalues.
8992   Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
8993   if (StmtExprMayBindToTemp)
8994     return MaybeBindToTemporary(ResStmtExpr);
8995   return Owned(ResStmtExpr);
8996 }
8997 
8998 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
8999                                       TypeSourceInfo *TInfo,
9000                                       OffsetOfComponent *CompPtr,
9001                                       unsigned NumComponents,
9002                                       SourceLocation RParenLoc) {
9003   QualType ArgTy = TInfo->getType();
9004   bool Dependent = ArgTy->isDependentType();
9005   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
9006 
9007   // We must have at least one component that refers to the type, and the first
9008   // one is known to be a field designator.  Verify that the ArgTy represents
9009   // a struct/union/class.
9010   if (!Dependent && !ArgTy->isRecordType())
9011     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
9012                        << ArgTy << TypeRange);
9013 
9014   // Type must be complete per C99 7.17p3 because a declaring a variable
9015   // with an incomplete type would be ill-formed.
9016   if (!Dependent
9017       && RequireCompleteType(BuiltinLoc, ArgTy,
9018                              diag::err_offsetof_incomplete_type, TypeRange))
9019     return ExprError();
9020 
9021   // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
9022   // GCC extension, diagnose them.
9023   // FIXME: This diagnostic isn't actually visible because the location is in
9024   // a system header!
9025   if (NumComponents != 1)
9026     Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
9027       << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
9028 
9029   bool DidWarnAboutNonPOD = false;
9030   QualType CurrentType = ArgTy;
9031   typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
9032   SmallVector<OffsetOfNode, 4> Comps;
9033   SmallVector<Expr*, 4> Exprs;
9034   for (unsigned i = 0; i != NumComponents; ++i) {
9035     const OffsetOfComponent &OC = CompPtr[i];
9036     if (OC.isBrackets) {
9037       // Offset of an array sub-field.  TODO: Should we allow vector elements?
9038       if (!CurrentType->isDependentType()) {
9039         const ArrayType *AT = Context.getAsArrayType(CurrentType);
9040         if(!AT)
9041           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
9042                            << CurrentType);
9043         CurrentType = AT->getElementType();
9044       } else
9045         CurrentType = Context.DependentTy;
9046 
9047       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
9048       if (IdxRval.isInvalid())
9049         return ExprError();
9050       Expr *Idx = IdxRval.take();
9051 
9052       // The expression must be an integral expression.
9053       // FIXME: An integral constant expression?
9054       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
9055           !Idx->getType()->isIntegerType())
9056         return ExprError(Diag(Idx->getLocStart(),
9057                               diag::err_typecheck_subscript_not_integer)
9058                          << Idx->getSourceRange());
9059 
9060       // Record this array index.
9061       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
9062       Exprs.push_back(Idx);
9063       continue;
9064     }
9065 
9066     // Offset of a field.
9067     if (CurrentType->isDependentType()) {
9068       // We have the offset of a field, but we can't look into the dependent
9069       // type. Just record the identifier of the field.
9070       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
9071       CurrentType = Context.DependentTy;
9072       continue;
9073     }
9074 
9075     // We need to have a complete type to look into.
9076     if (RequireCompleteType(OC.LocStart, CurrentType,
9077                             diag::err_offsetof_incomplete_type))
9078       return ExprError();
9079 
9080     // Look for the designated field.
9081     const RecordType *RC = CurrentType->getAs<RecordType>();
9082     if (!RC)
9083       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
9084                        << CurrentType);
9085     RecordDecl *RD = RC->getDecl();
9086 
9087     // C++ [lib.support.types]p5:
9088     //   The macro offsetof accepts a restricted set of type arguments in this
9089     //   International Standard. type shall be a POD structure or a POD union
9090     //   (clause 9).
9091     // C++11 [support.types]p4:
9092     //   If type is not a standard-layout class (Clause 9), the results are
9093     //   undefined.
9094     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
9095       bool IsSafe = LangOpts.CPlusPlus0x? CRD->isStandardLayout() : CRD->isPOD();
9096       unsigned DiagID =
9097         LangOpts.CPlusPlus0x? diag::warn_offsetof_non_standardlayout_type
9098                             : diag::warn_offsetof_non_pod_type;
9099 
9100       if (!IsSafe && !DidWarnAboutNonPOD &&
9101           DiagRuntimeBehavior(BuiltinLoc, 0,
9102                               PDiag(DiagID)
9103                               << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
9104                               << CurrentType))
9105         DidWarnAboutNonPOD = true;
9106     }
9107 
9108     // Look for the field.
9109     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
9110     LookupQualifiedName(R, RD);
9111     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
9112     IndirectFieldDecl *IndirectMemberDecl = 0;
9113     if (!MemberDecl) {
9114       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
9115         MemberDecl = IndirectMemberDecl->getAnonField();
9116     }
9117 
9118     if (!MemberDecl)
9119       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
9120                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
9121                                                               OC.LocEnd));
9122 
9123     // C99 7.17p3:
9124     //   (If the specified member is a bit-field, the behavior is undefined.)
9125     //
9126     // We diagnose this as an error.
9127     if (MemberDecl->isBitField()) {
9128       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
9129         << MemberDecl->getDeclName()
9130         << SourceRange(BuiltinLoc, RParenLoc);
9131       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
9132       return ExprError();
9133     }
9134 
9135     RecordDecl *Parent = MemberDecl->getParent();
9136     if (IndirectMemberDecl)
9137       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
9138 
9139     // If the member was found in a base class, introduce OffsetOfNodes for
9140     // the base class indirections.
9141     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
9142                        /*DetectVirtual=*/false);
9143     if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
9144       CXXBasePath &Path = Paths.front();
9145       for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
9146            B != BEnd; ++B)
9147         Comps.push_back(OffsetOfNode(B->Base));
9148     }
9149 
9150     if (IndirectMemberDecl) {
9151       for (IndirectFieldDecl::chain_iterator FI =
9152            IndirectMemberDecl->chain_begin(),
9153            FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
9154         assert(isa<FieldDecl>(*FI));
9155         Comps.push_back(OffsetOfNode(OC.LocStart,
9156                                      cast<FieldDecl>(*FI), OC.LocEnd));
9157       }
9158     } else
9159       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
9160 
9161     CurrentType = MemberDecl->getType().getNonReferenceType();
9162   }
9163 
9164   return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
9165                                     TInfo, Comps, Exprs, RParenLoc));
9166 }
9167 
9168 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
9169                                       SourceLocation BuiltinLoc,
9170                                       SourceLocation TypeLoc,
9171                                       ParsedType ParsedArgTy,
9172                                       OffsetOfComponent *CompPtr,
9173                                       unsigned NumComponents,
9174                                       SourceLocation RParenLoc) {
9175 
9176   TypeSourceInfo *ArgTInfo;
9177   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
9178   if (ArgTy.isNull())
9179     return ExprError();
9180 
9181   if (!ArgTInfo)
9182     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
9183 
9184   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
9185                               RParenLoc);
9186 }
9187 
9188 
9189 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
9190                                  Expr *CondExpr,
9191                                  Expr *LHSExpr, Expr *RHSExpr,
9192                                  SourceLocation RPLoc) {
9193   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
9194 
9195   ExprValueKind VK = VK_RValue;
9196   ExprObjectKind OK = OK_Ordinary;
9197   QualType resType;
9198   bool ValueDependent = false;
9199   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
9200     resType = Context.DependentTy;
9201     ValueDependent = true;
9202   } else {
9203     // The conditional expression is required to be a constant expression.
9204     llvm::APSInt condEval(32);
9205     ExprResult CondICE
9206       = VerifyIntegerConstantExpression(CondExpr, &condEval,
9207           diag::err_typecheck_choose_expr_requires_constant, false);
9208     if (CondICE.isInvalid())
9209       return ExprError();
9210     CondExpr = CondICE.take();
9211 
9212     // If the condition is > zero, then the AST type is the same as the LSHExpr.
9213     Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
9214 
9215     resType = ActiveExpr->getType();
9216     ValueDependent = ActiveExpr->isValueDependent();
9217     VK = ActiveExpr->getValueKind();
9218     OK = ActiveExpr->getObjectKind();
9219   }
9220 
9221   return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
9222                                         resType, VK, OK, RPLoc,
9223                                         resType->isDependentType(),
9224                                         ValueDependent));
9225 }
9226 
9227 //===----------------------------------------------------------------------===//
9228 // Clang Extensions.
9229 //===----------------------------------------------------------------------===//
9230 
9231 /// ActOnBlockStart - This callback is invoked when a block literal is started.
9232 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
9233   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
9234   PushBlockScope(CurScope, Block);
9235   CurContext->addDecl(Block);
9236   if (CurScope)
9237     PushDeclContext(CurScope, Block);
9238   else
9239     CurContext = Block;
9240 
9241   getCurBlock()->HasImplicitReturnType = true;
9242 
9243   // Enter a new evaluation context to insulate the block from any
9244   // cleanups from the enclosing full-expression.
9245   PushExpressionEvaluationContext(PotentiallyEvaluated);
9246 }
9247 
9248 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
9249                                Scope *CurScope) {
9250   assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
9251   assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
9252   BlockScopeInfo *CurBlock = getCurBlock();
9253 
9254   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
9255   QualType T = Sig->getType();
9256 
9257   // FIXME: We should allow unexpanded parameter packs here, but that would,
9258   // in turn, make the block expression contain unexpanded parameter packs.
9259   if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
9260     // Drop the parameters.
9261     FunctionProtoType::ExtProtoInfo EPI;
9262     EPI.HasTrailingReturn = false;
9263     EPI.TypeQuals |= DeclSpec::TQ_const;
9264     T = Context.getFunctionType(Context.DependentTy, /*Args=*/0, /*NumArgs=*/0,
9265                                 EPI);
9266     Sig = Context.getTrivialTypeSourceInfo(T);
9267   }
9268 
9269   // GetTypeForDeclarator always produces a function type for a block
9270   // literal signature.  Furthermore, it is always a FunctionProtoType
9271   // unless the function was written with a typedef.
9272   assert(T->isFunctionType() &&
9273          "GetTypeForDeclarator made a non-function block signature");
9274 
9275   // Look for an explicit signature in that function type.
9276   FunctionProtoTypeLoc ExplicitSignature;
9277 
9278   TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
9279   if (isa<FunctionProtoTypeLoc>(tmp)) {
9280     ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp);
9281 
9282     // Check whether that explicit signature was synthesized by
9283     // GetTypeForDeclarator.  If so, don't save that as part of the
9284     // written signature.
9285     if (ExplicitSignature.getLocalRangeBegin() ==
9286         ExplicitSignature.getLocalRangeEnd()) {
9287       // This would be much cheaper if we stored TypeLocs instead of
9288       // TypeSourceInfos.
9289       TypeLoc Result = ExplicitSignature.getResultLoc();
9290       unsigned Size = Result.getFullDataSize();
9291       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
9292       Sig->getTypeLoc().initializeFullCopy(Result, Size);
9293 
9294       ExplicitSignature = FunctionProtoTypeLoc();
9295     }
9296   }
9297 
9298   CurBlock->TheDecl->setSignatureAsWritten(Sig);
9299   CurBlock->FunctionType = T;
9300 
9301   const FunctionType *Fn = T->getAs<FunctionType>();
9302   QualType RetTy = Fn->getResultType();
9303   bool isVariadic =
9304     (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
9305 
9306   CurBlock->TheDecl->setIsVariadic(isVariadic);
9307 
9308   // Don't allow returning a objc interface by value.
9309   if (RetTy->isObjCObjectType()) {
9310     Diag(ParamInfo.getLocStart(),
9311          diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
9312     return;
9313   }
9314 
9315   // Context.DependentTy is used as a placeholder for a missing block
9316   // return type.  TODO:  what should we do with declarators like:
9317   //   ^ * { ... }
9318   // If the answer is "apply template argument deduction"....
9319   if (RetTy != Context.DependentTy) {
9320     CurBlock->ReturnType = RetTy;
9321     CurBlock->TheDecl->setBlockMissingReturnType(false);
9322     CurBlock->HasImplicitReturnType = false;
9323   }
9324 
9325   // Push block parameters from the declarator if we had them.
9326   SmallVector<ParmVarDecl*, 8> Params;
9327   if (ExplicitSignature) {
9328     for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
9329       ParmVarDecl *Param = ExplicitSignature.getArg(I);
9330       if (Param->getIdentifier() == 0 &&
9331           !Param->isImplicit() &&
9332           !Param->isInvalidDecl() &&
9333           !getLangOpts().CPlusPlus)
9334         Diag(Param->getLocation(), diag::err_parameter_name_omitted);
9335       Params.push_back(Param);
9336     }
9337 
9338   // Fake up parameter variables if we have a typedef, like
9339   //   ^ fntype { ... }
9340   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
9341     for (FunctionProtoType::arg_type_iterator
9342            I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
9343       ParmVarDecl *Param =
9344         BuildParmVarDeclForTypedef(CurBlock->TheDecl,
9345                                    ParamInfo.getLocStart(),
9346                                    *I);
9347       Params.push_back(Param);
9348     }
9349   }
9350 
9351   // Set the parameters on the block decl.
9352   if (!Params.empty()) {
9353     CurBlock->TheDecl->setParams(Params);
9354     CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
9355                              CurBlock->TheDecl->param_end(),
9356                              /*CheckParameterNames=*/false);
9357   }
9358 
9359   // Finally we can process decl attributes.
9360   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
9361 
9362   // Put the parameter variables in scope.  We can bail out immediately
9363   // if we don't have any.
9364   if (Params.empty())
9365     return;
9366 
9367   for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
9368          E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
9369     (*AI)->setOwningFunction(CurBlock->TheDecl);
9370 
9371     // If this has an identifier, add it to the scope stack.
9372     if ((*AI)->getIdentifier()) {
9373       CheckShadow(CurBlock->TheScope, *AI);
9374 
9375       PushOnScopeChains(*AI, CurBlock->TheScope);
9376     }
9377   }
9378 }
9379 
9380 /// ActOnBlockError - If there is an error parsing a block, this callback
9381 /// is invoked to pop the information about the block from the action impl.
9382 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
9383   // Leave the expression-evaluation context.
9384   DiscardCleanupsInEvaluationContext();
9385   PopExpressionEvaluationContext();
9386 
9387   // Pop off CurBlock, handle nested blocks.
9388   PopDeclContext();
9389   PopFunctionScopeInfo();
9390 }
9391 
9392 /// ActOnBlockStmtExpr - This is called when the body of a block statement
9393 /// literal was successfully completed.  ^(int x){...}
9394 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
9395                                     Stmt *Body, Scope *CurScope) {
9396   // If blocks are disabled, emit an error.
9397   if (!LangOpts.Blocks)
9398     Diag(CaretLoc, diag::err_blocks_disable);
9399 
9400   // Leave the expression-evaluation context.
9401   if (hasAnyUnrecoverableErrorsInThisFunction())
9402     DiscardCleanupsInEvaluationContext();
9403   assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!");
9404   PopExpressionEvaluationContext();
9405 
9406   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
9407 
9408   if (BSI->HasImplicitReturnType)
9409     deduceClosureReturnType(*BSI);
9410 
9411   PopDeclContext();
9412 
9413   QualType RetTy = Context.VoidTy;
9414   if (!BSI->ReturnType.isNull())
9415     RetTy = BSI->ReturnType;
9416 
9417   bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
9418   QualType BlockTy;
9419 
9420   // Set the captured variables on the block.
9421   // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
9422   SmallVector<BlockDecl::Capture, 4> Captures;
9423   for (unsigned i = 0, e = BSI->Captures.size(); i != e; i++) {
9424     CapturingScopeInfo::Capture &Cap = BSI->Captures[i];
9425     if (Cap.isThisCapture())
9426       continue;
9427     BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
9428                               Cap.isNested(), Cap.getCopyExpr());
9429     Captures.push_back(NewCap);
9430   }
9431   BSI->TheDecl->setCaptures(Context, Captures.begin(), Captures.end(),
9432                             BSI->CXXThisCaptureIndex != 0);
9433 
9434   // If the user wrote a function type in some form, try to use that.
9435   if (!BSI->FunctionType.isNull()) {
9436     const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
9437 
9438     FunctionType::ExtInfo Ext = FTy->getExtInfo();
9439     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
9440 
9441     // Turn protoless block types into nullary block types.
9442     if (isa<FunctionNoProtoType>(FTy)) {
9443       FunctionProtoType::ExtProtoInfo EPI;
9444       EPI.ExtInfo = Ext;
9445       BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
9446 
9447     // Otherwise, if we don't need to change anything about the function type,
9448     // preserve its sugar structure.
9449     } else if (FTy->getResultType() == RetTy &&
9450                (!NoReturn || FTy->getNoReturnAttr())) {
9451       BlockTy = BSI->FunctionType;
9452 
9453     // Otherwise, make the minimal modifications to the function type.
9454     } else {
9455       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
9456       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9457       EPI.TypeQuals = 0; // FIXME: silently?
9458       EPI.ExtInfo = Ext;
9459       BlockTy = Context.getFunctionType(RetTy,
9460                                         FPT->arg_type_begin(),
9461                                         FPT->getNumArgs(),
9462                                         EPI);
9463     }
9464 
9465   // If we don't have a function type, just build one from nothing.
9466   } else {
9467     FunctionProtoType::ExtProtoInfo EPI;
9468     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
9469     BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
9470   }
9471 
9472   DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
9473                            BSI->TheDecl->param_end());
9474   BlockTy = Context.getBlockPointerType(BlockTy);
9475 
9476   // If needed, diagnose invalid gotos and switches in the block.
9477   if (getCurFunction()->NeedsScopeChecking() &&
9478       !hasAnyUnrecoverableErrorsInThisFunction() &&
9479       !PP.isCodeCompletionEnabled())
9480     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
9481 
9482   BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
9483 
9484   // Try to apply the named return value optimization. We have to check again
9485   // if we can do this, though, because blocks keep return statements around
9486   // to deduce an implicit return type.
9487   if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
9488       !BSI->TheDecl->isDependentContext())
9489     computeNRVO(Body, getCurBlock());
9490 
9491   BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
9492   const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy();
9493   PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
9494 
9495   // If the block isn't obviously global, i.e. it captures anything at
9496   // all, then we need to do a few things in the surrounding context:
9497   if (Result->getBlockDecl()->hasCaptures()) {
9498     // First, this expression has a new cleanup object.
9499     ExprCleanupObjects.push_back(Result->getBlockDecl());
9500     ExprNeedsCleanups = true;
9501 
9502     // It also gets a branch-protected scope if any of the captured
9503     // variables needs destruction.
9504     for (BlockDecl::capture_const_iterator
9505            ci = Result->getBlockDecl()->capture_begin(),
9506            ce = Result->getBlockDecl()->capture_end(); ci != ce; ++ci) {
9507       const VarDecl *var = ci->getVariable();
9508       if (var->getType().isDestructedType() != QualType::DK_none) {
9509         getCurFunction()->setHasBranchProtectedScope();
9510         break;
9511       }
9512     }
9513   }
9514 
9515   return Owned(Result);
9516 }
9517 
9518 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
9519                                         Expr *E, ParsedType Ty,
9520                                         SourceLocation RPLoc) {
9521   TypeSourceInfo *TInfo;
9522   GetTypeFromParser(Ty, &TInfo);
9523   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
9524 }
9525 
9526 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
9527                                 Expr *E, TypeSourceInfo *TInfo,
9528                                 SourceLocation RPLoc) {
9529   Expr *OrigExpr = E;
9530 
9531   // Get the va_list type
9532   QualType VaListType = Context.getBuiltinVaListType();
9533   if (VaListType->isArrayType()) {
9534     // Deal with implicit array decay; for example, on x86-64,
9535     // va_list is an array, but it's supposed to decay to
9536     // a pointer for va_arg.
9537     VaListType = Context.getArrayDecayedType(VaListType);
9538     // Make sure the input expression also decays appropriately.
9539     ExprResult Result = UsualUnaryConversions(E);
9540     if (Result.isInvalid())
9541       return ExprError();
9542     E = Result.take();
9543   } else {
9544     // Otherwise, the va_list argument must be an l-value because
9545     // it is modified by va_arg.
9546     if (!E->isTypeDependent() &&
9547         CheckForModifiableLvalue(E, BuiltinLoc, *this))
9548       return ExprError();
9549   }
9550 
9551   if (!E->isTypeDependent() &&
9552       !Context.hasSameType(VaListType, E->getType())) {
9553     return ExprError(Diag(E->getLocStart(),
9554                          diag::err_first_argument_to_va_arg_not_of_type_va_list)
9555       << OrigExpr->getType() << E->getSourceRange());
9556   }
9557 
9558   if (!TInfo->getType()->isDependentType()) {
9559     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
9560                             diag::err_second_parameter_to_va_arg_incomplete,
9561                             TInfo->getTypeLoc()))
9562       return ExprError();
9563 
9564     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
9565                                TInfo->getType(),
9566                                diag::err_second_parameter_to_va_arg_abstract,
9567                                TInfo->getTypeLoc()))
9568       return ExprError();
9569 
9570     if (!TInfo->getType().isPODType(Context)) {
9571       Diag(TInfo->getTypeLoc().getBeginLoc(),
9572            TInfo->getType()->isObjCLifetimeType()
9573              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
9574              : diag::warn_second_parameter_to_va_arg_not_pod)
9575         << TInfo->getType()
9576         << TInfo->getTypeLoc().getSourceRange();
9577     }
9578 
9579     // Check for va_arg where arguments of the given type will be promoted
9580     // (i.e. this va_arg is guaranteed to have undefined behavior).
9581     QualType PromoteType;
9582     if (TInfo->getType()->isPromotableIntegerType()) {
9583       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
9584       if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
9585         PromoteType = QualType();
9586     }
9587     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
9588       PromoteType = Context.DoubleTy;
9589     if (!PromoteType.isNull())
9590       Diag(TInfo->getTypeLoc().getBeginLoc(),
9591           diag::warn_second_parameter_to_va_arg_never_compatible)
9592         << TInfo->getType()
9593         << PromoteType
9594         << TInfo->getTypeLoc().getSourceRange();
9595   }
9596 
9597   QualType T = TInfo->getType().getNonLValueExprType(Context);
9598   return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
9599 }
9600 
9601 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
9602   // The type of __null will be int or long, depending on the size of
9603   // pointers on the target.
9604   QualType Ty;
9605   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
9606   if (pw == Context.getTargetInfo().getIntWidth())
9607     Ty = Context.IntTy;
9608   else if (pw == Context.getTargetInfo().getLongWidth())
9609     Ty = Context.LongTy;
9610   else if (pw == Context.getTargetInfo().getLongLongWidth())
9611     Ty = Context.LongLongTy;
9612   else {
9613     llvm_unreachable("I don't know size of pointer!");
9614   }
9615 
9616   return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
9617 }
9618 
9619 static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
9620                                            Expr *SrcExpr, FixItHint &Hint) {
9621   if (!SemaRef.getLangOpts().ObjC1)
9622     return;
9623 
9624   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
9625   if (!PT)
9626     return;
9627 
9628   // Check if the destination is of type 'id'.
9629   if (!PT->isObjCIdType()) {
9630     // Check if the destination is the 'NSString' interface.
9631     const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
9632     if (!ID || !ID->getIdentifier()->isStr("NSString"))
9633       return;
9634   }
9635 
9636   // Ignore any parens, implicit casts (should only be
9637   // array-to-pointer decays), and not-so-opaque values.  The last is
9638   // important for making this trigger for property assignments.
9639   SrcExpr = SrcExpr->IgnoreParenImpCasts();
9640   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
9641     if (OV->getSourceExpr())
9642       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
9643 
9644   StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
9645   if (!SL || !SL->isAscii())
9646     return;
9647 
9648   Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
9649 }
9650 
9651 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
9652                                     SourceLocation Loc,
9653                                     QualType DstType, QualType SrcType,
9654                                     Expr *SrcExpr, AssignmentAction Action,
9655                                     bool *Complained) {
9656   if (Complained)
9657     *Complained = false;
9658 
9659   // Decode the result (notice that AST's are still created for extensions).
9660   bool CheckInferredResultType = false;
9661   bool isInvalid = false;
9662   unsigned DiagKind = 0;
9663   FixItHint Hint;
9664   ConversionFixItGenerator ConvHints;
9665   bool MayHaveConvFixit = false;
9666   bool MayHaveFunctionDiff = false;
9667 
9668   switch (ConvTy) {
9669   case Compatible:
9670       DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
9671       return false;
9672 
9673   case PointerToInt:
9674     DiagKind = diag::ext_typecheck_convert_pointer_int;
9675     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9676     MayHaveConvFixit = true;
9677     break;
9678   case IntToPointer:
9679     DiagKind = diag::ext_typecheck_convert_int_pointer;
9680     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9681     MayHaveConvFixit = true;
9682     break;
9683   case IncompatiblePointer:
9684     MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
9685     DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
9686     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
9687       SrcType->isObjCObjectPointerType();
9688     if (Hint.isNull() && !CheckInferredResultType) {
9689       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9690     }
9691     MayHaveConvFixit = true;
9692     break;
9693   case IncompatiblePointerSign:
9694     DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
9695     break;
9696   case FunctionVoidPointer:
9697     DiagKind = diag::ext_typecheck_convert_pointer_void_func;
9698     break;
9699   case IncompatiblePointerDiscardsQualifiers: {
9700     // Perform array-to-pointer decay if necessary.
9701     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
9702 
9703     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
9704     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
9705     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
9706       DiagKind = diag::err_typecheck_incompatible_address_space;
9707       break;
9708 
9709 
9710     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
9711       DiagKind = diag::err_typecheck_incompatible_ownership;
9712       break;
9713     }
9714 
9715     llvm_unreachable("unknown error case for discarding qualifiers!");
9716     // fallthrough
9717   }
9718   case CompatiblePointerDiscardsQualifiers:
9719     // If the qualifiers lost were because we were applying the
9720     // (deprecated) C++ conversion from a string literal to a char*
9721     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
9722     // Ideally, this check would be performed in
9723     // checkPointerTypesForAssignment. However, that would require a
9724     // bit of refactoring (so that the second argument is an
9725     // expression, rather than a type), which should be done as part
9726     // of a larger effort to fix checkPointerTypesForAssignment for
9727     // C++ semantics.
9728     if (getLangOpts().CPlusPlus &&
9729         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
9730       return false;
9731     DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
9732     break;
9733   case IncompatibleNestedPointerQualifiers:
9734     DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
9735     break;
9736   case IntToBlockPointer:
9737     DiagKind = diag::err_int_to_block_pointer;
9738     break;
9739   case IncompatibleBlockPointer:
9740     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
9741     break;
9742   case IncompatibleObjCQualifiedId:
9743     // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
9744     // it can give a more specific diagnostic.
9745     DiagKind = diag::warn_incompatible_qualified_id;
9746     break;
9747   case IncompatibleVectors:
9748     DiagKind = diag::warn_incompatible_vectors;
9749     break;
9750   case IncompatibleObjCWeakRef:
9751     DiagKind = diag::err_arc_weak_unavailable_assign;
9752     break;
9753   case Incompatible:
9754     DiagKind = diag::err_typecheck_convert_incompatible;
9755     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9756     MayHaveConvFixit = true;
9757     isInvalid = true;
9758     MayHaveFunctionDiff = true;
9759     break;
9760   }
9761 
9762   QualType FirstType, SecondType;
9763   switch (Action) {
9764   case AA_Assigning:
9765   case AA_Initializing:
9766     // The destination type comes first.
9767     FirstType = DstType;
9768     SecondType = SrcType;
9769     break;
9770 
9771   case AA_Returning:
9772   case AA_Passing:
9773   case AA_Converting:
9774   case AA_Sending:
9775   case AA_Casting:
9776     // The source type comes first.
9777     FirstType = SrcType;
9778     SecondType = DstType;
9779     break;
9780   }
9781 
9782   PartialDiagnostic FDiag = PDiag(DiagKind);
9783   FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
9784 
9785   // If we can fix the conversion, suggest the FixIts.
9786   assert(ConvHints.isNull() || Hint.isNull());
9787   if (!ConvHints.isNull()) {
9788     for (std::vector<FixItHint>::iterator HI = ConvHints.Hints.begin(),
9789          HE = ConvHints.Hints.end(); HI != HE; ++HI)
9790       FDiag << *HI;
9791   } else {
9792     FDiag << Hint;
9793   }
9794   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
9795 
9796   if (MayHaveFunctionDiff)
9797     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
9798 
9799   Diag(Loc, FDiag);
9800 
9801   if (SecondType == Context.OverloadTy)
9802     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
9803                               FirstType);
9804 
9805   if (CheckInferredResultType)
9806     EmitRelatedResultTypeNote(SrcExpr);
9807 
9808   if (Complained)
9809     *Complained = true;
9810   return isInvalid;
9811 }
9812 
9813 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
9814                                                  llvm::APSInt *Result) {
9815   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
9816   public:
9817     virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
9818       S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
9819     }
9820   } Diagnoser;
9821 
9822   return VerifyIntegerConstantExpression(E, Result, Diagnoser);
9823 }
9824 
9825 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
9826                                                  llvm::APSInt *Result,
9827                                                  unsigned DiagID,
9828                                                  bool AllowFold) {
9829   class IDDiagnoser : public VerifyICEDiagnoser {
9830     unsigned DiagID;
9831 
9832   public:
9833     IDDiagnoser(unsigned DiagID)
9834       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
9835 
9836     virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
9837       S.Diag(Loc, DiagID) << SR;
9838     }
9839   } Diagnoser(DiagID);
9840 
9841   return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
9842 }
9843 
9844 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
9845                                             SourceRange SR) {
9846   S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
9847 }
9848 
9849 ExprResult
9850 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
9851                                       VerifyICEDiagnoser &Diagnoser,
9852                                       bool AllowFold) {
9853   SourceLocation DiagLoc = E->getLocStart();
9854 
9855   if (getLangOpts().CPlusPlus0x) {
9856     // C++11 [expr.const]p5:
9857     //   If an expression of literal class type is used in a context where an
9858     //   integral constant expression is required, then that class type shall
9859     //   have a single non-explicit conversion function to an integral or
9860     //   unscoped enumeration type
9861     ExprResult Converted;
9862     if (!Diagnoser.Suppress) {
9863       class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
9864       public:
9865         CXX11ConvertDiagnoser() : ICEConvertDiagnoser(false, true) { }
9866 
9867         virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
9868                                                  QualType T) {
9869           return S.Diag(Loc, diag::err_ice_not_integral) << T;
9870         }
9871 
9872         virtual DiagnosticBuilder diagnoseIncomplete(Sema &S,
9873                                                      SourceLocation Loc,
9874                                                      QualType T) {
9875           return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
9876         }
9877 
9878         virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S,
9879                                                        SourceLocation Loc,
9880                                                        QualType T,
9881                                                        QualType ConvTy) {
9882           return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
9883         }
9884 
9885         virtual DiagnosticBuilder noteExplicitConv(Sema &S,
9886                                                    CXXConversionDecl *Conv,
9887                                                    QualType ConvTy) {
9888           return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
9889                    << ConvTy->isEnumeralType() << ConvTy;
9890         }
9891 
9892         virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
9893                                                     QualType T) {
9894           return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
9895         }
9896 
9897         virtual DiagnosticBuilder noteAmbiguous(Sema &S,
9898                                                 CXXConversionDecl *Conv,
9899                                                 QualType ConvTy) {
9900           return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
9901                    << ConvTy->isEnumeralType() << ConvTy;
9902         }
9903 
9904         virtual DiagnosticBuilder diagnoseConversion(Sema &S,
9905                                                      SourceLocation Loc,
9906                                                      QualType T,
9907                                                      QualType ConvTy) {
9908           return DiagnosticBuilder::getEmpty();
9909         }
9910       } ConvertDiagnoser;
9911 
9912       Converted = ConvertToIntegralOrEnumerationType(DiagLoc, E,
9913                                                      ConvertDiagnoser,
9914                                              /*AllowScopedEnumerations*/ false);
9915     } else {
9916       // The caller wants to silently enquire whether this is an ICE. Don't
9917       // produce any diagnostics if it isn't.
9918       class SilentICEConvertDiagnoser : public ICEConvertDiagnoser {
9919       public:
9920         SilentICEConvertDiagnoser() : ICEConvertDiagnoser(true, true) { }
9921 
9922         virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
9923                                                  QualType T) {
9924           return DiagnosticBuilder::getEmpty();
9925         }
9926 
9927         virtual DiagnosticBuilder diagnoseIncomplete(Sema &S,
9928                                                      SourceLocation Loc,
9929                                                      QualType T) {
9930           return DiagnosticBuilder::getEmpty();
9931         }
9932 
9933         virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S,
9934                                                        SourceLocation Loc,
9935                                                        QualType T,
9936                                                        QualType ConvTy) {
9937           return DiagnosticBuilder::getEmpty();
9938         }
9939 
9940         virtual DiagnosticBuilder noteExplicitConv(Sema &S,
9941                                                    CXXConversionDecl *Conv,
9942                                                    QualType ConvTy) {
9943           return DiagnosticBuilder::getEmpty();
9944         }
9945 
9946         virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
9947                                                     QualType T) {
9948           return DiagnosticBuilder::getEmpty();
9949         }
9950 
9951         virtual DiagnosticBuilder noteAmbiguous(Sema &S,
9952                                                 CXXConversionDecl *Conv,
9953                                                 QualType ConvTy) {
9954           return DiagnosticBuilder::getEmpty();
9955         }
9956 
9957         virtual DiagnosticBuilder diagnoseConversion(Sema &S,
9958                                                      SourceLocation Loc,
9959                                                      QualType T,
9960                                                      QualType ConvTy) {
9961           return DiagnosticBuilder::getEmpty();
9962         }
9963       } ConvertDiagnoser;
9964 
9965       Converted = ConvertToIntegralOrEnumerationType(DiagLoc, E,
9966                                                      ConvertDiagnoser, false);
9967     }
9968     if (Converted.isInvalid())
9969       return Converted;
9970     E = Converted.take();
9971     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
9972       return ExprError();
9973   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
9974     // An ICE must be of integral or unscoped enumeration type.
9975     if (!Diagnoser.Suppress)
9976       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
9977     return ExprError();
9978   }
9979 
9980   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
9981   // in the non-ICE case.
9982   if (!getLangOpts().CPlusPlus0x && E->isIntegerConstantExpr(Context)) {
9983     if (Result)
9984       *Result = E->EvaluateKnownConstInt(Context);
9985     return Owned(E);
9986   }
9987 
9988   Expr::EvalResult EvalResult;
9989   llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
9990   EvalResult.Diag = &Notes;
9991 
9992   // Try to evaluate the expression, and produce diagnostics explaining why it's
9993   // not a constant expression as a side-effect.
9994   bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
9995                 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
9996 
9997   // In C++11, we can rely on diagnostics being produced for any expression
9998   // which is not a constant expression. If no diagnostics were produced, then
9999   // this is a constant expression.
10000   if (Folded && getLangOpts().CPlusPlus0x && Notes.empty()) {
10001     if (Result)
10002       *Result = EvalResult.Val.getInt();
10003     return Owned(E);
10004   }
10005 
10006   // If our only note is the usual "invalid subexpression" note, just point
10007   // the caret at its location rather than producing an essentially
10008   // redundant note.
10009   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
10010         diag::note_invalid_subexpr_in_const_expr) {
10011     DiagLoc = Notes[0].first;
10012     Notes.clear();
10013   }
10014 
10015   if (!Folded || !AllowFold) {
10016     if (!Diagnoser.Suppress) {
10017       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
10018       for (unsigned I = 0, N = Notes.size(); I != N; ++I)
10019         Diag(Notes[I].first, Notes[I].second);
10020     }
10021 
10022     return ExprError();
10023   }
10024 
10025   Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
10026   for (unsigned I = 0, N = Notes.size(); I != N; ++I)
10027     Diag(Notes[I].first, Notes[I].second);
10028 
10029   if (Result)
10030     *Result = EvalResult.Val.getInt();
10031   return Owned(E);
10032 }
10033 
10034 namespace {
10035   // Handle the case where we conclude a expression which we speculatively
10036   // considered to be unevaluated is actually evaluated.
10037   class TransformToPE : public TreeTransform<TransformToPE> {
10038     typedef TreeTransform<TransformToPE> BaseTransform;
10039 
10040   public:
10041     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
10042 
10043     // Make sure we redo semantic analysis
10044     bool AlwaysRebuild() { return true; }
10045 
10046     // Make sure we handle LabelStmts correctly.
10047     // FIXME: This does the right thing, but maybe we need a more general
10048     // fix to TreeTransform?
10049     StmtResult TransformLabelStmt(LabelStmt *S) {
10050       S->getDecl()->setStmt(0);
10051       return BaseTransform::TransformLabelStmt(S);
10052     }
10053 
10054     // We need to special-case DeclRefExprs referring to FieldDecls which
10055     // are not part of a member pointer formation; normal TreeTransforming
10056     // doesn't catch this case because of the way we represent them in the AST.
10057     // FIXME: This is a bit ugly; is it really the best way to handle this
10058     // case?
10059     //
10060     // Error on DeclRefExprs referring to FieldDecls.
10061     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
10062       if (isa<FieldDecl>(E->getDecl()) &&
10063           !SemaRef.isUnevaluatedContext())
10064         return SemaRef.Diag(E->getLocation(),
10065                             diag::err_invalid_non_static_member_use)
10066             << E->getDecl() << E->getSourceRange();
10067 
10068       return BaseTransform::TransformDeclRefExpr(E);
10069     }
10070 
10071     // Exception: filter out member pointer formation
10072     ExprResult TransformUnaryOperator(UnaryOperator *E) {
10073       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
10074         return E;
10075 
10076       return BaseTransform::TransformUnaryOperator(E);
10077     }
10078 
10079     ExprResult TransformLambdaExpr(LambdaExpr *E) {
10080       // Lambdas never need to be transformed.
10081       return E;
10082     }
10083   };
10084 }
10085 
10086 ExprResult Sema::TranformToPotentiallyEvaluated(Expr *E) {
10087   assert(ExprEvalContexts.back().Context == Unevaluated &&
10088          "Should only transform unevaluated expressions");
10089   ExprEvalContexts.back().Context =
10090       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
10091   if (ExprEvalContexts.back().Context == Unevaluated)
10092     return E;
10093   return TransformToPE(*this).TransformExpr(E);
10094 }
10095 
10096 void
10097 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
10098                                       Decl *LambdaContextDecl,
10099                                       bool IsDecltype) {
10100   ExprEvalContexts.push_back(
10101              ExpressionEvaluationContextRecord(NewContext,
10102                                                ExprCleanupObjects.size(),
10103                                                ExprNeedsCleanups,
10104                                                LambdaContextDecl,
10105                                                IsDecltype));
10106   ExprNeedsCleanups = false;
10107   if (!MaybeODRUseExprs.empty())
10108     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
10109 }
10110 
10111 void Sema::PopExpressionEvaluationContext() {
10112   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
10113 
10114   if (!Rec.Lambdas.empty()) {
10115     if (Rec.Context == Unevaluated) {
10116       // C++11 [expr.prim.lambda]p2:
10117       //   A lambda-expression shall not appear in an unevaluated operand
10118       //   (Clause 5).
10119       for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I)
10120         Diag(Rec.Lambdas[I]->getLocStart(),
10121              diag::err_lambda_unevaluated_operand);
10122     } else {
10123       // Mark the capture expressions odr-used. This was deferred
10124       // during lambda expression creation.
10125       for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I) {
10126         LambdaExpr *Lambda = Rec.Lambdas[I];
10127         for (LambdaExpr::capture_init_iterator
10128                   C = Lambda->capture_init_begin(),
10129                CEnd = Lambda->capture_init_end();
10130              C != CEnd; ++C) {
10131           MarkDeclarationsReferencedInExpr(*C);
10132         }
10133       }
10134     }
10135   }
10136 
10137   // When are coming out of an unevaluated context, clear out any
10138   // temporaries that we may have created as part of the evaluation of
10139   // the expression in that context: they aren't relevant because they
10140   // will never be constructed.
10141   if (Rec.Context == Unevaluated || Rec.Context == ConstantEvaluated) {
10142     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
10143                              ExprCleanupObjects.end());
10144     ExprNeedsCleanups = Rec.ParentNeedsCleanups;
10145     CleanupVarDeclMarking();
10146     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
10147   // Otherwise, merge the contexts together.
10148   } else {
10149     ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
10150     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
10151                             Rec.SavedMaybeODRUseExprs.end());
10152   }
10153 
10154   // Pop the current expression evaluation context off the stack.
10155   ExprEvalContexts.pop_back();
10156 }
10157 
10158 void Sema::DiscardCleanupsInEvaluationContext() {
10159   ExprCleanupObjects.erase(
10160          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
10161          ExprCleanupObjects.end());
10162   ExprNeedsCleanups = false;
10163   MaybeODRUseExprs.clear();
10164 }
10165 
10166 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
10167   if (!E->getType()->isVariablyModifiedType())
10168     return E;
10169   return TranformToPotentiallyEvaluated(E);
10170 }
10171 
10172 static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) {
10173   // Do not mark anything as "used" within a dependent context; wait for
10174   // an instantiation.
10175   if (SemaRef.CurContext->isDependentContext())
10176     return false;
10177 
10178   switch (SemaRef.ExprEvalContexts.back().Context) {
10179     case Sema::Unevaluated:
10180       // We are in an expression that is not potentially evaluated; do nothing.
10181       // (Depending on how you read the standard, we actually do need to do
10182       // something here for null pointer constants, but the standard's
10183       // definition of a null pointer constant is completely crazy.)
10184       return false;
10185 
10186     case Sema::ConstantEvaluated:
10187     case Sema::PotentiallyEvaluated:
10188       // We are in a potentially evaluated expression (or a constant-expression
10189       // in C++03); we need to do implicit template instantiation, implicitly
10190       // define class members, and mark most declarations as used.
10191       return true;
10192 
10193     case Sema::PotentiallyEvaluatedIfUsed:
10194       // Referenced declarations will only be used if the construct in the
10195       // containing expression is used.
10196       return false;
10197   }
10198   llvm_unreachable("Invalid context");
10199 }
10200 
10201 /// \brief Mark a function referenced, and check whether it is odr-used
10202 /// (C++ [basic.def.odr]p2, C99 6.9p3)
10203 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func) {
10204   assert(Func && "No function?");
10205 
10206   Func->setReferenced();
10207 
10208   // Don't mark this function as used multiple times, unless it's a constexpr
10209   // function which we need to instantiate.
10210   if (Func->isUsed(false) &&
10211       !(Func->isConstexpr() && !Func->getBody() &&
10212         Func->isImplicitlyInstantiable()))
10213     return;
10214 
10215   if (!IsPotentiallyEvaluatedContext(*this))
10216     return;
10217 
10218   // Note that this declaration has been used.
10219   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
10220     if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
10221       if (Constructor->isDefaultConstructor()) {
10222         if (Constructor->isTrivial())
10223           return;
10224         if (!Constructor->isUsed(false))
10225           DefineImplicitDefaultConstructor(Loc, Constructor);
10226       } else if (Constructor->isCopyConstructor()) {
10227         if (!Constructor->isUsed(false))
10228           DefineImplicitCopyConstructor(Loc, Constructor);
10229       } else if (Constructor->isMoveConstructor()) {
10230         if (!Constructor->isUsed(false))
10231           DefineImplicitMoveConstructor(Loc, Constructor);
10232       }
10233     }
10234 
10235     MarkVTableUsed(Loc, Constructor->getParent());
10236   } else if (CXXDestructorDecl *Destructor =
10237                  dyn_cast<CXXDestructorDecl>(Func)) {
10238     if (Destructor->isDefaulted() && !Destructor->isDeleted() &&
10239         !Destructor->isUsed(false))
10240       DefineImplicitDestructor(Loc, Destructor);
10241     if (Destructor->isVirtual())
10242       MarkVTableUsed(Loc, Destructor->getParent());
10243   } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
10244     if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted() &&
10245         MethodDecl->isOverloadedOperator() &&
10246         MethodDecl->getOverloadedOperator() == OO_Equal) {
10247       if (!MethodDecl->isUsed(false)) {
10248         if (MethodDecl->isCopyAssignmentOperator())
10249           DefineImplicitCopyAssignment(Loc, MethodDecl);
10250         else
10251           DefineImplicitMoveAssignment(Loc, MethodDecl);
10252       }
10253     } else if (isa<CXXConversionDecl>(MethodDecl) &&
10254                MethodDecl->getParent()->isLambda()) {
10255       CXXConversionDecl *Conversion = cast<CXXConversionDecl>(MethodDecl);
10256       if (Conversion->isLambdaToBlockPointerConversion())
10257         DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
10258       else
10259         DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
10260     } else if (MethodDecl->isVirtual())
10261       MarkVTableUsed(Loc, MethodDecl->getParent());
10262   }
10263 
10264   // Recursive functions should be marked when used from another function.
10265   // FIXME: Is this really right?
10266   if (CurContext == Func) return;
10267 
10268   // Resolve the exception specification for any function which is
10269   // used: CodeGen will need it.
10270   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
10271   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
10272     ResolveExceptionSpec(Loc, FPT);
10273 
10274   // Implicit instantiation of function templates and member functions of
10275   // class templates.
10276   if (Func->isImplicitlyInstantiable()) {
10277     bool AlreadyInstantiated = false;
10278     SourceLocation PointOfInstantiation = Loc;
10279     if (FunctionTemplateSpecializationInfo *SpecInfo
10280                               = Func->getTemplateSpecializationInfo()) {
10281       if (SpecInfo->getPointOfInstantiation().isInvalid())
10282         SpecInfo->setPointOfInstantiation(Loc);
10283       else if (SpecInfo->getTemplateSpecializationKind()
10284                  == TSK_ImplicitInstantiation) {
10285         AlreadyInstantiated = true;
10286         PointOfInstantiation = SpecInfo->getPointOfInstantiation();
10287       }
10288     } else if (MemberSpecializationInfo *MSInfo
10289                                 = Func->getMemberSpecializationInfo()) {
10290       if (MSInfo->getPointOfInstantiation().isInvalid())
10291         MSInfo->setPointOfInstantiation(Loc);
10292       else if (MSInfo->getTemplateSpecializationKind()
10293                  == TSK_ImplicitInstantiation) {
10294         AlreadyInstantiated = true;
10295         PointOfInstantiation = MSInfo->getPointOfInstantiation();
10296       }
10297     }
10298 
10299     if (!AlreadyInstantiated || Func->isConstexpr()) {
10300       if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
10301           cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass())
10302         PendingLocalImplicitInstantiations.push_back(
10303             std::make_pair(Func, PointOfInstantiation));
10304       else if (Func->isConstexpr())
10305         // Do not defer instantiations of constexpr functions, to avoid the
10306         // expression evaluator needing to call back into Sema if it sees a
10307         // call to such a function.
10308         InstantiateFunctionDefinition(PointOfInstantiation, Func);
10309       else {
10310         PendingInstantiations.push_back(std::make_pair(Func,
10311                                                        PointOfInstantiation));
10312         // Notify the consumer that a function was implicitly instantiated.
10313         Consumer.HandleCXXImplicitFunctionInstantiation(Func);
10314       }
10315     }
10316   } else {
10317     // Walk redefinitions, as some of them may be instantiable.
10318     for (FunctionDecl::redecl_iterator i(Func->redecls_begin()),
10319          e(Func->redecls_end()); i != e; ++i) {
10320       if (!i->isUsed(false) && i->isImplicitlyInstantiable())
10321         MarkFunctionReferenced(Loc, *i);
10322     }
10323   }
10324 
10325   // Keep track of used but undefined functions.
10326   if (!Func->isPure() && !Func->hasBody() &&
10327       Func->getLinkage() != ExternalLinkage) {
10328     SourceLocation &old = UndefinedInternals[Func->getCanonicalDecl()];
10329     if (old.isInvalid()) old = Loc;
10330   }
10331 
10332   Func->setUsed(true);
10333 }
10334 
10335 static void
10336 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
10337                                    VarDecl *var, DeclContext *DC) {
10338   DeclContext *VarDC = var->getDeclContext();
10339 
10340   //  If the parameter still belongs to the translation unit, then
10341   //  we're actually just using one parameter in the declaration of
10342   //  the next.
10343   if (isa<ParmVarDecl>(var) &&
10344       isa<TranslationUnitDecl>(VarDC))
10345     return;
10346 
10347   // For C code, don't diagnose about capture if we're not actually in code
10348   // right now; it's impossible to write a non-constant expression outside of
10349   // function context, so we'll get other (more useful) diagnostics later.
10350   //
10351   // For C++, things get a bit more nasty... it would be nice to suppress this
10352   // diagnostic for certain cases like using a local variable in an array bound
10353   // for a member of a local class, but the correct predicate is not obvious.
10354   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
10355     return;
10356 
10357   if (isa<CXXMethodDecl>(VarDC) &&
10358       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
10359     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda)
10360       << var->getIdentifier();
10361   } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) {
10362     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
10363       << var->getIdentifier() << fn->getDeclName();
10364   } else if (isa<BlockDecl>(VarDC)) {
10365     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block)
10366       << var->getIdentifier();
10367   } else {
10368     // FIXME: Is there any other context where a local variable can be
10369     // declared?
10370     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context)
10371       << var->getIdentifier();
10372   }
10373 
10374   S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
10375     << var->getIdentifier();
10376 
10377   // FIXME: Add additional diagnostic info about class etc. which prevents
10378   // capture.
10379 }
10380 
10381 /// \brief Capture the given variable in the given lambda expression.
10382 static ExprResult captureInLambda(Sema &S, LambdaScopeInfo *LSI,
10383                                   VarDecl *Var, QualType FieldType,
10384                                   QualType DeclRefType,
10385                                   SourceLocation Loc,
10386                                   bool RefersToEnclosingLocal) {
10387   CXXRecordDecl *Lambda = LSI->Lambda;
10388 
10389   // Build the non-static data member.
10390   FieldDecl *Field
10391     = FieldDecl::Create(S.Context, Lambda, Loc, Loc, 0, FieldType,
10392                         S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
10393                         0, false, ICIS_NoInit);
10394   Field->setImplicit(true);
10395   Field->setAccess(AS_private);
10396   Lambda->addDecl(Field);
10397 
10398   // C++11 [expr.prim.lambda]p21:
10399   //   When the lambda-expression is evaluated, the entities that
10400   //   are captured by copy are used to direct-initialize each
10401   //   corresponding non-static data member of the resulting closure
10402   //   object. (For array members, the array elements are
10403   //   direct-initialized in increasing subscript order.) These
10404   //   initializations are performed in the (unspecified) order in
10405   //   which the non-static data members are declared.
10406 
10407   // Introduce a new evaluation context for the initialization, so
10408   // that temporaries introduced as part of the capture are retained
10409   // to be re-"exported" from the lambda expression itself.
10410   S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
10411 
10412   // C++ [expr.prim.labda]p12:
10413   //   An entity captured by a lambda-expression is odr-used (3.2) in
10414   //   the scope containing the lambda-expression.
10415   Expr *Ref = new (S.Context) DeclRefExpr(Var, RefersToEnclosingLocal,
10416                                           DeclRefType, VK_LValue, Loc);
10417   Var->setReferenced(true);
10418   Var->setUsed(true);
10419 
10420   // When the field has array type, create index variables for each
10421   // dimension of the array. We use these index variables to subscript
10422   // the source array, and other clients (e.g., CodeGen) will perform
10423   // the necessary iteration with these index variables.
10424   SmallVector<VarDecl *, 4> IndexVariables;
10425   QualType BaseType = FieldType;
10426   QualType SizeType = S.Context.getSizeType();
10427   LSI->ArrayIndexStarts.push_back(LSI->ArrayIndexVars.size());
10428   while (const ConstantArrayType *Array
10429                         = S.Context.getAsConstantArrayType(BaseType)) {
10430     // Create the iteration variable for this array index.
10431     IdentifierInfo *IterationVarName = 0;
10432     {
10433       SmallString<8> Str;
10434       llvm::raw_svector_ostream OS(Str);
10435       OS << "__i" << IndexVariables.size();
10436       IterationVarName = &S.Context.Idents.get(OS.str());
10437     }
10438     VarDecl *IterationVar
10439       = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
10440                         IterationVarName, SizeType,
10441                         S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
10442                         SC_None, SC_None);
10443     IndexVariables.push_back(IterationVar);
10444     LSI->ArrayIndexVars.push_back(IterationVar);
10445 
10446     // Create a reference to the iteration variable.
10447     ExprResult IterationVarRef
10448       = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
10449     assert(!IterationVarRef.isInvalid() &&
10450            "Reference to invented variable cannot fail!");
10451     IterationVarRef = S.DefaultLvalueConversion(IterationVarRef.take());
10452     assert(!IterationVarRef.isInvalid() &&
10453            "Conversion of invented variable cannot fail!");
10454 
10455     // Subscript the array with this iteration variable.
10456     ExprResult Subscript = S.CreateBuiltinArraySubscriptExpr(
10457                              Ref, Loc, IterationVarRef.take(), Loc);
10458     if (Subscript.isInvalid()) {
10459       S.CleanupVarDeclMarking();
10460       S.DiscardCleanupsInEvaluationContext();
10461       S.PopExpressionEvaluationContext();
10462       return ExprError();
10463     }
10464 
10465     Ref = Subscript.take();
10466     BaseType = Array->getElementType();
10467   }
10468 
10469   // Construct the entity that we will be initializing. For an array, this
10470   // will be first element in the array, which may require several levels
10471   // of array-subscript entities.
10472   SmallVector<InitializedEntity, 4> Entities;
10473   Entities.reserve(1 + IndexVariables.size());
10474   Entities.push_back(
10475     InitializedEntity::InitializeLambdaCapture(Var, Field, Loc));
10476   for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
10477     Entities.push_back(InitializedEntity::InitializeElement(S.Context,
10478                                                             0,
10479                                                             Entities.back()));
10480 
10481   InitializationKind InitKind
10482     = InitializationKind::CreateDirect(Loc, Loc, Loc);
10483   InitializationSequence Init(S, Entities.back(), InitKind, &Ref, 1);
10484   ExprResult Result(true);
10485   if (!Init.Diagnose(S, Entities.back(), InitKind, &Ref, 1))
10486     Result = Init.Perform(S, Entities.back(), InitKind, Ref);
10487 
10488   // If this initialization requires any cleanups (e.g., due to a
10489   // default argument to a copy constructor), note that for the
10490   // lambda.
10491   if (S.ExprNeedsCleanups)
10492     LSI->ExprNeedsCleanups = true;
10493 
10494   // Exit the expression evaluation context used for the capture.
10495   S.CleanupVarDeclMarking();
10496   S.DiscardCleanupsInEvaluationContext();
10497   S.PopExpressionEvaluationContext();
10498   return Result;
10499 }
10500 
10501 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
10502                               TryCaptureKind Kind, SourceLocation EllipsisLoc,
10503                               bool BuildAndDiagnose,
10504                               QualType &CaptureType,
10505                               QualType &DeclRefType) {
10506   bool Nested = false;
10507 
10508   DeclContext *DC = CurContext;
10509   if (Var->getDeclContext() == DC) return true;
10510   if (!Var->hasLocalStorage()) return true;
10511 
10512   bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
10513 
10514   // Walk up the stack to determine whether we can capture the variable,
10515   // performing the "simple" checks that don't depend on type. We stop when
10516   // we've either hit the declared scope of the variable or find an existing
10517   // capture of that variable.
10518   CaptureType = Var->getType();
10519   DeclRefType = CaptureType.getNonReferenceType();
10520   bool Explicit = (Kind != TryCapture_Implicit);
10521   unsigned FunctionScopesIndex = FunctionScopes.size() - 1;
10522   do {
10523     // Only block literals and lambda expressions can capture; other
10524     // scopes don't work.
10525     DeclContext *ParentDC;
10526     if (isa<BlockDecl>(DC))
10527       ParentDC = DC->getParent();
10528     else if (isa<CXXMethodDecl>(DC) &&
10529              cast<CXXMethodDecl>(DC)->getOverloadedOperator() == OO_Call &&
10530              cast<CXXRecordDecl>(DC->getParent())->isLambda())
10531       ParentDC = DC->getParent()->getParent();
10532     else {
10533       if (BuildAndDiagnose)
10534         diagnoseUncapturableValueReference(*this, Loc, Var, DC);
10535       return true;
10536     }
10537 
10538     CapturingScopeInfo *CSI =
10539       cast<CapturingScopeInfo>(FunctionScopes[FunctionScopesIndex]);
10540 
10541     // Check whether we've already captured it.
10542     if (CSI->CaptureMap.count(Var)) {
10543       // If we found a capture, any subcaptures are nested.
10544       Nested = true;
10545 
10546       // Retrieve the capture type for this variable.
10547       CaptureType = CSI->getCapture(Var).getCaptureType();
10548 
10549       // Compute the type of an expression that refers to this variable.
10550       DeclRefType = CaptureType.getNonReferenceType();
10551 
10552       const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var);
10553       if (Cap.isCopyCapture() &&
10554           !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable))
10555         DeclRefType.addConst();
10556       break;
10557     }
10558 
10559     bool IsBlock = isa<BlockScopeInfo>(CSI);
10560     bool IsLambda = !IsBlock;
10561 
10562     // Lambdas are not allowed to capture unnamed variables
10563     // (e.g. anonymous unions).
10564     // FIXME: The C++11 rule don't actually state this explicitly, but I'm
10565     // assuming that's the intent.
10566     if (IsLambda && !Var->getDeclName()) {
10567       if (BuildAndDiagnose) {
10568         Diag(Loc, diag::err_lambda_capture_anonymous_var);
10569         Diag(Var->getLocation(), diag::note_declared_at);
10570       }
10571       return true;
10572     }
10573 
10574     // Prohibit variably-modified types; they're difficult to deal with.
10575     if (Var->getType()->isVariablyModifiedType()) {
10576       if (BuildAndDiagnose) {
10577         if (IsBlock)
10578           Diag(Loc, diag::err_ref_vm_type);
10579         else
10580           Diag(Loc, diag::err_lambda_capture_vm_type) << Var->getDeclName();
10581         Diag(Var->getLocation(), diag::note_previous_decl)
10582           << Var->getDeclName();
10583       }
10584       return true;
10585     }
10586 
10587     // Lambdas are not allowed to capture __block variables; they don't
10588     // support the expected semantics.
10589     if (IsLambda && HasBlocksAttr) {
10590       if (BuildAndDiagnose) {
10591         Diag(Loc, diag::err_lambda_capture_block)
10592           << Var->getDeclName();
10593         Diag(Var->getLocation(), diag::note_previous_decl)
10594           << Var->getDeclName();
10595       }
10596       return true;
10597     }
10598 
10599     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
10600       // No capture-default
10601       if (BuildAndDiagnose) {
10602         Diag(Loc, diag::err_lambda_impcap) << Var->getDeclName();
10603         Diag(Var->getLocation(), diag::note_previous_decl)
10604           << Var->getDeclName();
10605         Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
10606              diag::note_lambda_decl);
10607       }
10608       return true;
10609     }
10610 
10611     FunctionScopesIndex--;
10612     DC = ParentDC;
10613     Explicit = false;
10614   } while (!Var->getDeclContext()->Equals(DC));
10615 
10616   // Walk back down the scope stack, computing the type of the capture at
10617   // each step, checking type-specific requirements, and adding captures if
10618   // requested.
10619   for (unsigned I = ++FunctionScopesIndex, N = FunctionScopes.size(); I != N;
10620        ++I) {
10621     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
10622 
10623     // Compute the type of the capture and of a reference to the capture within
10624     // this scope.
10625     if (isa<BlockScopeInfo>(CSI)) {
10626       Expr *CopyExpr = 0;
10627       bool ByRef = false;
10628 
10629       // Blocks are not allowed to capture arrays.
10630       if (CaptureType->isArrayType()) {
10631         if (BuildAndDiagnose) {
10632           Diag(Loc, diag::err_ref_array_type);
10633           Diag(Var->getLocation(), diag::note_previous_decl)
10634           << Var->getDeclName();
10635         }
10636         return true;
10637       }
10638 
10639       // Forbid the block-capture of autoreleasing variables.
10640       if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
10641         if (BuildAndDiagnose) {
10642           Diag(Loc, diag::err_arc_autoreleasing_capture)
10643             << /*block*/ 0;
10644           Diag(Var->getLocation(), diag::note_previous_decl)
10645             << Var->getDeclName();
10646         }
10647         return true;
10648       }
10649 
10650       if (HasBlocksAttr || CaptureType->isReferenceType()) {
10651         // Block capture by reference does not change the capture or
10652         // declaration reference types.
10653         ByRef = true;
10654       } else {
10655         // Block capture by copy introduces 'const'.
10656         CaptureType = CaptureType.getNonReferenceType().withConst();
10657         DeclRefType = CaptureType;
10658 
10659         if (getLangOpts().CPlusPlus && BuildAndDiagnose) {
10660           if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
10661             // The capture logic needs the destructor, so make sure we mark it.
10662             // Usually this is unnecessary because most local variables have
10663             // their destructors marked at declaration time, but parameters are
10664             // an exception because it's technically only the call site that
10665             // actually requires the destructor.
10666             if (isa<ParmVarDecl>(Var))
10667               FinalizeVarWithDestructor(Var, Record);
10668 
10669             // According to the blocks spec, the capture of a variable from
10670             // the stack requires a const copy constructor.  This is not true
10671             // of the copy/move done to move a __block variable to the heap.
10672             Expr *DeclRef = new (Context) DeclRefExpr(Var, false,
10673                                                       DeclRefType.withConst(),
10674                                                       VK_LValue, Loc);
10675             ExprResult Result
10676               = PerformCopyInitialization(
10677                   InitializedEntity::InitializeBlock(Var->getLocation(),
10678                                                      CaptureType, false),
10679                   Loc, Owned(DeclRef));
10680 
10681             // Build a full-expression copy expression if initialization
10682             // succeeded and used a non-trivial constructor.  Recover from
10683             // errors by pretending that the copy isn't necessary.
10684             if (!Result.isInvalid() &&
10685                 !cast<CXXConstructExpr>(Result.get())->getConstructor()
10686                    ->isTrivial()) {
10687               Result = MaybeCreateExprWithCleanups(Result);
10688               CopyExpr = Result.take();
10689             }
10690           }
10691         }
10692       }
10693 
10694       // Actually capture the variable.
10695       if (BuildAndDiagnose)
10696         CSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
10697                         SourceLocation(), CaptureType, CopyExpr);
10698       Nested = true;
10699       continue;
10700     }
10701 
10702     LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
10703 
10704     // Determine whether we are capturing by reference or by value.
10705     bool ByRef = false;
10706     if (I == N - 1 && Kind != TryCapture_Implicit) {
10707       ByRef = (Kind == TryCapture_ExplicitByRef);
10708     } else {
10709       ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
10710     }
10711 
10712     // Compute the type of the field that will capture this variable.
10713     if (ByRef) {
10714       // C++11 [expr.prim.lambda]p15:
10715       //   An entity is captured by reference if it is implicitly or
10716       //   explicitly captured but not captured by copy. It is
10717       //   unspecified whether additional unnamed non-static data
10718       //   members are declared in the closure type for entities
10719       //   captured by reference.
10720       //
10721       // FIXME: It is not clear whether we want to build an lvalue reference
10722       // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
10723       // to do the former, while EDG does the latter. Core issue 1249 will
10724       // clarify, but for now we follow GCC because it's a more permissive and
10725       // easily defensible position.
10726       CaptureType = Context.getLValueReferenceType(DeclRefType);
10727     } else {
10728       // C++11 [expr.prim.lambda]p14:
10729       //   For each entity captured by copy, an unnamed non-static
10730       //   data member is declared in the closure type. The
10731       //   declaration order of these members is unspecified. The type
10732       //   of such a data member is the type of the corresponding
10733       //   captured entity if the entity is not a reference to an
10734       //   object, or the referenced type otherwise. [Note: If the
10735       //   captured entity is a reference to a function, the
10736       //   corresponding data member is also a reference to a
10737       //   function. - end note ]
10738       if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
10739         if (!RefType->getPointeeType()->isFunctionType())
10740           CaptureType = RefType->getPointeeType();
10741       }
10742 
10743       // Forbid the lambda copy-capture of autoreleasing variables.
10744       if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
10745         if (BuildAndDiagnose) {
10746           Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
10747           Diag(Var->getLocation(), diag::note_previous_decl)
10748             << Var->getDeclName();
10749         }
10750         return true;
10751       }
10752     }
10753 
10754     // Capture this variable in the lambda.
10755     Expr *CopyExpr = 0;
10756     if (BuildAndDiagnose) {
10757       ExprResult Result = captureInLambda(*this, LSI, Var, CaptureType,
10758                                           DeclRefType, Loc,
10759                                           I == N-1);
10760       if (!Result.isInvalid())
10761         CopyExpr = Result.take();
10762     }
10763 
10764     // Compute the type of a reference to this captured variable.
10765     if (ByRef)
10766       DeclRefType = CaptureType.getNonReferenceType();
10767     else {
10768       // C++ [expr.prim.lambda]p5:
10769       //   The closure type for a lambda-expression has a public inline
10770       //   function call operator [...]. This function call operator is
10771       //   declared const (9.3.1) if and only if the lambda-expression’s
10772       //   parameter-declaration-clause is not followed by mutable.
10773       DeclRefType = CaptureType.getNonReferenceType();
10774       if (!LSI->Mutable && !CaptureType->isReferenceType())
10775         DeclRefType.addConst();
10776     }
10777 
10778     // Add the capture.
10779     if (BuildAndDiagnose)
10780       CSI->addCapture(Var, /*IsBlock=*/false, ByRef, Nested, Loc,
10781                       EllipsisLoc, CaptureType, CopyExpr);
10782     Nested = true;
10783   }
10784 
10785   return false;
10786 }
10787 
10788 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
10789                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {
10790   QualType CaptureType;
10791   QualType DeclRefType;
10792   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
10793                             /*BuildAndDiagnose=*/true, CaptureType,
10794                             DeclRefType);
10795 }
10796 
10797 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
10798   QualType CaptureType;
10799   QualType DeclRefType;
10800 
10801   // Determine whether we can capture this variable.
10802   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
10803                          /*BuildAndDiagnose=*/false, CaptureType, DeclRefType))
10804     return QualType();
10805 
10806   return DeclRefType;
10807 }
10808 
10809 static void MarkVarDeclODRUsed(Sema &SemaRef, VarDecl *Var,
10810                                SourceLocation Loc) {
10811   // Keep track of used but undefined variables.
10812   // FIXME: We shouldn't suppress this warning for static data members.
10813   if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
10814       Var->getLinkage() != ExternalLinkage &&
10815       !(Var->isStaticDataMember() && Var->hasInit())) {
10816     SourceLocation &old = SemaRef.UndefinedInternals[Var->getCanonicalDecl()];
10817     if (old.isInvalid()) old = Loc;
10818   }
10819 
10820   SemaRef.tryCaptureVariable(Var, Loc);
10821 
10822   Var->setUsed(true);
10823 }
10824 
10825 void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
10826   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
10827   // an object that satisfies the requirements for appearing in a
10828   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
10829   // is immediately applied."  This function handles the lvalue-to-rvalue
10830   // conversion part.
10831   MaybeODRUseExprs.erase(E->IgnoreParens());
10832 }
10833 
10834 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
10835   if (!Res.isUsable())
10836     return Res;
10837 
10838   // If a constant-expression is a reference to a variable where we delay
10839   // deciding whether it is an odr-use, just assume we will apply the
10840   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
10841   // (a non-type template argument), we have special handling anyway.
10842   UpdateMarkingForLValueToRValue(Res.get());
10843   return Res;
10844 }
10845 
10846 void Sema::CleanupVarDeclMarking() {
10847   for (llvm::SmallPtrSetIterator<Expr*> i = MaybeODRUseExprs.begin(),
10848                                         e = MaybeODRUseExprs.end();
10849        i != e; ++i) {
10850     VarDecl *Var;
10851     SourceLocation Loc;
10852     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(*i)) {
10853       Var = cast<VarDecl>(DRE->getDecl());
10854       Loc = DRE->getLocation();
10855     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(*i)) {
10856       Var = cast<VarDecl>(ME->getMemberDecl());
10857       Loc = ME->getMemberLoc();
10858     } else {
10859       llvm_unreachable("Unexpcted expression");
10860     }
10861 
10862     MarkVarDeclODRUsed(*this, Var, Loc);
10863   }
10864 
10865   MaybeODRUseExprs.clear();
10866 }
10867 
10868 // Mark a VarDecl referenced, and perform the necessary handling to compute
10869 // odr-uses.
10870 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
10871                                     VarDecl *Var, Expr *E) {
10872   Var->setReferenced();
10873 
10874   if (!IsPotentiallyEvaluatedContext(SemaRef))
10875     return;
10876 
10877   // Implicit instantiation of static data members of class templates.
10878   if (Var->isStaticDataMember() && Var->getInstantiatedFromStaticDataMember()) {
10879     MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
10880     assert(MSInfo && "Missing member specialization information?");
10881     bool AlreadyInstantiated = !MSInfo->getPointOfInstantiation().isInvalid();
10882     if (MSInfo->getTemplateSpecializationKind() == TSK_ImplicitInstantiation &&
10883         (!AlreadyInstantiated ||
10884          Var->isUsableInConstantExpressions(SemaRef.Context))) {
10885       if (!AlreadyInstantiated) {
10886         // This is a modification of an existing AST node. Notify listeners.
10887         if (ASTMutationListener *L = SemaRef.getASTMutationListener())
10888           L->StaticDataMemberInstantiated(Var);
10889         MSInfo->setPointOfInstantiation(Loc);
10890       }
10891       SourceLocation PointOfInstantiation = MSInfo->getPointOfInstantiation();
10892       if (Var->isUsableInConstantExpressions(SemaRef.Context))
10893         // Do not defer instantiations of variables which could be used in a
10894         // constant expression.
10895         SemaRef.InstantiateStaticDataMemberDefinition(PointOfInstantiation,Var);
10896       else
10897         SemaRef.PendingInstantiations.push_back(
10898             std::make_pair(Var, PointOfInstantiation));
10899     }
10900   }
10901 
10902   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
10903   // an object that satisfies the requirements for appearing in a
10904   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
10905   // is immediately applied."  We check the first part here, and
10906   // Sema::UpdateMarkingForLValueToRValue deals with the second part.
10907   // Note that we use the C++11 definition everywhere because nothing in
10908   // C++03 depends on whether we get the C++03 version correct. This does not
10909   // apply to references, since they are not objects.
10910   const VarDecl *DefVD;
10911   if (E && !isa<ParmVarDecl>(Var) && !Var->getType()->isReferenceType() &&
10912       Var->isUsableInConstantExpressions(SemaRef.Context) &&
10913       Var->getAnyInitializer(DefVD) && DefVD->checkInitIsICE())
10914     SemaRef.MaybeODRUseExprs.insert(E);
10915   else
10916     MarkVarDeclODRUsed(SemaRef, Var, Loc);
10917 }
10918 
10919 /// \brief Mark a variable referenced, and check whether it is odr-used
10920 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
10921 /// used directly for normal expressions referring to VarDecl.
10922 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
10923   DoMarkVarDeclReferenced(*this, Loc, Var, 0);
10924 }
10925 
10926 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
10927                                Decl *D, Expr *E) {
10928   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
10929     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
10930     return;
10931   }
10932 
10933   SemaRef.MarkAnyDeclReferenced(Loc, D);
10934 
10935   // If this is a call to a method via a cast, also mark the method in the
10936   // derived class used in case codegen can devirtualize the call.
10937   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
10938   if (!ME)
10939     return;
10940   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
10941   if (!MD)
10942     return;
10943   const Expr *Base = ME->getBase();
10944   const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
10945   if (!MostDerivedClassDecl)
10946     return;
10947   CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl);
10948   if (!DM)
10949     return;
10950   SemaRef.MarkAnyDeclReferenced(Loc, DM);
10951 }
10952 
10953 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
10954 void Sema::MarkDeclRefReferenced(DeclRefExpr *E) {
10955   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E);
10956 }
10957 
10958 /// \brief Perform reference-marking and odr-use handling for a MemberExpr.
10959 void Sema::MarkMemberReferenced(MemberExpr *E) {
10960   MarkExprReferenced(*this, E->getMemberLoc(), E->getMemberDecl(), E);
10961 }
10962 
10963 /// \brief Perform marking for a reference to an arbitrary declaration.  It
10964 /// marks the declaration referenced, and performs odr-use checking for functions
10965 /// and variables. This method should not be used when building an normal
10966 /// expression which refers to a variable.
10967 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D) {
10968   if (VarDecl *VD = dyn_cast<VarDecl>(D))
10969     MarkVariableReferenced(Loc, VD);
10970   else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
10971     MarkFunctionReferenced(Loc, FD);
10972   else
10973     D->setReferenced();
10974 }
10975 
10976 namespace {
10977   // Mark all of the declarations referenced
10978   // FIXME: Not fully implemented yet! We need to have a better understanding
10979   // of when we're entering
10980   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
10981     Sema &S;
10982     SourceLocation Loc;
10983 
10984   public:
10985     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
10986 
10987     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
10988 
10989     bool TraverseTemplateArgument(const TemplateArgument &Arg);
10990     bool TraverseRecordType(RecordType *T);
10991   };
10992 }
10993 
10994 bool MarkReferencedDecls::TraverseTemplateArgument(
10995   const TemplateArgument &Arg) {
10996   if (Arg.getKind() == TemplateArgument::Declaration) {
10997     if (Decl *D = Arg.getAsDecl())
10998       S.MarkAnyDeclReferenced(Loc, D);
10999   }
11000 
11001   return Inherited::TraverseTemplateArgument(Arg);
11002 }
11003 
11004 bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
11005   if (ClassTemplateSpecializationDecl *Spec
11006                   = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
11007     const TemplateArgumentList &Args = Spec->getTemplateArgs();
11008     return TraverseTemplateArguments(Args.data(), Args.size());
11009   }
11010 
11011   return true;
11012 }
11013 
11014 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
11015   MarkReferencedDecls Marker(*this, Loc);
11016   Marker.TraverseType(Context.getCanonicalType(T));
11017 }
11018 
11019 namespace {
11020   /// \brief Helper class that marks all of the declarations referenced by
11021   /// potentially-evaluated subexpressions as "referenced".
11022   class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
11023     Sema &S;
11024     bool SkipLocalVariables;
11025 
11026   public:
11027     typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
11028 
11029     EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
11030       : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
11031 
11032     void VisitDeclRefExpr(DeclRefExpr *E) {
11033       // If we were asked not to visit local variables, don't.
11034       if (SkipLocalVariables) {
11035         if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
11036           if (VD->hasLocalStorage())
11037             return;
11038       }
11039 
11040       S.MarkDeclRefReferenced(E);
11041     }
11042 
11043     void VisitMemberExpr(MemberExpr *E) {
11044       S.MarkMemberReferenced(E);
11045       Inherited::VisitMemberExpr(E);
11046     }
11047 
11048     void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
11049       S.MarkFunctionReferenced(E->getLocStart(),
11050             const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
11051       Visit(E->getSubExpr());
11052     }
11053 
11054     void VisitCXXNewExpr(CXXNewExpr *E) {
11055       if (E->getOperatorNew())
11056         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
11057       if (E->getOperatorDelete())
11058         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
11059       Inherited::VisitCXXNewExpr(E);
11060     }
11061 
11062     void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
11063       if (E->getOperatorDelete())
11064         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
11065       QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
11066       if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
11067         CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
11068         S.MarkFunctionReferenced(E->getLocStart(),
11069                                     S.LookupDestructor(Record));
11070       }
11071 
11072       Inherited::VisitCXXDeleteExpr(E);
11073     }
11074 
11075     void VisitCXXConstructExpr(CXXConstructExpr *E) {
11076       S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
11077       Inherited::VisitCXXConstructExpr(E);
11078     }
11079 
11080     void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
11081       Visit(E->getExpr());
11082     }
11083 
11084     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
11085       Inherited::VisitImplicitCastExpr(E);
11086 
11087       if (E->getCastKind() == CK_LValueToRValue)
11088         S.UpdateMarkingForLValueToRValue(E->getSubExpr());
11089     }
11090   };
11091 }
11092 
11093 /// \brief Mark any declarations that appear within this expression or any
11094 /// potentially-evaluated subexpressions as "referenced".
11095 ///
11096 /// \param SkipLocalVariables If true, don't mark local variables as
11097 /// 'referenced'.
11098 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
11099                                             bool SkipLocalVariables) {
11100   EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
11101 }
11102 
11103 /// \brief Emit a diagnostic that describes an effect on the run-time behavior
11104 /// of the program being compiled.
11105 ///
11106 /// This routine emits the given diagnostic when the code currently being
11107 /// type-checked is "potentially evaluated", meaning that there is a
11108 /// possibility that the code will actually be executable. Code in sizeof()
11109 /// expressions, code used only during overload resolution, etc., are not
11110 /// potentially evaluated. This routine will suppress such diagnostics or,
11111 /// in the absolutely nutty case of potentially potentially evaluated
11112 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
11113 /// later.
11114 ///
11115 /// This routine should be used for all diagnostics that describe the run-time
11116 /// behavior of a program, such as passing a non-POD value through an ellipsis.
11117 /// Failure to do so will likely result in spurious diagnostics or failures
11118 /// during overload resolution or within sizeof/alignof/typeof/typeid.
11119 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
11120                                const PartialDiagnostic &PD) {
11121   switch (ExprEvalContexts.back().Context) {
11122   case Unevaluated:
11123     // The argument will never be evaluated, so don't complain.
11124     break;
11125 
11126   case ConstantEvaluated:
11127     // Relevant diagnostics should be produced by constant evaluation.
11128     break;
11129 
11130   case PotentiallyEvaluated:
11131   case PotentiallyEvaluatedIfUsed:
11132     if (Statement && getCurFunctionOrMethodDecl()) {
11133       FunctionScopes.back()->PossiblyUnreachableDiags.
11134         push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
11135     }
11136     else
11137       Diag(Loc, PD);
11138 
11139     return true;
11140   }
11141 
11142   return false;
11143 }
11144 
11145 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
11146                                CallExpr *CE, FunctionDecl *FD) {
11147   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
11148     return false;
11149 
11150   // If we're inside a decltype's expression, don't check for a valid return
11151   // type or construct temporaries until we know whether this is the last call.
11152   if (ExprEvalContexts.back().IsDecltype) {
11153     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
11154     return false;
11155   }
11156 
11157   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
11158     FunctionDecl *FD;
11159     CallExpr *CE;
11160 
11161   public:
11162     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
11163       : FD(FD), CE(CE) { }
11164 
11165     virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
11166       if (!FD) {
11167         S.Diag(Loc, diag::err_call_incomplete_return)
11168           << T << CE->getSourceRange();
11169         return;
11170       }
11171 
11172       S.Diag(Loc, diag::err_call_function_incomplete_return)
11173         << CE->getSourceRange() << FD->getDeclName() << T;
11174       S.Diag(FD->getLocation(),
11175              diag::note_function_with_incomplete_return_type_declared_here)
11176         << FD->getDeclName();
11177     }
11178   } Diagnoser(FD, CE);
11179 
11180   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
11181     return true;
11182 
11183   return false;
11184 }
11185 
11186 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
11187 // will prevent this condition from triggering, which is what we want.
11188 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
11189   SourceLocation Loc;
11190 
11191   unsigned diagnostic = diag::warn_condition_is_assignment;
11192   bool IsOrAssign = false;
11193 
11194   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
11195     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
11196       return;
11197 
11198     IsOrAssign = Op->getOpcode() == BO_OrAssign;
11199 
11200     // Greylist some idioms by putting them into a warning subcategory.
11201     if (ObjCMessageExpr *ME
11202           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
11203       Selector Sel = ME->getSelector();
11204 
11205       // self = [<foo> init...]
11206       if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init"))
11207         diagnostic = diag::warn_condition_is_idiomatic_assignment;
11208 
11209       // <foo> = [<bar> nextObject]
11210       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
11211         diagnostic = diag::warn_condition_is_idiomatic_assignment;
11212     }
11213 
11214     Loc = Op->getOperatorLoc();
11215   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
11216     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
11217       return;
11218 
11219     IsOrAssign = Op->getOperator() == OO_PipeEqual;
11220     Loc = Op->getOperatorLoc();
11221   } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
11222     return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
11223   else {
11224     // Not an assignment.
11225     return;
11226   }
11227 
11228   Diag(Loc, diagnostic) << E->getSourceRange();
11229 
11230   SourceLocation Open = E->getLocStart();
11231   SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
11232   Diag(Loc, diag::note_condition_assign_silence)
11233         << FixItHint::CreateInsertion(Open, "(")
11234         << FixItHint::CreateInsertion(Close, ")");
11235 
11236   if (IsOrAssign)
11237     Diag(Loc, diag::note_condition_or_assign_to_comparison)
11238       << FixItHint::CreateReplacement(Loc, "!=");
11239   else
11240     Diag(Loc, diag::note_condition_assign_to_comparison)
11241       << FixItHint::CreateReplacement(Loc, "==");
11242 }
11243 
11244 /// \brief Redundant parentheses over an equality comparison can indicate
11245 /// that the user intended an assignment used as condition.
11246 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
11247   // Don't warn if the parens came from a macro.
11248   SourceLocation parenLoc = ParenE->getLocStart();
11249   if (parenLoc.isInvalid() || parenLoc.isMacroID())
11250     return;
11251   // Don't warn for dependent expressions.
11252   if (ParenE->isTypeDependent())
11253     return;
11254 
11255   Expr *E = ParenE->IgnoreParens();
11256 
11257   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
11258     if (opE->getOpcode() == BO_EQ &&
11259         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
11260                                                            == Expr::MLV_Valid) {
11261       SourceLocation Loc = opE->getOperatorLoc();
11262 
11263       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
11264       SourceRange ParenERange = ParenE->getSourceRange();
11265       Diag(Loc, diag::note_equality_comparison_silence)
11266         << FixItHint::CreateRemoval(ParenERange.getBegin())
11267         << FixItHint::CreateRemoval(ParenERange.getEnd());
11268       Diag(Loc, diag::note_equality_comparison_to_assign)
11269         << FixItHint::CreateReplacement(Loc, "=");
11270     }
11271 }
11272 
11273 ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
11274   DiagnoseAssignmentAsCondition(E);
11275   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
11276     DiagnoseEqualityWithExtraParens(parenE);
11277 
11278   ExprResult result = CheckPlaceholderExpr(E);
11279   if (result.isInvalid()) return ExprError();
11280   E = result.take();
11281 
11282   if (!E->isTypeDependent()) {
11283     if (getLangOpts().CPlusPlus)
11284       return CheckCXXBooleanCondition(E); // C++ 6.4p4
11285 
11286     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
11287     if (ERes.isInvalid())
11288       return ExprError();
11289     E = ERes.take();
11290 
11291     QualType T = E->getType();
11292     if (!T->isScalarType()) { // C99 6.8.4.1p1
11293       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
11294         << T << E->getSourceRange();
11295       return ExprError();
11296     }
11297   }
11298 
11299   return Owned(E);
11300 }
11301 
11302 ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
11303                                        Expr *SubExpr) {
11304   if (!SubExpr)
11305     return ExprError();
11306 
11307   return CheckBooleanCondition(SubExpr, Loc);
11308 }
11309 
11310 namespace {
11311   /// A visitor for rebuilding a call to an __unknown_any expression
11312   /// to have an appropriate type.
11313   struct RebuildUnknownAnyFunction
11314     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
11315 
11316     Sema &S;
11317 
11318     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
11319 
11320     ExprResult VisitStmt(Stmt *S) {
11321       llvm_unreachable("unexpected statement!");
11322     }
11323 
11324     ExprResult VisitExpr(Expr *E) {
11325       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
11326         << E->getSourceRange();
11327       return ExprError();
11328     }
11329 
11330     /// Rebuild an expression which simply semantically wraps another
11331     /// expression which it shares the type and value kind of.
11332     template <class T> ExprResult rebuildSugarExpr(T *E) {
11333       ExprResult SubResult = Visit(E->getSubExpr());
11334       if (SubResult.isInvalid()) return ExprError();
11335 
11336       Expr *SubExpr = SubResult.take();
11337       E->setSubExpr(SubExpr);
11338       E->setType(SubExpr->getType());
11339       E->setValueKind(SubExpr->getValueKind());
11340       assert(E->getObjectKind() == OK_Ordinary);
11341       return E;
11342     }
11343 
11344     ExprResult VisitParenExpr(ParenExpr *E) {
11345       return rebuildSugarExpr(E);
11346     }
11347 
11348     ExprResult VisitUnaryExtension(UnaryOperator *E) {
11349       return rebuildSugarExpr(E);
11350     }
11351 
11352     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
11353       ExprResult SubResult = Visit(E->getSubExpr());
11354       if (SubResult.isInvalid()) return ExprError();
11355 
11356       Expr *SubExpr = SubResult.take();
11357       E->setSubExpr(SubExpr);
11358       E->setType(S.Context.getPointerType(SubExpr->getType()));
11359       assert(E->getValueKind() == VK_RValue);
11360       assert(E->getObjectKind() == OK_Ordinary);
11361       return E;
11362     }
11363 
11364     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
11365       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
11366 
11367       E->setType(VD->getType());
11368 
11369       assert(E->getValueKind() == VK_RValue);
11370       if (S.getLangOpts().CPlusPlus &&
11371           !(isa<CXXMethodDecl>(VD) &&
11372             cast<CXXMethodDecl>(VD)->isInstance()))
11373         E->setValueKind(VK_LValue);
11374 
11375       return E;
11376     }
11377 
11378     ExprResult VisitMemberExpr(MemberExpr *E) {
11379       return resolveDecl(E, E->getMemberDecl());
11380     }
11381 
11382     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
11383       return resolveDecl(E, E->getDecl());
11384     }
11385   };
11386 }
11387 
11388 /// Given a function expression of unknown-any type, try to rebuild it
11389 /// to have a function type.
11390 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
11391   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
11392   if (Result.isInvalid()) return ExprError();
11393   return S.DefaultFunctionArrayConversion(Result.take());
11394 }
11395 
11396 namespace {
11397   /// A visitor for rebuilding an expression of type __unknown_anytype
11398   /// into one which resolves the type directly on the referring
11399   /// expression.  Strict preservation of the original source
11400   /// structure is not a goal.
11401   struct RebuildUnknownAnyExpr
11402     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
11403 
11404     Sema &S;
11405 
11406     /// The current destination type.
11407     QualType DestType;
11408 
11409     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
11410       : S(S), DestType(CastType) {}
11411 
11412     ExprResult VisitStmt(Stmt *S) {
11413       llvm_unreachable("unexpected statement!");
11414     }
11415 
11416     ExprResult VisitExpr(Expr *E) {
11417       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
11418         << E->getSourceRange();
11419       return ExprError();
11420     }
11421 
11422     ExprResult VisitCallExpr(CallExpr *E);
11423     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
11424 
11425     /// Rebuild an expression which simply semantically wraps another
11426     /// expression which it shares the type and value kind of.
11427     template <class T> ExprResult rebuildSugarExpr(T *E) {
11428       ExprResult SubResult = Visit(E->getSubExpr());
11429       if (SubResult.isInvalid()) return ExprError();
11430       Expr *SubExpr = SubResult.take();
11431       E->setSubExpr(SubExpr);
11432       E->setType(SubExpr->getType());
11433       E->setValueKind(SubExpr->getValueKind());
11434       assert(E->getObjectKind() == OK_Ordinary);
11435       return E;
11436     }
11437 
11438     ExprResult VisitParenExpr(ParenExpr *E) {
11439       return rebuildSugarExpr(E);
11440     }
11441 
11442     ExprResult VisitUnaryExtension(UnaryOperator *E) {
11443       return rebuildSugarExpr(E);
11444     }
11445 
11446     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
11447       const PointerType *Ptr = DestType->getAs<PointerType>();
11448       if (!Ptr) {
11449         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
11450           << E->getSourceRange();
11451         return ExprError();
11452       }
11453       assert(E->getValueKind() == VK_RValue);
11454       assert(E->getObjectKind() == OK_Ordinary);
11455       E->setType(DestType);
11456 
11457       // Build the sub-expression as if it were an object of the pointee type.
11458       DestType = Ptr->getPointeeType();
11459       ExprResult SubResult = Visit(E->getSubExpr());
11460       if (SubResult.isInvalid()) return ExprError();
11461       E->setSubExpr(SubResult.take());
11462       return E;
11463     }
11464 
11465     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
11466 
11467     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
11468 
11469     ExprResult VisitMemberExpr(MemberExpr *E) {
11470       return resolveDecl(E, E->getMemberDecl());
11471     }
11472 
11473     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
11474       return resolveDecl(E, E->getDecl());
11475     }
11476   };
11477 }
11478 
11479 /// Rebuilds a call expression which yielded __unknown_anytype.
11480 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
11481   Expr *CalleeExpr = E->getCallee();
11482 
11483   enum FnKind {
11484     FK_MemberFunction,
11485     FK_FunctionPointer,
11486     FK_BlockPointer
11487   };
11488 
11489   FnKind Kind;
11490   QualType CalleeType = CalleeExpr->getType();
11491   if (CalleeType == S.Context.BoundMemberTy) {
11492     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
11493     Kind = FK_MemberFunction;
11494     CalleeType = Expr::findBoundMemberType(CalleeExpr);
11495   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
11496     CalleeType = Ptr->getPointeeType();
11497     Kind = FK_FunctionPointer;
11498   } else {
11499     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
11500     Kind = FK_BlockPointer;
11501   }
11502   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
11503 
11504   // Verify that this is a legal result type of a function.
11505   if (DestType->isArrayType() || DestType->isFunctionType()) {
11506     unsigned diagID = diag::err_func_returning_array_function;
11507     if (Kind == FK_BlockPointer)
11508       diagID = diag::err_block_returning_array_function;
11509 
11510     S.Diag(E->getExprLoc(), diagID)
11511       << DestType->isFunctionType() << DestType;
11512     return ExprError();
11513   }
11514 
11515   // Otherwise, go ahead and set DestType as the call's result.
11516   E->setType(DestType.getNonLValueExprType(S.Context));
11517   E->setValueKind(Expr::getValueKindForType(DestType));
11518   assert(E->getObjectKind() == OK_Ordinary);
11519 
11520   // Rebuild the function type, replacing the result type with DestType.
11521   if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType))
11522     DestType = S.Context.getFunctionType(DestType,
11523                                          Proto->arg_type_begin(),
11524                                          Proto->getNumArgs(),
11525                                          Proto->getExtProtoInfo());
11526   else
11527     DestType = S.Context.getFunctionNoProtoType(DestType,
11528                                                 FnType->getExtInfo());
11529 
11530   // Rebuild the appropriate pointer-to-function type.
11531   switch (Kind) {
11532   case FK_MemberFunction:
11533     // Nothing to do.
11534     break;
11535 
11536   case FK_FunctionPointer:
11537     DestType = S.Context.getPointerType(DestType);
11538     break;
11539 
11540   case FK_BlockPointer:
11541     DestType = S.Context.getBlockPointerType(DestType);
11542     break;
11543   }
11544 
11545   // Finally, we can recurse.
11546   ExprResult CalleeResult = Visit(CalleeExpr);
11547   if (!CalleeResult.isUsable()) return ExprError();
11548   E->setCallee(CalleeResult.take());
11549 
11550   // Bind a temporary if necessary.
11551   return S.MaybeBindToTemporary(E);
11552 }
11553 
11554 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
11555   // Verify that this is a legal result type of a call.
11556   if (DestType->isArrayType() || DestType->isFunctionType()) {
11557     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
11558       << DestType->isFunctionType() << DestType;
11559     return ExprError();
11560   }
11561 
11562   // Rewrite the method result type if available.
11563   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
11564     assert(Method->getResultType() == S.Context.UnknownAnyTy);
11565     Method->setResultType(DestType);
11566   }
11567 
11568   // Change the type of the message.
11569   E->setType(DestType.getNonReferenceType());
11570   E->setValueKind(Expr::getValueKindForType(DestType));
11571 
11572   return S.MaybeBindToTemporary(E);
11573 }
11574 
11575 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
11576   // The only case we should ever see here is a function-to-pointer decay.
11577   if (E->getCastKind() == CK_FunctionToPointerDecay) {
11578     assert(E->getValueKind() == VK_RValue);
11579     assert(E->getObjectKind() == OK_Ordinary);
11580 
11581     E->setType(DestType);
11582 
11583     // Rebuild the sub-expression as the pointee (function) type.
11584     DestType = DestType->castAs<PointerType>()->getPointeeType();
11585 
11586     ExprResult Result = Visit(E->getSubExpr());
11587     if (!Result.isUsable()) return ExprError();
11588 
11589     E->setSubExpr(Result.take());
11590     return S.Owned(E);
11591   } else if (E->getCastKind() == CK_LValueToRValue) {
11592     assert(E->getValueKind() == VK_RValue);
11593     assert(E->getObjectKind() == OK_Ordinary);
11594 
11595     assert(isa<BlockPointerType>(E->getType()));
11596 
11597     E->setType(DestType);
11598 
11599     // The sub-expression has to be a lvalue reference, so rebuild it as such.
11600     DestType = S.Context.getLValueReferenceType(DestType);
11601 
11602     ExprResult Result = Visit(E->getSubExpr());
11603     if (!Result.isUsable()) return ExprError();
11604 
11605     E->setSubExpr(Result.take());
11606     return S.Owned(E);
11607   } else {
11608     llvm_unreachable("Unhandled cast type!");
11609   }
11610 }
11611 
11612 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
11613   ExprValueKind ValueKind = VK_LValue;
11614   QualType Type = DestType;
11615 
11616   // We know how to make this work for certain kinds of decls:
11617 
11618   //  - functions
11619   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
11620     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
11621       DestType = Ptr->getPointeeType();
11622       ExprResult Result = resolveDecl(E, VD);
11623       if (Result.isInvalid()) return ExprError();
11624       return S.ImpCastExprToType(Result.take(), Type,
11625                                  CK_FunctionToPointerDecay, VK_RValue);
11626     }
11627 
11628     if (!Type->isFunctionType()) {
11629       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
11630         << VD << E->getSourceRange();
11631       return ExprError();
11632     }
11633 
11634     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
11635       if (MD->isInstance()) {
11636         ValueKind = VK_RValue;
11637         Type = S.Context.BoundMemberTy;
11638       }
11639 
11640     // Function references aren't l-values in C.
11641     if (!S.getLangOpts().CPlusPlus)
11642       ValueKind = VK_RValue;
11643 
11644   //  - variables
11645   } else if (isa<VarDecl>(VD)) {
11646     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
11647       Type = RefTy->getPointeeType();
11648     } else if (Type->isFunctionType()) {
11649       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
11650         << VD << E->getSourceRange();
11651       return ExprError();
11652     }
11653 
11654   //  - nothing else
11655   } else {
11656     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
11657       << VD << E->getSourceRange();
11658     return ExprError();
11659   }
11660 
11661   VD->setType(DestType);
11662   E->setType(Type);
11663   E->setValueKind(ValueKind);
11664   return S.Owned(E);
11665 }
11666 
11667 /// Check a cast of an unknown-any type.  We intentionally only
11668 /// trigger this for C-style casts.
11669 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
11670                                      Expr *CastExpr, CastKind &CastKind,
11671                                      ExprValueKind &VK, CXXCastPath &Path) {
11672   // Rewrite the casted expression from scratch.
11673   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
11674   if (!result.isUsable()) return ExprError();
11675 
11676   CastExpr = result.take();
11677   VK = CastExpr->getValueKind();
11678   CastKind = CK_NoOp;
11679 
11680   return CastExpr;
11681 }
11682 
11683 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
11684   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
11685 }
11686 
11687 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
11688   Expr *orig = E;
11689   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
11690   while (true) {
11691     E = E->IgnoreParenImpCasts();
11692     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
11693       E = call->getCallee();
11694       diagID = diag::err_uncasted_call_of_unknown_any;
11695     } else {
11696       break;
11697     }
11698   }
11699 
11700   SourceLocation loc;
11701   NamedDecl *d;
11702   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
11703     loc = ref->getLocation();
11704     d = ref->getDecl();
11705   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
11706     loc = mem->getMemberLoc();
11707     d = mem->getMemberDecl();
11708   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
11709     diagID = diag::err_uncasted_call_of_unknown_any;
11710     loc = msg->getSelectorStartLoc();
11711     d = msg->getMethodDecl();
11712     if (!d) {
11713       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
11714         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
11715         << orig->getSourceRange();
11716       return ExprError();
11717     }
11718   } else {
11719     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
11720       << E->getSourceRange();
11721     return ExprError();
11722   }
11723 
11724   S.Diag(loc, diagID) << d << orig->getSourceRange();
11725 
11726   // Never recoverable.
11727   return ExprError();
11728 }
11729 
11730 /// Check for operands with placeholder types and complain if found.
11731 /// Returns true if there was an error and no recovery was possible.
11732 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
11733   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
11734   if (!placeholderType) return Owned(E);
11735 
11736   switch (placeholderType->getKind()) {
11737 
11738   // Overloaded expressions.
11739   case BuiltinType::Overload: {
11740     // Try to resolve a single function template specialization.
11741     // This is obligatory.
11742     ExprResult result = Owned(E);
11743     if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) {
11744       return result;
11745 
11746     // If that failed, try to recover with a call.
11747     } else {
11748       tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable),
11749                            /*complain*/ true);
11750       return result;
11751     }
11752   }
11753 
11754   // Bound member functions.
11755   case BuiltinType::BoundMember: {
11756     ExprResult result = Owned(E);
11757     tryToRecoverWithCall(result, PDiag(diag::err_bound_member_function),
11758                          /*complain*/ true);
11759     return result;
11760   }
11761 
11762   // ARC unbridged casts.
11763   case BuiltinType::ARCUnbridgedCast: {
11764     Expr *realCast = stripARCUnbridgedCast(E);
11765     diagnoseARCUnbridgedCast(realCast);
11766     return Owned(realCast);
11767   }
11768 
11769   // Expressions of unknown type.
11770   case BuiltinType::UnknownAny:
11771     return diagnoseUnknownAnyExpr(*this, E);
11772 
11773   // Pseudo-objects.
11774   case BuiltinType::PseudoObject:
11775     return checkPseudoObjectRValue(E);
11776 
11777   case BuiltinType::BuiltinFn:
11778     Diag(E->getLocStart(), diag::err_builtin_fn_use);
11779     return ExprError();
11780 
11781   // Everything else should be impossible.
11782 #define BUILTIN_TYPE(Id, SingletonId) \
11783   case BuiltinType::Id:
11784 #define PLACEHOLDER_TYPE(Id, SingletonId)
11785 #include "clang/AST/BuiltinTypes.def"
11786     break;
11787   }
11788 
11789   llvm_unreachable("invalid placeholder type!");
11790 }
11791 
11792 bool Sema::CheckCaseExpression(Expr *E) {
11793   if (E->isTypeDependent())
11794     return true;
11795   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
11796     return E->getType()->isIntegralOrEnumerationType();
11797   return false;
11798 }
11799 
11800 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
11801 ExprResult
11802 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
11803   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
11804          "Unknown Objective-C Boolean value!");
11805   QualType BoolT = Context.ObjCBuiltinBoolTy;
11806   if (!Context.getBOOLDecl()) {
11807     LookupResult Result(*this, &Context.Idents.get("BOOL"), SourceLocation(),
11808                         Sema::LookupOrdinaryName);
11809     if (LookupName(Result, getCurScope())) {
11810       NamedDecl *ND = Result.getFoundDecl();
11811       if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
11812         Context.setBOOLDecl(TD);
11813     }
11814   }
11815   if (Context.getBOOLDecl())
11816     BoolT = Context.getBOOLType();
11817   return Owned(new (Context) ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes,
11818                                         BoolT, OpLoc));
11819 }
11820