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 "TreeTransform.h"
16 #include "clang/AST/ASTConsumer.h"
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/ASTMutationListener.h"
19 #include "clang/AST/CXXInheritance.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/DeclTemplate.h"
22 #include "clang/AST/EvaluatedExprVisitor.h"
23 #include "clang/AST/Expr.h"
24 #include "clang/AST/ExprCXX.h"
25 #include "clang/AST/ExprObjC.h"
26 #include "clang/AST/RecursiveASTVisitor.h"
27 #include "clang/AST/TypeLoc.h"
28 #include "clang/Basic/PartialDiagnostic.h"
29 #include "clang/Basic/SourceManager.h"
30 #include "clang/Basic/TargetInfo.h"
31 #include "clang/Lex/LiteralSupport.h"
32 #include "clang/Lex/Preprocessor.h"
33 #include "clang/Sema/AnalysisBasedWarnings.h"
34 #include "clang/Sema/DeclSpec.h"
35 #include "clang/Sema/DelayedDiagnostic.h"
36 #include "clang/Sema/Designator.h"
37 #include "clang/Sema/Initialization.h"
38 #include "clang/Sema/Lookup.h"
39 #include "clang/Sema/ParsedTemplate.h"
40 #include "clang/Sema/Scope.h"
41 #include "clang/Sema/ScopeInfo.h"
42 #include "clang/Sema/SemaFixItUtils.h"
43 #include "clang/Sema/Template.h"
44 using namespace clang;
45 using namespace sema;
46 
47 /// \brief Determine whether the use of this declaration is valid, without
48 /// emitting diagnostics.
49 bool Sema::CanUseDecl(NamedDecl *D) {
50   // See if this is an auto-typed variable whose initializer we are parsing.
51   if (ParsingInitForAutoVars.count(D))
52     return false;
53 
54   // See if this is a deleted function.
55   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
56     if (FD->isDeleted())
57       return false;
58   }
59 
60   // See if this function is unavailable.
61   if (D->getAvailability() == AR_Unavailable &&
62       cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
63     return false;
64 
65   return true;
66 }
67 
68 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
69   // Warn if this is used but marked unused.
70   if (D->hasAttr<UnusedAttr>()) {
71     const Decl *DC = cast<Decl>(S.getCurObjCLexicalContext());
72     if (!DC->hasAttr<UnusedAttr>())
73       S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
74   }
75 }
76 
77 static AvailabilityResult DiagnoseAvailabilityOfDecl(Sema &S,
78                               NamedDecl *D, SourceLocation Loc,
79                               const ObjCInterfaceDecl *UnknownObjCClass) {
80   // See if this declaration is unavailable or deprecated.
81   std::string Message;
82   AvailabilityResult Result = D->getAvailability(&Message);
83   if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D))
84     if (Result == AR_Available) {
85       const DeclContext *DC = ECD->getDeclContext();
86       if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC))
87         Result = TheEnumDecl->getAvailability(&Message);
88     }
89 
90   const ObjCPropertyDecl *ObjCPDecl = 0;
91   if (Result == AR_Deprecated || Result == AR_Unavailable) {
92     if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
93       if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) {
94         AvailabilityResult PDeclResult = PD->getAvailability(0);
95         if (PDeclResult == Result)
96           ObjCPDecl = PD;
97       }
98     }
99   }
100 
101   switch (Result) {
102     case AR_Available:
103     case AR_NotYetIntroduced:
104       break;
105 
106     case AR_Deprecated:
107       S.EmitDeprecationWarning(D, Message, Loc, UnknownObjCClass, ObjCPDecl);
108       break;
109 
110     case AR_Unavailable:
111       if (S.getCurContextAvailability() != AR_Unavailable) {
112         if (Message.empty()) {
113           if (!UnknownObjCClass) {
114             S.Diag(Loc, diag::err_unavailable) << D->getDeclName();
115             if (ObjCPDecl)
116               S.Diag(ObjCPDecl->getLocation(), diag::note_property_attribute)
117                 << ObjCPDecl->getDeclName() << 1;
118           }
119           else
120             S.Diag(Loc, diag::warn_unavailable_fwdclass_message)
121               << D->getDeclName();
122         }
123         else
124           S.Diag(Loc, diag::err_unavailable_message)
125             << D->getDeclName() << Message;
126         S.Diag(D->getLocation(), diag::note_unavailable_here)
127                   << isa<FunctionDecl>(D) << false;
128         if (ObjCPDecl)
129           S.Diag(ObjCPDecl->getLocation(), diag::note_property_attribute)
130           << ObjCPDecl->getDeclName() << 1;
131       }
132       break;
133     }
134     return Result;
135 }
136 
137 /// \brief Emit a note explaining that this function is deleted or unavailable.
138 void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
139   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
140 
141   if (Method && Method->isDeleted() && !Method->isDeletedAsWritten()) {
142     // If the method was explicitly defaulted, point at that declaration.
143     if (!Method->isImplicit())
144       Diag(Decl->getLocation(), diag::note_implicitly_deleted);
145 
146     // Try to diagnose why this special member function was implicitly
147     // deleted. This might fail, if that reason no longer applies.
148     CXXSpecialMember CSM = getSpecialMember(Method);
149     if (CSM != CXXInvalid)
150       ShouldDeleteSpecialMember(Method, CSM, /*Diagnose=*/true);
151 
152     return;
153   }
154 
155   Diag(Decl->getLocation(), diag::note_unavailable_here)
156     << 1 << Decl->isDeleted();
157 }
158 
159 /// \brief Determine whether a FunctionDecl was ever declared with an
160 /// explicit storage class.
161 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
162   for (FunctionDecl::redecl_iterator I = D->redecls_begin(),
163                                      E = D->redecls_end();
164        I != E; ++I) {
165     if (I->getStorageClassAsWritten() != SC_None)
166       return true;
167   }
168   return false;
169 }
170 
171 /// \brief Check whether we're in an extern inline function and referring to a
172 /// variable or function with internal linkage (C11 6.7.4p3).
173 ///
174 /// This is only a warning because we used to silently accept this code, but
175 /// in many cases it will not behave correctly. This is not enabled in C++ mode
176 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
177 /// and so while there may still be user mistakes, most of the time we can't
178 /// prove that there are errors.
179 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
180                                                       const NamedDecl *D,
181                                                       SourceLocation Loc) {
182   // This is disabled under C++; there are too many ways for this to fire in
183   // contexts where the warning is a false positive, or where it is technically
184   // correct but benign.
185   if (S.getLangOpts().CPlusPlus)
186     return;
187 
188   // Check if this is an inlined function or method.
189   FunctionDecl *Current = S.getCurFunctionDecl();
190   if (!Current)
191     return;
192   if (!Current->isInlined())
193     return;
194   if (Current->getLinkage() != ExternalLinkage)
195     return;
196 
197   // Check if the decl has internal linkage.
198   if (D->getLinkage() != InternalLinkage)
199     return;
200 
201   // Downgrade from ExtWarn to Extension if
202   //  (1) the supposedly external inline function is in the main file,
203   //      and probably won't be included anywhere else.
204   //  (2) the thing we're referencing is a pure function.
205   //  (3) the thing we're referencing is another inline function.
206   // This last can give us false negatives, but it's better than warning on
207   // wrappers for simple C library functions.
208   const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
209   bool DowngradeWarning = S.getSourceManager().isFromMainFile(Loc);
210   if (!DowngradeWarning && UsedFn)
211     DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
212 
213   S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline
214                                : diag::warn_internal_in_extern_inline)
215     << /*IsVar=*/!UsedFn << D;
216 
217   // Suggest "static" on the inline function, if possible.
218   if (!hasAnyExplicitStorageClass(Current)) {
219     const FunctionDecl *FirstDecl = Current->getCanonicalDecl();
220     SourceLocation DeclBegin = FirstDecl->getSourceRange().getBegin();
221     S.Diag(DeclBegin, diag::note_convert_inline_to_static)
222       << Current << FixItHint::CreateInsertion(DeclBegin, "static ");
223   }
224 
225   S.Diag(D->getCanonicalDecl()->getLocation(),
226          diag::note_internal_decl_declared_here)
227     << D;
228 }
229 
230 /// \brief Determine whether the use of this declaration is valid, and
231 /// emit any corresponding diagnostics.
232 ///
233 /// This routine diagnoses various problems with referencing
234 /// declarations that can occur when using a declaration. For example,
235 /// it might warn if a deprecated or unavailable declaration is being
236 /// used, or produce an error (and return true) if a C++0x deleted
237 /// function is being used.
238 ///
239 /// \returns true if there was an error (this declaration cannot be
240 /// referenced), false otherwise.
241 ///
242 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
243                              const ObjCInterfaceDecl *UnknownObjCClass) {
244   if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
245     // If there were any diagnostics suppressed by template argument deduction,
246     // emit them now.
247     llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >::iterator
248       Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
249     if (Pos != SuppressedDiagnostics.end()) {
250       SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second;
251       for (unsigned I = 0, N = Suppressed.size(); I != N; ++I)
252         Diag(Suppressed[I].first, Suppressed[I].second);
253 
254       // Clear out the list of suppressed diagnostics, so that we don't emit
255       // them again for this specialization. However, we don't obsolete this
256       // entry from the table, because we want to avoid ever emitting these
257       // diagnostics again.
258       Suppressed.clear();
259     }
260   }
261 
262   // See if this is an auto-typed variable whose initializer we are parsing.
263   if (ParsingInitForAutoVars.count(D)) {
264     Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
265       << D->getDeclName();
266     return true;
267   }
268 
269   // See if this is a deleted function.
270   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
271     if (FD->isDeleted()) {
272       Diag(Loc, diag::err_deleted_function_use);
273       NoteDeletedFunction(FD);
274       return true;
275     }
276   }
277   DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass);
278 
279   DiagnoseUnusedOfDecl(*this, D, Loc);
280 
281   diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
282 
283   return false;
284 }
285 
286 /// \brief Retrieve the message suffix that should be added to a
287 /// diagnostic complaining about the given function being deleted or
288 /// unavailable.
289 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
290   std::string Message;
291   if (FD->getAvailability(&Message))
292     return ": " + Message;
293 
294   return std::string();
295 }
296 
297 /// DiagnoseSentinelCalls - This routine checks whether a call or
298 /// message-send is to a declaration with the sentinel attribute, and
299 /// if so, it checks that the requirements of the sentinel are
300 /// satisfied.
301 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
302                                  Expr **args, unsigned numArgs) {
303   const SentinelAttr *attr = D->getAttr<SentinelAttr>();
304   if (!attr)
305     return;
306 
307   // The number of formal parameters of the declaration.
308   unsigned numFormalParams;
309 
310   // The kind of declaration.  This is also an index into a %select in
311   // the diagnostic.
312   enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
313 
314   if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
315     numFormalParams = MD->param_size();
316     calleeType = CT_Method;
317   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
318     numFormalParams = FD->param_size();
319     calleeType = CT_Function;
320   } else if (isa<VarDecl>(D)) {
321     QualType type = cast<ValueDecl>(D)->getType();
322     const FunctionType *fn = 0;
323     if (const PointerType *ptr = type->getAs<PointerType>()) {
324       fn = ptr->getPointeeType()->getAs<FunctionType>();
325       if (!fn) return;
326       calleeType = CT_Function;
327     } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
328       fn = ptr->getPointeeType()->castAs<FunctionType>();
329       calleeType = CT_Block;
330     } else {
331       return;
332     }
333 
334     if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
335       numFormalParams = proto->getNumArgs();
336     } else {
337       numFormalParams = 0;
338     }
339   } else {
340     return;
341   }
342 
343   // "nullPos" is the number of formal parameters at the end which
344   // effectively count as part of the variadic arguments.  This is
345   // useful if you would prefer to not have *any* formal parameters,
346   // but the language forces you to have at least one.
347   unsigned nullPos = attr->getNullPos();
348   assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
349   numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
350 
351   // The number of arguments which should follow the sentinel.
352   unsigned numArgsAfterSentinel = attr->getSentinel();
353 
354   // If there aren't enough arguments for all the formal parameters,
355   // the sentinel, and the args after the sentinel, complain.
356   if (numArgs < numFormalParams + numArgsAfterSentinel + 1) {
357     Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
358     Diag(D->getLocation(), diag::note_sentinel_here) << calleeType;
359     return;
360   }
361 
362   // Otherwise, find the sentinel expression.
363   Expr *sentinelExpr = args[numArgs - numArgsAfterSentinel - 1];
364   if (!sentinelExpr) return;
365   if (sentinelExpr->isValueDependent()) return;
366   if (Context.isSentinelNullExpr(sentinelExpr)) return;
367 
368   // Pick a reasonable string to insert.  Optimistically use 'nil' or
369   // 'NULL' if those are actually defined in the context.  Only use
370   // 'nil' for ObjC methods, where it's much more likely that the
371   // variadic arguments form a list of object pointers.
372   SourceLocation MissingNilLoc
373     = PP.getLocForEndOfToken(sentinelExpr->getLocEnd());
374   std::string NullValue;
375   if (calleeType == CT_Method &&
376       PP.getIdentifierInfo("nil")->hasMacroDefinition())
377     NullValue = "nil";
378   else if (PP.getIdentifierInfo("NULL")->hasMacroDefinition())
379     NullValue = "NULL";
380   else
381     NullValue = "(void*) 0";
382 
383   if (MissingNilLoc.isInvalid())
384     Diag(Loc, diag::warn_missing_sentinel) << calleeType;
385   else
386     Diag(MissingNilLoc, diag::warn_missing_sentinel)
387       << calleeType
388       << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
389   Diag(D->getLocation(), diag::note_sentinel_here) << calleeType;
390 }
391 
392 SourceRange Sema::getExprRange(Expr *E) const {
393   return E ? E->getSourceRange() : SourceRange();
394 }
395 
396 //===----------------------------------------------------------------------===//
397 //  Standard Promotions and Conversions
398 //===----------------------------------------------------------------------===//
399 
400 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
401 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) {
402   // Handle any placeholder expressions which made it here.
403   if (E->getType()->isPlaceholderType()) {
404     ExprResult result = CheckPlaceholderExpr(E);
405     if (result.isInvalid()) return ExprError();
406     E = result.take();
407   }
408 
409   QualType Ty = E->getType();
410   assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
411 
412   if (Ty->isFunctionType())
413     E = ImpCastExprToType(E, Context.getPointerType(Ty),
414                           CK_FunctionToPointerDecay).take();
415   else if (Ty->isArrayType()) {
416     // In C90 mode, arrays only promote to pointers if the array expression is
417     // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
418     // type 'array of type' is converted to an expression that has type 'pointer
419     // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
420     // that has type 'array of type' ...".  The relevant change is "an lvalue"
421     // (C90) to "an expression" (C99).
422     //
423     // C++ 4.2p1:
424     // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
425     // T" can be converted to an rvalue of type "pointer to T".
426     //
427     if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
428       E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
429                             CK_ArrayToPointerDecay).take();
430   }
431   return Owned(E);
432 }
433 
434 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
435   // Check to see if we are dereferencing a null pointer.  If so,
436   // and if not volatile-qualified, this is undefined behavior that the
437   // optimizer will delete, so warn about it.  People sometimes try to use this
438   // to get a deterministic trap and are surprised by clang's behavior.  This
439   // only handles the pattern "*null", which is a very syntactic check.
440   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
441     if (UO->getOpcode() == UO_Deref &&
442         UO->getSubExpr()->IgnoreParenCasts()->
443           isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
444         !UO->getType().isVolatileQualified()) {
445     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
446                           S.PDiag(diag::warn_indirection_through_null)
447                             << UO->getSubExpr()->getSourceRange());
448     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
449                         S.PDiag(diag::note_indirection_through_null));
450   }
451 }
452 
453 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
454   // Handle any placeholder expressions which made it here.
455   if (E->getType()->isPlaceholderType()) {
456     ExprResult result = CheckPlaceholderExpr(E);
457     if (result.isInvalid()) return ExprError();
458     E = result.take();
459   }
460 
461   // C++ [conv.lval]p1:
462   //   A glvalue of a non-function, non-array type T can be
463   //   converted to a prvalue.
464   if (!E->isGLValue()) return Owned(E);
465 
466   QualType T = E->getType();
467   assert(!T.isNull() && "r-value conversion on typeless expression?");
468 
469   // We don't want to throw lvalue-to-rvalue casts on top of
470   // expressions of certain types in C++.
471   if (getLangOpts().CPlusPlus &&
472       (E->getType() == Context.OverloadTy ||
473        T->isDependentType() ||
474        T->isRecordType()))
475     return Owned(E);
476 
477   // The C standard is actually really unclear on this point, and
478   // DR106 tells us what the result should be but not why.  It's
479   // generally best to say that void types just doesn't undergo
480   // lvalue-to-rvalue at all.  Note that expressions of unqualified
481   // 'void' type are never l-values, but qualified void can be.
482   if (T->isVoidType())
483     return Owned(E);
484 
485   // OpenCL usually rejects direct accesses to values of 'half' type.
486   if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16 &&
487       T->isHalfType()) {
488     Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
489       << 0 << T;
490     return ExprError();
491   }
492 
493   CheckForNullPointerDereference(*this, E);
494 
495   // C++ [conv.lval]p1:
496   //   [...] If T is a non-class type, the type of the prvalue is the
497   //   cv-unqualified version of T. Otherwise, the type of the
498   //   rvalue is T.
499   //
500   // C99 6.3.2.1p2:
501   //   If the lvalue has qualified type, the value has the unqualified
502   //   version of the type of the lvalue; otherwise, the value has the
503   //   type of the lvalue.
504   if (T.hasQualifiers())
505     T = T.getUnqualifiedType();
506 
507   UpdateMarkingForLValueToRValue(E);
508 
509   // Loading a __weak object implicitly retains the value, so we need a cleanup to
510   // balance that.
511   if (getLangOpts().ObjCAutoRefCount &&
512       E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
513     ExprNeedsCleanups = true;
514 
515   ExprResult Res = Owned(ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
516                                                   E, 0, VK_RValue));
517 
518   // C11 6.3.2.1p2:
519   //   ... if the lvalue has atomic type, the value has the non-atomic version
520   //   of the type of the lvalue ...
521   if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
522     T = Atomic->getValueType().getUnqualifiedType();
523     Res = Owned(ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic,
524                                          Res.get(), 0, VK_RValue));
525   }
526 
527   return Res;
528 }
529 
530 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) {
531   ExprResult Res = DefaultFunctionArrayConversion(E);
532   if (Res.isInvalid())
533     return ExprError();
534   Res = DefaultLvalueConversion(Res.take());
535   if (Res.isInvalid())
536     return ExprError();
537   return Res;
538 }
539 
540 
541 /// UsualUnaryConversions - Performs various conversions that are common to most
542 /// operators (C99 6.3). The conversions of array and function types are
543 /// sometimes suppressed. For example, the array->pointer conversion doesn't
544 /// apply if the array is an argument to the sizeof or address (&) operators.
545 /// In these instances, this routine should *not* be called.
546 ExprResult Sema::UsualUnaryConversions(Expr *E) {
547   // First, convert to an r-value.
548   ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
549   if (Res.isInvalid())
550     return ExprError();
551   E = Res.take();
552 
553   QualType Ty = E->getType();
554   assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
555 
556   // Half FP have to be promoted to float unless it is natively supported
557   if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
558     return ImpCastExprToType(Res.take(), Context.FloatTy, CK_FloatingCast);
559 
560   // Try to perform integral promotions if the object has a theoretically
561   // promotable type.
562   if (Ty->isIntegralOrUnscopedEnumerationType()) {
563     // C99 6.3.1.1p2:
564     //
565     //   The following may be used in an expression wherever an int or
566     //   unsigned int may be used:
567     //     - an object or expression with an integer type whose integer
568     //       conversion rank is less than or equal to the rank of int
569     //       and unsigned int.
570     //     - A bit-field of type _Bool, int, signed int, or unsigned int.
571     //
572     //   If an int can represent all values of the original type, the
573     //   value is converted to an int; otherwise, it is converted to an
574     //   unsigned int. These are called the integer promotions. All
575     //   other types are unchanged by the integer promotions.
576 
577     QualType PTy = Context.isPromotableBitField(E);
578     if (!PTy.isNull()) {
579       E = ImpCastExprToType(E, PTy, CK_IntegralCast).take();
580       return Owned(E);
581     }
582     if (Ty->isPromotableIntegerType()) {
583       QualType PT = Context.getPromotedIntegerType(Ty);
584       E = ImpCastExprToType(E, PT, CK_IntegralCast).take();
585       return Owned(E);
586     }
587   }
588   return Owned(E);
589 }
590 
591 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
592 /// do not have a prototype. Arguments that have type float or __fp16
593 /// are promoted to double. All other argument types are converted by
594 /// UsualUnaryConversions().
595 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
596   QualType Ty = E->getType();
597   assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
598 
599   ExprResult Res = UsualUnaryConversions(E);
600   if (Res.isInvalid())
601     return ExprError();
602   E = Res.take();
603 
604   // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to
605   // double.
606   const BuiltinType *BTy = Ty->getAs<BuiltinType>();
607   if (BTy && (BTy->getKind() == BuiltinType::Half ||
608               BTy->getKind() == BuiltinType::Float))
609     E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).take();
610 
611   // C++ performs lvalue-to-rvalue conversion as a default argument
612   // promotion, even on class types, but note:
613   //   C++11 [conv.lval]p2:
614   //     When an lvalue-to-rvalue conversion occurs in an unevaluated
615   //     operand or a subexpression thereof the value contained in the
616   //     referenced object is not accessed. Otherwise, if the glvalue
617   //     has a class type, the conversion copy-initializes a temporary
618   //     of type T from the glvalue and the result of the conversion
619   //     is a prvalue for the temporary.
620   // FIXME: add some way to gate this entire thing for correctness in
621   // potentially potentially evaluated contexts.
622   if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
623     ExprResult Temp = PerformCopyInitialization(
624                        InitializedEntity::InitializeTemporary(E->getType()),
625                                                 E->getExprLoc(),
626                                                 Owned(E));
627     if (Temp.isInvalid())
628       return ExprError();
629     E = Temp.get();
630   }
631 
632   return Owned(E);
633 }
634 
635 /// Determine the degree of POD-ness for an expression.
636 /// Incomplete types are considered POD, since this check can be performed
637 /// when we're in an unevaluated context.
638 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
639   if (Ty->isIncompleteType()) {
640     if (Ty->isObjCObjectType())
641       return VAK_Invalid;
642     return VAK_Valid;
643   }
644 
645   if (Ty.isCXX98PODType(Context))
646     return VAK_Valid;
647 
648   // C++11 [expr.call]p7:
649   //   Passing a potentially-evaluated argument of class type (Clause 9)
650   //   having a non-trivial copy constructor, a non-trivial move constructor,
651   //   or a non-trivial destructor, with no corresponding parameter,
652   //   is conditionally-supported with implementation-defined semantics.
653   if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
654     if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
655       if (!Record->hasNonTrivialCopyConstructor() &&
656           !Record->hasNonTrivialMoveConstructor() &&
657           !Record->hasNonTrivialDestructor())
658         return VAK_ValidInCXX11;
659 
660   if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
661     return VAK_Valid;
662   return VAK_Invalid;
663 }
664 
665 bool Sema::variadicArgumentPODCheck(const Expr *E, VariadicCallType CT) {
666   // Don't allow one to pass an Objective-C interface to a vararg.
667   const QualType & Ty = E->getType();
668 
669   // Complain about passing non-POD types through varargs.
670   switch (isValidVarArgType(Ty)) {
671   case VAK_Valid:
672     break;
673   case VAK_ValidInCXX11:
674     DiagRuntimeBehavior(E->getLocStart(), 0,
675         PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
676         << E->getType() << CT);
677     break;
678   case VAK_Invalid: {
679     if (Ty->isObjCObjectType())
680       return DiagRuntimeBehavior(E->getLocStart(), 0,
681                           PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
682                             << Ty << CT);
683 
684     return DiagRuntimeBehavior(E->getLocStart(), 0,
685                    PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
686                    << getLangOpts().CPlusPlus11 << Ty << CT);
687   }
688   }
689   // c++ rules are enforced elsewhere.
690   return false;
691 }
692 
693 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
694 /// will create a trap if the resulting type is not a POD type.
695 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
696                                                   FunctionDecl *FDecl) {
697   if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
698     // Strip the unbridged-cast placeholder expression off, if applicable.
699     if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
700         (CT == VariadicMethod ||
701          (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
702       E = stripARCUnbridgedCast(E);
703 
704     // Otherwise, do normal placeholder checking.
705     } else {
706       ExprResult ExprRes = CheckPlaceholderExpr(E);
707       if (ExprRes.isInvalid())
708         return ExprError();
709       E = ExprRes.take();
710     }
711   }
712 
713   ExprResult ExprRes = DefaultArgumentPromotion(E);
714   if (ExprRes.isInvalid())
715     return ExprError();
716   E = ExprRes.take();
717 
718   // Diagnostics regarding non-POD argument types are
719   // emitted along with format string checking in Sema::CheckFunctionCall().
720   if (isValidVarArgType(E->getType()) == VAK_Invalid) {
721     // Turn this into a trap.
722     CXXScopeSpec SS;
723     SourceLocation TemplateKWLoc;
724     UnqualifiedId Name;
725     Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
726                        E->getLocStart());
727     ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
728                                           Name, true, false);
729     if (TrapFn.isInvalid())
730       return ExprError();
731 
732     ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(),
733                                     E->getLocStart(), MultiExprArg(),
734                                     E->getLocEnd());
735     if (Call.isInvalid())
736       return ExprError();
737 
738     ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
739                                   Call.get(), E);
740     if (Comma.isInvalid())
741       return ExprError();
742     return Comma.get();
743   }
744 
745   if (!getLangOpts().CPlusPlus &&
746       RequireCompleteType(E->getExprLoc(), E->getType(),
747                           diag::err_call_incomplete_argument))
748     return ExprError();
749 
750   return Owned(E);
751 }
752 
753 /// \brief Converts an integer to complex float type.  Helper function of
754 /// UsualArithmeticConversions()
755 ///
756 /// \return false if the integer expression is an integer type and is
757 /// successfully converted to the complex type.
758 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
759                                                   ExprResult &ComplexExpr,
760                                                   QualType IntTy,
761                                                   QualType ComplexTy,
762                                                   bool SkipCast) {
763   if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
764   if (SkipCast) return false;
765   if (IntTy->isIntegerType()) {
766     QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
767     IntExpr = S.ImpCastExprToType(IntExpr.take(), fpTy, CK_IntegralToFloating);
768     IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
769                                   CK_FloatingRealToComplex);
770   } else {
771     assert(IntTy->isComplexIntegerType());
772     IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
773                                   CK_IntegralComplexToFloatingComplex);
774   }
775   return false;
776 }
777 
778 /// \brief Takes two complex float types and converts them to the same type.
779 /// Helper function of UsualArithmeticConversions()
780 static QualType
781 handleComplexFloatToComplexFloatConverstion(Sema &S, ExprResult &LHS,
782                                             ExprResult &RHS, QualType LHSType,
783                                             QualType RHSType,
784                                             bool IsCompAssign) {
785   int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
786 
787   if (order < 0) {
788     // _Complex float -> _Complex double
789     if (!IsCompAssign)
790       LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingComplexCast);
791     return RHSType;
792   }
793   if (order > 0)
794     // _Complex float -> _Complex double
795     RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingComplexCast);
796   return LHSType;
797 }
798 
799 /// \brief Converts otherExpr to complex float and promotes complexExpr if
800 /// necessary.  Helper function of UsualArithmeticConversions()
801 static QualType handleOtherComplexFloatConversion(Sema &S,
802                                                   ExprResult &ComplexExpr,
803                                                   ExprResult &OtherExpr,
804                                                   QualType ComplexTy,
805                                                   QualType OtherTy,
806                                                   bool ConvertComplexExpr,
807                                                   bool ConvertOtherExpr) {
808   int order = S.Context.getFloatingTypeOrder(ComplexTy, OtherTy);
809 
810   // If just the complexExpr is complex, the otherExpr needs to be converted,
811   // and the complexExpr might need to be promoted.
812   if (order > 0) { // complexExpr is wider
813     // float -> _Complex double
814     if (ConvertOtherExpr) {
815       QualType fp = cast<ComplexType>(ComplexTy)->getElementType();
816       OtherExpr = S.ImpCastExprToType(OtherExpr.take(), fp, CK_FloatingCast);
817       OtherExpr = S.ImpCastExprToType(OtherExpr.take(), ComplexTy,
818                                       CK_FloatingRealToComplex);
819     }
820     return ComplexTy;
821   }
822 
823   // otherTy is at least as wide.  Find its corresponding complex type.
824   QualType result = (order == 0 ? ComplexTy :
825                                   S.Context.getComplexType(OtherTy));
826 
827   // double -> _Complex double
828   if (ConvertOtherExpr)
829     OtherExpr = S.ImpCastExprToType(OtherExpr.take(), result,
830                                     CK_FloatingRealToComplex);
831 
832   // _Complex float -> _Complex double
833   if (ConvertComplexExpr && order < 0)
834     ComplexExpr = S.ImpCastExprToType(ComplexExpr.take(), result,
835                                       CK_FloatingComplexCast);
836 
837   return result;
838 }
839 
840 /// \brief Handle arithmetic conversion with complex types.  Helper function of
841 /// UsualArithmeticConversions()
842 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
843                                              ExprResult &RHS, QualType LHSType,
844                                              QualType RHSType,
845                                              bool IsCompAssign) {
846   // if we have an integer operand, the result is the complex type.
847   if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
848                                              /*skipCast*/false))
849     return LHSType;
850   if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
851                                              /*skipCast*/IsCompAssign))
852     return RHSType;
853 
854   // This handles complex/complex, complex/float, or float/complex.
855   // When both operands are complex, the shorter operand is converted to the
856   // type of the longer, and that is the type of the result. This corresponds
857   // to what is done when combining two real floating-point operands.
858   // The fun begins when size promotion occur across type domains.
859   // From H&S 6.3.4: When one operand is complex and the other is a real
860   // floating-point type, the less precise type is converted, within it's
861   // real or complex domain, to the precision of the other type. For example,
862   // when combining a "long double" with a "double _Complex", the
863   // "double _Complex" is promoted to "long double _Complex".
864 
865   bool LHSComplexFloat = LHSType->isComplexType();
866   bool RHSComplexFloat = RHSType->isComplexType();
867 
868   // If both are complex, just cast to the more precise type.
869   if (LHSComplexFloat && RHSComplexFloat)
870     return handleComplexFloatToComplexFloatConverstion(S, LHS, RHS,
871                                                        LHSType, RHSType,
872                                                        IsCompAssign);
873 
874   // If only one operand is complex, promote it if necessary and convert the
875   // other operand to complex.
876   if (LHSComplexFloat)
877     return handleOtherComplexFloatConversion(
878         S, LHS, RHS, LHSType, RHSType, /*convertComplexExpr*/!IsCompAssign,
879         /*convertOtherExpr*/ true);
880 
881   assert(RHSComplexFloat);
882   return handleOtherComplexFloatConversion(
883       S, RHS, LHS, RHSType, LHSType, /*convertComplexExpr*/true,
884       /*convertOtherExpr*/ !IsCompAssign);
885 }
886 
887 /// \brief Hande arithmetic conversion from integer to float.  Helper function
888 /// of UsualArithmeticConversions()
889 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
890                                            ExprResult &IntExpr,
891                                            QualType FloatTy, QualType IntTy,
892                                            bool ConvertFloat, bool ConvertInt) {
893   if (IntTy->isIntegerType()) {
894     if (ConvertInt)
895       // Convert intExpr to the lhs floating point type.
896       IntExpr = S.ImpCastExprToType(IntExpr.take(), FloatTy,
897                                     CK_IntegralToFloating);
898     return FloatTy;
899   }
900 
901   // Convert both sides to the appropriate complex float.
902   assert(IntTy->isComplexIntegerType());
903   QualType result = S.Context.getComplexType(FloatTy);
904 
905   // _Complex int -> _Complex float
906   if (ConvertInt)
907     IntExpr = S.ImpCastExprToType(IntExpr.take(), result,
908                                   CK_IntegralComplexToFloatingComplex);
909 
910   // float -> _Complex float
911   if (ConvertFloat)
912     FloatExpr = S.ImpCastExprToType(FloatExpr.take(), result,
913                                     CK_FloatingRealToComplex);
914 
915   return result;
916 }
917 
918 /// \brief Handle arithmethic conversion with floating point types.  Helper
919 /// function of UsualArithmeticConversions()
920 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
921                                       ExprResult &RHS, QualType LHSType,
922                                       QualType RHSType, bool IsCompAssign) {
923   bool LHSFloat = LHSType->isRealFloatingType();
924   bool RHSFloat = RHSType->isRealFloatingType();
925 
926   // If we have two real floating types, convert the smaller operand
927   // to the bigger result.
928   if (LHSFloat && RHSFloat) {
929     int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
930     if (order > 0) {
931       RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingCast);
932       return LHSType;
933     }
934 
935     assert(order < 0 && "illegal float comparison");
936     if (!IsCompAssign)
937       LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingCast);
938     return RHSType;
939   }
940 
941   if (LHSFloat)
942     return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
943                                       /*convertFloat=*/!IsCompAssign,
944                                       /*convertInt=*/ true);
945   assert(RHSFloat);
946   return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
947                                     /*convertInt=*/ true,
948                                     /*convertFloat=*/!IsCompAssign);
949 }
950 
951 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
952 
953 namespace {
954 /// These helper callbacks are placed in an anonymous namespace to
955 /// permit their use as function template parameters.
956 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
957   return S.ImpCastExprToType(op, toType, CK_IntegralCast);
958 }
959 
960 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
961   return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
962                              CK_IntegralComplexCast);
963 }
964 }
965 
966 /// \brief Handle integer arithmetic conversions.  Helper function of
967 /// UsualArithmeticConversions()
968 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
969 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
970                                         ExprResult &RHS, QualType LHSType,
971                                         QualType RHSType, bool IsCompAssign) {
972   // The rules for this case are in C99 6.3.1.8
973   int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
974   bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
975   bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
976   if (LHSSigned == RHSSigned) {
977     // Same signedness; use the higher-ranked type
978     if (order >= 0) {
979       RHS = (*doRHSCast)(S, RHS.take(), LHSType);
980       return LHSType;
981     } else if (!IsCompAssign)
982       LHS = (*doLHSCast)(S, LHS.take(), RHSType);
983     return RHSType;
984   } else if (order != (LHSSigned ? 1 : -1)) {
985     // The unsigned type has greater than or equal rank to the
986     // signed type, so use the unsigned type
987     if (RHSSigned) {
988       RHS = (*doRHSCast)(S, RHS.take(), LHSType);
989       return LHSType;
990     } else if (!IsCompAssign)
991       LHS = (*doLHSCast)(S, LHS.take(), RHSType);
992     return RHSType;
993   } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
994     // The two types are different widths; if we are here, that
995     // means the signed type is larger than the unsigned type, so
996     // use the signed type.
997     if (LHSSigned) {
998       RHS = (*doRHSCast)(S, RHS.take(), LHSType);
999       return LHSType;
1000     } else if (!IsCompAssign)
1001       LHS = (*doLHSCast)(S, LHS.take(), RHSType);
1002     return RHSType;
1003   } else {
1004     // The signed type is higher-ranked than the unsigned type,
1005     // but isn't actually any bigger (like unsigned int and long
1006     // on most 32-bit systems).  Use the unsigned type corresponding
1007     // to the signed type.
1008     QualType result =
1009       S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1010     RHS = (*doRHSCast)(S, RHS.take(), result);
1011     if (!IsCompAssign)
1012       LHS = (*doLHSCast)(S, LHS.take(), result);
1013     return result;
1014   }
1015 }
1016 
1017 /// \brief Handle conversions with GCC complex int extension.  Helper function
1018 /// of UsualArithmeticConversions()
1019 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1020                                            ExprResult &RHS, QualType LHSType,
1021                                            QualType RHSType,
1022                                            bool IsCompAssign) {
1023   const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1024   const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1025 
1026   if (LHSComplexInt && RHSComplexInt) {
1027     QualType LHSEltType = LHSComplexInt->getElementType();
1028     QualType RHSEltType = RHSComplexInt->getElementType();
1029     QualType ScalarType =
1030       handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1031         (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1032 
1033     return S.Context.getComplexType(ScalarType);
1034   }
1035 
1036   if (LHSComplexInt) {
1037     QualType LHSEltType = LHSComplexInt->getElementType();
1038     QualType ScalarType =
1039       handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1040         (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1041     QualType ComplexType = S.Context.getComplexType(ScalarType);
1042     RHS = S.ImpCastExprToType(RHS.take(), ComplexType,
1043                               CK_IntegralRealToComplex);
1044 
1045     return ComplexType;
1046   }
1047 
1048   assert(RHSComplexInt);
1049 
1050   QualType RHSEltType = RHSComplexInt->getElementType();
1051   QualType ScalarType =
1052     handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1053       (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1054   QualType ComplexType = S.Context.getComplexType(ScalarType);
1055 
1056   if (!IsCompAssign)
1057     LHS = S.ImpCastExprToType(LHS.take(), ComplexType,
1058                               CK_IntegralRealToComplex);
1059   return ComplexType;
1060 }
1061 
1062 /// UsualArithmeticConversions - Performs various conversions that are common to
1063 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1064 /// routine returns the first non-arithmetic type found. The client is
1065 /// responsible for emitting appropriate error diagnostics.
1066 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1067                                           bool IsCompAssign) {
1068   if (!IsCompAssign) {
1069     LHS = UsualUnaryConversions(LHS.take());
1070     if (LHS.isInvalid())
1071       return QualType();
1072   }
1073 
1074   RHS = UsualUnaryConversions(RHS.take());
1075   if (RHS.isInvalid())
1076     return QualType();
1077 
1078   // For conversion purposes, we ignore any qualifiers.
1079   // For example, "const float" and "float" are equivalent.
1080   QualType LHSType =
1081     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1082   QualType RHSType =
1083     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1084 
1085   // For conversion purposes, we ignore any atomic qualifier on the LHS.
1086   if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1087     LHSType = AtomicLHS->getValueType();
1088 
1089   // If both types are identical, no conversion is needed.
1090   if (LHSType == RHSType)
1091     return LHSType;
1092 
1093   // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1094   // The caller can deal with this (e.g. pointer + int).
1095   if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1096     return QualType();
1097 
1098   // Apply unary and bitfield promotions to the LHS's type.
1099   QualType LHSUnpromotedType = LHSType;
1100   if (LHSType->isPromotableIntegerType())
1101     LHSType = Context.getPromotedIntegerType(LHSType);
1102   QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1103   if (!LHSBitfieldPromoteTy.isNull())
1104     LHSType = LHSBitfieldPromoteTy;
1105   if (LHSType != LHSUnpromotedType && !IsCompAssign)
1106     LHS = ImpCastExprToType(LHS.take(), LHSType, CK_IntegralCast);
1107 
1108   // If both types are identical, no conversion is needed.
1109   if (LHSType == RHSType)
1110     return LHSType;
1111 
1112   // At this point, we have two different arithmetic types.
1113 
1114   // Handle complex types first (C99 6.3.1.8p1).
1115   if (LHSType->isComplexType() || RHSType->isComplexType())
1116     return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1117                                         IsCompAssign);
1118 
1119   // Now handle "real" floating types (i.e. float, double, long double).
1120   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1121     return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1122                                  IsCompAssign);
1123 
1124   // Handle GCC complex int extension.
1125   if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1126     return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1127                                       IsCompAssign);
1128 
1129   // Finally, we have two differing integer types.
1130   return handleIntegerConversion<doIntegralCast, doIntegralCast>
1131            (*this, LHS, RHS, LHSType, RHSType, IsCompAssign);
1132 }
1133 
1134 
1135 //===----------------------------------------------------------------------===//
1136 //  Semantic Analysis for various Expression Types
1137 //===----------------------------------------------------------------------===//
1138 
1139 
1140 ExprResult
1141 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1142                                 SourceLocation DefaultLoc,
1143                                 SourceLocation RParenLoc,
1144                                 Expr *ControllingExpr,
1145                                 MultiTypeArg ArgTypes,
1146                                 MultiExprArg ArgExprs) {
1147   unsigned NumAssocs = ArgTypes.size();
1148   assert(NumAssocs == ArgExprs.size());
1149 
1150   ParsedType *ParsedTypes = ArgTypes.data();
1151   Expr **Exprs = ArgExprs.data();
1152 
1153   TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1154   for (unsigned i = 0; i < NumAssocs; ++i) {
1155     if (ParsedTypes[i])
1156       (void) GetTypeFromParser(ParsedTypes[i], &Types[i]);
1157     else
1158       Types[i] = 0;
1159   }
1160 
1161   ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1162                                              ControllingExpr, Types, Exprs,
1163                                              NumAssocs);
1164   delete [] Types;
1165   return ER;
1166 }
1167 
1168 ExprResult
1169 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1170                                  SourceLocation DefaultLoc,
1171                                  SourceLocation RParenLoc,
1172                                  Expr *ControllingExpr,
1173                                  TypeSourceInfo **Types,
1174                                  Expr **Exprs,
1175                                  unsigned NumAssocs) {
1176   if (ControllingExpr->getType()->isPlaceholderType()) {
1177     ExprResult result = CheckPlaceholderExpr(ControllingExpr);
1178     if (result.isInvalid()) return ExprError();
1179     ControllingExpr = result.take();
1180   }
1181 
1182   bool TypeErrorFound = false,
1183        IsResultDependent = ControllingExpr->isTypeDependent(),
1184        ContainsUnexpandedParameterPack
1185          = ControllingExpr->containsUnexpandedParameterPack();
1186 
1187   for (unsigned i = 0; i < NumAssocs; ++i) {
1188     if (Exprs[i]->containsUnexpandedParameterPack())
1189       ContainsUnexpandedParameterPack = true;
1190 
1191     if (Types[i]) {
1192       if (Types[i]->getType()->containsUnexpandedParameterPack())
1193         ContainsUnexpandedParameterPack = true;
1194 
1195       if (Types[i]->getType()->isDependentType()) {
1196         IsResultDependent = true;
1197       } else {
1198         // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1199         // complete object type other than a variably modified type."
1200         unsigned D = 0;
1201         if (Types[i]->getType()->isIncompleteType())
1202           D = diag::err_assoc_type_incomplete;
1203         else if (!Types[i]->getType()->isObjectType())
1204           D = diag::err_assoc_type_nonobject;
1205         else if (Types[i]->getType()->isVariablyModifiedType())
1206           D = diag::err_assoc_type_variably_modified;
1207 
1208         if (D != 0) {
1209           Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1210             << Types[i]->getTypeLoc().getSourceRange()
1211             << Types[i]->getType();
1212           TypeErrorFound = true;
1213         }
1214 
1215         // C11 6.5.1.1p2 "No two generic associations in the same generic
1216         // selection shall specify compatible types."
1217         for (unsigned j = i+1; j < NumAssocs; ++j)
1218           if (Types[j] && !Types[j]->getType()->isDependentType() &&
1219               Context.typesAreCompatible(Types[i]->getType(),
1220                                          Types[j]->getType())) {
1221             Diag(Types[j]->getTypeLoc().getBeginLoc(),
1222                  diag::err_assoc_compatible_types)
1223               << Types[j]->getTypeLoc().getSourceRange()
1224               << Types[j]->getType()
1225               << Types[i]->getType();
1226             Diag(Types[i]->getTypeLoc().getBeginLoc(),
1227                  diag::note_compat_assoc)
1228               << Types[i]->getTypeLoc().getSourceRange()
1229               << Types[i]->getType();
1230             TypeErrorFound = true;
1231           }
1232       }
1233     }
1234   }
1235   if (TypeErrorFound)
1236     return ExprError();
1237 
1238   // If we determined that the generic selection is result-dependent, don't
1239   // try to compute the result expression.
1240   if (IsResultDependent)
1241     return Owned(new (Context) GenericSelectionExpr(
1242                    Context, KeyLoc, ControllingExpr,
1243                    llvm::makeArrayRef(Types, NumAssocs),
1244                    llvm::makeArrayRef(Exprs, NumAssocs),
1245                    DefaultLoc, RParenLoc, ContainsUnexpandedParameterPack));
1246 
1247   SmallVector<unsigned, 1> CompatIndices;
1248   unsigned DefaultIndex = -1U;
1249   for (unsigned i = 0; i < NumAssocs; ++i) {
1250     if (!Types[i])
1251       DefaultIndex = i;
1252     else if (Context.typesAreCompatible(ControllingExpr->getType(),
1253                                         Types[i]->getType()))
1254       CompatIndices.push_back(i);
1255   }
1256 
1257   // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1258   // type compatible with at most one of the types named in its generic
1259   // association list."
1260   if (CompatIndices.size() > 1) {
1261     // We strip parens here because the controlling expression is typically
1262     // parenthesized in macro definitions.
1263     ControllingExpr = ControllingExpr->IgnoreParens();
1264     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1265       << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1266       << (unsigned) CompatIndices.size();
1267     for (SmallVector<unsigned, 1>::iterator I = CompatIndices.begin(),
1268          E = CompatIndices.end(); I != E; ++I) {
1269       Diag(Types[*I]->getTypeLoc().getBeginLoc(),
1270            diag::note_compat_assoc)
1271         << Types[*I]->getTypeLoc().getSourceRange()
1272         << Types[*I]->getType();
1273     }
1274     return ExprError();
1275   }
1276 
1277   // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1278   // its controlling expression shall have type compatible with exactly one of
1279   // the types named in its generic association list."
1280   if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1281     // We strip parens here because the controlling expression is typically
1282     // parenthesized in macro definitions.
1283     ControllingExpr = ControllingExpr->IgnoreParens();
1284     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1285       << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1286     return ExprError();
1287   }
1288 
1289   // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1290   // type name that is compatible with the type of the controlling expression,
1291   // then the result expression of the generic selection is the expression
1292   // in that generic association. Otherwise, the result expression of the
1293   // generic selection is the expression in the default generic association."
1294   unsigned ResultIndex =
1295     CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1296 
1297   return Owned(new (Context) GenericSelectionExpr(
1298                  Context, KeyLoc, ControllingExpr,
1299                  llvm::makeArrayRef(Types, NumAssocs),
1300                  llvm::makeArrayRef(Exprs, NumAssocs),
1301                  DefaultLoc, RParenLoc, ContainsUnexpandedParameterPack,
1302                  ResultIndex));
1303 }
1304 
1305 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1306 /// location of the token and the offset of the ud-suffix within it.
1307 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1308                                      unsigned Offset) {
1309   return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1310                                         S.getLangOpts());
1311 }
1312 
1313 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1314 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1315 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1316                                                  IdentifierInfo *UDSuffix,
1317                                                  SourceLocation UDSuffixLoc,
1318                                                  ArrayRef<Expr*> Args,
1319                                                  SourceLocation LitEndLoc) {
1320   assert(Args.size() <= 2 && "too many arguments for literal operator");
1321 
1322   QualType ArgTy[2];
1323   for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1324     ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1325     if (ArgTy[ArgIdx]->isArrayType())
1326       ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1327   }
1328 
1329   DeclarationName OpName =
1330     S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1331   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1332   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1333 
1334   LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1335   if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1336                               /*AllowRawAndTemplate*/false) == Sema::LOLR_Error)
1337     return ExprError();
1338 
1339   return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1340 }
1341 
1342 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1343 /// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
1344 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1345 /// multiple tokens.  However, the common case is that StringToks points to one
1346 /// string.
1347 ///
1348 ExprResult
1349 Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks,
1350                          Scope *UDLScope) {
1351   assert(NumStringToks && "Must have at least one string!");
1352 
1353   StringLiteralParser Literal(StringToks, NumStringToks, PP);
1354   if (Literal.hadError)
1355     return ExprError();
1356 
1357   SmallVector<SourceLocation, 4> StringTokLocs;
1358   for (unsigned i = 0; i != NumStringToks; ++i)
1359     StringTokLocs.push_back(StringToks[i].getLocation());
1360 
1361   QualType StrTy = Context.CharTy;
1362   if (Literal.isWide())
1363     StrTy = Context.getWCharType();
1364   else if (Literal.isUTF16())
1365     StrTy = Context.Char16Ty;
1366   else if (Literal.isUTF32())
1367     StrTy = Context.Char32Ty;
1368   else if (Literal.isPascal())
1369     StrTy = Context.UnsignedCharTy;
1370 
1371   StringLiteral::StringKind Kind = StringLiteral::Ascii;
1372   if (Literal.isWide())
1373     Kind = StringLiteral::Wide;
1374   else if (Literal.isUTF8())
1375     Kind = StringLiteral::UTF8;
1376   else if (Literal.isUTF16())
1377     Kind = StringLiteral::UTF16;
1378   else if (Literal.isUTF32())
1379     Kind = StringLiteral::UTF32;
1380 
1381   // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
1382   if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
1383     StrTy.addConst();
1384 
1385   // Get an array type for the string, according to C99 6.4.5.  This includes
1386   // the nul terminator character as well as the string length for pascal
1387   // strings.
1388   StrTy = Context.getConstantArrayType(StrTy,
1389                                  llvm::APInt(32, Literal.GetNumStringChars()+1),
1390                                        ArrayType::Normal, 0);
1391 
1392   // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1393   StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1394                                              Kind, Literal.Pascal, StrTy,
1395                                              &StringTokLocs[0],
1396                                              StringTokLocs.size());
1397   if (Literal.getUDSuffix().empty())
1398     return Owned(Lit);
1399 
1400   // We're building a user-defined literal.
1401   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1402   SourceLocation UDSuffixLoc =
1403     getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1404                    Literal.getUDSuffixOffset());
1405 
1406   // Make sure we're allowed user-defined literals here.
1407   if (!UDLScope)
1408     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1409 
1410   // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1411   //   operator "" X (str, len)
1412   QualType SizeType = Context.getSizeType();
1413   llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1414   IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1415                                                   StringTokLocs[0]);
1416   Expr *Args[] = { Lit, LenArg };
1417   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
1418                                         Args, StringTokLocs.back());
1419 }
1420 
1421 ExprResult
1422 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1423                        SourceLocation Loc,
1424                        const CXXScopeSpec *SS) {
1425   DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1426   return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1427 }
1428 
1429 /// BuildDeclRefExpr - Build an expression that references a
1430 /// declaration that does not require a closure capture.
1431 ExprResult
1432 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1433                        const DeclarationNameInfo &NameInfo,
1434                        const CXXScopeSpec *SS) {
1435   if (getLangOpts().CUDA)
1436     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
1437       if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) {
1438         CUDAFunctionTarget CallerTarget = IdentifyCUDATarget(Caller),
1439                            CalleeTarget = IdentifyCUDATarget(Callee);
1440         if (CheckCUDATarget(CallerTarget, CalleeTarget)) {
1441           Diag(NameInfo.getLoc(), diag::err_ref_bad_target)
1442             << CalleeTarget << D->getIdentifier() << CallerTarget;
1443           Diag(D->getLocation(), diag::note_previous_decl)
1444             << D->getIdentifier();
1445           return ExprError();
1446         }
1447       }
1448 
1449   bool refersToEnclosingScope =
1450     (CurContext != D->getDeclContext() &&
1451      D->getDeclContext()->isFunctionOrMethod());
1452 
1453   DeclRefExpr *E = DeclRefExpr::Create(Context,
1454                                        SS ? SS->getWithLocInContext(Context)
1455                                               : NestedNameSpecifierLoc(),
1456                                        SourceLocation(),
1457                                        D, refersToEnclosingScope,
1458                                        NameInfo, Ty, VK);
1459 
1460   MarkDeclRefReferenced(E);
1461 
1462   if (getLangOpts().ObjCARCWeak && isa<VarDecl>(D) &&
1463       Ty.getObjCLifetime() == Qualifiers::OCL_Weak) {
1464     DiagnosticsEngine::Level Level =
1465       Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
1466                                E->getLocStart());
1467     if (Level != DiagnosticsEngine::Ignored)
1468       getCurFunction()->recordUseOfWeak(E);
1469   }
1470 
1471   // Just in case we're building an illegal pointer-to-member.
1472   FieldDecl *FD = dyn_cast<FieldDecl>(D);
1473   if (FD && FD->isBitField())
1474     E->setObjectKind(OK_BitField);
1475 
1476   return Owned(E);
1477 }
1478 
1479 /// Decomposes the given name into a DeclarationNameInfo, its location, and
1480 /// possibly a list of template arguments.
1481 ///
1482 /// If this produces template arguments, it is permitted to call
1483 /// DecomposeTemplateName.
1484 ///
1485 /// This actually loses a lot of source location information for
1486 /// non-standard name kinds; we should consider preserving that in
1487 /// some way.
1488 void
1489 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1490                              TemplateArgumentListInfo &Buffer,
1491                              DeclarationNameInfo &NameInfo,
1492                              const TemplateArgumentListInfo *&TemplateArgs) {
1493   if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1494     Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1495     Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1496 
1497     ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
1498                                        Id.TemplateId->NumArgs);
1499     translateTemplateArguments(TemplateArgsPtr, Buffer);
1500 
1501     TemplateName TName = Id.TemplateId->Template.get();
1502     SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1503     NameInfo = Context.getNameForTemplate(TName, TNameLoc);
1504     TemplateArgs = &Buffer;
1505   } else {
1506     NameInfo = GetNameFromUnqualifiedId(Id);
1507     TemplateArgs = 0;
1508   }
1509 }
1510 
1511 /// Diagnose an empty lookup.
1512 ///
1513 /// \return false if new lookup candidates were found
1514 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1515                                CorrectionCandidateCallback &CCC,
1516                                TemplateArgumentListInfo *ExplicitTemplateArgs,
1517                                llvm::ArrayRef<Expr *> Args) {
1518   DeclarationName Name = R.getLookupName();
1519 
1520   unsigned diagnostic = diag::err_undeclared_var_use;
1521   unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
1522   if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1523       Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
1524       Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
1525     diagnostic = diag::err_undeclared_use;
1526     diagnostic_suggest = diag::err_undeclared_use_suggest;
1527   }
1528 
1529   // If the original lookup was an unqualified lookup, fake an
1530   // unqualified lookup.  This is useful when (for example) the
1531   // original lookup would not have found something because it was a
1532   // dependent name.
1533   DeclContext *DC = (SS.isEmpty() && !CallsUndergoingInstantiation.empty())
1534     ? CurContext : 0;
1535   while (DC) {
1536     if (isa<CXXRecordDecl>(DC)) {
1537       LookupQualifiedName(R, DC);
1538 
1539       if (!R.empty()) {
1540         // Don't give errors about ambiguities in this lookup.
1541         R.suppressDiagnostics();
1542 
1543         // During a default argument instantiation the CurContext points
1544         // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1545         // function parameter list, hence add an explicit check.
1546         bool isDefaultArgument = !ActiveTemplateInstantiations.empty() &&
1547                               ActiveTemplateInstantiations.back().Kind ==
1548             ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
1549         CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1550         bool isInstance = CurMethod &&
1551                           CurMethod->isInstance() &&
1552                           DC == CurMethod->getParent() && !isDefaultArgument;
1553 
1554 
1555         // Give a code modification hint to insert 'this->'.
1556         // TODO: fixit for inserting 'Base<T>::' in the other cases.
1557         // Actually quite difficult!
1558         if (getLangOpts().MicrosoftMode)
1559           diagnostic = diag::warn_found_via_dependent_bases_lookup;
1560         if (isInstance) {
1561           Diag(R.getNameLoc(), diagnostic) << Name
1562             << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1563           UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1564               CallsUndergoingInstantiation.back()->getCallee());
1565 
1566 
1567           CXXMethodDecl *DepMethod;
1568           if (CurMethod->getTemplatedKind() ==
1569               FunctionDecl::TK_FunctionTemplateSpecialization)
1570             DepMethod = cast<CXXMethodDecl>(CurMethod->getPrimaryTemplate()->
1571                 getInstantiatedFromMemberTemplate()->getTemplatedDecl());
1572           else
1573             DepMethod = cast<CXXMethodDecl>(
1574                 CurMethod->getInstantiatedFromMemberFunction());
1575           assert(DepMethod && "No template pattern found");
1576 
1577           QualType DepThisType = DepMethod->getThisType(Context);
1578           CheckCXXThisCapture(R.getNameLoc());
1579           CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1580                                      R.getNameLoc(), DepThisType, false);
1581           TemplateArgumentListInfo TList;
1582           if (ULE->hasExplicitTemplateArgs())
1583             ULE->copyTemplateArgumentsInto(TList);
1584 
1585           CXXScopeSpec SS;
1586           SS.Adopt(ULE->getQualifierLoc());
1587           CXXDependentScopeMemberExpr *DepExpr =
1588               CXXDependentScopeMemberExpr::Create(
1589                   Context, DepThis, DepThisType, true, SourceLocation(),
1590                   SS.getWithLocInContext(Context),
1591                   ULE->getTemplateKeywordLoc(), 0,
1592                   R.getLookupNameInfo(),
1593                   ULE->hasExplicitTemplateArgs() ? &TList : 0);
1594           CallsUndergoingInstantiation.back()->setCallee(DepExpr);
1595         } else {
1596           Diag(R.getNameLoc(), diagnostic) << Name;
1597         }
1598 
1599         // Do we really want to note all of these?
1600         for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1601           Diag((*I)->getLocation(), diag::note_dependent_var_use);
1602 
1603         // Return true if we are inside a default argument instantiation
1604         // and the found name refers to an instance member function, otherwise
1605         // the function calling DiagnoseEmptyLookup will try to create an
1606         // implicit member call and this is wrong for default argument.
1607         if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1608           Diag(R.getNameLoc(), diag::err_member_call_without_object);
1609           return true;
1610         }
1611 
1612         // Tell the callee to try to recover.
1613         return false;
1614       }
1615 
1616       R.clear();
1617     }
1618 
1619     // In Microsoft mode, if we are performing lookup from within a friend
1620     // function definition declared at class scope then we must set
1621     // DC to the lexical parent to be able to search into the parent
1622     // class.
1623     if (getLangOpts().MicrosoftMode && isa<FunctionDecl>(DC) &&
1624         cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1625         DC->getLexicalParent()->isRecord())
1626       DC = DC->getLexicalParent();
1627     else
1628       DC = DC->getParent();
1629   }
1630 
1631   // We didn't find anything, so try to correct for a typo.
1632   TypoCorrection Corrected;
1633   if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
1634                                     S, &SS, CCC))) {
1635     std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1636     std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOpts()));
1637     R.setLookupName(Corrected.getCorrection());
1638 
1639     if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
1640       if (Corrected.isOverloaded()) {
1641         OverloadCandidateSet OCS(R.getNameLoc());
1642         OverloadCandidateSet::iterator Best;
1643         for (TypoCorrection::decl_iterator CD = Corrected.begin(),
1644                                         CDEnd = Corrected.end();
1645              CD != CDEnd; ++CD) {
1646           if (FunctionTemplateDecl *FTD =
1647                    dyn_cast<FunctionTemplateDecl>(*CD))
1648             AddTemplateOverloadCandidate(
1649                 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
1650                 Args, OCS);
1651           else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
1652             if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1653               AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
1654                                    Args, OCS);
1655         }
1656         switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1657           case OR_Success:
1658             ND = Best->Function;
1659             break;
1660           default:
1661             break;
1662         }
1663       }
1664       R.addDecl(ND);
1665       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
1666         if (SS.isEmpty())
1667           Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr
1668             << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1669         else
1670           Diag(R.getNameLoc(), diag::err_no_member_suggest)
1671             << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
1672             << SS.getRange()
1673             << FixItHint::CreateReplacement(Corrected.getCorrectionRange(),
1674                                             CorrectedStr);
1675 
1676         unsigned diag = isa<ImplicitParamDecl>(ND)
1677           ? diag::note_implicit_param_decl
1678           : diag::note_previous_decl;
1679 
1680         Diag(ND->getLocation(), diag)
1681           << CorrectedQuotedStr;
1682 
1683         // Tell the callee to try to recover.
1684         return false;
1685       }
1686 
1687       if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) {
1688         // FIXME: If we ended up with a typo for a type name or
1689         // Objective-C class name, we're in trouble because the parser
1690         // is in the wrong place to recover. Suggest the typo
1691         // correction, but don't make it a fix-it since we're not going
1692         // to recover well anyway.
1693         if (SS.isEmpty())
1694           Diag(R.getNameLoc(), diagnostic_suggest)
1695             << Name << CorrectedQuotedStr;
1696         else
1697           Diag(R.getNameLoc(), diag::err_no_member_suggest)
1698             << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
1699             << SS.getRange();
1700 
1701         // Don't try to recover; it won't work.
1702         return true;
1703       }
1704     } else {
1705       // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
1706       // because we aren't able to recover.
1707       if (SS.isEmpty())
1708         Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr;
1709       else
1710         Diag(R.getNameLoc(), diag::err_no_member_suggest)
1711         << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
1712         << SS.getRange();
1713       return true;
1714     }
1715   }
1716   R.clear();
1717 
1718   // Emit a special diagnostic for failed member lookups.
1719   // FIXME: computing the declaration context might fail here (?)
1720   if (!SS.isEmpty()) {
1721     Diag(R.getNameLoc(), diag::err_no_member)
1722       << Name << computeDeclContext(SS, false)
1723       << SS.getRange();
1724     return true;
1725   }
1726 
1727   // Give up, we can't recover.
1728   Diag(R.getNameLoc(), diagnostic) << Name;
1729   return true;
1730 }
1731 
1732 ExprResult Sema::ActOnIdExpression(Scope *S,
1733                                    CXXScopeSpec &SS,
1734                                    SourceLocation TemplateKWLoc,
1735                                    UnqualifiedId &Id,
1736                                    bool HasTrailingLParen,
1737                                    bool IsAddressOfOperand,
1738                                    CorrectionCandidateCallback *CCC) {
1739   assert(!(IsAddressOfOperand && HasTrailingLParen) &&
1740          "cannot be direct & operand and have a trailing lparen");
1741 
1742   if (SS.isInvalid())
1743     return ExprError();
1744 
1745   TemplateArgumentListInfo TemplateArgsBuffer;
1746 
1747   // Decompose the UnqualifiedId into the following data.
1748   DeclarationNameInfo NameInfo;
1749   const TemplateArgumentListInfo *TemplateArgs;
1750   DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
1751 
1752   DeclarationName Name = NameInfo.getName();
1753   IdentifierInfo *II = Name.getAsIdentifierInfo();
1754   SourceLocation NameLoc = NameInfo.getLoc();
1755 
1756   // C++ [temp.dep.expr]p3:
1757   //   An id-expression is type-dependent if it contains:
1758   //     -- an identifier that was declared with a dependent type,
1759   //        (note: handled after lookup)
1760   //     -- a template-id that is dependent,
1761   //        (note: handled in BuildTemplateIdExpr)
1762   //     -- a conversion-function-id that specifies a dependent type,
1763   //     -- a nested-name-specifier that contains a class-name that
1764   //        names a dependent type.
1765   // Determine whether this is a member of an unknown specialization;
1766   // we need to handle these differently.
1767   bool DependentID = false;
1768   if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1769       Name.getCXXNameType()->isDependentType()) {
1770     DependentID = true;
1771   } else if (SS.isSet()) {
1772     if (DeclContext *DC = computeDeclContext(SS, false)) {
1773       if (RequireCompleteDeclContext(SS, DC))
1774         return ExprError();
1775     } else {
1776       DependentID = true;
1777     }
1778   }
1779 
1780   if (DependentID)
1781     return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1782                                       IsAddressOfOperand, TemplateArgs);
1783 
1784   // Perform the required lookup.
1785   LookupResult R(*this, NameInfo,
1786                  (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
1787                   ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
1788   if (TemplateArgs) {
1789     // Lookup the template name again to correctly establish the context in
1790     // which it was found. This is really unfortunate as we already did the
1791     // lookup to determine that it was a template name in the first place. If
1792     // this becomes a performance hit, we can work harder to preserve those
1793     // results until we get here but it's likely not worth it.
1794     bool MemberOfUnknownSpecialization;
1795     LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1796                        MemberOfUnknownSpecialization);
1797 
1798     if (MemberOfUnknownSpecialization ||
1799         (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
1800       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1801                                         IsAddressOfOperand, TemplateArgs);
1802   } else {
1803     bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
1804     LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
1805 
1806     // If the result might be in a dependent base class, this is a dependent
1807     // id-expression.
1808     if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
1809       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1810                                         IsAddressOfOperand, TemplateArgs);
1811 
1812     // If this reference is in an Objective-C method, then we need to do
1813     // some special Objective-C lookup, too.
1814     if (IvarLookupFollowUp) {
1815       ExprResult E(LookupInObjCMethod(R, S, II, true));
1816       if (E.isInvalid())
1817         return ExprError();
1818 
1819       if (Expr *Ex = E.takeAs<Expr>())
1820         return Owned(Ex);
1821     }
1822   }
1823 
1824   if (R.isAmbiguous())
1825     return ExprError();
1826 
1827   // Determine whether this name might be a candidate for
1828   // argument-dependent lookup.
1829   bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
1830 
1831   if (R.empty() && !ADL) {
1832     // Otherwise, this could be an implicitly declared function reference (legal
1833     // in C90, extension in C99, forbidden in C++).
1834     if (HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
1835       NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1836       if (D) R.addDecl(D);
1837     }
1838 
1839     // If this name wasn't predeclared and if this is not a function
1840     // call, diagnose the problem.
1841     if (R.empty()) {
1842 
1843       // In Microsoft mode, if we are inside a template class member function
1844       // and we can't resolve an identifier then assume the identifier is type
1845       // dependent. The goal is to postpone name lookup to instantiation time
1846       // to be able to search into type dependent base classes.
1847       if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
1848           isa<CXXMethodDecl>(CurContext))
1849         return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1850                                           IsAddressOfOperand, TemplateArgs);
1851 
1852       CorrectionCandidateCallback DefaultValidator;
1853       if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator))
1854         return ExprError();
1855 
1856       assert(!R.empty() &&
1857              "DiagnoseEmptyLookup returned false but added no results");
1858 
1859       // If we found an Objective-C instance variable, let
1860       // LookupInObjCMethod build the appropriate expression to
1861       // reference the ivar.
1862       if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1863         R.clear();
1864         ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
1865         // In a hopelessly buggy code, Objective-C instance variable
1866         // lookup fails and no expression will be built to reference it.
1867         if (!E.isInvalid() && !E.get())
1868           return ExprError();
1869         return E;
1870       }
1871     }
1872   }
1873 
1874   // This is guaranteed from this point on.
1875   assert(!R.empty() || ADL);
1876 
1877   // Check whether this might be a C++ implicit instance member access.
1878   // C++ [class.mfct.non-static]p3:
1879   //   When an id-expression that is not part of a class member access
1880   //   syntax and not used to form a pointer to member is used in the
1881   //   body of a non-static member function of class X, if name lookup
1882   //   resolves the name in the id-expression to a non-static non-type
1883   //   member of some class C, the id-expression is transformed into a
1884   //   class member access expression using (*this) as the
1885   //   postfix-expression to the left of the . operator.
1886   //
1887   // But we don't actually need to do this for '&' operands if R
1888   // resolved to a function or overloaded function set, because the
1889   // expression is ill-formed if it actually works out to be a
1890   // non-static member function:
1891   //
1892   // C++ [expr.ref]p4:
1893   //   Otherwise, if E1.E2 refers to a non-static member function. . .
1894   //   [t]he expression can be used only as the left-hand operand of a
1895   //   member function call.
1896   //
1897   // There are other safeguards against such uses, but it's important
1898   // to get this right here so that we don't end up making a
1899   // spuriously dependent expression if we're inside a dependent
1900   // instance method.
1901   if (!R.empty() && (*R.begin())->isCXXClassMember()) {
1902     bool MightBeImplicitMember;
1903     if (!IsAddressOfOperand)
1904       MightBeImplicitMember = true;
1905     else if (!SS.isEmpty())
1906       MightBeImplicitMember = false;
1907     else if (R.isOverloadedResult())
1908       MightBeImplicitMember = false;
1909     else if (R.isUnresolvableResult())
1910       MightBeImplicitMember = true;
1911     else
1912       MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
1913                               isa<IndirectFieldDecl>(R.getFoundDecl());
1914 
1915     if (MightBeImplicitMember)
1916       return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
1917                                              R, TemplateArgs);
1918   }
1919 
1920   if (TemplateArgs || TemplateKWLoc.isValid())
1921     return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
1922 
1923   return BuildDeclarationNameExpr(SS, R, ADL);
1924 }
1925 
1926 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1927 /// declaration name, generally during template instantiation.
1928 /// There's a large number of things which don't need to be done along
1929 /// this path.
1930 ExprResult
1931 Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
1932                                         const DeclarationNameInfo &NameInfo,
1933                                         bool IsAddressOfOperand) {
1934   DeclContext *DC = computeDeclContext(SS, false);
1935   if (!DC)
1936     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
1937                                      NameInfo, /*TemplateArgs=*/0);
1938 
1939   if (RequireCompleteDeclContext(SS, DC))
1940     return ExprError();
1941 
1942   LookupResult R(*this, NameInfo, LookupOrdinaryName);
1943   LookupQualifiedName(R, DC);
1944 
1945   if (R.isAmbiguous())
1946     return ExprError();
1947 
1948   if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
1949     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
1950                                      NameInfo, /*TemplateArgs=*/0);
1951 
1952   if (R.empty()) {
1953     Diag(NameInfo.getLoc(), diag::err_no_member)
1954       << NameInfo.getName() << DC << SS.getRange();
1955     return ExprError();
1956   }
1957 
1958   // Defend against this resolving to an implicit member access. We usually
1959   // won't get here if this might be a legitimate a class member (we end up in
1960   // BuildMemberReferenceExpr instead), but this can be valid if we're forming
1961   // a pointer-to-member or in an unevaluated context in C++11.
1962   if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
1963     return BuildPossibleImplicitMemberExpr(SS,
1964                                            /*TemplateKWLoc=*/SourceLocation(),
1965                                            R, /*TemplateArgs=*/0);
1966 
1967   return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
1968 }
1969 
1970 /// LookupInObjCMethod - The parser has read a name in, and Sema has
1971 /// detected that we're currently inside an ObjC method.  Perform some
1972 /// additional lookup.
1973 ///
1974 /// Ideally, most of this would be done by lookup, but there's
1975 /// actually quite a lot of extra work involved.
1976 ///
1977 /// Returns a null sentinel to indicate trivial success.
1978 ExprResult
1979 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
1980                          IdentifierInfo *II, bool AllowBuiltinCreation) {
1981   SourceLocation Loc = Lookup.getNameLoc();
1982   ObjCMethodDecl *CurMethod = getCurMethodDecl();
1983 
1984   // Check for error condition which is already reported.
1985   if (!CurMethod)
1986     return ExprError();
1987 
1988   // There are two cases to handle here.  1) scoped lookup could have failed,
1989   // in which case we should look for an ivar.  2) scoped lookup could have
1990   // found a decl, but that decl is outside the current instance method (i.e.
1991   // a global variable).  In these two cases, we do a lookup for an ivar with
1992   // this name, if the lookup sucedes, we replace it our current decl.
1993 
1994   // If we're in a class method, we don't normally want to look for
1995   // ivars.  But if we don't find anything else, and there's an
1996   // ivar, that's an error.
1997   bool IsClassMethod = CurMethod->isClassMethod();
1998 
1999   bool LookForIvars;
2000   if (Lookup.empty())
2001     LookForIvars = true;
2002   else if (IsClassMethod)
2003     LookForIvars = false;
2004   else
2005     LookForIvars = (Lookup.isSingleResult() &&
2006                     Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2007   ObjCInterfaceDecl *IFace = 0;
2008   if (LookForIvars) {
2009     IFace = CurMethod->getClassInterface();
2010     ObjCInterfaceDecl *ClassDeclared;
2011     ObjCIvarDecl *IV = 0;
2012     if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2013       // Diagnose using an ivar in a class method.
2014       if (IsClassMethod)
2015         return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
2016                          << IV->getDeclName());
2017 
2018       // If we're referencing an invalid decl, just return this as a silent
2019       // error node.  The error diagnostic was already emitted on the decl.
2020       if (IV->isInvalidDecl())
2021         return ExprError();
2022 
2023       // Check if referencing a field with __attribute__((deprecated)).
2024       if (DiagnoseUseOfDecl(IV, Loc))
2025         return ExprError();
2026 
2027       // Diagnose the use of an ivar outside of the declaring class.
2028       if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2029           !declaresSameEntity(ClassDeclared, IFace) &&
2030           !getLangOpts().DebuggerSupport)
2031         Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
2032 
2033       // FIXME: This should use a new expr for a direct reference, don't
2034       // turn this into Self->ivar, just return a BareIVarExpr or something.
2035       IdentifierInfo &II = Context.Idents.get("self");
2036       UnqualifiedId SelfName;
2037       SelfName.setIdentifier(&II, SourceLocation());
2038       SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
2039       CXXScopeSpec SelfScopeSpec;
2040       SourceLocation TemplateKWLoc;
2041       ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
2042                                               SelfName, false, false);
2043       if (SelfExpr.isInvalid())
2044         return ExprError();
2045 
2046       SelfExpr = DefaultLvalueConversion(SelfExpr.take());
2047       if (SelfExpr.isInvalid())
2048         return ExprError();
2049 
2050       MarkAnyDeclReferenced(Loc, IV, true);
2051 
2052       ObjCMethodFamily MF = CurMethod->getMethodFamily();
2053       if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2054           !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2055         Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2056 
2057       ObjCIvarRefExpr *Result = new (Context) ObjCIvarRefExpr(IV, IV->getType(),
2058                                                               Loc,
2059                                                               SelfExpr.take(),
2060                                                               true, true);
2061 
2062       if (getLangOpts().ObjCAutoRefCount) {
2063         if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2064           DiagnosticsEngine::Level Level =
2065             Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, Loc);
2066           if (Level != DiagnosticsEngine::Ignored)
2067             getCurFunction()->recordUseOfWeak(Result);
2068         }
2069         if (CurContext->isClosure())
2070           Diag(Loc, diag::warn_implicitly_retains_self)
2071             << FixItHint::CreateInsertion(Loc, "self->");
2072       }
2073 
2074       return Owned(Result);
2075     }
2076   } else if (CurMethod->isInstanceMethod()) {
2077     // We should warn if a local variable hides an ivar.
2078     if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2079       ObjCInterfaceDecl *ClassDeclared;
2080       if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2081         if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2082             declaresSameEntity(IFace, ClassDeclared))
2083           Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2084       }
2085     }
2086   } else if (Lookup.isSingleResult() &&
2087              Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2088     // If accessing a stand-alone ivar in a class method, this is an error.
2089     if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
2090       return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
2091                        << IV->getDeclName());
2092   }
2093 
2094   if (Lookup.empty() && II && AllowBuiltinCreation) {
2095     // FIXME. Consolidate this with similar code in LookupName.
2096     if (unsigned BuiltinID = II->getBuiltinID()) {
2097       if (!(getLangOpts().CPlusPlus &&
2098             Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2099         NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2100                                            S, Lookup.isForRedeclaration(),
2101                                            Lookup.getNameLoc());
2102         if (D) Lookup.addDecl(D);
2103       }
2104     }
2105   }
2106   // Sentinel value saying that we didn't do anything special.
2107   return Owned((Expr*) 0);
2108 }
2109 
2110 /// \brief Cast a base object to a member's actual type.
2111 ///
2112 /// Logically this happens in three phases:
2113 ///
2114 /// * First we cast from the base type to the naming class.
2115 ///   The naming class is the class into which we were looking
2116 ///   when we found the member;  it's the qualifier type if a
2117 ///   qualifier was provided, and otherwise it's the base type.
2118 ///
2119 /// * Next we cast from the naming class to the declaring class.
2120 ///   If the member we found was brought into a class's scope by
2121 ///   a using declaration, this is that class;  otherwise it's
2122 ///   the class declaring the member.
2123 ///
2124 /// * Finally we cast from the declaring class to the "true"
2125 ///   declaring class of the member.  This conversion does not
2126 ///   obey access control.
2127 ExprResult
2128 Sema::PerformObjectMemberConversion(Expr *From,
2129                                     NestedNameSpecifier *Qualifier,
2130                                     NamedDecl *FoundDecl,
2131                                     NamedDecl *Member) {
2132   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2133   if (!RD)
2134     return Owned(From);
2135 
2136   QualType DestRecordType;
2137   QualType DestType;
2138   QualType FromRecordType;
2139   QualType FromType = From->getType();
2140   bool PointerConversions = false;
2141   if (isa<FieldDecl>(Member)) {
2142     DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2143 
2144     if (FromType->getAs<PointerType>()) {
2145       DestType = Context.getPointerType(DestRecordType);
2146       FromRecordType = FromType->getPointeeType();
2147       PointerConversions = true;
2148     } else {
2149       DestType = DestRecordType;
2150       FromRecordType = FromType;
2151     }
2152   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2153     if (Method->isStatic())
2154       return Owned(From);
2155 
2156     DestType = Method->getThisType(Context);
2157     DestRecordType = DestType->getPointeeType();
2158 
2159     if (FromType->getAs<PointerType>()) {
2160       FromRecordType = FromType->getPointeeType();
2161       PointerConversions = true;
2162     } else {
2163       FromRecordType = FromType;
2164       DestType = DestRecordType;
2165     }
2166   } else {
2167     // No conversion necessary.
2168     return Owned(From);
2169   }
2170 
2171   if (DestType->isDependentType() || FromType->isDependentType())
2172     return Owned(From);
2173 
2174   // If the unqualified types are the same, no conversion is necessary.
2175   if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2176     return Owned(From);
2177 
2178   SourceRange FromRange = From->getSourceRange();
2179   SourceLocation FromLoc = FromRange.getBegin();
2180 
2181   ExprValueKind VK = From->getValueKind();
2182 
2183   // C++ [class.member.lookup]p8:
2184   //   [...] Ambiguities can often be resolved by qualifying a name with its
2185   //   class name.
2186   //
2187   // If the member was a qualified name and the qualified referred to a
2188   // specific base subobject type, we'll cast to that intermediate type
2189   // first and then to the object in which the member is declared. That allows
2190   // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2191   //
2192   //   class Base { public: int x; };
2193   //   class Derived1 : public Base { };
2194   //   class Derived2 : public Base { };
2195   //   class VeryDerived : public Derived1, public Derived2 { void f(); };
2196   //
2197   //   void VeryDerived::f() {
2198   //     x = 17; // error: ambiguous base subobjects
2199   //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
2200   //   }
2201   if (Qualifier) {
2202     QualType QType = QualType(Qualifier->getAsType(), 0);
2203     assert(!QType.isNull() && "lookup done with dependent qualifier?");
2204     assert(QType->isRecordType() && "lookup done with non-record type");
2205 
2206     QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2207 
2208     // In C++98, the qualifier type doesn't actually have to be a base
2209     // type of the object type, in which case we just ignore it.
2210     // Otherwise build the appropriate casts.
2211     if (IsDerivedFrom(FromRecordType, QRecordType)) {
2212       CXXCastPath BasePath;
2213       if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2214                                        FromLoc, FromRange, &BasePath))
2215         return ExprError();
2216 
2217       if (PointerConversions)
2218         QType = Context.getPointerType(QType);
2219       From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2220                                VK, &BasePath).take();
2221 
2222       FromType = QType;
2223       FromRecordType = QRecordType;
2224 
2225       // If the qualifier type was the same as the destination type,
2226       // we're done.
2227       if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2228         return Owned(From);
2229     }
2230   }
2231 
2232   bool IgnoreAccess = false;
2233 
2234   // If we actually found the member through a using declaration, cast
2235   // down to the using declaration's type.
2236   //
2237   // Pointer equality is fine here because only one declaration of a
2238   // class ever has member declarations.
2239   if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2240     assert(isa<UsingShadowDecl>(FoundDecl));
2241     QualType URecordType = Context.getTypeDeclType(
2242                            cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2243 
2244     // We only need to do this if the naming-class to declaring-class
2245     // conversion is non-trivial.
2246     if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2247       assert(IsDerivedFrom(FromRecordType, URecordType));
2248       CXXCastPath BasePath;
2249       if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2250                                        FromLoc, FromRange, &BasePath))
2251         return ExprError();
2252 
2253       QualType UType = URecordType;
2254       if (PointerConversions)
2255         UType = Context.getPointerType(UType);
2256       From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2257                                VK, &BasePath).take();
2258       FromType = UType;
2259       FromRecordType = URecordType;
2260     }
2261 
2262     // We don't do access control for the conversion from the
2263     // declaring class to the true declaring class.
2264     IgnoreAccess = true;
2265   }
2266 
2267   CXXCastPath BasePath;
2268   if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2269                                    FromLoc, FromRange, &BasePath,
2270                                    IgnoreAccess))
2271     return ExprError();
2272 
2273   return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2274                            VK, &BasePath);
2275 }
2276 
2277 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2278                                       const LookupResult &R,
2279                                       bool HasTrailingLParen) {
2280   // Only when used directly as the postfix-expression of a call.
2281   if (!HasTrailingLParen)
2282     return false;
2283 
2284   // Never if a scope specifier was provided.
2285   if (SS.isSet())
2286     return false;
2287 
2288   // Only in C++ or ObjC++.
2289   if (!getLangOpts().CPlusPlus)
2290     return false;
2291 
2292   // Turn off ADL when we find certain kinds of declarations during
2293   // normal lookup:
2294   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2295     NamedDecl *D = *I;
2296 
2297     // C++0x [basic.lookup.argdep]p3:
2298     //     -- a declaration of a class member
2299     // Since using decls preserve this property, we check this on the
2300     // original decl.
2301     if (D->isCXXClassMember())
2302       return false;
2303 
2304     // C++0x [basic.lookup.argdep]p3:
2305     //     -- a block-scope function declaration that is not a
2306     //        using-declaration
2307     // NOTE: we also trigger this for function templates (in fact, we
2308     // don't check the decl type at all, since all other decl types
2309     // turn off ADL anyway).
2310     if (isa<UsingShadowDecl>(D))
2311       D = cast<UsingShadowDecl>(D)->getTargetDecl();
2312     else if (D->getDeclContext()->isFunctionOrMethod())
2313       return false;
2314 
2315     // C++0x [basic.lookup.argdep]p3:
2316     //     -- a declaration that is neither a function or a function
2317     //        template
2318     // And also for builtin functions.
2319     if (isa<FunctionDecl>(D)) {
2320       FunctionDecl *FDecl = cast<FunctionDecl>(D);
2321 
2322       // But also builtin functions.
2323       if (FDecl->getBuiltinID() && FDecl->isImplicit())
2324         return false;
2325     } else if (!isa<FunctionTemplateDecl>(D))
2326       return false;
2327   }
2328 
2329   return true;
2330 }
2331 
2332 
2333 /// Diagnoses obvious problems with the use of the given declaration
2334 /// as an expression.  This is only actually called for lookups that
2335 /// were not overloaded, and it doesn't promise that the declaration
2336 /// will in fact be used.
2337 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2338   if (isa<TypedefNameDecl>(D)) {
2339     S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2340     return true;
2341   }
2342 
2343   if (isa<ObjCInterfaceDecl>(D)) {
2344     S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2345     return true;
2346   }
2347 
2348   if (isa<NamespaceDecl>(D)) {
2349     S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2350     return true;
2351   }
2352 
2353   return false;
2354 }
2355 
2356 ExprResult
2357 Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2358                                LookupResult &R,
2359                                bool NeedsADL) {
2360   // If this is a single, fully-resolved result and we don't need ADL,
2361   // just build an ordinary singleton decl ref.
2362   if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
2363     return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
2364                                     R.getFoundDecl());
2365 
2366   // We only need to check the declaration if there's exactly one
2367   // result, because in the overloaded case the results can only be
2368   // functions and function templates.
2369   if (R.isSingleResult() &&
2370       CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
2371     return ExprError();
2372 
2373   // Otherwise, just build an unresolved lookup expression.  Suppress
2374   // any lookup-related diagnostics; we'll hash these out later, when
2375   // we've picked a target.
2376   R.suppressDiagnostics();
2377 
2378   UnresolvedLookupExpr *ULE
2379     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2380                                    SS.getWithLocInContext(Context),
2381                                    R.getLookupNameInfo(),
2382                                    NeedsADL, R.isOverloadedResult(),
2383                                    R.begin(), R.end());
2384 
2385   return Owned(ULE);
2386 }
2387 
2388 /// \brief Complete semantic analysis for a reference to the given declaration.
2389 ExprResult
2390 Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2391                                const DeclarationNameInfo &NameInfo,
2392                                NamedDecl *D) {
2393   assert(D && "Cannot refer to a NULL declaration");
2394   assert(!isa<FunctionTemplateDecl>(D) &&
2395          "Cannot refer unambiguously to a function template");
2396 
2397   SourceLocation Loc = NameInfo.getLoc();
2398   if (CheckDeclInExpr(*this, Loc, D))
2399     return ExprError();
2400 
2401   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2402     // Specifically diagnose references to class templates that are missing
2403     // a template argument list.
2404     Diag(Loc, diag::err_template_decl_ref)
2405       << Template << SS.getRange();
2406     Diag(Template->getLocation(), diag::note_template_decl_here);
2407     return ExprError();
2408   }
2409 
2410   // Make sure that we're referring to a value.
2411   ValueDecl *VD = dyn_cast<ValueDecl>(D);
2412   if (!VD) {
2413     Diag(Loc, diag::err_ref_non_value)
2414       << D << SS.getRange();
2415     Diag(D->getLocation(), diag::note_declared_at);
2416     return ExprError();
2417   }
2418 
2419   // Check whether this declaration can be used. Note that we suppress
2420   // this check when we're going to perform argument-dependent lookup
2421   // on this function name, because this might not be the function
2422   // that overload resolution actually selects.
2423   if (DiagnoseUseOfDecl(VD, Loc))
2424     return ExprError();
2425 
2426   // Only create DeclRefExpr's for valid Decl's.
2427   if (VD->isInvalidDecl())
2428     return ExprError();
2429 
2430   // Handle members of anonymous structs and unions.  If we got here,
2431   // and the reference is to a class member indirect field, then this
2432   // must be the subject of a pointer-to-member expression.
2433   if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2434     if (!indirectField->isCXXClassMember())
2435       return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2436                                                       indirectField);
2437 
2438   {
2439     QualType type = VD->getType();
2440     ExprValueKind valueKind = VK_RValue;
2441 
2442     switch (D->getKind()) {
2443     // Ignore all the non-ValueDecl kinds.
2444 #define ABSTRACT_DECL(kind)
2445 #define VALUE(type, base)
2446 #define DECL(type, base) \
2447     case Decl::type:
2448 #include "clang/AST/DeclNodes.inc"
2449       llvm_unreachable("invalid value decl kind");
2450 
2451     // These shouldn't make it here.
2452     case Decl::ObjCAtDefsField:
2453     case Decl::ObjCIvar:
2454       llvm_unreachable("forming non-member reference to ivar?");
2455 
2456     // Enum constants are always r-values and never references.
2457     // Unresolved using declarations are dependent.
2458     case Decl::EnumConstant:
2459     case Decl::UnresolvedUsingValue:
2460       valueKind = VK_RValue;
2461       break;
2462 
2463     // Fields and indirect fields that got here must be for
2464     // pointer-to-member expressions; we just call them l-values for
2465     // internal consistency, because this subexpression doesn't really
2466     // exist in the high-level semantics.
2467     case Decl::Field:
2468     case Decl::IndirectField:
2469       assert(getLangOpts().CPlusPlus &&
2470              "building reference to field in C?");
2471 
2472       // These can't have reference type in well-formed programs, but
2473       // for internal consistency we do this anyway.
2474       type = type.getNonReferenceType();
2475       valueKind = VK_LValue;
2476       break;
2477 
2478     // Non-type template parameters are either l-values or r-values
2479     // depending on the type.
2480     case Decl::NonTypeTemplateParm: {
2481       if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2482         type = reftype->getPointeeType();
2483         valueKind = VK_LValue; // even if the parameter is an r-value reference
2484         break;
2485       }
2486 
2487       // For non-references, we need to strip qualifiers just in case
2488       // the template parameter was declared as 'const int' or whatever.
2489       valueKind = VK_RValue;
2490       type = type.getUnqualifiedType();
2491       break;
2492     }
2493 
2494     case Decl::Var:
2495       // In C, "extern void blah;" is valid and is an r-value.
2496       if (!getLangOpts().CPlusPlus &&
2497           !type.hasQualifiers() &&
2498           type->isVoidType()) {
2499         valueKind = VK_RValue;
2500         break;
2501       }
2502       // fallthrough
2503 
2504     case Decl::ImplicitParam:
2505     case Decl::ParmVar: {
2506       // These are always l-values.
2507       valueKind = VK_LValue;
2508       type = type.getNonReferenceType();
2509 
2510       // FIXME: Does the addition of const really only apply in
2511       // potentially-evaluated contexts? Since the variable isn't actually
2512       // captured in an unevaluated context, it seems that the answer is no.
2513       if (!isUnevaluatedContext()) {
2514         QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
2515         if (!CapturedType.isNull())
2516           type = CapturedType;
2517       }
2518 
2519       break;
2520     }
2521 
2522     case Decl::Function: {
2523       if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
2524         if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
2525           type = Context.BuiltinFnTy;
2526           valueKind = VK_RValue;
2527           break;
2528         }
2529       }
2530 
2531       const FunctionType *fty = type->castAs<FunctionType>();
2532 
2533       // If we're referring to a function with an __unknown_anytype
2534       // result type, make the entire expression __unknown_anytype.
2535       if (fty->getResultType() == Context.UnknownAnyTy) {
2536         type = Context.UnknownAnyTy;
2537         valueKind = VK_RValue;
2538         break;
2539       }
2540 
2541       // Functions are l-values in C++.
2542       if (getLangOpts().CPlusPlus) {
2543         valueKind = VK_LValue;
2544         break;
2545       }
2546 
2547       // C99 DR 316 says that, if a function type comes from a
2548       // function definition (without a prototype), that type is only
2549       // used for checking compatibility. Therefore, when referencing
2550       // the function, we pretend that we don't have the full function
2551       // type.
2552       if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2553           isa<FunctionProtoType>(fty))
2554         type = Context.getFunctionNoProtoType(fty->getResultType(),
2555                                               fty->getExtInfo());
2556 
2557       // Functions are r-values in C.
2558       valueKind = VK_RValue;
2559       break;
2560     }
2561 
2562     case Decl::CXXMethod:
2563       // If we're referring to a method with an __unknown_anytype
2564       // result type, make the entire expression __unknown_anytype.
2565       // This should only be possible with a type written directly.
2566       if (const FunctionProtoType *proto
2567             = dyn_cast<FunctionProtoType>(VD->getType()))
2568         if (proto->getResultType() == Context.UnknownAnyTy) {
2569           type = Context.UnknownAnyTy;
2570           valueKind = VK_RValue;
2571           break;
2572         }
2573 
2574       // C++ methods are l-values if static, r-values if non-static.
2575       if (cast<CXXMethodDecl>(VD)->isStatic()) {
2576         valueKind = VK_LValue;
2577         break;
2578       }
2579       // fallthrough
2580 
2581     case Decl::CXXConversion:
2582     case Decl::CXXDestructor:
2583     case Decl::CXXConstructor:
2584       valueKind = VK_RValue;
2585       break;
2586     }
2587 
2588     return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS);
2589   }
2590 }
2591 
2592 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
2593   PredefinedExpr::IdentType IT;
2594 
2595   switch (Kind) {
2596   default: llvm_unreachable("Unknown simple primary expr!");
2597   case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2598   case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
2599   case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break;
2600   case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
2601   }
2602 
2603   // Pre-defined identifiers are of type char[x], where x is the length of the
2604   // string.
2605 
2606   Decl *currentDecl = getCurFunctionOrMethodDecl();
2607   // Blocks and lambdas can occur at global scope. Don't emit a warning.
2608   if (!currentDecl) {
2609     if (const BlockScopeInfo *BSI = getCurBlock())
2610       currentDecl = BSI->TheDecl;
2611     else if (const LambdaScopeInfo *LSI = getCurLambda())
2612       currentDecl = LSI->CallOperator;
2613   }
2614 
2615   if (!currentDecl) {
2616     Diag(Loc, diag::ext_predef_outside_function);
2617     currentDecl = Context.getTranslationUnitDecl();
2618   }
2619 
2620   QualType ResTy;
2621   if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2622     ResTy = Context.DependentTy;
2623   } else {
2624     unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
2625 
2626     llvm::APInt LengthI(32, Length + 1);
2627     if (IT == PredefinedExpr::LFunction)
2628       ResTy = Context.WCharTy.withConst();
2629     else
2630       ResTy = Context.CharTy.withConst();
2631     ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2632   }
2633   return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
2634 }
2635 
2636 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
2637   SmallString<16> CharBuffer;
2638   bool Invalid = false;
2639   StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
2640   if (Invalid)
2641     return ExprError();
2642 
2643   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
2644                             PP, Tok.getKind());
2645   if (Literal.hadError())
2646     return ExprError();
2647 
2648   QualType Ty;
2649   if (Literal.isWide())
2650     Ty = Context.WCharTy; // L'x' -> wchar_t in C and C++.
2651   else if (Literal.isUTF16())
2652     Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
2653   else if (Literal.isUTF32())
2654     Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
2655   else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
2656     Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
2657   else
2658     Ty = Context.CharTy;  // 'x' -> char in C++
2659 
2660   CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
2661   if (Literal.isWide())
2662     Kind = CharacterLiteral::Wide;
2663   else if (Literal.isUTF16())
2664     Kind = CharacterLiteral::UTF16;
2665   else if (Literal.isUTF32())
2666     Kind = CharacterLiteral::UTF32;
2667 
2668   Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
2669                                              Tok.getLocation());
2670 
2671   if (Literal.getUDSuffix().empty())
2672     return Owned(Lit);
2673 
2674   // We're building a user-defined literal.
2675   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2676   SourceLocation UDSuffixLoc =
2677     getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
2678 
2679   // Make sure we're allowed user-defined literals here.
2680   if (!UDLScope)
2681     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
2682 
2683   // C++11 [lex.ext]p6: The literal L is treated as a call of the form
2684   //   operator "" X (ch)
2685   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
2686                                         llvm::makeArrayRef(&Lit, 1),
2687                                         Tok.getLocation());
2688 }
2689 
2690 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
2691   unsigned IntSize = Context.getTargetInfo().getIntWidth();
2692   return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
2693                                       Context.IntTy, Loc));
2694 }
2695 
2696 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
2697                                   QualType Ty, SourceLocation Loc) {
2698   const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
2699 
2700   using llvm::APFloat;
2701   APFloat Val(Format);
2702 
2703   APFloat::opStatus result = Literal.GetFloatValue(Val);
2704 
2705   // Overflow is always an error, but underflow is only an error if
2706   // we underflowed to zero (APFloat reports denormals as underflow).
2707   if ((result & APFloat::opOverflow) ||
2708       ((result & APFloat::opUnderflow) && Val.isZero())) {
2709     unsigned diagnostic;
2710     SmallString<20> buffer;
2711     if (result & APFloat::opOverflow) {
2712       diagnostic = diag::warn_float_overflow;
2713       APFloat::getLargest(Format).toString(buffer);
2714     } else {
2715       diagnostic = diag::warn_float_underflow;
2716       APFloat::getSmallest(Format).toString(buffer);
2717     }
2718 
2719     S.Diag(Loc, diagnostic)
2720       << Ty
2721       << StringRef(buffer.data(), buffer.size());
2722   }
2723 
2724   bool isExact = (result == APFloat::opOK);
2725   return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
2726 }
2727 
2728 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
2729   // Fast path for a single digit (which is quite common).  A single digit
2730   // cannot have a trigraph, escaped newline, radix prefix, or suffix.
2731   if (Tok.getLength() == 1) {
2732     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
2733     return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
2734   }
2735 
2736   SmallString<128> SpellingBuffer;
2737   // NumericLiteralParser wants to overread by one character.  Add padding to
2738   // the buffer in case the token is copied to the buffer.  If getSpelling()
2739   // returns a StringRef to the memory buffer, it should have a null char at
2740   // the EOF, so it is also safe.
2741   SpellingBuffer.resize(Tok.getLength() + 1);
2742 
2743   // Get the spelling of the token, which eliminates trigraphs, etc.
2744   bool Invalid = false;
2745   StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
2746   if (Invalid)
2747     return ExprError();
2748 
2749   NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
2750   if (Literal.hadError)
2751     return ExprError();
2752 
2753   if (Literal.hasUDSuffix()) {
2754     // We're building a user-defined literal.
2755     IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2756     SourceLocation UDSuffixLoc =
2757       getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
2758 
2759     // Make sure we're allowed user-defined literals here.
2760     if (!UDLScope)
2761       return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
2762 
2763     QualType CookedTy;
2764     if (Literal.isFloatingLiteral()) {
2765       // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
2766       // long double, the literal is treated as a call of the form
2767       //   operator "" X (f L)
2768       CookedTy = Context.LongDoubleTy;
2769     } else {
2770       // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
2771       // unsigned long long, the literal is treated as a call of the form
2772       //   operator "" X (n ULL)
2773       CookedTy = Context.UnsignedLongLongTy;
2774     }
2775 
2776     DeclarationName OpName =
2777       Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
2778     DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
2779     OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
2780 
2781     // Perform literal operator lookup to determine if we're building a raw
2782     // literal or a cooked one.
2783     LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
2784     switch (LookupLiteralOperator(UDLScope, R, llvm::makeArrayRef(&CookedTy, 1),
2785                                   /*AllowRawAndTemplate*/true)) {
2786     case LOLR_Error:
2787       return ExprError();
2788 
2789     case LOLR_Cooked: {
2790       Expr *Lit;
2791       if (Literal.isFloatingLiteral()) {
2792         Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
2793       } else {
2794         llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
2795         if (Literal.GetIntegerValue(ResultVal))
2796           Diag(Tok.getLocation(), diag::warn_integer_too_large);
2797         Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
2798                                      Tok.getLocation());
2799       }
2800       return BuildLiteralOperatorCall(R, OpNameInfo,
2801                                       llvm::makeArrayRef(&Lit, 1),
2802                                       Tok.getLocation());
2803     }
2804 
2805     case LOLR_Raw: {
2806       // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
2807       // literal is treated as a call of the form
2808       //   operator "" X ("n")
2809       SourceLocation TokLoc = Tok.getLocation();
2810       unsigned Length = Literal.getUDSuffixOffset();
2811       QualType StrTy = Context.getConstantArrayType(
2812           Context.CharTy.withConst(), llvm::APInt(32, Length + 1),
2813           ArrayType::Normal, 0);
2814       Expr *Lit = StringLiteral::Create(
2815           Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
2816           /*Pascal*/false, StrTy, &TokLoc, 1);
2817       return BuildLiteralOperatorCall(R, OpNameInfo,
2818                                       llvm::makeArrayRef(&Lit, 1), TokLoc);
2819     }
2820 
2821     case LOLR_Template:
2822       // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
2823       // template), L is treated as a call fo the form
2824       //   operator "" X <'c1', 'c2', ... 'ck'>()
2825       // where n is the source character sequence c1 c2 ... ck.
2826       TemplateArgumentListInfo ExplicitArgs;
2827       unsigned CharBits = Context.getIntWidth(Context.CharTy);
2828       bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
2829       llvm::APSInt Value(CharBits, CharIsUnsigned);
2830       for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
2831         Value = TokSpelling[I];
2832         TemplateArgument Arg(Context, Value, Context.CharTy);
2833         TemplateArgumentLocInfo ArgInfo;
2834         ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
2835       }
2836       return BuildLiteralOperatorCall(R, OpNameInfo, ArrayRef<Expr*>(),
2837                                       Tok.getLocation(), &ExplicitArgs);
2838     }
2839 
2840     llvm_unreachable("unexpected literal operator lookup result");
2841   }
2842 
2843   Expr *Res;
2844 
2845   if (Literal.isFloatingLiteral()) {
2846     QualType Ty;
2847     if (Literal.isFloat)
2848       Ty = Context.FloatTy;
2849     else if (!Literal.isLong)
2850       Ty = Context.DoubleTy;
2851     else
2852       Ty = Context.LongDoubleTy;
2853 
2854     Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
2855 
2856     if (Ty == Context.DoubleTy) {
2857       if (getLangOpts().SinglePrecisionConstants) {
2858         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
2859       } else if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
2860         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
2861         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
2862       }
2863     }
2864   } else if (!Literal.isIntegerLiteral()) {
2865     return ExprError();
2866   } else {
2867     QualType Ty;
2868 
2869     // 'long long' is a C99 or C++11 feature.
2870     if (!getLangOpts().C99 && Literal.isLongLong) {
2871       if (getLangOpts().CPlusPlus)
2872         Diag(Tok.getLocation(),
2873              getLangOpts().CPlusPlus11 ?
2874              diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
2875       else
2876         Diag(Tok.getLocation(), diag::ext_c99_longlong);
2877     }
2878 
2879     // Get the value in the widest-possible width.
2880     unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
2881     // The microsoft literal suffix extensions support 128-bit literals, which
2882     // may be wider than [u]intmax_t.
2883     // FIXME: Actually, they don't. We seem to have accidentally invented the
2884     //        i128 suffix.
2885     if (Literal.isMicrosoftInteger && MaxWidth < 128 &&
2886         PP.getTargetInfo().hasInt128Type())
2887       MaxWidth = 128;
2888     llvm::APInt ResultVal(MaxWidth, 0);
2889 
2890     if (Literal.GetIntegerValue(ResultVal)) {
2891       // If this value didn't fit into uintmax_t, warn and force to ull.
2892       Diag(Tok.getLocation(), diag::warn_integer_too_large);
2893       Ty = Context.UnsignedLongLongTy;
2894       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
2895              "long long is not intmax_t?");
2896     } else {
2897       // If this value fits into a ULL, try to figure out what else it fits into
2898       // according to the rules of C99 6.4.4.1p5.
2899 
2900       // Octal, Hexadecimal, and integers with a U suffix are allowed to
2901       // be an unsigned int.
2902       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2903 
2904       // Check from smallest to largest, picking the smallest type we can.
2905       unsigned Width = 0;
2906       if (!Literal.isLong && !Literal.isLongLong) {
2907         // Are int/unsigned possibilities?
2908         unsigned IntSize = Context.getTargetInfo().getIntWidth();
2909 
2910         // Does it fit in a unsigned int?
2911         if (ResultVal.isIntN(IntSize)) {
2912           // Does it fit in a signed int?
2913           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
2914             Ty = Context.IntTy;
2915           else if (AllowUnsigned)
2916             Ty = Context.UnsignedIntTy;
2917           Width = IntSize;
2918         }
2919       }
2920 
2921       // Are long/unsigned long possibilities?
2922       if (Ty.isNull() && !Literal.isLongLong) {
2923         unsigned LongSize = Context.getTargetInfo().getLongWidth();
2924 
2925         // Does it fit in a unsigned long?
2926         if (ResultVal.isIntN(LongSize)) {
2927           // Does it fit in a signed long?
2928           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
2929             Ty = Context.LongTy;
2930           else if (AllowUnsigned)
2931             Ty = Context.UnsignedLongTy;
2932           Width = LongSize;
2933         }
2934       }
2935 
2936       // Check long long if needed.
2937       if (Ty.isNull()) {
2938         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
2939 
2940         // Does it fit in a unsigned long long?
2941         if (ResultVal.isIntN(LongLongSize)) {
2942           // Does it fit in a signed long long?
2943           // To be compatible with MSVC, hex integer literals ending with the
2944           // LL or i64 suffix are always signed in Microsoft mode.
2945           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
2946               (getLangOpts().MicrosoftExt && Literal.isLongLong)))
2947             Ty = Context.LongLongTy;
2948           else if (AllowUnsigned)
2949             Ty = Context.UnsignedLongLongTy;
2950           Width = LongLongSize;
2951         }
2952       }
2953 
2954       // If it doesn't fit in unsigned long long, and we're using Microsoft
2955       // extensions, then its a 128-bit integer literal.
2956       if (Ty.isNull() && Literal.isMicrosoftInteger &&
2957           PP.getTargetInfo().hasInt128Type()) {
2958         if (Literal.isUnsigned)
2959           Ty = Context.UnsignedInt128Ty;
2960         else
2961           Ty = Context.Int128Ty;
2962         Width = 128;
2963       }
2964 
2965       // If we still couldn't decide a type, we probably have something that
2966       // does not fit in a signed long long, but has no U suffix.
2967       if (Ty.isNull()) {
2968         Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
2969         Ty = Context.UnsignedLongLongTy;
2970         Width = Context.getTargetInfo().getLongLongWidth();
2971       }
2972 
2973       if (ResultVal.getBitWidth() != Width)
2974         ResultVal = ResultVal.trunc(Width);
2975     }
2976     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
2977   }
2978 
2979   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
2980   if (Literal.isImaginary)
2981     Res = new (Context) ImaginaryLiteral(Res,
2982                                         Context.getComplexType(Res->getType()));
2983 
2984   return Owned(Res);
2985 }
2986 
2987 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
2988   assert((E != 0) && "ActOnParenExpr() missing expr");
2989   return Owned(new (Context) ParenExpr(L, R, E));
2990 }
2991 
2992 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
2993                                          SourceLocation Loc,
2994                                          SourceRange ArgRange) {
2995   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
2996   // scalar or vector data type argument..."
2997   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
2998   // type (C99 6.2.5p18) or void.
2999   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3000     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3001       << T << ArgRange;
3002     return true;
3003   }
3004 
3005   assert((T->isVoidType() || !T->isIncompleteType()) &&
3006          "Scalar types should always be complete");
3007   return false;
3008 }
3009 
3010 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3011                                            SourceLocation Loc,
3012                                            SourceRange ArgRange,
3013                                            UnaryExprOrTypeTrait TraitKind) {
3014   // C99 6.5.3.4p1:
3015   if (T->isFunctionType() &&
3016       (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) {
3017     // sizeof(function)/alignof(function) is allowed as an extension.
3018     S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3019       << TraitKind << ArgRange;
3020     return false;
3021   }
3022 
3023   // Allow sizeof(void)/alignof(void) as an extension.
3024   if (T->isVoidType()) {
3025     S.Diag(Loc, diag::ext_sizeof_alignof_void_type) << TraitKind << ArgRange;
3026     return false;
3027   }
3028 
3029   return true;
3030 }
3031 
3032 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
3033                                              SourceLocation Loc,
3034                                              SourceRange ArgRange,
3035                                              UnaryExprOrTypeTrait TraitKind) {
3036   // Reject sizeof(interface) and sizeof(interface<proto>) if the
3037   // runtime doesn't allow it.
3038   if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
3039     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3040       << T << (TraitKind == UETT_SizeOf)
3041       << ArgRange;
3042     return true;
3043   }
3044 
3045   return false;
3046 }
3047 
3048 /// \brief Check the constrains on expression operands to unary type expression
3049 /// and type traits.
3050 ///
3051 /// Completes any types necessary and validates the constraints on the operand
3052 /// expression. The logic mostly mirrors the type-based overload, but may modify
3053 /// the expression as it completes the type for that expression through template
3054 /// instantiation, etc.
3055 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
3056                                             UnaryExprOrTypeTrait ExprKind) {
3057   QualType ExprTy = E->getType();
3058 
3059   // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
3060   //   the result is the size of the referenced type."
3061   // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
3062   //   result shall be the alignment of the referenced type."
3063   if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
3064     ExprTy = Ref->getPointeeType();
3065 
3066   if (ExprKind == UETT_VecStep)
3067     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
3068                                         E->getSourceRange());
3069 
3070   // Whitelist some types as extensions
3071   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
3072                                       E->getSourceRange(), ExprKind))
3073     return false;
3074 
3075   if (RequireCompleteExprType(E,
3076                               diag::err_sizeof_alignof_incomplete_type,
3077                               ExprKind, E->getSourceRange()))
3078     return true;
3079 
3080   // Completeing the expression's type may have changed it.
3081   ExprTy = E->getType();
3082   if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
3083     ExprTy = Ref->getPointeeType();
3084 
3085   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
3086                                        E->getSourceRange(), ExprKind))
3087     return true;
3088 
3089   if (ExprKind == UETT_SizeOf) {
3090     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
3091       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
3092         QualType OType = PVD->getOriginalType();
3093         QualType Type = PVD->getType();
3094         if (Type->isPointerType() && OType->isArrayType()) {
3095           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
3096             << Type << OType;
3097           Diag(PVD->getLocation(), diag::note_declared_at);
3098         }
3099       }
3100     }
3101   }
3102 
3103   return false;
3104 }
3105 
3106 /// \brief Check the constraints on operands to unary expression and type
3107 /// traits.
3108 ///
3109 /// This will complete any types necessary, and validate the various constraints
3110 /// on those operands.
3111 ///
3112 /// The UsualUnaryConversions() function is *not* called by this routine.
3113 /// C99 6.3.2.1p[2-4] all state:
3114 ///   Except when it is the operand of the sizeof operator ...
3115 ///
3116 /// C++ [expr.sizeof]p4
3117 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3118 ///   standard conversions are not applied to the operand of sizeof.
3119 ///
3120 /// This policy is followed for all of the unary trait expressions.
3121 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
3122                                             SourceLocation OpLoc,
3123                                             SourceRange ExprRange,
3124                                             UnaryExprOrTypeTrait ExprKind) {
3125   if (ExprType->isDependentType())
3126     return false;
3127 
3128   // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
3129   //   the result is the size of the referenced type."
3130   // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
3131   //   result shall be the alignment of the referenced type."
3132   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3133     ExprType = Ref->getPointeeType();
3134 
3135   if (ExprKind == UETT_VecStep)
3136     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
3137 
3138   // Whitelist some types as extensions
3139   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
3140                                       ExprKind))
3141     return false;
3142 
3143   if (RequireCompleteType(OpLoc, ExprType,
3144                           diag::err_sizeof_alignof_incomplete_type,
3145                           ExprKind, ExprRange))
3146     return true;
3147 
3148   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
3149                                        ExprKind))
3150     return true;
3151 
3152   return false;
3153 }
3154 
3155 static bool CheckAlignOfExpr(Sema &S, Expr *E) {
3156   E = E->IgnoreParens();
3157 
3158   // alignof decl is always ok.
3159   if (isa<DeclRefExpr>(E))
3160     return false;
3161 
3162   // Cannot know anything else if the expression is dependent.
3163   if (E->isTypeDependent())
3164     return false;
3165 
3166   if (E->getBitField()) {
3167     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield)
3168        << 1 << E->getSourceRange();
3169     return true;
3170   }
3171 
3172   // Alignment of a field access is always okay, so long as it isn't a
3173   // bit-field.
3174   if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
3175     if (isa<FieldDecl>(ME->getMemberDecl()))
3176       return false;
3177 
3178   return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
3179 }
3180 
3181 bool Sema::CheckVecStepExpr(Expr *E) {
3182   E = E->IgnoreParens();
3183 
3184   // Cannot know anything else if the expression is dependent.
3185   if (E->isTypeDependent())
3186     return false;
3187 
3188   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
3189 }
3190 
3191 /// \brief Build a sizeof or alignof expression given a type operand.
3192 ExprResult
3193 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3194                                      SourceLocation OpLoc,
3195                                      UnaryExprOrTypeTrait ExprKind,
3196                                      SourceRange R) {
3197   if (!TInfo)
3198     return ExprError();
3199 
3200   QualType T = TInfo->getType();
3201 
3202   if (!T->isDependentType() &&
3203       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
3204     return ExprError();
3205 
3206   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
3207   return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo,
3208                                                       Context.getSizeType(),
3209                                                       OpLoc, R.getEnd()));
3210 }
3211 
3212 /// \brief Build a sizeof or alignof expression given an expression
3213 /// operand.
3214 ExprResult
3215 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
3216                                      UnaryExprOrTypeTrait ExprKind) {
3217   ExprResult PE = CheckPlaceholderExpr(E);
3218   if (PE.isInvalid())
3219     return ExprError();
3220 
3221   E = PE.get();
3222 
3223   // Verify that the operand is valid.
3224   bool isInvalid = false;
3225   if (E->isTypeDependent()) {
3226     // Delay type-checking for type-dependent expressions.
3227   } else if (ExprKind == UETT_AlignOf) {
3228     isInvalid = CheckAlignOfExpr(*this, E);
3229   } else if (ExprKind == UETT_VecStep) {
3230     isInvalid = CheckVecStepExpr(E);
3231   } else if (E->getBitField()) {  // C99 6.5.3.4p1.
3232     Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0;
3233     isInvalid = true;
3234   } else {
3235     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
3236   }
3237 
3238   if (isInvalid)
3239     return ExprError();
3240 
3241   if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
3242     PE = TransformToPotentiallyEvaluated(E);
3243     if (PE.isInvalid()) return ExprError();
3244     E = PE.take();
3245   }
3246 
3247   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
3248   return Owned(new (Context) UnaryExprOrTypeTraitExpr(
3249       ExprKind, E, Context.getSizeType(), OpLoc,
3250       E->getSourceRange().getEnd()));
3251 }
3252 
3253 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
3254 /// expr and the same for @c alignof and @c __alignof
3255 /// Note that the ArgRange is invalid if isType is false.
3256 ExprResult
3257 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
3258                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
3259                                     void *TyOrEx, const SourceRange &ArgRange) {
3260   // If error parsing type, ignore.
3261   if (TyOrEx == 0) return ExprError();
3262 
3263   if (IsType) {
3264     TypeSourceInfo *TInfo;
3265     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
3266     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
3267   }
3268 
3269   Expr *ArgEx = (Expr *)TyOrEx;
3270   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
3271   return Result;
3272 }
3273 
3274 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
3275                                      bool IsReal) {
3276   if (V.get()->isTypeDependent())
3277     return S.Context.DependentTy;
3278 
3279   // _Real and _Imag are only l-values for normal l-values.
3280   if (V.get()->getObjectKind() != OK_Ordinary) {
3281     V = S.DefaultLvalueConversion(V.take());
3282     if (V.isInvalid())
3283       return QualType();
3284   }
3285 
3286   // These operators return the element type of a complex type.
3287   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
3288     return CT->getElementType();
3289 
3290   // Otherwise they pass through real integer and floating point types here.
3291   if (V.get()->getType()->isArithmeticType())
3292     return V.get()->getType();
3293 
3294   // Test for placeholders.
3295   ExprResult PR = S.CheckPlaceholderExpr(V.get());
3296   if (PR.isInvalid()) return QualType();
3297   if (PR.get() != V.get()) {
3298     V = PR;
3299     return CheckRealImagOperand(S, V, Loc, IsReal);
3300   }
3301 
3302   // Reject anything else.
3303   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
3304     << (IsReal ? "__real" : "__imag");
3305   return QualType();
3306 }
3307 
3308 
3309 
3310 ExprResult
3311 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
3312                           tok::TokenKind Kind, Expr *Input) {
3313   UnaryOperatorKind Opc;
3314   switch (Kind) {
3315   default: llvm_unreachable("Unknown unary op!");
3316   case tok::plusplus:   Opc = UO_PostInc; break;
3317   case tok::minusminus: Opc = UO_PostDec; break;
3318   }
3319 
3320   // Since this might is a postfix expression, get rid of ParenListExprs.
3321   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
3322   if (Result.isInvalid()) return ExprError();
3323   Input = Result.take();
3324 
3325   return BuildUnaryOp(S, OpLoc, Opc, Input);
3326 }
3327 
3328 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal.
3329 ///
3330 /// \return true on error
3331 static bool checkArithmeticOnObjCPointer(Sema &S,
3332                                          SourceLocation opLoc,
3333                                          Expr *op) {
3334   assert(op->getType()->isObjCObjectPointerType());
3335   if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic())
3336     return false;
3337 
3338   S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
3339     << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
3340     << op->getSourceRange();
3341   return true;
3342 }
3343 
3344 ExprResult
3345 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
3346                               Expr *idx, SourceLocation rbLoc) {
3347   // Since this might be a postfix expression, get rid of ParenListExprs.
3348   if (isa<ParenListExpr>(base)) {
3349     ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
3350     if (result.isInvalid()) return ExprError();
3351     base = result.take();
3352   }
3353 
3354   // Handle any non-overload placeholder types in the base and index
3355   // expressions.  We can't handle overloads here because the other
3356   // operand might be an overloadable type, in which case the overload
3357   // resolution for the operator overload should get the first crack
3358   // at the overload.
3359   if (base->getType()->isNonOverloadPlaceholderType()) {
3360     ExprResult result = CheckPlaceholderExpr(base);
3361     if (result.isInvalid()) return ExprError();
3362     base = result.take();
3363   }
3364   if (idx->getType()->isNonOverloadPlaceholderType()) {
3365     ExprResult result = CheckPlaceholderExpr(idx);
3366     if (result.isInvalid()) return ExprError();
3367     idx = result.take();
3368   }
3369 
3370   // Build an unanalyzed expression if either operand is type-dependent.
3371   if (getLangOpts().CPlusPlus &&
3372       (base->isTypeDependent() || idx->isTypeDependent())) {
3373     return Owned(new (Context) ArraySubscriptExpr(base, idx,
3374                                                   Context.DependentTy,
3375                                                   VK_LValue, OK_Ordinary,
3376                                                   rbLoc));
3377   }
3378 
3379   // Use C++ overloaded-operator rules if either operand has record
3380   // type.  The spec says to do this if either type is *overloadable*,
3381   // but enum types can't declare subscript operators or conversion
3382   // operators, so there's nothing interesting for overload resolution
3383   // to do if there aren't any record types involved.
3384   //
3385   // ObjC pointers have their own subscripting logic that is not tied
3386   // to overload resolution and so should not take this path.
3387   if (getLangOpts().CPlusPlus &&
3388       (base->getType()->isRecordType() ||
3389        (!base->getType()->isObjCObjectPointerType() &&
3390         idx->getType()->isRecordType()))) {
3391     return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
3392   }
3393 
3394   return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
3395 }
3396 
3397 ExprResult
3398 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
3399                                       Expr *Idx, SourceLocation RLoc) {
3400   Expr *LHSExp = Base;
3401   Expr *RHSExp = Idx;
3402 
3403   // Perform default conversions.
3404   if (!LHSExp->getType()->getAs<VectorType>()) {
3405     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
3406     if (Result.isInvalid())
3407       return ExprError();
3408     LHSExp = Result.take();
3409   }
3410   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
3411   if (Result.isInvalid())
3412     return ExprError();
3413   RHSExp = Result.take();
3414 
3415   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
3416   ExprValueKind VK = VK_LValue;
3417   ExprObjectKind OK = OK_Ordinary;
3418 
3419   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
3420   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
3421   // in the subscript position. As a result, we need to derive the array base
3422   // and index from the expression types.
3423   Expr *BaseExpr, *IndexExpr;
3424   QualType ResultType;
3425   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3426     BaseExpr = LHSExp;
3427     IndexExpr = RHSExp;
3428     ResultType = Context.DependentTy;
3429   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
3430     BaseExpr = LHSExp;
3431     IndexExpr = RHSExp;
3432     ResultType = PTy->getPointeeType();
3433   } else if (const ObjCObjectPointerType *PTy =
3434                LHSTy->getAs<ObjCObjectPointerType>()) {
3435     BaseExpr = LHSExp;
3436     IndexExpr = RHSExp;
3437 
3438     // Use custom logic if this should be the pseudo-object subscript
3439     // expression.
3440     if (!LangOpts.ObjCRuntime.isSubscriptPointerArithmetic())
3441       return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, 0, 0);
3442 
3443     ResultType = PTy->getPointeeType();
3444     if (!LangOpts.ObjCRuntime.allowsPointerArithmetic()) {
3445       Diag(LLoc, diag::err_subscript_nonfragile_interface)
3446         << ResultType << BaseExpr->getSourceRange();
3447       return ExprError();
3448     }
3449   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
3450      // Handle the uncommon case of "123[Ptr]".
3451     BaseExpr = RHSExp;
3452     IndexExpr = LHSExp;
3453     ResultType = PTy->getPointeeType();
3454   } else if (const ObjCObjectPointerType *PTy =
3455                RHSTy->getAs<ObjCObjectPointerType>()) {
3456      // Handle the uncommon case of "123[Ptr]".
3457     BaseExpr = RHSExp;
3458     IndexExpr = LHSExp;
3459     ResultType = PTy->getPointeeType();
3460     if (!LangOpts.ObjCRuntime.allowsPointerArithmetic()) {
3461       Diag(LLoc, diag::err_subscript_nonfragile_interface)
3462         << ResultType << BaseExpr->getSourceRange();
3463       return ExprError();
3464     }
3465   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
3466     BaseExpr = LHSExp;    // vectors: V[123]
3467     IndexExpr = RHSExp;
3468     VK = LHSExp->getValueKind();
3469     if (VK != VK_RValue)
3470       OK = OK_VectorComponent;
3471 
3472     // FIXME: need to deal with const...
3473     ResultType = VTy->getElementType();
3474   } else if (LHSTy->isArrayType()) {
3475     // If we see an array that wasn't promoted by
3476     // DefaultFunctionArrayLvalueConversion, it must be an array that
3477     // wasn't promoted because of the C90 rule that doesn't
3478     // allow promoting non-lvalue arrays.  Warn, then
3479     // force the promotion here.
3480     Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3481         LHSExp->getSourceRange();
3482     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
3483                                CK_ArrayToPointerDecay).take();
3484     LHSTy = LHSExp->getType();
3485 
3486     BaseExpr = LHSExp;
3487     IndexExpr = RHSExp;
3488     ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
3489   } else if (RHSTy->isArrayType()) {
3490     // Same as previous, except for 123[f().a] case
3491     Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3492         RHSExp->getSourceRange();
3493     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
3494                                CK_ArrayToPointerDecay).take();
3495     RHSTy = RHSExp->getType();
3496 
3497     BaseExpr = RHSExp;
3498     IndexExpr = LHSExp;
3499     ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
3500   } else {
3501     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3502        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
3503   }
3504   // C99 6.5.2.1p1
3505   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
3506     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3507                      << IndexExpr->getSourceRange());
3508 
3509   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
3510        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3511          && !IndexExpr->isTypeDependent())
3512     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3513 
3514   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
3515   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3516   // type. Note that Functions are not objects, and that (in C99 parlance)
3517   // incomplete types are not object types.
3518   if (ResultType->isFunctionType()) {
3519     Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3520       << ResultType << BaseExpr->getSourceRange();
3521     return ExprError();
3522   }
3523 
3524   if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
3525     // GNU extension: subscripting on pointer to void
3526     Diag(LLoc, diag::ext_gnu_subscript_void_type)
3527       << BaseExpr->getSourceRange();
3528 
3529     // C forbids expressions of unqualified void type from being l-values.
3530     // See IsCForbiddenLValueType.
3531     if (!ResultType.hasQualifiers()) VK = VK_RValue;
3532   } else if (!ResultType->isDependentType() &&
3533       RequireCompleteType(LLoc, ResultType,
3534                           diag::err_subscript_incomplete_type, BaseExpr))
3535     return ExprError();
3536 
3537   assert(VK == VK_RValue || LangOpts.CPlusPlus ||
3538          !ResultType.isCForbiddenLValueType());
3539 
3540   return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
3541                                                 ResultType, VK, OK, RLoc));
3542 }
3543 
3544 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
3545                                         FunctionDecl *FD,
3546                                         ParmVarDecl *Param) {
3547   if (Param->hasUnparsedDefaultArg()) {
3548     Diag(CallLoc,
3549          diag::err_use_of_default_argument_to_function_declared_later) <<
3550       FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
3551     Diag(UnparsedDefaultArgLocs[Param],
3552          diag::note_default_argument_declared_here);
3553     return ExprError();
3554   }
3555 
3556   if (Param->hasUninstantiatedDefaultArg()) {
3557     Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
3558 
3559     EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated,
3560                                                  Param);
3561 
3562     // Instantiate the expression.
3563     MultiLevelTemplateArgumentList ArgList
3564       = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
3565 
3566     std::pair<const TemplateArgument *, unsigned> Innermost
3567       = ArgList.getInnermost();
3568     InstantiatingTemplate Inst(*this, CallLoc, Param,
3569                                ArrayRef<TemplateArgument>(Innermost.first,
3570                                                           Innermost.second));
3571     if (Inst)
3572       return ExprError();
3573 
3574     ExprResult Result;
3575     {
3576       // C++ [dcl.fct.default]p5:
3577       //   The names in the [default argument] expression are bound, and
3578       //   the semantic constraints are checked, at the point where the
3579       //   default argument expression appears.
3580       ContextRAII SavedContext(*this, FD);
3581       LocalInstantiationScope Local(*this);
3582       Result = SubstExpr(UninstExpr, ArgList);
3583     }
3584     if (Result.isInvalid())
3585       return ExprError();
3586 
3587     // Check the expression as an initializer for the parameter.
3588     InitializedEntity Entity
3589       = InitializedEntity::InitializeParameter(Context, Param);
3590     InitializationKind Kind
3591       = InitializationKind::CreateCopy(Param->getLocation(),
3592              /*FIXME:EqualLoc*/UninstExpr->getLocStart());
3593     Expr *ResultE = Result.takeAs<Expr>();
3594 
3595     InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
3596     Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
3597     if (Result.isInvalid())
3598       return ExprError();
3599 
3600     Expr *Arg = Result.takeAs<Expr>();
3601     CheckCompletedExpr(Arg, Param->getOuterLocStart());
3602     // Build the default argument expression.
3603     return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param, Arg));
3604   }
3605 
3606   // If the default expression creates temporaries, we need to
3607   // push them to the current stack of expression temporaries so they'll
3608   // be properly destroyed.
3609   // FIXME: We should really be rebuilding the default argument with new
3610   // bound temporaries; see the comment in PR5810.
3611   // We don't need to do that with block decls, though, because
3612   // blocks in default argument expression can never capture anything.
3613   if (isa<ExprWithCleanups>(Param->getInit())) {
3614     // Set the "needs cleanups" bit regardless of whether there are
3615     // any explicit objects.
3616     ExprNeedsCleanups = true;
3617 
3618     // Append all the objects to the cleanup list.  Right now, this
3619     // should always be a no-op, because blocks in default argument
3620     // expressions should never be able to capture anything.
3621     assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() &&
3622            "default argument expression has capturing blocks?");
3623   }
3624 
3625   // We already type-checked the argument, so we know it works.
3626   // Just mark all of the declarations in this potentially-evaluated expression
3627   // as being "referenced".
3628   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
3629                                    /*SkipLocalVariables=*/true);
3630   return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
3631 }
3632 
3633 
3634 Sema::VariadicCallType
3635 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
3636                           Expr *Fn) {
3637   if (Proto && Proto->isVariadic()) {
3638     if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
3639       return VariadicConstructor;
3640     else if (Fn && Fn->getType()->isBlockPointerType())
3641       return VariadicBlock;
3642     else if (FDecl) {
3643       if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3644         if (Method->isInstance())
3645           return VariadicMethod;
3646     }
3647     return VariadicFunction;
3648   }
3649   return VariadicDoesNotApply;
3650 }
3651 
3652 /// ConvertArgumentsForCall - Converts the arguments specified in
3653 /// Args/NumArgs to the parameter types of the function FDecl with
3654 /// function prototype Proto. Call is the call expression itself, and
3655 /// Fn is the function expression. For a C++ member function, this
3656 /// routine does not attempt to convert the object argument. Returns
3657 /// true if the call is ill-formed.
3658 bool
3659 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
3660                               FunctionDecl *FDecl,
3661                               const FunctionProtoType *Proto,
3662                               Expr **Args, unsigned NumArgs,
3663                               SourceLocation RParenLoc,
3664                               bool IsExecConfig) {
3665   // Bail out early if calling a builtin with custom typechecking.
3666   // We don't need to do this in the
3667   if (FDecl)
3668     if (unsigned ID = FDecl->getBuiltinID())
3669       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
3670         return false;
3671 
3672   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
3673   // assignment, to the types of the corresponding parameter, ...
3674   unsigned NumArgsInProto = Proto->getNumArgs();
3675   bool Invalid = false;
3676   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumArgsInProto;
3677   unsigned FnKind = Fn->getType()->isBlockPointerType()
3678                        ? 1 /* block */
3679                        : (IsExecConfig ? 3 /* kernel function (exec config) */
3680                                        : 0 /* function */);
3681 
3682   // If too few arguments are available (and we don't have default
3683   // arguments for the remaining parameters), don't make the call.
3684   if (NumArgs < NumArgsInProto) {
3685     if (NumArgs < MinArgs) {
3686       if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
3687         Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic()
3688                           ? diag::err_typecheck_call_too_few_args_one
3689                           : diag::err_typecheck_call_too_few_args_at_least_one)
3690           << FnKind
3691           << FDecl->getParamDecl(0) << Fn->getSourceRange();
3692       else
3693         Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic()
3694                           ? diag::err_typecheck_call_too_few_args
3695                           : diag::err_typecheck_call_too_few_args_at_least)
3696           << FnKind
3697           << MinArgs << NumArgs << Fn->getSourceRange();
3698 
3699       // Emit the location of the prototype.
3700       if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
3701         Diag(FDecl->getLocStart(), diag::note_callee_decl)
3702           << FDecl;
3703 
3704       return true;
3705     }
3706     Call->setNumArgs(Context, NumArgsInProto);
3707   }
3708 
3709   // If too many are passed and not variadic, error on the extras and drop
3710   // them.
3711   if (NumArgs > NumArgsInProto) {
3712     if (!Proto->isVariadic()) {
3713       if (NumArgsInProto == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
3714         Diag(Args[NumArgsInProto]->getLocStart(),
3715              MinArgs == NumArgsInProto
3716                ? diag::err_typecheck_call_too_many_args_one
3717                : diag::err_typecheck_call_too_many_args_at_most_one)
3718           << FnKind
3719           << FDecl->getParamDecl(0) << NumArgs << Fn->getSourceRange()
3720           << SourceRange(Args[NumArgsInProto]->getLocStart(),
3721                          Args[NumArgs-1]->getLocEnd());
3722       else
3723         Diag(Args[NumArgsInProto]->getLocStart(),
3724              MinArgs == NumArgsInProto
3725                ? diag::err_typecheck_call_too_many_args
3726                : diag::err_typecheck_call_too_many_args_at_most)
3727           << FnKind
3728           << NumArgsInProto << NumArgs << Fn->getSourceRange()
3729           << SourceRange(Args[NumArgsInProto]->getLocStart(),
3730                          Args[NumArgs-1]->getLocEnd());
3731 
3732       // Emit the location of the prototype.
3733       if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
3734         Diag(FDecl->getLocStart(), diag::note_callee_decl)
3735           << FDecl;
3736 
3737       // This deletes the extra arguments.
3738       Call->setNumArgs(Context, NumArgsInProto);
3739       return true;
3740     }
3741   }
3742   SmallVector<Expr *, 8> AllArgs;
3743   VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
3744 
3745   Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
3746                                    Proto, 0, Args, NumArgs, AllArgs, CallType);
3747   if (Invalid)
3748     return true;
3749   unsigned TotalNumArgs = AllArgs.size();
3750   for (unsigned i = 0; i < TotalNumArgs; ++i)
3751     Call->setArg(i, AllArgs[i]);
3752 
3753   return false;
3754 }
3755 
3756 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
3757                                   FunctionDecl *FDecl,
3758                                   const FunctionProtoType *Proto,
3759                                   unsigned FirstProtoArg,
3760                                   Expr **Args, unsigned NumArgs,
3761                                   SmallVector<Expr *, 8> &AllArgs,
3762                                   VariadicCallType CallType,
3763                                   bool AllowExplicit,
3764                                   bool IsListInitialization) {
3765   unsigned NumArgsInProto = Proto->getNumArgs();
3766   unsigned NumArgsToCheck = NumArgs;
3767   bool Invalid = false;
3768   if (NumArgs != NumArgsInProto)
3769     // Use default arguments for missing arguments
3770     NumArgsToCheck = NumArgsInProto;
3771   unsigned ArgIx = 0;
3772   // Continue to check argument types (even if we have too few/many args).
3773   for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
3774     QualType ProtoArgType = Proto->getArgType(i);
3775 
3776     Expr *Arg;
3777     ParmVarDecl *Param;
3778     if (ArgIx < NumArgs) {
3779       Arg = Args[ArgIx++];
3780 
3781       if (RequireCompleteType(Arg->getLocStart(),
3782                               ProtoArgType,
3783                               diag::err_call_incomplete_argument, Arg))
3784         return true;
3785 
3786       // Pass the argument
3787       Param = 0;
3788       if (FDecl && i < FDecl->getNumParams())
3789         Param = FDecl->getParamDecl(i);
3790 
3791       // Strip the unbridged-cast placeholder expression off, if applicable.
3792       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
3793           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
3794           (!Param || !Param->hasAttr<CFConsumedAttr>()))
3795         Arg = stripARCUnbridgedCast(Arg);
3796 
3797       InitializedEntity Entity = Param ?
3798           InitializedEntity::InitializeParameter(Context, Param, ProtoArgType)
3799         : InitializedEntity::InitializeParameter(Context, ProtoArgType,
3800                                                  Proto->isArgConsumed(i));
3801       ExprResult ArgE = PerformCopyInitialization(Entity,
3802                                                   SourceLocation(),
3803                                                   Owned(Arg),
3804                                                   IsListInitialization,
3805                                                   AllowExplicit);
3806       if (ArgE.isInvalid())
3807         return true;
3808 
3809       Arg = ArgE.takeAs<Expr>();
3810     } else {
3811       assert(FDecl && "can't use default arguments without a known callee");
3812       Param = FDecl->getParamDecl(i);
3813 
3814       ExprResult ArgExpr =
3815         BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
3816       if (ArgExpr.isInvalid())
3817         return true;
3818 
3819       Arg = ArgExpr.takeAs<Expr>();
3820     }
3821 
3822     // Check for array bounds violations for each argument to the call. This
3823     // check only triggers warnings when the argument isn't a more complex Expr
3824     // with its own checking, such as a BinaryOperator.
3825     CheckArrayAccess(Arg);
3826 
3827     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
3828     CheckStaticArrayArgument(CallLoc, Param, Arg);
3829 
3830     AllArgs.push_back(Arg);
3831   }
3832 
3833   // If this is a variadic call, handle args passed through "...".
3834   if (CallType != VariadicDoesNotApply) {
3835     // Assume that extern "C" functions with variadic arguments that
3836     // return __unknown_anytype aren't *really* variadic.
3837     if (Proto->getResultType() == Context.UnknownAnyTy &&
3838         FDecl && FDecl->isExternC()) {
3839       for (unsigned i = ArgIx; i != NumArgs; ++i) {
3840         QualType paramType; // ignored
3841         ExprResult arg = checkUnknownAnyArg(CallLoc, Args[i], paramType);
3842         Invalid |= arg.isInvalid();
3843         AllArgs.push_back(arg.take());
3844       }
3845 
3846     // Otherwise do argument promotion, (C99 6.5.2.2p7).
3847     } else {
3848       for (unsigned i = ArgIx; i != NumArgs; ++i) {
3849         ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType,
3850                                                           FDecl);
3851         Invalid |= Arg.isInvalid();
3852         AllArgs.push_back(Arg.take());
3853       }
3854     }
3855 
3856     // Check for array bounds violations.
3857     for (unsigned i = ArgIx; i != NumArgs; ++i)
3858       CheckArrayAccess(Args[i]);
3859   }
3860   return Invalid;
3861 }
3862 
3863 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
3864   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
3865   if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
3866     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
3867       << ATL.getLocalSourceRange();
3868 }
3869 
3870 /// CheckStaticArrayArgument - If the given argument corresponds to a static
3871 /// array parameter, check that it is non-null, and that if it is formed by
3872 /// array-to-pointer decay, the underlying array is sufficiently large.
3873 ///
3874 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
3875 /// array type derivation, then for each call to the function, the value of the
3876 /// corresponding actual argument shall provide access to the first element of
3877 /// an array with at least as many elements as specified by the size expression.
3878 void
3879 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
3880                                ParmVarDecl *Param,
3881                                const Expr *ArgExpr) {
3882   // Static array parameters are not supported in C++.
3883   if (!Param || getLangOpts().CPlusPlus)
3884     return;
3885 
3886   QualType OrigTy = Param->getOriginalType();
3887 
3888   const ArrayType *AT = Context.getAsArrayType(OrigTy);
3889   if (!AT || AT->getSizeModifier() != ArrayType::Static)
3890     return;
3891 
3892   if (ArgExpr->isNullPointerConstant(Context,
3893                                      Expr::NPC_NeverValueDependent)) {
3894     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
3895     DiagnoseCalleeStaticArrayParam(*this, Param);
3896     return;
3897   }
3898 
3899   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
3900   if (!CAT)
3901     return;
3902 
3903   const ConstantArrayType *ArgCAT =
3904     Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
3905   if (!ArgCAT)
3906     return;
3907 
3908   if (ArgCAT->getSize().ult(CAT->getSize())) {
3909     Diag(CallLoc, diag::warn_static_array_too_small)
3910       << ArgExpr->getSourceRange()
3911       << (unsigned) ArgCAT->getSize().getZExtValue()
3912       << (unsigned) CAT->getSize().getZExtValue();
3913     DiagnoseCalleeStaticArrayParam(*this, Param);
3914   }
3915 }
3916 
3917 /// Given a function expression of unknown-any type, try to rebuild it
3918 /// to have a function type.
3919 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
3920 
3921 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
3922 /// This provides the location of the left/right parens and a list of comma
3923 /// locations.
3924 ExprResult
3925 Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
3926                     MultiExprArg ArgExprs, SourceLocation RParenLoc,
3927                     Expr *ExecConfig, bool IsExecConfig) {
3928   // Since this might be a postfix expression, get rid of ParenListExprs.
3929   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
3930   if (Result.isInvalid()) return ExprError();
3931   Fn = Result.take();
3932 
3933   if (getLangOpts().CPlusPlus) {
3934     // If this is a pseudo-destructor expression, build the call immediately.
3935     if (isa<CXXPseudoDestructorExpr>(Fn)) {
3936       if (!ArgExprs.empty()) {
3937         // Pseudo-destructor calls should not have any arguments.
3938         Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
3939           << FixItHint::CreateRemoval(
3940                                     SourceRange(ArgExprs[0]->getLocStart(),
3941                                                 ArgExprs.back()->getLocEnd()));
3942       }
3943 
3944       return Owned(new (Context) CallExpr(Context, Fn, MultiExprArg(),
3945                                           Context.VoidTy, VK_RValue,
3946                                           RParenLoc));
3947     }
3948 
3949     // Determine whether this is a dependent call inside a C++ template,
3950     // in which case we won't do any semantic analysis now.
3951     // FIXME: Will need to cache the results of name lookup (including ADL) in
3952     // Fn.
3953     bool Dependent = false;
3954     if (Fn->isTypeDependent())
3955       Dependent = true;
3956     else if (Expr::hasAnyTypeDependentArguments(ArgExprs))
3957       Dependent = true;
3958 
3959     if (Dependent) {
3960       if (ExecConfig) {
3961         return Owned(new (Context) CUDAKernelCallExpr(
3962             Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
3963             Context.DependentTy, VK_RValue, RParenLoc));
3964       } else {
3965         return Owned(new (Context) CallExpr(Context, Fn, ArgExprs,
3966                                             Context.DependentTy, VK_RValue,
3967                                             RParenLoc));
3968       }
3969     }
3970 
3971     // Determine whether this is a call to an object (C++ [over.call.object]).
3972     if (Fn->getType()->isRecordType())
3973       return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc,
3974                                                 ArgExprs.data(),
3975                                                 ArgExprs.size(), RParenLoc));
3976 
3977     if (Fn->getType() == Context.UnknownAnyTy) {
3978       ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
3979       if (result.isInvalid()) return ExprError();
3980       Fn = result.take();
3981     }
3982 
3983     if (Fn->getType() == Context.BoundMemberTy) {
3984       return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs.data(),
3985                                        ArgExprs.size(), RParenLoc);
3986     }
3987   }
3988 
3989   // Check for overloaded calls.  This can happen even in C due to extensions.
3990   if (Fn->getType() == Context.OverloadTy) {
3991     OverloadExpr::FindResult find = OverloadExpr::find(Fn);
3992 
3993     // We aren't supposed to apply this logic for if there's an '&' involved.
3994     if (!find.HasFormOfMemberPointer) {
3995       OverloadExpr *ovl = find.Expression;
3996       if (isa<UnresolvedLookupExpr>(ovl)) {
3997         UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
3998         return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, ArgExprs.data(),
3999                                        ArgExprs.size(), RParenLoc, ExecConfig);
4000       } else {
4001         return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs.data(),
4002                                          ArgExprs.size(), RParenLoc);
4003       }
4004     }
4005   }
4006 
4007   // If we're directly calling a function, get the appropriate declaration.
4008   if (Fn->getType() == Context.UnknownAnyTy) {
4009     ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
4010     if (result.isInvalid()) return ExprError();
4011     Fn = result.take();
4012   }
4013 
4014   Expr *NakedFn = Fn->IgnoreParens();
4015 
4016   NamedDecl *NDecl = 0;
4017   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
4018     if (UnOp->getOpcode() == UO_AddrOf)
4019       NakedFn = UnOp->getSubExpr()->IgnoreParens();
4020 
4021   if (isa<DeclRefExpr>(NakedFn))
4022     NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
4023   else if (isa<MemberExpr>(NakedFn))
4024     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
4025 
4026   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs.data(),
4027                                ArgExprs.size(), RParenLoc, ExecConfig,
4028                                IsExecConfig);
4029 }
4030 
4031 ExprResult
4032 Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
4033                               MultiExprArg ExecConfig, SourceLocation GGGLoc) {
4034   FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
4035   if (!ConfigDecl)
4036     return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
4037                           << "cudaConfigureCall");
4038   QualType ConfigQTy = ConfigDecl->getType();
4039 
4040   DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
4041       ConfigDecl, false, ConfigQTy, VK_LValue, LLLLoc);
4042   MarkFunctionReferenced(LLLLoc, ConfigDecl);
4043 
4044   return ActOnCallExpr(S, ConfigDR, LLLLoc, ExecConfig, GGGLoc, 0,
4045                        /*IsExecConfig=*/true);
4046 }
4047 
4048 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
4049 ///
4050 /// __builtin_astype( value, dst type )
4051 ///
4052 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
4053                                  SourceLocation BuiltinLoc,
4054                                  SourceLocation RParenLoc) {
4055   ExprValueKind VK = VK_RValue;
4056   ExprObjectKind OK = OK_Ordinary;
4057   QualType DstTy = GetTypeFromParser(ParsedDestTy);
4058   QualType SrcTy = E->getType();
4059   if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
4060     return ExprError(Diag(BuiltinLoc,
4061                           diag::err_invalid_astype_of_different_size)
4062                      << DstTy
4063                      << SrcTy
4064                      << E->getSourceRange());
4065   return Owned(new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc,
4066                RParenLoc));
4067 }
4068 
4069 /// BuildResolvedCallExpr - Build a call to a resolved expression,
4070 /// i.e. an expression not of \p OverloadTy.  The expression should
4071 /// unary-convert to an expression of function-pointer or
4072 /// block-pointer type.
4073 ///
4074 /// \param NDecl the declaration being called, if available
4075 ExprResult
4076 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
4077                             SourceLocation LParenLoc,
4078                             Expr **Args, unsigned NumArgs,
4079                             SourceLocation RParenLoc,
4080                             Expr *Config, bool IsExecConfig) {
4081   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
4082   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
4083 
4084   // Promote the function operand.
4085   // We special-case function promotion here because we only allow promoting
4086   // builtin functions to function pointers in the callee of a call.
4087   ExprResult Result;
4088   if (BuiltinID &&
4089       Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
4090     Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()),
4091                                CK_BuiltinFnToFnPtr).take();
4092   } else {
4093     Result = UsualUnaryConversions(Fn);
4094   }
4095   if (Result.isInvalid())
4096     return ExprError();
4097   Fn = Result.take();
4098 
4099   // Make the call expr early, before semantic checks.  This guarantees cleanup
4100   // of arguments and function on error.
4101   CallExpr *TheCall;
4102   if (Config)
4103     TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
4104                                                cast<CallExpr>(Config),
4105                                                llvm::makeArrayRef(Args,NumArgs),
4106                                                Context.BoolTy,
4107                                                VK_RValue,
4108                                                RParenLoc);
4109   else
4110     TheCall = new (Context) CallExpr(Context, Fn,
4111                                      llvm::makeArrayRef(Args, NumArgs),
4112                                      Context.BoolTy,
4113                                      VK_RValue,
4114                                      RParenLoc);
4115 
4116   // Bail out early if calling a builtin with custom typechecking.
4117   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
4118     return CheckBuiltinFunctionCall(BuiltinID, TheCall);
4119 
4120  retry:
4121   const FunctionType *FuncT;
4122   if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
4123     // C99 6.5.2.2p1 - "The expression that denotes the called function shall
4124     // have type pointer to function".
4125     FuncT = PT->getPointeeType()->getAs<FunctionType>();
4126     if (FuncT == 0)
4127       return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4128                          << Fn->getType() << Fn->getSourceRange());
4129   } else if (const BlockPointerType *BPT =
4130                Fn->getType()->getAs<BlockPointerType>()) {
4131     FuncT = BPT->getPointeeType()->castAs<FunctionType>();
4132   } else {
4133     // Handle calls to expressions of unknown-any type.
4134     if (Fn->getType() == Context.UnknownAnyTy) {
4135       ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
4136       if (rewrite.isInvalid()) return ExprError();
4137       Fn = rewrite.take();
4138       TheCall->setCallee(Fn);
4139       goto retry;
4140     }
4141 
4142     return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4143       << Fn->getType() << Fn->getSourceRange());
4144   }
4145 
4146   if (getLangOpts().CUDA) {
4147     if (Config) {
4148       // CUDA: Kernel calls must be to global functions
4149       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
4150         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
4151             << FDecl->getName() << Fn->getSourceRange());
4152 
4153       // CUDA: Kernel function must have 'void' return type
4154       if (!FuncT->getResultType()->isVoidType())
4155         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
4156             << Fn->getType() << Fn->getSourceRange());
4157     } else {
4158       // CUDA: Calls to global functions must be configured
4159       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
4160         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
4161             << FDecl->getName() << Fn->getSourceRange());
4162     }
4163   }
4164 
4165   // Check for a valid return type
4166   if (CheckCallReturnType(FuncT->getResultType(),
4167                           Fn->getLocStart(), TheCall,
4168                           FDecl))
4169     return ExprError();
4170 
4171   // We know the result type of the call, set it.
4172   TheCall->setType(FuncT->getCallResultType(Context));
4173   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
4174 
4175   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
4176   if (Proto) {
4177     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
4178                                 RParenLoc, IsExecConfig))
4179       return ExprError();
4180   } else {
4181     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
4182 
4183     if (FDecl) {
4184       // Check if we have too few/too many template arguments, based
4185       // on our knowledge of the function definition.
4186       const FunctionDecl *Def = 0;
4187       if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
4188         Proto = Def->getType()->getAs<FunctionProtoType>();
4189         if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
4190           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
4191             << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
4192       }
4193 
4194       // If the function we're calling isn't a function prototype, but we have
4195       // a function prototype from a prior declaratiom, use that prototype.
4196       if (!FDecl->hasPrototype())
4197         Proto = FDecl->getType()->getAs<FunctionProtoType>();
4198     }
4199 
4200     // Promote the arguments (C99 6.5.2.2p6).
4201     for (unsigned i = 0; i != NumArgs; i++) {
4202       Expr *Arg = Args[i];
4203 
4204       if (Proto && i < Proto->getNumArgs()) {
4205         InitializedEntity Entity
4206           = InitializedEntity::InitializeParameter(Context,
4207                                                    Proto->getArgType(i),
4208                                                    Proto->isArgConsumed(i));
4209         ExprResult ArgE = PerformCopyInitialization(Entity,
4210                                                     SourceLocation(),
4211                                                     Owned(Arg));
4212         if (ArgE.isInvalid())
4213           return true;
4214 
4215         Arg = ArgE.takeAs<Expr>();
4216 
4217       } else {
4218         ExprResult ArgE = DefaultArgumentPromotion(Arg);
4219 
4220         if (ArgE.isInvalid())
4221           return true;
4222 
4223         Arg = ArgE.takeAs<Expr>();
4224       }
4225 
4226       if (RequireCompleteType(Arg->getLocStart(),
4227                               Arg->getType(),
4228                               diag::err_call_incomplete_argument, Arg))
4229         return ExprError();
4230 
4231       TheCall->setArg(i, Arg);
4232     }
4233   }
4234 
4235   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4236     if (!Method->isStatic())
4237       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
4238         << Fn->getSourceRange());
4239 
4240   // Check for sentinels
4241   if (NDecl)
4242     DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
4243 
4244   // Do special checking on direct calls to functions.
4245   if (FDecl) {
4246     if (CheckFunctionCall(FDecl, TheCall, Proto))
4247       return ExprError();
4248 
4249     if (BuiltinID)
4250       return CheckBuiltinFunctionCall(BuiltinID, TheCall);
4251   } else if (NDecl) {
4252     if (CheckBlockCall(NDecl, TheCall, Proto))
4253       return ExprError();
4254   }
4255 
4256   return MaybeBindToTemporary(TheCall);
4257 }
4258 
4259 ExprResult
4260 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
4261                            SourceLocation RParenLoc, Expr *InitExpr) {
4262   assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
4263   // FIXME: put back this assert when initializers are worked out.
4264   //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
4265 
4266   TypeSourceInfo *TInfo;
4267   QualType literalType = GetTypeFromParser(Ty, &TInfo);
4268   if (!TInfo)
4269     TInfo = Context.getTrivialTypeSourceInfo(literalType);
4270 
4271   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
4272 }
4273 
4274 ExprResult
4275 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
4276                                SourceLocation RParenLoc, Expr *LiteralExpr) {
4277   QualType literalType = TInfo->getType();
4278 
4279   if (literalType->isArrayType()) {
4280     if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
4281           diag::err_illegal_decl_array_incomplete_type,
4282           SourceRange(LParenLoc,
4283                       LiteralExpr->getSourceRange().getEnd())))
4284       return ExprError();
4285     if (literalType->isVariableArrayType())
4286       return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
4287         << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
4288   } else if (!literalType->isDependentType() &&
4289              RequireCompleteType(LParenLoc, literalType,
4290                diag::err_typecheck_decl_incomplete_type,
4291                SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
4292     return ExprError();
4293 
4294   InitializedEntity Entity
4295     = InitializedEntity::InitializeTemporary(literalType);
4296   InitializationKind Kind
4297     = InitializationKind::CreateCStyleCast(LParenLoc,
4298                                            SourceRange(LParenLoc, RParenLoc),
4299                                            /*InitList=*/true);
4300   InitializationSequence InitSeq(*this, Entity, Kind, &LiteralExpr, 1);
4301   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
4302                                       &literalType);
4303   if (Result.isInvalid())
4304     return ExprError();
4305   LiteralExpr = Result.get();
4306 
4307   bool isFileScope = getCurFunctionOrMethodDecl() == 0;
4308   if (isFileScope) { // 6.5.2.5p3
4309     if (CheckForConstantInitializer(LiteralExpr, literalType))
4310       return ExprError();
4311   }
4312 
4313   // In C, compound literals are l-values for some reason.
4314   ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue;
4315 
4316   return MaybeBindToTemporary(
4317            new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
4318                                              VK, LiteralExpr, isFileScope));
4319 }
4320 
4321 ExprResult
4322 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
4323                     SourceLocation RBraceLoc) {
4324   // Immediately handle non-overload placeholders.  Overloads can be
4325   // resolved contextually, but everything else here can't.
4326   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
4327     if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
4328       ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
4329 
4330       // Ignore failures; dropping the entire initializer list because
4331       // of one failure would be terrible for indexing/etc.
4332       if (result.isInvalid()) continue;
4333 
4334       InitArgList[I] = result.take();
4335     }
4336   }
4337 
4338   // Semantic analysis for initializers is done by ActOnDeclarator() and
4339   // CheckInitializer() - it requires knowledge of the object being intialized.
4340 
4341   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
4342                                                RBraceLoc);
4343   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
4344   return Owned(E);
4345 }
4346 
4347 /// Do an explicit extend of the given block pointer if we're in ARC.
4348 static void maybeExtendBlockObject(Sema &S, ExprResult &E) {
4349   assert(E.get()->getType()->isBlockPointerType());
4350   assert(E.get()->isRValue());
4351 
4352   // Only do this in an r-value context.
4353   if (!S.getLangOpts().ObjCAutoRefCount) return;
4354 
4355   E = ImplicitCastExpr::Create(S.Context, E.get()->getType(),
4356                                CK_ARCExtendBlockObject, E.get(),
4357                                /*base path*/ 0, VK_RValue);
4358   S.ExprNeedsCleanups = true;
4359 }
4360 
4361 /// Prepare a conversion of the given expression to an ObjC object
4362 /// pointer type.
4363 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
4364   QualType type = E.get()->getType();
4365   if (type->isObjCObjectPointerType()) {
4366     return CK_BitCast;
4367   } else if (type->isBlockPointerType()) {
4368     maybeExtendBlockObject(*this, E);
4369     return CK_BlockPointerToObjCPointerCast;
4370   } else {
4371     assert(type->isPointerType());
4372     return CK_CPointerToObjCPointerCast;
4373   }
4374 }
4375 
4376 /// Prepares for a scalar cast, performing all the necessary stages
4377 /// except the final cast and returning the kind required.
4378 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
4379   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
4380   // Also, callers should have filtered out the invalid cases with
4381   // pointers.  Everything else should be possible.
4382 
4383   QualType SrcTy = Src.get()->getType();
4384   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
4385     return CK_NoOp;
4386 
4387   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
4388   case Type::STK_MemberPointer:
4389     llvm_unreachable("member pointer type in C");
4390 
4391   case Type::STK_CPointer:
4392   case Type::STK_BlockPointer:
4393   case Type::STK_ObjCObjectPointer:
4394     switch (DestTy->getScalarTypeKind()) {
4395     case Type::STK_CPointer:
4396       return CK_BitCast;
4397     case Type::STK_BlockPointer:
4398       return (SrcKind == Type::STK_BlockPointer
4399                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
4400     case Type::STK_ObjCObjectPointer:
4401       if (SrcKind == Type::STK_ObjCObjectPointer)
4402         return CK_BitCast;
4403       if (SrcKind == Type::STK_CPointer)
4404         return CK_CPointerToObjCPointerCast;
4405       maybeExtendBlockObject(*this, Src);
4406       return CK_BlockPointerToObjCPointerCast;
4407     case Type::STK_Bool:
4408       return CK_PointerToBoolean;
4409     case Type::STK_Integral:
4410       return CK_PointerToIntegral;
4411     case Type::STK_Floating:
4412     case Type::STK_FloatingComplex:
4413     case Type::STK_IntegralComplex:
4414     case Type::STK_MemberPointer:
4415       llvm_unreachable("illegal cast from pointer");
4416     }
4417     llvm_unreachable("Should have returned before this");
4418 
4419   case Type::STK_Bool: // casting from bool is like casting from an integer
4420   case Type::STK_Integral:
4421     switch (DestTy->getScalarTypeKind()) {
4422     case Type::STK_CPointer:
4423     case Type::STK_ObjCObjectPointer:
4424     case Type::STK_BlockPointer:
4425       if (Src.get()->isNullPointerConstant(Context,
4426                                            Expr::NPC_ValueDependentIsNull))
4427         return CK_NullToPointer;
4428       return CK_IntegralToPointer;
4429     case Type::STK_Bool:
4430       return CK_IntegralToBoolean;
4431     case Type::STK_Integral:
4432       return CK_IntegralCast;
4433     case Type::STK_Floating:
4434       return CK_IntegralToFloating;
4435     case Type::STK_IntegralComplex:
4436       Src = ImpCastExprToType(Src.take(),
4437                               DestTy->castAs<ComplexType>()->getElementType(),
4438                               CK_IntegralCast);
4439       return CK_IntegralRealToComplex;
4440     case Type::STK_FloatingComplex:
4441       Src = ImpCastExprToType(Src.take(),
4442                               DestTy->castAs<ComplexType>()->getElementType(),
4443                               CK_IntegralToFloating);
4444       return CK_FloatingRealToComplex;
4445     case Type::STK_MemberPointer:
4446       llvm_unreachable("member pointer type in C");
4447     }
4448     llvm_unreachable("Should have returned before this");
4449 
4450   case Type::STK_Floating:
4451     switch (DestTy->getScalarTypeKind()) {
4452     case Type::STK_Floating:
4453       return CK_FloatingCast;
4454     case Type::STK_Bool:
4455       return CK_FloatingToBoolean;
4456     case Type::STK_Integral:
4457       return CK_FloatingToIntegral;
4458     case Type::STK_FloatingComplex:
4459       Src = ImpCastExprToType(Src.take(),
4460                               DestTy->castAs<ComplexType>()->getElementType(),
4461                               CK_FloatingCast);
4462       return CK_FloatingRealToComplex;
4463     case Type::STK_IntegralComplex:
4464       Src = ImpCastExprToType(Src.take(),
4465                               DestTy->castAs<ComplexType>()->getElementType(),
4466                               CK_FloatingToIntegral);
4467       return CK_IntegralRealToComplex;
4468     case Type::STK_CPointer:
4469     case Type::STK_ObjCObjectPointer:
4470     case Type::STK_BlockPointer:
4471       llvm_unreachable("valid float->pointer cast?");
4472     case Type::STK_MemberPointer:
4473       llvm_unreachable("member pointer type in C");
4474     }
4475     llvm_unreachable("Should have returned before this");
4476 
4477   case Type::STK_FloatingComplex:
4478     switch (DestTy->getScalarTypeKind()) {
4479     case Type::STK_FloatingComplex:
4480       return CK_FloatingComplexCast;
4481     case Type::STK_IntegralComplex:
4482       return CK_FloatingComplexToIntegralComplex;
4483     case Type::STK_Floating: {
4484       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
4485       if (Context.hasSameType(ET, DestTy))
4486         return CK_FloatingComplexToReal;
4487       Src = ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal);
4488       return CK_FloatingCast;
4489     }
4490     case Type::STK_Bool:
4491       return CK_FloatingComplexToBoolean;
4492     case Type::STK_Integral:
4493       Src = ImpCastExprToType(Src.take(),
4494                               SrcTy->castAs<ComplexType>()->getElementType(),
4495                               CK_FloatingComplexToReal);
4496       return CK_FloatingToIntegral;
4497     case Type::STK_CPointer:
4498     case Type::STK_ObjCObjectPointer:
4499     case Type::STK_BlockPointer:
4500       llvm_unreachable("valid complex float->pointer cast?");
4501     case Type::STK_MemberPointer:
4502       llvm_unreachable("member pointer type in C");
4503     }
4504     llvm_unreachable("Should have returned before this");
4505 
4506   case Type::STK_IntegralComplex:
4507     switch (DestTy->getScalarTypeKind()) {
4508     case Type::STK_FloatingComplex:
4509       return CK_IntegralComplexToFloatingComplex;
4510     case Type::STK_IntegralComplex:
4511       return CK_IntegralComplexCast;
4512     case Type::STK_Integral: {
4513       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
4514       if (Context.hasSameType(ET, DestTy))
4515         return CK_IntegralComplexToReal;
4516       Src = ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal);
4517       return CK_IntegralCast;
4518     }
4519     case Type::STK_Bool:
4520       return CK_IntegralComplexToBoolean;
4521     case Type::STK_Floating:
4522       Src = ImpCastExprToType(Src.take(),
4523                               SrcTy->castAs<ComplexType>()->getElementType(),
4524                               CK_IntegralComplexToReal);
4525       return CK_IntegralToFloating;
4526     case Type::STK_CPointer:
4527     case Type::STK_ObjCObjectPointer:
4528     case Type::STK_BlockPointer:
4529       llvm_unreachable("valid complex int->pointer cast?");
4530     case Type::STK_MemberPointer:
4531       llvm_unreachable("member pointer type in C");
4532     }
4533     llvm_unreachable("Should have returned before this");
4534   }
4535 
4536   llvm_unreachable("Unhandled scalar cast");
4537 }
4538 
4539 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
4540                            CastKind &Kind) {
4541   assert(VectorTy->isVectorType() && "Not a vector type!");
4542 
4543   if (Ty->isVectorType() || Ty->isIntegerType()) {
4544     if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
4545       return Diag(R.getBegin(),
4546                   Ty->isVectorType() ?
4547                   diag::err_invalid_conversion_between_vectors :
4548                   diag::err_invalid_conversion_between_vector_and_integer)
4549         << VectorTy << Ty << R;
4550   } else
4551     return Diag(R.getBegin(),
4552                 diag::err_invalid_conversion_between_vector_and_scalar)
4553       << VectorTy << Ty << R;
4554 
4555   Kind = CK_BitCast;
4556   return false;
4557 }
4558 
4559 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
4560                                     Expr *CastExpr, CastKind &Kind) {
4561   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
4562 
4563   QualType SrcTy = CastExpr->getType();
4564 
4565   // If SrcTy is a VectorType, the total size must match to explicitly cast to
4566   // an ExtVectorType.
4567   // In OpenCL, casts between vectors of different types are not allowed.
4568   // (See OpenCL 6.2).
4569   if (SrcTy->isVectorType()) {
4570     if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)
4571         || (getLangOpts().OpenCL &&
4572             (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
4573       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
4574         << DestTy << SrcTy << R;
4575       return ExprError();
4576     }
4577     Kind = CK_BitCast;
4578     return Owned(CastExpr);
4579   }
4580 
4581   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
4582   // conversion will take place first from scalar to elt type, and then
4583   // splat from elt type to vector.
4584   if (SrcTy->isPointerType())
4585     return Diag(R.getBegin(),
4586                 diag::err_invalid_conversion_between_vector_and_scalar)
4587       << DestTy << SrcTy << R;
4588 
4589   QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
4590   ExprResult CastExprRes = Owned(CastExpr);
4591   CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy);
4592   if (CastExprRes.isInvalid())
4593     return ExprError();
4594   CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take();
4595 
4596   Kind = CK_VectorSplat;
4597   return Owned(CastExpr);
4598 }
4599 
4600 ExprResult
4601 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
4602                     Declarator &D, ParsedType &Ty,
4603                     SourceLocation RParenLoc, Expr *CastExpr) {
4604   assert(!D.isInvalidType() && (CastExpr != 0) &&
4605          "ActOnCastExpr(): missing type or expr");
4606 
4607   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
4608   if (D.isInvalidType())
4609     return ExprError();
4610 
4611   if (getLangOpts().CPlusPlus) {
4612     // Check that there are no default arguments (C++ only).
4613     CheckExtraCXXDefaultArguments(D);
4614   }
4615 
4616   checkUnusedDeclAttributes(D);
4617 
4618   QualType castType = castTInfo->getType();
4619   Ty = CreateParsedType(castType, castTInfo);
4620 
4621   bool isVectorLiteral = false;
4622 
4623   // Check for an altivec or OpenCL literal,
4624   // i.e. all the elements are integer constants.
4625   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
4626   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
4627   if ((getLangOpts().AltiVec || getLangOpts().OpenCL)
4628        && castType->isVectorType() && (PE || PLE)) {
4629     if (PLE && PLE->getNumExprs() == 0) {
4630       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
4631       return ExprError();
4632     }
4633     if (PE || PLE->getNumExprs() == 1) {
4634       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
4635       if (!E->getType()->isVectorType())
4636         isVectorLiteral = true;
4637     }
4638     else
4639       isVectorLiteral = true;
4640   }
4641 
4642   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
4643   // then handle it as such.
4644   if (isVectorLiteral)
4645     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
4646 
4647   // If the Expr being casted is a ParenListExpr, handle it specially.
4648   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
4649   // sequence of BinOp comma operators.
4650   if (isa<ParenListExpr>(CastExpr)) {
4651     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
4652     if (Result.isInvalid()) return ExprError();
4653     CastExpr = Result.take();
4654   }
4655 
4656   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
4657 }
4658 
4659 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
4660                                     SourceLocation RParenLoc, Expr *E,
4661                                     TypeSourceInfo *TInfo) {
4662   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
4663          "Expected paren or paren list expression");
4664 
4665   Expr **exprs;
4666   unsigned numExprs;
4667   Expr *subExpr;
4668   SourceLocation LiteralLParenLoc, LiteralRParenLoc;
4669   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
4670     LiteralLParenLoc = PE->getLParenLoc();
4671     LiteralRParenLoc = PE->getRParenLoc();
4672     exprs = PE->getExprs();
4673     numExprs = PE->getNumExprs();
4674   } else { // isa<ParenExpr> by assertion at function entrance
4675     LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
4676     LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
4677     subExpr = cast<ParenExpr>(E)->getSubExpr();
4678     exprs = &subExpr;
4679     numExprs = 1;
4680   }
4681 
4682   QualType Ty = TInfo->getType();
4683   assert(Ty->isVectorType() && "Expected vector type");
4684 
4685   SmallVector<Expr *, 8> initExprs;
4686   const VectorType *VTy = Ty->getAs<VectorType>();
4687   unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
4688 
4689   // '(...)' form of vector initialization in AltiVec: the number of
4690   // initializers must be one or must match the size of the vector.
4691   // If a single value is specified in the initializer then it will be
4692   // replicated to all the components of the vector
4693   if (VTy->getVectorKind() == VectorType::AltiVecVector) {
4694     // The number of initializers must be one or must match the size of the
4695     // vector. If a single value is specified in the initializer then it will
4696     // be replicated to all the components of the vector
4697     if (numExprs == 1) {
4698       QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
4699       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
4700       if (Literal.isInvalid())
4701         return ExprError();
4702       Literal = ImpCastExprToType(Literal.take(), ElemTy,
4703                                   PrepareScalarCast(Literal, ElemTy));
4704       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4705     }
4706     else if (numExprs < numElems) {
4707       Diag(E->getExprLoc(),
4708            diag::err_incorrect_number_of_vector_initializers);
4709       return ExprError();
4710     }
4711     else
4712       initExprs.append(exprs, exprs + numExprs);
4713   }
4714   else {
4715     // For OpenCL, when the number of initializers is a single value,
4716     // it will be replicated to all components of the vector.
4717     if (getLangOpts().OpenCL &&
4718         VTy->getVectorKind() == VectorType::GenericVector &&
4719         numExprs == 1) {
4720         QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
4721         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
4722         if (Literal.isInvalid())
4723           return ExprError();
4724         Literal = ImpCastExprToType(Literal.take(), ElemTy,
4725                                     PrepareScalarCast(Literal, ElemTy));
4726         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4727     }
4728 
4729     initExprs.append(exprs, exprs + numExprs);
4730   }
4731   // FIXME: This means that pretty-printing the final AST will produce curly
4732   // braces instead of the original commas.
4733   InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
4734                                                    initExprs, LiteralRParenLoc);
4735   initE->setType(Ty);
4736   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
4737 }
4738 
4739 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
4740 /// the ParenListExpr into a sequence of comma binary operators.
4741 ExprResult
4742 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
4743   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
4744   if (!E)
4745     return Owned(OrigExpr);
4746 
4747   ExprResult Result(E->getExpr(0));
4748 
4749   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
4750     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
4751                         E->getExpr(i));
4752 
4753   if (Result.isInvalid()) return ExprError();
4754 
4755   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
4756 }
4757 
4758 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
4759                                     SourceLocation R,
4760                                     MultiExprArg Val) {
4761   Expr *expr = new (Context) ParenListExpr(Context, L, Val, R);
4762   return Owned(expr);
4763 }
4764 
4765 /// \brief Emit a specialized diagnostic when one expression is a null pointer
4766 /// constant and the other is not a pointer.  Returns true if a diagnostic is
4767 /// emitted.
4768 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
4769                                       SourceLocation QuestionLoc) {
4770   Expr *NullExpr = LHSExpr;
4771   Expr *NonPointerExpr = RHSExpr;
4772   Expr::NullPointerConstantKind NullKind =
4773       NullExpr->isNullPointerConstant(Context,
4774                                       Expr::NPC_ValueDependentIsNotNull);
4775 
4776   if (NullKind == Expr::NPCK_NotNull) {
4777     NullExpr = RHSExpr;
4778     NonPointerExpr = LHSExpr;
4779     NullKind =
4780         NullExpr->isNullPointerConstant(Context,
4781                                         Expr::NPC_ValueDependentIsNotNull);
4782   }
4783 
4784   if (NullKind == Expr::NPCK_NotNull)
4785     return false;
4786 
4787   if (NullKind == Expr::NPCK_ZeroExpression)
4788     return false;
4789 
4790   if (NullKind == Expr::NPCK_ZeroLiteral) {
4791     // In this case, check to make sure that we got here from a "NULL"
4792     // string in the source code.
4793     NullExpr = NullExpr->IgnoreParenImpCasts();
4794     SourceLocation loc = NullExpr->getExprLoc();
4795     if (!findMacroSpelling(loc, "NULL"))
4796       return false;
4797   }
4798 
4799   int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
4800   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
4801       << NonPointerExpr->getType() << DiagType
4802       << NonPointerExpr->getSourceRange();
4803   return true;
4804 }
4805 
4806 /// \brief Return false if the condition expression is valid, true otherwise.
4807 static bool checkCondition(Sema &S, Expr *Cond) {
4808   QualType CondTy = Cond->getType();
4809 
4810   // C99 6.5.15p2
4811   if (CondTy->isScalarType()) return false;
4812 
4813   // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
4814   if (S.getLangOpts().OpenCL && CondTy->isVectorType())
4815     return false;
4816 
4817   // Emit the proper error message.
4818   S.Diag(Cond->getLocStart(), S.getLangOpts().OpenCL ?
4819                               diag::err_typecheck_cond_expect_scalar :
4820                               diag::err_typecheck_cond_expect_scalar_or_vector)
4821     << CondTy;
4822   return true;
4823 }
4824 
4825 /// \brief Return false if the two expressions can be converted to a vector,
4826 /// true otherwise
4827 static bool checkConditionalConvertScalarsToVectors(Sema &S, ExprResult &LHS,
4828                                                     ExprResult &RHS,
4829                                                     QualType CondTy) {
4830   // Both operands should be of scalar type.
4831   if (!LHS.get()->getType()->isScalarType()) {
4832     S.Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4833       << CondTy;
4834     return true;
4835   }
4836   if (!RHS.get()->getType()->isScalarType()) {
4837     S.Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4838       << CondTy;
4839     return true;
4840   }
4841 
4842   // Implicity convert these scalars to the type of the condition.
4843   LHS = S.ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast);
4844   RHS = S.ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast);
4845   return false;
4846 }
4847 
4848 /// \brief Handle when one or both operands are void type.
4849 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
4850                                          ExprResult &RHS) {
4851     Expr *LHSExpr = LHS.get();
4852     Expr *RHSExpr = RHS.get();
4853 
4854     if (!LHSExpr->getType()->isVoidType())
4855       S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4856         << RHSExpr->getSourceRange();
4857     if (!RHSExpr->getType()->isVoidType())
4858       S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4859         << LHSExpr->getSourceRange();
4860     LHS = S.ImpCastExprToType(LHS.take(), S.Context.VoidTy, CK_ToVoid);
4861     RHS = S.ImpCastExprToType(RHS.take(), S.Context.VoidTy, CK_ToVoid);
4862     return S.Context.VoidTy;
4863 }
4864 
4865 /// \brief Return false if the NullExpr can be promoted to PointerTy,
4866 /// true otherwise.
4867 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
4868                                         QualType PointerTy) {
4869   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
4870       !NullExpr.get()->isNullPointerConstant(S.Context,
4871                                             Expr::NPC_ValueDependentIsNull))
4872     return true;
4873 
4874   NullExpr = S.ImpCastExprToType(NullExpr.take(), PointerTy, CK_NullToPointer);
4875   return false;
4876 }
4877 
4878 /// \brief Checks compatibility between two pointers and return the resulting
4879 /// type.
4880 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
4881                                                      ExprResult &RHS,
4882                                                      SourceLocation Loc) {
4883   QualType LHSTy = LHS.get()->getType();
4884   QualType RHSTy = RHS.get()->getType();
4885 
4886   if (S.Context.hasSameType(LHSTy, RHSTy)) {
4887     // Two identical pointers types are always compatible.
4888     return LHSTy;
4889   }
4890 
4891   QualType lhptee, rhptee;
4892 
4893   // Get the pointee types.
4894   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
4895     lhptee = LHSBTy->getPointeeType();
4896     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
4897   } else {
4898     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
4899     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
4900   }
4901 
4902   // C99 6.5.15p6: If both operands are pointers to compatible types or to
4903   // differently qualified versions of compatible types, the result type is
4904   // a pointer to an appropriately qualified version of the composite
4905   // type.
4906 
4907   // Only CVR-qualifiers exist in the standard, and the differently-qualified
4908   // clause doesn't make sense for our extensions. E.g. address space 2 should
4909   // be incompatible with address space 3: they may live on different devices or
4910   // anything.
4911   Qualifiers lhQual = lhptee.getQualifiers();
4912   Qualifiers rhQual = rhptee.getQualifiers();
4913 
4914   unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
4915   lhQual.removeCVRQualifiers();
4916   rhQual.removeCVRQualifiers();
4917 
4918   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
4919   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
4920 
4921   QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
4922 
4923   if (CompositeTy.isNull()) {
4924     S.Diag(Loc, diag::warn_typecheck_cond_incompatible_pointers)
4925       << LHSTy << RHSTy << LHS.get()->getSourceRange()
4926       << RHS.get()->getSourceRange();
4927     // In this situation, we assume void* type. No especially good
4928     // reason, but this is what gcc does, and we do have to pick
4929     // to get a consistent AST.
4930     QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy);
4931     LHS = S.ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4932     RHS = S.ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
4933     return incompatTy;
4934   }
4935 
4936   // The pointer types are compatible.
4937   QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual);
4938   ResultTy = S.Context.getPointerType(ResultTy);
4939 
4940   LHS = S.ImpCastExprToType(LHS.take(), ResultTy, CK_BitCast);
4941   RHS = S.ImpCastExprToType(RHS.take(), ResultTy, CK_BitCast);
4942   return ResultTy;
4943 }
4944 
4945 /// \brief Return the resulting type when the operands are both block pointers.
4946 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
4947                                                           ExprResult &LHS,
4948                                                           ExprResult &RHS,
4949                                                           SourceLocation Loc) {
4950   QualType LHSTy = LHS.get()->getType();
4951   QualType RHSTy = RHS.get()->getType();
4952 
4953   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
4954     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
4955       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
4956       LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4957       RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4958       return destType;
4959     }
4960     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
4961       << LHSTy << RHSTy << LHS.get()->getSourceRange()
4962       << RHS.get()->getSourceRange();
4963     return QualType();
4964   }
4965 
4966   // We have 2 block pointer types.
4967   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
4968 }
4969 
4970 /// \brief Return the resulting type when the operands are both pointers.
4971 static QualType
4972 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
4973                                             ExprResult &RHS,
4974                                             SourceLocation Loc) {
4975   // get the pointer types
4976   QualType LHSTy = LHS.get()->getType();
4977   QualType RHSTy = RHS.get()->getType();
4978 
4979   // get the "pointed to" types
4980   QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4981   QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4982 
4983   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
4984   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
4985     // Figure out necessary qualifiers (C99 6.5.15p6)
4986     QualType destPointee
4987       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4988     QualType destType = S.Context.getPointerType(destPointee);
4989     // Add qualifiers if necessary.
4990     LHS = S.ImpCastExprToType(LHS.take(), destType, CK_NoOp);
4991     // Promote to void*.
4992     RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4993     return destType;
4994   }
4995   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
4996     QualType destPointee
4997       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4998     QualType destType = S.Context.getPointerType(destPointee);
4999     // Add qualifiers if necessary.
5000     RHS = S.ImpCastExprToType(RHS.take(), destType, CK_NoOp);
5001     // Promote to void*.
5002     LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
5003     return destType;
5004   }
5005 
5006   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
5007 }
5008 
5009 /// \brief Return false if the first expression is not an integer and the second
5010 /// expression is not a pointer, true otherwise.
5011 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
5012                                         Expr* PointerExpr, SourceLocation Loc,
5013                                         bool IsIntFirstExpr) {
5014   if (!PointerExpr->getType()->isPointerType() ||
5015       !Int.get()->getType()->isIntegerType())
5016     return false;
5017 
5018   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
5019   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
5020 
5021   S.Diag(Loc, diag::warn_typecheck_cond_pointer_integer_mismatch)
5022     << Expr1->getType() << Expr2->getType()
5023     << Expr1->getSourceRange() << Expr2->getSourceRange();
5024   Int = S.ImpCastExprToType(Int.take(), PointerExpr->getType(),
5025                             CK_IntegralToPointer);
5026   return true;
5027 }
5028 
5029 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
5030 /// In that case, LHS = cond.
5031 /// C99 6.5.15
5032 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
5033                                         ExprResult &RHS, ExprValueKind &VK,
5034                                         ExprObjectKind &OK,
5035                                         SourceLocation QuestionLoc) {
5036 
5037   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
5038   if (!LHSResult.isUsable()) return QualType();
5039   LHS = LHSResult;
5040 
5041   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
5042   if (!RHSResult.isUsable()) return QualType();
5043   RHS = RHSResult;
5044 
5045   // C++ is sufficiently different to merit its own checker.
5046   if (getLangOpts().CPlusPlus)
5047     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
5048 
5049   VK = VK_RValue;
5050   OK = OK_Ordinary;
5051 
5052   Cond = UsualUnaryConversions(Cond.take());
5053   if (Cond.isInvalid())
5054     return QualType();
5055   LHS = UsualUnaryConversions(LHS.take());
5056   if (LHS.isInvalid())
5057     return QualType();
5058   RHS = UsualUnaryConversions(RHS.take());
5059   if (RHS.isInvalid())
5060     return QualType();
5061 
5062   QualType CondTy = Cond.get()->getType();
5063   QualType LHSTy = LHS.get()->getType();
5064   QualType RHSTy = RHS.get()->getType();
5065 
5066   // first, check the condition.
5067   if (checkCondition(*this, Cond.get()))
5068     return QualType();
5069 
5070   // Now check the two expressions.
5071   if (LHSTy->isVectorType() || RHSTy->isVectorType())
5072     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
5073 
5074   // OpenCL: If the condition is a vector, and both operands are scalar,
5075   // attempt to implicity convert them to the vector type to act like the
5076   // built in select.
5077   if (getLangOpts().OpenCL && CondTy->isVectorType())
5078     if (checkConditionalConvertScalarsToVectors(*this, LHS, RHS, CondTy))
5079       return QualType();
5080 
5081   // If both operands have arithmetic type, do the usual arithmetic conversions
5082   // to find a common type: C99 6.5.15p3,5.
5083   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
5084     UsualArithmeticConversions(LHS, RHS);
5085     if (LHS.isInvalid() || RHS.isInvalid())
5086       return QualType();
5087     return LHS.get()->getType();
5088   }
5089 
5090   // If both operands are the same structure or union type, the result is that
5091   // type.
5092   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
5093     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
5094       if (LHSRT->getDecl() == RHSRT->getDecl())
5095         // "If both the operands have structure or union type, the result has
5096         // that type."  This implies that CV qualifiers are dropped.
5097         return LHSTy.getUnqualifiedType();
5098     // FIXME: Type of conditional expression must be complete in C mode.
5099   }
5100 
5101   // C99 6.5.15p5: "If both operands have void type, the result has void type."
5102   // The following || allows only one side to be void (a GCC-ism).
5103   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
5104     return checkConditionalVoidType(*this, LHS, RHS);
5105   }
5106 
5107   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
5108   // the type of the other operand."
5109   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
5110   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
5111 
5112   // All objective-c pointer type analysis is done here.
5113   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
5114                                                         QuestionLoc);
5115   if (LHS.isInvalid() || RHS.isInvalid())
5116     return QualType();
5117   if (!compositeType.isNull())
5118     return compositeType;
5119 
5120 
5121   // Handle block pointer types.
5122   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
5123     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
5124                                                      QuestionLoc);
5125 
5126   // Check constraints for C object pointers types (C99 6.5.15p3,6).
5127   if (LHSTy->isPointerType() && RHSTy->isPointerType())
5128     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
5129                                                        QuestionLoc);
5130 
5131   // GCC compatibility: soften pointer/integer mismatch.  Note that
5132   // null pointers have been filtered out by this point.
5133   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
5134       /*isIntFirstExpr=*/true))
5135     return RHSTy;
5136   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
5137       /*isIntFirstExpr=*/false))
5138     return LHSTy;
5139 
5140   // Emit a better diagnostic if one of the expressions is a null pointer
5141   // constant and the other is not a pointer type. In this case, the user most
5142   // likely forgot to take the address of the other expression.
5143   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
5144     return QualType();
5145 
5146   // Otherwise, the operands are not compatible.
5147   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
5148     << LHSTy << RHSTy << LHS.get()->getSourceRange()
5149     << RHS.get()->getSourceRange();
5150   return QualType();
5151 }
5152 
5153 /// FindCompositeObjCPointerType - Helper method to find composite type of
5154 /// two objective-c pointer types of the two input expressions.
5155 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
5156                                             SourceLocation QuestionLoc) {
5157   QualType LHSTy = LHS.get()->getType();
5158   QualType RHSTy = RHS.get()->getType();
5159 
5160   // Handle things like Class and struct objc_class*.  Here we case the result
5161   // to the pseudo-builtin, because that will be implicitly cast back to the
5162   // redefinition type if an attempt is made to access its fields.
5163   if (LHSTy->isObjCClassType() &&
5164       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
5165     RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
5166     return LHSTy;
5167   }
5168   if (RHSTy->isObjCClassType() &&
5169       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
5170     LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
5171     return RHSTy;
5172   }
5173   // And the same for struct objc_object* / id
5174   if (LHSTy->isObjCIdType() &&
5175       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
5176     RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
5177     return LHSTy;
5178   }
5179   if (RHSTy->isObjCIdType() &&
5180       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
5181     LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
5182     return RHSTy;
5183   }
5184   // And the same for struct objc_selector* / SEL
5185   if (Context.isObjCSelType(LHSTy) &&
5186       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
5187     RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
5188     return LHSTy;
5189   }
5190   if (Context.isObjCSelType(RHSTy) &&
5191       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
5192     LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
5193     return RHSTy;
5194   }
5195   // Check constraints for Objective-C object pointers types.
5196   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
5197 
5198     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5199       // Two identical object pointer types are always compatible.
5200       return LHSTy;
5201     }
5202     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
5203     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
5204     QualType compositeType = LHSTy;
5205 
5206     // If both operands are interfaces and either operand can be
5207     // assigned to the other, use that type as the composite
5208     // type. This allows
5209     //   xxx ? (A*) a : (B*) b
5210     // where B is a subclass of A.
5211     //
5212     // Additionally, as for assignment, if either type is 'id'
5213     // allow silent coercion. Finally, if the types are
5214     // incompatible then make sure to use 'id' as the composite
5215     // type so the result is acceptable for sending messages to.
5216 
5217     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
5218     // It could return the composite type.
5219     if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
5220       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
5221     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
5222       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
5223     } else if ((LHSTy->isObjCQualifiedIdType() ||
5224                 RHSTy->isObjCQualifiedIdType()) &&
5225                Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
5226       // Need to handle "id<xx>" explicitly.
5227       // GCC allows qualified id and any Objective-C type to devolve to
5228       // id. Currently localizing to here until clear this should be
5229       // part of ObjCQualifiedIdTypesAreCompatible.
5230       compositeType = Context.getObjCIdType();
5231     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
5232       compositeType = Context.getObjCIdType();
5233     } else if (!(compositeType =
5234                  Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
5235       ;
5236     else {
5237       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
5238       << LHSTy << RHSTy
5239       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5240       QualType incompatTy = Context.getObjCIdType();
5241       LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
5242       RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
5243       return incompatTy;
5244     }
5245     // The object pointer types are compatible.
5246     LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast);
5247     RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast);
5248     return compositeType;
5249   }
5250   // Check Objective-C object pointer types and 'void *'
5251   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
5252     if (getLangOpts().ObjCAutoRefCount) {
5253       // ARC forbids the implicit conversion of object pointers to 'void *',
5254       // so these types are not compatible.
5255       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
5256           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5257       LHS = RHS = true;
5258       return QualType();
5259     }
5260     QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5261     QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5262     QualType destPointee
5263     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
5264     QualType destType = Context.getPointerType(destPointee);
5265     // Add qualifiers if necessary.
5266     LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
5267     // Promote to void*.
5268     RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
5269     return destType;
5270   }
5271   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
5272     if (getLangOpts().ObjCAutoRefCount) {
5273       // ARC forbids the implicit conversion of object pointers to 'void *',
5274       // so these types are not compatible.
5275       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
5276           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5277       LHS = RHS = true;
5278       return QualType();
5279     }
5280     QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5281     QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
5282     QualType destPointee
5283     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
5284     QualType destType = Context.getPointerType(destPointee);
5285     // Add qualifiers if necessary.
5286     RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
5287     // Promote to void*.
5288     LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
5289     return destType;
5290   }
5291   return QualType();
5292 }
5293 
5294 /// SuggestParentheses - Emit a note with a fixit hint that wraps
5295 /// ParenRange in parentheses.
5296 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
5297                                const PartialDiagnostic &Note,
5298                                SourceRange ParenRange) {
5299   SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
5300   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
5301       EndLoc.isValid()) {
5302     Self.Diag(Loc, Note)
5303       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
5304       << FixItHint::CreateInsertion(EndLoc, ")");
5305   } else {
5306     // We can't display the parentheses, so just show the bare note.
5307     Self.Diag(Loc, Note) << ParenRange;
5308   }
5309 }
5310 
5311 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
5312   return Opc >= BO_Mul && Opc <= BO_Shr;
5313 }
5314 
5315 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
5316 /// expression, either using a built-in or overloaded operator,
5317 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
5318 /// expression.
5319 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
5320                                    Expr **RHSExprs) {
5321   // Don't strip parenthesis: we should not warn if E is in parenthesis.
5322   E = E->IgnoreImpCasts();
5323   E = E->IgnoreConversionOperator();
5324   E = E->IgnoreImpCasts();
5325 
5326   // Built-in binary operator.
5327   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
5328     if (IsArithmeticOp(OP->getOpcode())) {
5329       *Opcode = OP->getOpcode();
5330       *RHSExprs = OP->getRHS();
5331       return true;
5332     }
5333   }
5334 
5335   // Overloaded operator.
5336   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
5337     if (Call->getNumArgs() != 2)
5338       return false;
5339 
5340     // Make sure this is really a binary operator that is safe to pass into
5341     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
5342     OverloadedOperatorKind OO = Call->getOperator();
5343     if (OO < OO_Plus || OO > OO_Arrow)
5344       return false;
5345 
5346     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
5347     if (IsArithmeticOp(OpKind)) {
5348       *Opcode = OpKind;
5349       *RHSExprs = Call->getArg(1);
5350       return true;
5351     }
5352   }
5353 
5354   return false;
5355 }
5356 
5357 static bool IsLogicOp(BinaryOperatorKind Opc) {
5358   return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
5359 }
5360 
5361 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
5362 /// or is a logical expression such as (x==y) which has int type, but is
5363 /// commonly interpreted as boolean.
5364 static bool ExprLooksBoolean(Expr *E) {
5365   E = E->IgnoreParenImpCasts();
5366 
5367   if (E->getType()->isBooleanType())
5368     return true;
5369   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
5370     return IsLogicOp(OP->getOpcode());
5371   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
5372     return OP->getOpcode() == UO_LNot;
5373 
5374   return false;
5375 }
5376 
5377 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
5378 /// and binary operator are mixed in a way that suggests the programmer assumed
5379 /// the conditional operator has higher precedence, for example:
5380 /// "int x = a + someBinaryCondition ? 1 : 2".
5381 static void DiagnoseConditionalPrecedence(Sema &Self,
5382                                           SourceLocation OpLoc,
5383                                           Expr *Condition,
5384                                           Expr *LHSExpr,
5385                                           Expr *RHSExpr) {
5386   BinaryOperatorKind CondOpcode;
5387   Expr *CondRHS;
5388 
5389   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
5390     return;
5391   if (!ExprLooksBoolean(CondRHS))
5392     return;
5393 
5394   // The condition is an arithmetic binary expression, with a right-
5395   // hand side that looks boolean, so warn.
5396 
5397   Self.Diag(OpLoc, diag::warn_precedence_conditional)
5398       << Condition->getSourceRange()
5399       << BinaryOperator::getOpcodeStr(CondOpcode);
5400 
5401   SuggestParentheses(Self, OpLoc,
5402     Self.PDiag(diag::note_precedence_silence)
5403       << BinaryOperator::getOpcodeStr(CondOpcode),
5404     SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
5405 
5406   SuggestParentheses(Self, OpLoc,
5407     Self.PDiag(diag::note_precedence_conditional_first),
5408     SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
5409 }
5410 
5411 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
5412 /// in the case of a the GNU conditional expr extension.
5413 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
5414                                     SourceLocation ColonLoc,
5415                                     Expr *CondExpr, Expr *LHSExpr,
5416                                     Expr *RHSExpr) {
5417   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
5418   // was the condition.
5419   OpaqueValueExpr *opaqueValue = 0;
5420   Expr *commonExpr = 0;
5421   if (LHSExpr == 0) {
5422     commonExpr = CondExpr;
5423 
5424     // We usually want to apply unary conversions *before* saving, except
5425     // in the special case of a C++ l-value conditional.
5426     if (!(getLangOpts().CPlusPlus
5427           && !commonExpr->isTypeDependent()
5428           && commonExpr->getValueKind() == RHSExpr->getValueKind()
5429           && commonExpr->isGLValue()
5430           && commonExpr->isOrdinaryOrBitFieldObject()
5431           && RHSExpr->isOrdinaryOrBitFieldObject()
5432           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
5433       ExprResult commonRes = UsualUnaryConversions(commonExpr);
5434       if (commonRes.isInvalid())
5435         return ExprError();
5436       commonExpr = commonRes.take();
5437     }
5438 
5439     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
5440                                                 commonExpr->getType(),
5441                                                 commonExpr->getValueKind(),
5442                                                 commonExpr->getObjectKind(),
5443                                                 commonExpr);
5444     LHSExpr = CondExpr = opaqueValue;
5445   }
5446 
5447   ExprValueKind VK = VK_RValue;
5448   ExprObjectKind OK = OK_Ordinary;
5449   ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
5450   QualType result = CheckConditionalOperands(Cond, LHS, RHS,
5451                                              VK, OK, QuestionLoc);
5452   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
5453       RHS.isInvalid())
5454     return ExprError();
5455 
5456   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
5457                                 RHS.get());
5458 
5459   if (!commonExpr)
5460     return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc,
5461                                                    LHS.take(), ColonLoc,
5462                                                    RHS.take(), result, VK, OK));
5463 
5464   return Owned(new (Context)
5465     BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(),
5466                               RHS.take(), QuestionLoc, ColonLoc, result, VK,
5467                               OK));
5468 }
5469 
5470 // checkPointerTypesForAssignment - This is a very tricky routine (despite
5471 // being closely modeled after the C99 spec:-). The odd characteristic of this
5472 // routine is it effectively iqnores the qualifiers on the top level pointee.
5473 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
5474 // FIXME: add a couple examples in this comment.
5475 static Sema::AssignConvertType
5476 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
5477   assert(LHSType.isCanonical() && "LHS not canonicalized!");
5478   assert(RHSType.isCanonical() && "RHS not canonicalized!");
5479 
5480   // get the "pointed to" type (ignoring qualifiers at the top level)
5481   const Type *lhptee, *rhptee;
5482   Qualifiers lhq, rhq;
5483   llvm::tie(lhptee, lhq) = cast<PointerType>(LHSType)->getPointeeType().split();
5484   llvm::tie(rhptee, rhq) = cast<PointerType>(RHSType)->getPointeeType().split();
5485 
5486   Sema::AssignConvertType ConvTy = Sema::Compatible;
5487 
5488   // C99 6.5.16.1p1: This following citation is common to constraints
5489   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
5490   // qualifiers of the type *pointed to* by the right;
5491   Qualifiers lq;
5492 
5493   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
5494   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
5495       lhq.compatiblyIncludesObjCLifetime(rhq)) {
5496     // Ignore lifetime for further calculation.
5497     lhq.removeObjCLifetime();
5498     rhq.removeObjCLifetime();
5499   }
5500 
5501   if (!lhq.compatiblyIncludes(rhq)) {
5502     // Treat address-space mismatches as fatal.  TODO: address subspaces
5503     if (lhq.getAddressSpace() != rhq.getAddressSpace())
5504       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5505 
5506     // It's okay to add or remove GC or lifetime qualifiers when converting to
5507     // and from void*.
5508     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
5509                         .compatiblyIncludes(
5510                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
5511              && (lhptee->isVoidType() || rhptee->isVoidType()))
5512       ; // keep old
5513 
5514     // Treat lifetime mismatches as fatal.
5515     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
5516       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5517 
5518     // For GCC compatibility, other qualifier mismatches are treated
5519     // as still compatible in C.
5520     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
5521   }
5522 
5523   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
5524   // incomplete type and the other is a pointer to a qualified or unqualified
5525   // version of void...
5526   if (lhptee->isVoidType()) {
5527     if (rhptee->isIncompleteOrObjectType())
5528       return ConvTy;
5529 
5530     // As an extension, we allow cast to/from void* to function pointer.
5531     assert(rhptee->isFunctionType());
5532     return Sema::FunctionVoidPointer;
5533   }
5534 
5535   if (rhptee->isVoidType()) {
5536     if (lhptee->isIncompleteOrObjectType())
5537       return ConvTy;
5538 
5539     // As an extension, we allow cast to/from void* to function pointer.
5540     assert(lhptee->isFunctionType());
5541     return Sema::FunctionVoidPointer;
5542   }
5543 
5544   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
5545   // unqualified versions of compatible types, ...
5546   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
5547   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
5548     // Check if the pointee types are compatible ignoring the sign.
5549     // We explicitly check for char so that we catch "char" vs
5550     // "unsigned char" on systems where "char" is unsigned.
5551     if (lhptee->isCharType())
5552       ltrans = S.Context.UnsignedCharTy;
5553     else if (lhptee->hasSignedIntegerRepresentation())
5554       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
5555 
5556     if (rhptee->isCharType())
5557       rtrans = S.Context.UnsignedCharTy;
5558     else if (rhptee->hasSignedIntegerRepresentation())
5559       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
5560 
5561     if (ltrans == rtrans) {
5562       // Types are compatible ignoring the sign. Qualifier incompatibility
5563       // takes priority over sign incompatibility because the sign
5564       // warning can be disabled.
5565       if (ConvTy != Sema::Compatible)
5566         return ConvTy;
5567 
5568       return Sema::IncompatiblePointerSign;
5569     }
5570 
5571     // If we are a multi-level pointer, it's possible that our issue is simply
5572     // one of qualification - e.g. char ** -> const char ** is not allowed. If
5573     // the eventual target type is the same and the pointers have the same
5574     // level of indirection, this must be the issue.
5575     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
5576       do {
5577         lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
5578         rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
5579       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
5580 
5581       if (lhptee == rhptee)
5582         return Sema::IncompatibleNestedPointerQualifiers;
5583     }
5584 
5585     // General pointer incompatibility takes priority over qualifiers.
5586     return Sema::IncompatiblePointer;
5587   }
5588   if (!S.getLangOpts().CPlusPlus &&
5589       S.IsNoReturnConversion(ltrans, rtrans, ltrans))
5590     return Sema::IncompatiblePointer;
5591   return ConvTy;
5592 }
5593 
5594 /// checkBlockPointerTypesForAssignment - This routine determines whether two
5595 /// block pointer types are compatible or whether a block and normal pointer
5596 /// are compatible. It is more restrict than comparing two function pointer
5597 // types.
5598 static Sema::AssignConvertType
5599 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
5600                                     QualType RHSType) {
5601   assert(LHSType.isCanonical() && "LHS not canonicalized!");
5602   assert(RHSType.isCanonical() && "RHS not canonicalized!");
5603 
5604   QualType lhptee, rhptee;
5605 
5606   // get the "pointed to" type (ignoring qualifiers at the top level)
5607   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
5608   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
5609 
5610   // In C++, the types have to match exactly.
5611   if (S.getLangOpts().CPlusPlus)
5612     return Sema::IncompatibleBlockPointer;
5613 
5614   Sema::AssignConvertType ConvTy = Sema::Compatible;
5615 
5616   // For blocks we enforce that qualifiers are identical.
5617   if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
5618     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
5619 
5620   if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
5621     return Sema::IncompatibleBlockPointer;
5622 
5623   return ConvTy;
5624 }
5625 
5626 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
5627 /// for assignment compatibility.
5628 static Sema::AssignConvertType
5629 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
5630                                    QualType RHSType) {
5631   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
5632   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
5633 
5634   if (LHSType->isObjCBuiltinType()) {
5635     // Class is not compatible with ObjC object pointers.
5636     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
5637         !RHSType->isObjCQualifiedClassType())
5638       return Sema::IncompatiblePointer;
5639     return Sema::Compatible;
5640   }
5641   if (RHSType->isObjCBuiltinType()) {
5642     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
5643         !LHSType->isObjCQualifiedClassType())
5644       return Sema::IncompatiblePointer;
5645     return Sema::Compatible;
5646   }
5647   QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
5648   QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
5649 
5650   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
5651       // make an exception for id<P>
5652       !LHSType->isObjCQualifiedIdType())
5653     return Sema::CompatiblePointerDiscardsQualifiers;
5654 
5655   if (S.Context.typesAreCompatible(LHSType, RHSType))
5656     return Sema::Compatible;
5657   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
5658     return Sema::IncompatibleObjCQualifiedId;
5659   return Sema::IncompatiblePointer;
5660 }
5661 
5662 Sema::AssignConvertType
5663 Sema::CheckAssignmentConstraints(SourceLocation Loc,
5664                                  QualType LHSType, QualType RHSType) {
5665   // Fake up an opaque expression.  We don't actually care about what
5666   // cast operations are required, so if CheckAssignmentConstraints
5667   // adds casts to this they'll be wasted, but fortunately that doesn't
5668   // usually happen on valid code.
5669   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
5670   ExprResult RHSPtr = &RHSExpr;
5671   CastKind K = CK_Invalid;
5672 
5673   return CheckAssignmentConstraints(LHSType, RHSPtr, K);
5674 }
5675 
5676 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
5677 /// has code to accommodate several GCC extensions when type checking
5678 /// pointers. Here are some objectionable examples that GCC considers warnings:
5679 ///
5680 ///  int a, *pint;
5681 ///  short *pshort;
5682 ///  struct foo *pfoo;
5683 ///
5684 ///  pint = pshort; // warning: assignment from incompatible pointer type
5685 ///  a = pint; // warning: assignment makes integer from pointer without a cast
5686 ///  pint = a; // warning: assignment makes pointer from integer without a cast
5687 ///  pint = pfoo; // warning: assignment from incompatible pointer type
5688 ///
5689 /// As a result, the code for dealing with pointers is more complex than the
5690 /// C99 spec dictates.
5691 ///
5692 /// Sets 'Kind' for any result kind except Incompatible.
5693 Sema::AssignConvertType
5694 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
5695                                  CastKind &Kind) {
5696   QualType RHSType = RHS.get()->getType();
5697   QualType OrigLHSType = LHSType;
5698 
5699   // Get canonical types.  We're not formatting these types, just comparing
5700   // them.
5701   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
5702   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
5703 
5704   // Common case: no conversion required.
5705   if (LHSType == RHSType) {
5706     Kind = CK_NoOp;
5707     return Compatible;
5708   }
5709 
5710   // If we have an atomic type, try a non-atomic assignment, then just add an
5711   // atomic qualification step.
5712   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
5713     Sema::AssignConvertType result =
5714       CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
5715     if (result != Compatible)
5716       return result;
5717     if (Kind != CK_NoOp)
5718       RHS = ImpCastExprToType(RHS.take(), AtomicTy->getValueType(), Kind);
5719     Kind = CK_NonAtomicToAtomic;
5720     return Compatible;
5721   }
5722 
5723   // If the left-hand side is a reference type, then we are in a
5724   // (rare!) case where we've allowed the use of references in C,
5725   // e.g., as a parameter type in a built-in function. In this case,
5726   // just make sure that the type referenced is compatible with the
5727   // right-hand side type. The caller is responsible for adjusting
5728   // LHSType so that the resulting expression does not have reference
5729   // type.
5730   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
5731     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
5732       Kind = CK_LValueBitCast;
5733       return Compatible;
5734     }
5735     return Incompatible;
5736   }
5737 
5738   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
5739   // to the same ExtVector type.
5740   if (LHSType->isExtVectorType()) {
5741     if (RHSType->isExtVectorType())
5742       return Incompatible;
5743     if (RHSType->isArithmeticType()) {
5744       // CK_VectorSplat does T -> vector T, so first cast to the
5745       // element type.
5746       QualType elType = cast<ExtVectorType>(LHSType)->getElementType();
5747       if (elType != RHSType) {
5748         Kind = PrepareScalarCast(RHS, elType);
5749         RHS = ImpCastExprToType(RHS.take(), elType, Kind);
5750       }
5751       Kind = CK_VectorSplat;
5752       return Compatible;
5753     }
5754   }
5755 
5756   // Conversions to or from vector type.
5757   if (LHSType->isVectorType() || RHSType->isVectorType()) {
5758     if (LHSType->isVectorType() && RHSType->isVectorType()) {
5759       // Allow assignments of an AltiVec vector type to an equivalent GCC
5760       // vector type and vice versa
5761       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
5762         Kind = CK_BitCast;
5763         return Compatible;
5764       }
5765 
5766       // If we are allowing lax vector conversions, and LHS and RHS are both
5767       // vectors, the total size only needs to be the same. This is a bitcast;
5768       // no bits are changed but the result type is different.
5769       if (getLangOpts().LaxVectorConversions &&
5770           (Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType))) {
5771         Kind = CK_BitCast;
5772         return IncompatibleVectors;
5773       }
5774     }
5775     return Incompatible;
5776   }
5777 
5778   // Arithmetic conversions.
5779   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
5780       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
5781     Kind = PrepareScalarCast(RHS, LHSType);
5782     return Compatible;
5783   }
5784 
5785   // Conversions to normal pointers.
5786   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
5787     // U* -> T*
5788     if (isa<PointerType>(RHSType)) {
5789       Kind = CK_BitCast;
5790       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
5791     }
5792 
5793     // int -> T*
5794     if (RHSType->isIntegerType()) {
5795       Kind = CK_IntegralToPointer; // FIXME: null?
5796       return IntToPointer;
5797     }
5798 
5799     // C pointers are not compatible with ObjC object pointers,
5800     // with two exceptions:
5801     if (isa<ObjCObjectPointerType>(RHSType)) {
5802       //  - conversions to void*
5803       if (LHSPointer->getPointeeType()->isVoidType()) {
5804         Kind = CK_BitCast;
5805         return Compatible;
5806       }
5807 
5808       //  - conversions from 'Class' to the redefinition type
5809       if (RHSType->isObjCClassType() &&
5810           Context.hasSameType(LHSType,
5811                               Context.getObjCClassRedefinitionType())) {
5812         Kind = CK_BitCast;
5813         return Compatible;
5814       }
5815 
5816       Kind = CK_BitCast;
5817       return IncompatiblePointer;
5818     }
5819 
5820     // U^ -> void*
5821     if (RHSType->getAs<BlockPointerType>()) {
5822       if (LHSPointer->getPointeeType()->isVoidType()) {
5823         Kind = CK_BitCast;
5824         return Compatible;
5825       }
5826     }
5827 
5828     return Incompatible;
5829   }
5830 
5831   // Conversions to block pointers.
5832   if (isa<BlockPointerType>(LHSType)) {
5833     // U^ -> T^
5834     if (RHSType->isBlockPointerType()) {
5835       Kind = CK_BitCast;
5836       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
5837     }
5838 
5839     // int or null -> T^
5840     if (RHSType->isIntegerType()) {
5841       Kind = CK_IntegralToPointer; // FIXME: null
5842       return IntToBlockPointer;
5843     }
5844 
5845     // id -> T^
5846     if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
5847       Kind = CK_AnyPointerToBlockPointerCast;
5848       return Compatible;
5849     }
5850 
5851     // void* -> T^
5852     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
5853       if (RHSPT->getPointeeType()->isVoidType()) {
5854         Kind = CK_AnyPointerToBlockPointerCast;
5855         return Compatible;
5856       }
5857 
5858     return Incompatible;
5859   }
5860 
5861   // Conversions to Objective-C pointers.
5862   if (isa<ObjCObjectPointerType>(LHSType)) {
5863     // A* -> B*
5864     if (RHSType->isObjCObjectPointerType()) {
5865       Kind = CK_BitCast;
5866       Sema::AssignConvertType result =
5867         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
5868       if (getLangOpts().ObjCAutoRefCount &&
5869           result == Compatible &&
5870           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
5871         result = IncompatibleObjCWeakRef;
5872       return result;
5873     }
5874 
5875     // int or null -> A*
5876     if (RHSType->isIntegerType()) {
5877       Kind = CK_IntegralToPointer; // FIXME: null
5878       return IntToPointer;
5879     }
5880 
5881     // In general, C pointers are not compatible with ObjC object pointers,
5882     // with two exceptions:
5883     if (isa<PointerType>(RHSType)) {
5884       Kind = CK_CPointerToObjCPointerCast;
5885 
5886       //  - conversions from 'void*'
5887       if (RHSType->isVoidPointerType()) {
5888         return Compatible;
5889       }
5890 
5891       //  - conversions to 'Class' from its redefinition type
5892       if (LHSType->isObjCClassType() &&
5893           Context.hasSameType(RHSType,
5894                               Context.getObjCClassRedefinitionType())) {
5895         return Compatible;
5896       }
5897 
5898       return IncompatiblePointer;
5899     }
5900 
5901     // T^ -> A*
5902     if (RHSType->isBlockPointerType()) {
5903       maybeExtendBlockObject(*this, RHS);
5904       Kind = CK_BlockPointerToObjCPointerCast;
5905       return Compatible;
5906     }
5907 
5908     return Incompatible;
5909   }
5910 
5911   // Conversions from pointers that are not covered by the above.
5912   if (isa<PointerType>(RHSType)) {
5913     // T* -> _Bool
5914     if (LHSType == Context.BoolTy) {
5915       Kind = CK_PointerToBoolean;
5916       return Compatible;
5917     }
5918 
5919     // T* -> int
5920     if (LHSType->isIntegerType()) {
5921       Kind = CK_PointerToIntegral;
5922       return PointerToInt;
5923     }
5924 
5925     return Incompatible;
5926   }
5927 
5928   // Conversions from Objective-C pointers that are not covered by the above.
5929   if (isa<ObjCObjectPointerType>(RHSType)) {
5930     // T* -> _Bool
5931     if (LHSType == Context.BoolTy) {
5932       Kind = CK_PointerToBoolean;
5933       return Compatible;
5934     }
5935 
5936     // T* -> int
5937     if (LHSType->isIntegerType()) {
5938       Kind = CK_PointerToIntegral;
5939       return PointerToInt;
5940     }
5941 
5942     return Incompatible;
5943   }
5944 
5945   // struct A -> struct B
5946   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
5947     if (Context.typesAreCompatible(LHSType, RHSType)) {
5948       Kind = CK_NoOp;
5949       return Compatible;
5950     }
5951   }
5952 
5953   return Incompatible;
5954 }
5955 
5956 /// \brief Constructs a transparent union from an expression that is
5957 /// used to initialize the transparent union.
5958 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
5959                                       ExprResult &EResult, QualType UnionType,
5960                                       FieldDecl *Field) {
5961   // Build an initializer list that designates the appropriate member
5962   // of the transparent union.
5963   Expr *E = EResult.take();
5964   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
5965                                                    E, SourceLocation());
5966   Initializer->setType(UnionType);
5967   Initializer->setInitializedFieldInUnion(Field);
5968 
5969   // Build a compound literal constructing a value of the transparent
5970   // union type from this initializer list.
5971   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
5972   EResult = S.Owned(
5973     new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
5974                                 VK_RValue, Initializer, false));
5975 }
5976 
5977 Sema::AssignConvertType
5978 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
5979                                                ExprResult &RHS) {
5980   QualType RHSType = RHS.get()->getType();
5981 
5982   // If the ArgType is a Union type, we want to handle a potential
5983   // transparent_union GCC extension.
5984   const RecordType *UT = ArgType->getAsUnionType();
5985   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
5986     return Incompatible;
5987 
5988   // The field to initialize within the transparent union.
5989   RecordDecl *UD = UT->getDecl();
5990   FieldDecl *InitField = 0;
5991   // It's compatible if the expression matches any of the fields.
5992   for (RecordDecl::field_iterator it = UD->field_begin(),
5993          itend = UD->field_end();
5994        it != itend; ++it) {
5995     if (it->getType()->isPointerType()) {
5996       // If the transparent union contains a pointer type, we allow:
5997       // 1) void pointer
5998       // 2) null pointer constant
5999       if (RHSType->isPointerType())
6000         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
6001           RHS = ImpCastExprToType(RHS.take(), it->getType(), CK_BitCast);
6002           InitField = *it;
6003           break;
6004         }
6005 
6006       if (RHS.get()->isNullPointerConstant(Context,
6007                                            Expr::NPC_ValueDependentIsNull)) {
6008         RHS = ImpCastExprToType(RHS.take(), it->getType(),
6009                                 CK_NullToPointer);
6010         InitField = *it;
6011         break;
6012       }
6013     }
6014 
6015     CastKind Kind = CK_Invalid;
6016     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
6017           == Compatible) {
6018       RHS = ImpCastExprToType(RHS.take(), it->getType(), Kind);
6019       InitField = *it;
6020       break;
6021     }
6022   }
6023 
6024   if (!InitField)
6025     return Incompatible;
6026 
6027   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
6028   return Compatible;
6029 }
6030 
6031 Sema::AssignConvertType
6032 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS,
6033                                        bool Diagnose) {
6034   if (getLangOpts().CPlusPlus) {
6035     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
6036       // C++ 5.17p3: If the left operand is not of class type, the
6037       // expression is implicitly converted (C++ 4) to the
6038       // cv-unqualified type of the left operand.
6039       ExprResult Res;
6040       if (Diagnose) {
6041         Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
6042                                         AA_Assigning);
6043       } else {
6044         ImplicitConversionSequence ICS =
6045             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
6046                                   /*SuppressUserConversions=*/false,
6047                                   /*AllowExplicit=*/false,
6048                                   /*InOverloadResolution=*/false,
6049                                   /*CStyle=*/false,
6050                                   /*AllowObjCWritebackConversion=*/false);
6051         if (ICS.isFailure())
6052           return Incompatible;
6053         Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
6054                                         ICS, AA_Assigning);
6055       }
6056       if (Res.isInvalid())
6057         return Incompatible;
6058       Sema::AssignConvertType result = Compatible;
6059       if (getLangOpts().ObjCAutoRefCount &&
6060           !CheckObjCARCUnavailableWeakConversion(LHSType,
6061                                                  RHS.get()->getType()))
6062         result = IncompatibleObjCWeakRef;
6063       RHS = Res;
6064       return result;
6065     }
6066 
6067     // FIXME: Currently, we fall through and treat C++ classes like C
6068     // structures.
6069     // FIXME: We also fall through for atomics; not sure what should
6070     // happen there, though.
6071   }
6072 
6073   // C99 6.5.16.1p1: the left operand is a pointer and the right is
6074   // a null pointer constant.
6075   if ((LHSType->isPointerType() ||
6076        LHSType->isObjCObjectPointerType() ||
6077        LHSType->isBlockPointerType())
6078       && RHS.get()->isNullPointerConstant(Context,
6079                                           Expr::NPC_ValueDependentIsNull)) {
6080     RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
6081     return Compatible;
6082   }
6083 
6084   // This check seems unnatural, however it is necessary to ensure the proper
6085   // conversion of functions/arrays. If the conversion were done for all
6086   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
6087   // expressions that suppress this implicit conversion (&, sizeof).
6088   //
6089   // Suppress this for references: C++ 8.5.3p5.
6090   if (!LHSType->isReferenceType()) {
6091     RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
6092     if (RHS.isInvalid())
6093       return Incompatible;
6094   }
6095 
6096   CastKind Kind = CK_Invalid;
6097   Sema::AssignConvertType result =
6098     CheckAssignmentConstraints(LHSType, RHS, Kind);
6099 
6100   // C99 6.5.16.1p2: The value of the right operand is converted to the
6101   // type of the assignment expression.
6102   // CheckAssignmentConstraints allows the left-hand side to be a reference,
6103   // so that we can use references in built-in functions even in C.
6104   // The getNonReferenceType() call makes sure that the resulting expression
6105   // does not have reference type.
6106   if (result != Incompatible && RHS.get()->getType() != LHSType)
6107     RHS = ImpCastExprToType(RHS.take(),
6108                             LHSType.getNonLValueExprType(Context), Kind);
6109   return result;
6110 }
6111 
6112 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
6113                                ExprResult &RHS) {
6114   Diag(Loc, diag::err_typecheck_invalid_operands)
6115     << LHS.get()->getType() << RHS.get()->getType()
6116     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6117   return QualType();
6118 }
6119 
6120 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
6121                                    SourceLocation Loc, bool IsCompAssign) {
6122   if (!IsCompAssign) {
6123     LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
6124     if (LHS.isInvalid())
6125       return QualType();
6126   }
6127   RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
6128   if (RHS.isInvalid())
6129     return QualType();
6130 
6131   // For conversion purposes, we ignore any qualifiers.
6132   // For example, "const float" and "float" are equivalent.
6133   QualType LHSType =
6134     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
6135   QualType RHSType =
6136     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
6137 
6138   // If the vector types are identical, return.
6139   if (LHSType == RHSType)
6140     return LHSType;
6141 
6142   // Handle the case of equivalent AltiVec and GCC vector types
6143   if (LHSType->isVectorType() && RHSType->isVectorType() &&
6144       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
6145     if (LHSType->isExtVectorType()) {
6146       RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
6147       return LHSType;
6148     }
6149 
6150     if (!IsCompAssign)
6151       LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
6152     return RHSType;
6153   }
6154 
6155   if (getLangOpts().LaxVectorConversions &&
6156       Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType)) {
6157     // If we are allowing lax vector conversions, and LHS and RHS are both
6158     // vectors, the total size only needs to be the same. This is a
6159     // bitcast; no bits are changed but the result type is different.
6160     // FIXME: Should we really be allowing this?
6161     RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
6162     return LHSType;
6163   }
6164 
6165   // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
6166   // swap back (so that we don't reverse the inputs to a subtract, for instance.
6167   bool swapped = false;
6168   if (RHSType->isExtVectorType() && !IsCompAssign) {
6169     swapped = true;
6170     std::swap(RHS, LHS);
6171     std::swap(RHSType, LHSType);
6172   }
6173 
6174   // Handle the case of an ext vector and scalar.
6175   if (const ExtVectorType *LV = LHSType->getAs<ExtVectorType>()) {
6176     QualType EltTy = LV->getElementType();
6177     if (EltTy->isIntegralType(Context) && RHSType->isIntegralType(Context)) {
6178       int order = Context.getIntegerTypeOrder(EltTy, RHSType);
6179       if (order > 0)
6180         RHS = ImpCastExprToType(RHS.take(), EltTy, CK_IntegralCast);
6181       if (order >= 0) {
6182         RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
6183         if (swapped) std::swap(RHS, LHS);
6184         return LHSType;
6185       }
6186     }
6187     if (EltTy->isRealFloatingType() && RHSType->isScalarType() &&
6188         RHSType->isRealFloatingType()) {
6189       int order = Context.getFloatingTypeOrder(EltTy, RHSType);
6190       if (order > 0)
6191         RHS = ImpCastExprToType(RHS.take(), EltTy, CK_FloatingCast);
6192       if (order >= 0) {
6193         RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
6194         if (swapped) std::swap(RHS, LHS);
6195         return LHSType;
6196       }
6197     }
6198   }
6199 
6200   // Vectors of different size or scalar and non-ext-vector are errors.
6201   if (swapped) std::swap(RHS, LHS);
6202   Diag(Loc, diag::err_typecheck_vector_not_convertable)
6203     << LHS.get()->getType() << RHS.get()->getType()
6204     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6205   return QualType();
6206 }
6207 
6208 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
6209 // expression.  These are mainly cases where the null pointer is used as an
6210 // integer instead of a pointer.
6211 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
6212                                 SourceLocation Loc, bool IsCompare) {
6213   // The canonical way to check for a GNU null is with isNullPointerConstant,
6214   // but we use a bit of a hack here for speed; this is a relatively
6215   // hot path, and isNullPointerConstant is slow.
6216   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
6217   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
6218 
6219   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
6220 
6221   // Avoid analyzing cases where the result will either be invalid (and
6222   // diagnosed as such) or entirely valid and not something to warn about.
6223   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
6224       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
6225     return;
6226 
6227   // Comparison operations would not make sense with a null pointer no matter
6228   // what the other expression is.
6229   if (!IsCompare) {
6230     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
6231         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
6232         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
6233     return;
6234   }
6235 
6236   // The rest of the operations only make sense with a null pointer
6237   // if the other expression is a pointer.
6238   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
6239       NonNullType->canDecayToPointerType())
6240     return;
6241 
6242   S.Diag(Loc, diag::warn_null_in_comparison_operation)
6243       << LHSNull /* LHS is NULL */ << NonNullType
6244       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6245 }
6246 
6247 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
6248                                            SourceLocation Loc,
6249                                            bool IsCompAssign, bool IsDiv) {
6250   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6251 
6252   if (LHS.get()->getType()->isVectorType() ||
6253       RHS.get()->getType()->isVectorType())
6254     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
6255 
6256   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
6257   if (LHS.isInvalid() || RHS.isInvalid())
6258     return QualType();
6259 
6260 
6261   if (compType.isNull() || !compType->isArithmeticType())
6262     return InvalidOperands(Loc, LHS, RHS);
6263 
6264   // Check for division by zero.
6265   if (IsDiv &&
6266       RHS.get()->isNullPointerConstant(Context,
6267                                        Expr::NPC_ValueDependentIsNotNull))
6268     DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_division_by_zero)
6269                                           << RHS.get()->getSourceRange());
6270 
6271   return compType;
6272 }
6273 
6274 QualType Sema::CheckRemainderOperands(
6275   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
6276   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6277 
6278   if (LHS.get()->getType()->isVectorType() ||
6279       RHS.get()->getType()->isVectorType()) {
6280     if (LHS.get()->getType()->hasIntegerRepresentation() &&
6281         RHS.get()->getType()->hasIntegerRepresentation())
6282       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
6283     return InvalidOperands(Loc, LHS, RHS);
6284   }
6285 
6286   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
6287   if (LHS.isInvalid() || RHS.isInvalid())
6288     return QualType();
6289 
6290   if (compType.isNull() || !compType->isIntegerType())
6291     return InvalidOperands(Loc, LHS, RHS);
6292 
6293   // Check for remainder by zero.
6294   if (RHS.get()->isNullPointerConstant(Context,
6295                                        Expr::NPC_ValueDependentIsNotNull))
6296     DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_remainder_by_zero)
6297                                  << RHS.get()->getSourceRange());
6298 
6299   return compType;
6300 }
6301 
6302 /// \brief Diagnose invalid arithmetic on two void pointers.
6303 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
6304                                                 Expr *LHSExpr, Expr *RHSExpr) {
6305   S.Diag(Loc, S.getLangOpts().CPlusPlus
6306                 ? diag::err_typecheck_pointer_arith_void_type
6307                 : diag::ext_gnu_void_ptr)
6308     << 1 /* two pointers */ << LHSExpr->getSourceRange()
6309                             << RHSExpr->getSourceRange();
6310 }
6311 
6312 /// \brief Diagnose invalid arithmetic on a void pointer.
6313 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
6314                                             Expr *Pointer) {
6315   S.Diag(Loc, S.getLangOpts().CPlusPlus
6316                 ? diag::err_typecheck_pointer_arith_void_type
6317                 : diag::ext_gnu_void_ptr)
6318     << 0 /* one pointer */ << Pointer->getSourceRange();
6319 }
6320 
6321 /// \brief Diagnose invalid arithmetic on two function pointers.
6322 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
6323                                                     Expr *LHS, Expr *RHS) {
6324   assert(LHS->getType()->isAnyPointerType());
6325   assert(RHS->getType()->isAnyPointerType());
6326   S.Diag(Loc, S.getLangOpts().CPlusPlus
6327                 ? diag::err_typecheck_pointer_arith_function_type
6328                 : diag::ext_gnu_ptr_func_arith)
6329     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
6330     // We only show the second type if it differs from the first.
6331     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
6332                                                    RHS->getType())
6333     << RHS->getType()->getPointeeType()
6334     << LHS->getSourceRange() << RHS->getSourceRange();
6335 }
6336 
6337 /// \brief Diagnose invalid arithmetic on a function pointer.
6338 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
6339                                                 Expr *Pointer) {
6340   assert(Pointer->getType()->isAnyPointerType());
6341   S.Diag(Loc, S.getLangOpts().CPlusPlus
6342                 ? diag::err_typecheck_pointer_arith_function_type
6343                 : diag::ext_gnu_ptr_func_arith)
6344     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
6345     << 0 /* one pointer, so only one type */
6346     << Pointer->getSourceRange();
6347 }
6348 
6349 /// \brief Emit error if Operand is incomplete pointer type
6350 ///
6351 /// \returns True if pointer has incomplete type
6352 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
6353                                                  Expr *Operand) {
6354   assert(Operand->getType()->isAnyPointerType() &&
6355          !Operand->getType()->isDependentType());
6356   QualType PointeeTy = Operand->getType()->getPointeeType();
6357   return S.RequireCompleteType(Loc, PointeeTy,
6358                                diag::err_typecheck_arithmetic_incomplete_type,
6359                                PointeeTy, Operand->getSourceRange());
6360 }
6361 
6362 /// \brief Check the validity of an arithmetic pointer operand.
6363 ///
6364 /// If the operand has pointer type, this code will check for pointer types
6365 /// which are invalid in arithmetic operations. These will be diagnosed
6366 /// appropriately, including whether or not the use is supported as an
6367 /// extension.
6368 ///
6369 /// \returns True when the operand is valid to use (even if as an extension).
6370 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
6371                                             Expr *Operand) {
6372   if (!Operand->getType()->isAnyPointerType()) return true;
6373 
6374   QualType PointeeTy = Operand->getType()->getPointeeType();
6375   if (PointeeTy->isVoidType()) {
6376     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
6377     return !S.getLangOpts().CPlusPlus;
6378   }
6379   if (PointeeTy->isFunctionType()) {
6380     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
6381     return !S.getLangOpts().CPlusPlus;
6382   }
6383 
6384   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
6385 
6386   return true;
6387 }
6388 
6389 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
6390 /// operands.
6391 ///
6392 /// This routine will diagnose any invalid arithmetic on pointer operands much
6393 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
6394 /// for emitting a single diagnostic even for operations where both LHS and RHS
6395 /// are (potentially problematic) pointers.
6396 ///
6397 /// \returns True when the operand is valid to use (even if as an extension).
6398 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
6399                                                 Expr *LHSExpr, Expr *RHSExpr) {
6400   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
6401   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
6402   if (!isLHSPointer && !isRHSPointer) return true;
6403 
6404   QualType LHSPointeeTy, RHSPointeeTy;
6405   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
6406   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
6407 
6408   // Check for arithmetic on pointers to incomplete types.
6409   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
6410   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
6411   if (isLHSVoidPtr || isRHSVoidPtr) {
6412     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
6413     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
6414     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
6415 
6416     return !S.getLangOpts().CPlusPlus;
6417   }
6418 
6419   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
6420   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
6421   if (isLHSFuncPtr || isRHSFuncPtr) {
6422     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
6423     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
6424                                                                 RHSExpr);
6425     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
6426 
6427     return !S.getLangOpts().CPlusPlus;
6428   }
6429 
6430   if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
6431     return false;
6432   if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
6433     return false;
6434 
6435   return true;
6436 }
6437 
6438 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
6439 /// literal.
6440 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
6441                                   Expr *LHSExpr, Expr *RHSExpr) {
6442   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
6443   Expr* IndexExpr = RHSExpr;
6444   if (!StrExpr) {
6445     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
6446     IndexExpr = LHSExpr;
6447   }
6448 
6449   bool IsStringPlusInt = StrExpr &&
6450       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
6451   if (!IsStringPlusInt)
6452     return;
6453 
6454   llvm::APSInt index;
6455   if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
6456     unsigned StrLenWithNull = StrExpr->getLength() + 1;
6457     if (index.isNonNegative() &&
6458         index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
6459                               index.isUnsigned()))
6460       return;
6461   }
6462 
6463   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
6464   Self.Diag(OpLoc, diag::warn_string_plus_int)
6465       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
6466 
6467   // Only print a fixit for "str" + int, not for int + "str".
6468   if (IndexExpr == RHSExpr) {
6469     SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd());
6470     Self.Diag(OpLoc, diag::note_string_plus_int_silence)
6471         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
6472         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
6473         << FixItHint::CreateInsertion(EndLoc, "]");
6474   } else
6475     Self.Diag(OpLoc, diag::note_string_plus_int_silence);
6476 }
6477 
6478 /// \brief Emit error when two pointers are incompatible.
6479 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
6480                                            Expr *LHSExpr, Expr *RHSExpr) {
6481   assert(LHSExpr->getType()->isAnyPointerType());
6482   assert(RHSExpr->getType()->isAnyPointerType());
6483   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
6484     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
6485     << RHSExpr->getSourceRange();
6486 }
6487 
6488 QualType Sema::CheckAdditionOperands( // C99 6.5.6
6489     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc,
6490     QualType* CompLHSTy) {
6491   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6492 
6493   if (LHS.get()->getType()->isVectorType() ||
6494       RHS.get()->getType()->isVectorType()) {
6495     QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
6496     if (CompLHSTy) *CompLHSTy = compType;
6497     return compType;
6498   }
6499 
6500   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6501   if (LHS.isInvalid() || RHS.isInvalid())
6502     return QualType();
6503 
6504   // Diagnose "string literal" '+' int.
6505   if (Opc == BO_Add)
6506     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
6507 
6508   // handle the common case first (both operands are arithmetic).
6509   if (!compType.isNull() && compType->isArithmeticType()) {
6510     if (CompLHSTy) *CompLHSTy = compType;
6511     return compType;
6512   }
6513 
6514   // Type-checking.  Ultimately the pointer's going to be in PExp;
6515   // note that we bias towards the LHS being the pointer.
6516   Expr *PExp = LHS.get(), *IExp = RHS.get();
6517 
6518   bool isObjCPointer;
6519   if (PExp->getType()->isPointerType()) {
6520     isObjCPointer = false;
6521   } else if (PExp->getType()->isObjCObjectPointerType()) {
6522     isObjCPointer = true;
6523   } else {
6524     std::swap(PExp, IExp);
6525     if (PExp->getType()->isPointerType()) {
6526       isObjCPointer = false;
6527     } else if (PExp->getType()->isObjCObjectPointerType()) {
6528       isObjCPointer = true;
6529     } else {
6530       return InvalidOperands(Loc, LHS, RHS);
6531     }
6532   }
6533   assert(PExp->getType()->isAnyPointerType());
6534 
6535   if (!IExp->getType()->isIntegerType())
6536     return InvalidOperands(Loc, LHS, RHS);
6537 
6538   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
6539     return QualType();
6540 
6541   if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
6542     return QualType();
6543 
6544   // Check array bounds for pointer arithemtic
6545   CheckArrayAccess(PExp, IExp);
6546 
6547   if (CompLHSTy) {
6548     QualType LHSTy = Context.isPromotableBitField(LHS.get());
6549     if (LHSTy.isNull()) {
6550       LHSTy = LHS.get()->getType();
6551       if (LHSTy->isPromotableIntegerType())
6552         LHSTy = Context.getPromotedIntegerType(LHSTy);
6553     }
6554     *CompLHSTy = LHSTy;
6555   }
6556 
6557   return PExp->getType();
6558 }
6559 
6560 // C99 6.5.6
6561 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
6562                                         SourceLocation Loc,
6563                                         QualType* CompLHSTy) {
6564   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6565 
6566   if (LHS.get()->getType()->isVectorType() ||
6567       RHS.get()->getType()->isVectorType()) {
6568     QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
6569     if (CompLHSTy) *CompLHSTy = compType;
6570     return compType;
6571   }
6572 
6573   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6574   if (LHS.isInvalid() || RHS.isInvalid())
6575     return QualType();
6576 
6577   // Enforce type constraints: C99 6.5.6p3.
6578 
6579   // Handle the common case first (both operands are arithmetic).
6580   if (!compType.isNull() && compType->isArithmeticType()) {
6581     if (CompLHSTy) *CompLHSTy = compType;
6582     return compType;
6583   }
6584 
6585   // Either ptr - int   or   ptr - ptr.
6586   if (LHS.get()->getType()->isAnyPointerType()) {
6587     QualType lpointee = LHS.get()->getType()->getPointeeType();
6588 
6589     // Diagnose bad cases where we step over interface counts.
6590     if (LHS.get()->getType()->isObjCObjectPointerType() &&
6591         checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
6592       return QualType();
6593 
6594     // The result type of a pointer-int computation is the pointer type.
6595     if (RHS.get()->getType()->isIntegerType()) {
6596       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
6597         return QualType();
6598 
6599       // Check array bounds for pointer arithemtic
6600       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/0,
6601                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
6602 
6603       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
6604       return LHS.get()->getType();
6605     }
6606 
6607     // Handle pointer-pointer subtractions.
6608     if (const PointerType *RHSPTy
6609           = RHS.get()->getType()->getAs<PointerType>()) {
6610       QualType rpointee = RHSPTy->getPointeeType();
6611 
6612       if (getLangOpts().CPlusPlus) {
6613         // Pointee types must be the same: C++ [expr.add]
6614         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
6615           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
6616         }
6617       } else {
6618         // Pointee types must be compatible C99 6.5.6p3
6619         if (!Context.typesAreCompatible(
6620                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
6621                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
6622           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
6623           return QualType();
6624         }
6625       }
6626 
6627       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
6628                                                LHS.get(), RHS.get()))
6629         return QualType();
6630 
6631       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
6632       return Context.getPointerDiffType();
6633     }
6634   }
6635 
6636   return InvalidOperands(Loc, LHS, RHS);
6637 }
6638 
6639 static bool isScopedEnumerationType(QualType T) {
6640   if (const EnumType *ET = dyn_cast<EnumType>(T))
6641     return ET->getDecl()->isScoped();
6642   return false;
6643 }
6644 
6645 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
6646                                    SourceLocation Loc, unsigned Opc,
6647                                    QualType LHSType) {
6648   // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
6649   // so skip remaining warnings as we don't want to modify values within Sema.
6650   if (S.getLangOpts().OpenCL)
6651     return;
6652 
6653   llvm::APSInt Right;
6654   // Check right/shifter operand
6655   if (RHS.get()->isValueDependent() ||
6656       !RHS.get()->isIntegerConstantExpr(Right, S.Context))
6657     return;
6658 
6659   if (Right.isNegative()) {
6660     S.DiagRuntimeBehavior(Loc, RHS.get(),
6661                           S.PDiag(diag::warn_shift_negative)
6662                             << RHS.get()->getSourceRange());
6663     return;
6664   }
6665   llvm::APInt LeftBits(Right.getBitWidth(),
6666                        S.Context.getTypeSize(LHS.get()->getType()));
6667   if (Right.uge(LeftBits)) {
6668     S.DiagRuntimeBehavior(Loc, RHS.get(),
6669                           S.PDiag(diag::warn_shift_gt_typewidth)
6670                             << RHS.get()->getSourceRange());
6671     return;
6672   }
6673   if (Opc != BO_Shl)
6674     return;
6675 
6676   // When left shifting an ICE which is signed, we can check for overflow which
6677   // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
6678   // integers have defined behavior modulo one more than the maximum value
6679   // representable in the result type, so never warn for those.
6680   llvm::APSInt Left;
6681   if (LHS.get()->isValueDependent() ||
6682       !LHS.get()->isIntegerConstantExpr(Left, S.Context) ||
6683       LHSType->hasUnsignedIntegerRepresentation())
6684     return;
6685   llvm::APInt ResultBits =
6686       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
6687   if (LeftBits.uge(ResultBits))
6688     return;
6689   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
6690   Result = Result.shl(Right);
6691 
6692   // Print the bit representation of the signed integer as an unsigned
6693   // hexadecimal number.
6694   SmallString<40> HexResult;
6695   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
6696 
6697   // If we are only missing a sign bit, this is less likely to result in actual
6698   // bugs -- if the result is cast back to an unsigned type, it will have the
6699   // expected value. Thus we place this behind a different warning that can be
6700   // turned off separately if needed.
6701   if (LeftBits == ResultBits - 1) {
6702     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
6703         << HexResult.str() << LHSType
6704         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6705     return;
6706   }
6707 
6708   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
6709     << HexResult.str() << Result.getMinSignedBits() << LHSType
6710     << Left.getBitWidth() << LHS.get()->getSourceRange()
6711     << RHS.get()->getSourceRange();
6712 }
6713 
6714 // C99 6.5.7
6715 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
6716                                   SourceLocation Loc, unsigned Opc,
6717                                   bool IsCompAssign) {
6718   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6719 
6720   // C99 6.5.7p2: Each of the operands shall have integer type.
6721   if (!LHS.get()->getType()->hasIntegerRepresentation() ||
6722       !RHS.get()->getType()->hasIntegerRepresentation())
6723     return InvalidOperands(Loc, LHS, RHS);
6724 
6725   // C++0x: Don't allow scoped enums. FIXME: Use something better than
6726   // hasIntegerRepresentation() above instead of this.
6727   if (isScopedEnumerationType(LHS.get()->getType()) ||
6728       isScopedEnumerationType(RHS.get()->getType())) {
6729     return InvalidOperands(Loc, LHS, RHS);
6730   }
6731 
6732   // Vector shifts promote their scalar inputs to vector type.
6733   if (LHS.get()->getType()->isVectorType() ||
6734       RHS.get()->getType()->isVectorType())
6735     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
6736 
6737   // Shifts don't perform usual arithmetic conversions, they just do integer
6738   // promotions on each operand. C99 6.5.7p3
6739 
6740   // For the LHS, do usual unary conversions, but then reset them away
6741   // if this is a compound assignment.
6742   ExprResult OldLHS = LHS;
6743   LHS = UsualUnaryConversions(LHS.take());
6744   if (LHS.isInvalid())
6745     return QualType();
6746   QualType LHSType = LHS.get()->getType();
6747   if (IsCompAssign) LHS = OldLHS;
6748 
6749   // The RHS is simpler.
6750   RHS = UsualUnaryConversions(RHS.take());
6751   if (RHS.isInvalid())
6752     return QualType();
6753 
6754   // Sanity-check shift operands
6755   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
6756 
6757   // "The type of the result is that of the promoted left operand."
6758   return LHSType;
6759 }
6760 
6761 static bool IsWithinTemplateSpecialization(Decl *D) {
6762   if (DeclContext *DC = D->getDeclContext()) {
6763     if (isa<ClassTemplateSpecializationDecl>(DC))
6764       return true;
6765     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
6766       return FD->isFunctionTemplateSpecialization();
6767   }
6768   return false;
6769 }
6770 
6771 /// If two different enums are compared, raise a warning.
6772 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS,
6773                                 Expr *RHS) {
6774   QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
6775   QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
6776 
6777   const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
6778   if (!LHSEnumType)
6779     return;
6780   const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
6781   if (!RHSEnumType)
6782     return;
6783 
6784   // Ignore anonymous enums.
6785   if (!LHSEnumType->getDecl()->getIdentifier())
6786     return;
6787   if (!RHSEnumType->getDecl()->getIdentifier())
6788     return;
6789 
6790   if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
6791     return;
6792 
6793   S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
6794       << LHSStrippedType << RHSStrippedType
6795       << LHS->getSourceRange() << RHS->getSourceRange();
6796 }
6797 
6798 /// \brief Diagnose bad pointer comparisons.
6799 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
6800                                               ExprResult &LHS, ExprResult &RHS,
6801                                               bool IsError) {
6802   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
6803                       : diag::ext_typecheck_comparison_of_distinct_pointers)
6804     << LHS.get()->getType() << RHS.get()->getType()
6805     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6806 }
6807 
6808 /// \brief Returns false if the pointers are converted to a composite type,
6809 /// true otherwise.
6810 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
6811                                            ExprResult &LHS, ExprResult &RHS) {
6812   // C++ [expr.rel]p2:
6813   //   [...] Pointer conversions (4.10) and qualification
6814   //   conversions (4.4) are performed on pointer operands (or on
6815   //   a pointer operand and a null pointer constant) to bring
6816   //   them to their composite pointer type. [...]
6817   //
6818   // C++ [expr.eq]p1 uses the same notion for (in)equality
6819   // comparisons of pointers.
6820 
6821   // C++ [expr.eq]p2:
6822   //   In addition, pointers to members can be compared, or a pointer to
6823   //   member and a null pointer constant. Pointer to member conversions
6824   //   (4.11) and qualification conversions (4.4) are performed to bring
6825   //   them to a common type. If one operand is a null pointer constant,
6826   //   the common type is the type of the other operand. Otherwise, the
6827   //   common type is a pointer to member type similar (4.4) to the type
6828   //   of one of the operands, with a cv-qualification signature (4.4)
6829   //   that is the union of the cv-qualification signatures of the operand
6830   //   types.
6831 
6832   QualType LHSType = LHS.get()->getType();
6833   QualType RHSType = RHS.get()->getType();
6834   assert((LHSType->isPointerType() && RHSType->isPointerType()) ||
6835          (LHSType->isMemberPointerType() && RHSType->isMemberPointerType()));
6836 
6837   bool NonStandardCompositeType = false;
6838   bool *BoolPtr = S.isSFINAEContext() ? 0 : &NonStandardCompositeType;
6839   QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr);
6840   if (T.isNull()) {
6841     diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
6842     return true;
6843   }
6844 
6845   if (NonStandardCompositeType)
6846     S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
6847       << LHSType << RHSType << T << LHS.get()->getSourceRange()
6848       << RHS.get()->getSourceRange();
6849 
6850   LHS = S.ImpCastExprToType(LHS.take(), T, CK_BitCast);
6851   RHS = S.ImpCastExprToType(RHS.take(), T, CK_BitCast);
6852   return false;
6853 }
6854 
6855 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
6856                                                     ExprResult &LHS,
6857                                                     ExprResult &RHS,
6858                                                     bool IsError) {
6859   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
6860                       : diag::ext_typecheck_comparison_of_fptr_to_void)
6861     << LHS.get()->getType() << RHS.get()->getType()
6862     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6863 }
6864 
6865 static bool isObjCObjectLiteral(ExprResult &E) {
6866   switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
6867   case Stmt::ObjCArrayLiteralClass:
6868   case Stmt::ObjCDictionaryLiteralClass:
6869   case Stmt::ObjCStringLiteralClass:
6870   case Stmt::ObjCBoxedExprClass:
6871     return true;
6872   default:
6873     // Note that ObjCBoolLiteral is NOT an object literal!
6874     return false;
6875   }
6876 }
6877 
6878 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
6879   const ObjCObjectPointerType *Type =
6880     LHS->getType()->getAs<ObjCObjectPointerType>();
6881 
6882   // If this is not actually an Objective-C object, bail out.
6883   if (!Type)
6884     return false;
6885 
6886   // Get the LHS object's interface type.
6887   QualType InterfaceType = Type->getPointeeType();
6888   if (const ObjCObjectType *iQFaceTy =
6889       InterfaceType->getAsObjCQualifiedInterfaceType())
6890     InterfaceType = iQFaceTy->getBaseType();
6891 
6892   // If the RHS isn't an Objective-C object, bail out.
6893   if (!RHS->getType()->isObjCObjectPointerType())
6894     return false;
6895 
6896   // Try to find the -isEqual: method.
6897   Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
6898   ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
6899                                                       InterfaceType,
6900                                                       /*instance=*/true);
6901   if (!Method) {
6902     if (Type->isObjCIdType()) {
6903       // For 'id', just check the global pool.
6904       Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
6905                                                   /*receiverId=*/true,
6906                                                   /*warn=*/false);
6907     } else {
6908       // Check protocols.
6909       Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
6910                                              /*instance=*/true);
6911     }
6912   }
6913 
6914   if (!Method)
6915     return false;
6916 
6917   QualType T = Method->param_begin()[0]->getType();
6918   if (!T->isObjCObjectPointerType())
6919     return false;
6920 
6921   QualType R = Method->getResultType();
6922   if (!R->isScalarType())
6923     return false;
6924 
6925   return true;
6926 }
6927 
6928 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
6929   FromE = FromE->IgnoreParenImpCasts();
6930   switch (FromE->getStmtClass()) {
6931     default:
6932       break;
6933     case Stmt::ObjCStringLiteralClass:
6934       // "string literal"
6935       return LK_String;
6936     case Stmt::ObjCArrayLiteralClass:
6937       // "array literal"
6938       return LK_Array;
6939     case Stmt::ObjCDictionaryLiteralClass:
6940       // "dictionary literal"
6941       return LK_Dictionary;
6942     case Stmt::BlockExprClass:
6943       return LK_Block;
6944     case Stmt::ObjCBoxedExprClass: {
6945       Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
6946       switch (Inner->getStmtClass()) {
6947         case Stmt::IntegerLiteralClass:
6948         case Stmt::FloatingLiteralClass:
6949         case Stmt::CharacterLiteralClass:
6950         case Stmt::ObjCBoolLiteralExprClass:
6951         case Stmt::CXXBoolLiteralExprClass:
6952           // "numeric literal"
6953           return LK_Numeric;
6954         case Stmt::ImplicitCastExprClass: {
6955           CastKind CK = cast<CastExpr>(Inner)->getCastKind();
6956           // Boolean literals can be represented by implicit casts.
6957           if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
6958             return LK_Numeric;
6959           break;
6960         }
6961         default:
6962           break;
6963       }
6964       return LK_Boxed;
6965     }
6966   }
6967   return LK_None;
6968 }
6969 
6970 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
6971                                           ExprResult &LHS, ExprResult &RHS,
6972                                           BinaryOperator::Opcode Opc){
6973   Expr *Literal;
6974   Expr *Other;
6975   if (isObjCObjectLiteral(LHS)) {
6976     Literal = LHS.get();
6977     Other = RHS.get();
6978   } else {
6979     Literal = RHS.get();
6980     Other = LHS.get();
6981   }
6982 
6983   // Don't warn on comparisons against nil.
6984   Other = Other->IgnoreParenCasts();
6985   if (Other->isNullPointerConstant(S.getASTContext(),
6986                                    Expr::NPC_ValueDependentIsNotNull))
6987     return;
6988 
6989   // This should be kept in sync with warn_objc_literal_comparison.
6990   // LK_String should always be after the other literals, since it has its own
6991   // warning flag.
6992   Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
6993   assert(LiteralKind != Sema::LK_Block);
6994   if (LiteralKind == Sema::LK_None) {
6995     llvm_unreachable("Unknown Objective-C object literal kind");
6996   }
6997 
6998   if (LiteralKind == Sema::LK_String)
6999     S.Diag(Loc, diag::warn_objc_string_literal_comparison)
7000       << Literal->getSourceRange();
7001   else
7002     S.Diag(Loc, diag::warn_objc_literal_comparison)
7003       << LiteralKind << Literal->getSourceRange();
7004 
7005   if (BinaryOperator::isEqualityOp(Opc) &&
7006       hasIsEqualMethod(S, LHS.get(), RHS.get())) {
7007     SourceLocation Start = LHS.get()->getLocStart();
7008     SourceLocation End = S.PP.getLocForEndOfToken(RHS.get()->getLocEnd());
7009     CharSourceRange OpRange =
7010       CharSourceRange::getCharRange(Loc, S.PP.getLocForEndOfToken(Loc));
7011 
7012     S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
7013       << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
7014       << FixItHint::CreateReplacement(OpRange, " isEqual:")
7015       << FixItHint::CreateInsertion(End, "]");
7016   }
7017 }
7018 
7019 // C99 6.5.8, C++ [expr.rel]
7020 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
7021                                     SourceLocation Loc, unsigned OpaqueOpc,
7022                                     bool IsRelational) {
7023   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
7024 
7025   BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
7026 
7027   // Handle vector comparisons separately.
7028   if (LHS.get()->getType()->isVectorType() ||
7029       RHS.get()->getType()->isVectorType())
7030     return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
7031 
7032   QualType LHSType = LHS.get()->getType();
7033   QualType RHSType = RHS.get()->getType();
7034 
7035   Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
7036   Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
7037 
7038   checkEnumComparison(*this, Loc, LHS.get(), RHS.get());
7039 
7040   if (!LHSType->hasFloatingRepresentation() &&
7041       !(LHSType->isBlockPointerType() && IsRelational) &&
7042       !LHS.get()->getLocStart().isMacroID() &&
7043       !RHS.get()->getLocStart().isMacroID()) {
7044     // For non-floating point types, check for self-comparisons of the form
7045     // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
7046     // often indicate logic errors in the program.
7047     //
7048     // NOTE: Don't warn about comparison expressions resulting from macro
7049     // expansion. Also don't warn about comparisons which are only self
7050     // comparisons within a template specialization. The warnings should catch
7051     // obvious cases in the definition of the template anyways. The idea is to
7052     // warn when the typed comparison operator will always evaluate to the same
7053     // result.
7054     if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
7055       if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
7056         if (DRL->getDecl() == DRR->getDecl() &&
7057             !IsWithinTemplateSpecialization(DRL->getDecl())) {
7058           DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
7059                               << 0 // self-
7060                               << (Opc == BO_EQ
7061                                   || Opc == BO_LE
7062                                   || Opc == BO_GE));
7063         } else if (LHSType->isArrayType() && RHSType->isArrayType() &&
7064                    !DRL->getDecl()->getType()->isReferenceType() &&
7065                    !DRR->getDecl()->getType()->isReferenceType()) {
7066             // what is it always going to eval to?
7067             char always_evals_to;
7068             switch(Opc) {
7069             case BO_EQ: // e.g. array1 == array2
7070               always_evals_to = 0; // false
7071               break;
7072             case BO_NE: // e.g. array1 != array2
7073               always_evals_to = 1; // true
7074               break;
7075             default:
7076               // best we can say is 'a constant'
7077               always_evals_to = 2; // e.g. array1 <= array2
7078               break;
7079             }
7080             DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
7081                                 << 1 // array
7082                                 << always_evals_to);
7083         }
7084       }
7085     }
7086 
7087     if (isa<CastExpr>(LHSStripped))
7088       LHSStripped = LHSStripped->IgnoreParenCasts();
7089     if (isa<CastExpr>(RHSStripped))
7090       RHSStripped = RHSStripped->IgnoreParenCasts();
7091 
7092     // Warn about comparisons against a string constant (unless the other
7093     // operand is null), the user probably wants strcmp.
7094     Expr *literalString = 0;
7095     Expr *literalStringStripped = 0;
7096     if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
7097         !RHSStripped->isNullPointerConstant(Context,
7098                                             Expr::NPC_ValueDependentIsNull)) {
7099       literalString = LHS.get();
7100       literalStringStripped = LHSStripped;
7101     } else if ((isa<StringLiteral>(RHSStripped) ||
7102                 isa<ObjCEncodeExpr>(RHSStripped)) &&
7103                !LHSStripped->isNullPointerConstant(Context,
7104                                             Expr::NPC_ValueDependentIsNull)) {
7105       literalString = RHS.get();
7106       literalStringStripped = RHSStripped;
7107     }
7108 
7109     if (literalString) {
7110       std::string resultComparison;
7111       switch (Opc) {
7112       case BO_LT: resultComparison = ") < 0"; break;
7113       case BO_GT: resultComparison = ") > 0"; break;
7114       case BO_LE: resultComparison = ") <= 0"; break;
7115       case BO_GE: resultComparison = ") >= 0"; break;
7116       case BO_EQ: resultComparison = ") == 0"; break;
7117       case BO_NE: resultComparison = ") != 0"; break;
7118       default: llvm_unreachable("Invalid comparison operator");
7119       }
7120 
7121       DiagRuntimeBehavior(Loc, 0,
7122         PDiag(diag::warn_stringcompare)
7123           << isa<ObjCEncodeExpr>(literalStringStripped)
7124           << literalString->getSourceRange());
7125     }
7126   }
7127 
7128   // C99 6.5.8p3 / C99 6.5.9p4
7129   if (LHS.get()->getType()->isArithmeticType() &&
7130       RHS.get()->getType()->isArithmeticType()) {
7131     UsualArithmeticConversions(LHS, RHS);
7132     if (LHS.isInvalid() || RHS.isInvalid())
7133       return QualType();
7134   }
7135   else {
7136     LHS = UsualUnaryConversions(LHS.take());
7137     if (LHS.isInvalid())
7138       return QualType();
7139 
7140     RHS = UsualUnaryConversions(RHS.take());
7141     if (RHS.isInvalid())
7142       return QualType();
7143   }
7144 
7145   LHSType = LHS.get()->getType();
7146   RHSType = RHS.get()->getType();
7147 
7148   // The result of comparisons is 'bool' in C++, 'int' in C.
7149   QualType ResultTy = Context.getLogicalOperationType();
7150 
7151   if (IsRelational) {
7152     if (LHSType->isRealType() && RHSType->isRealType())
7153       return ResultTy;
7154   } else {
7155     // Check for comparisons of floating point operands using != and ==.
7156     if (LHSType->hasFloatingRepresentation())
7157       CheckFloatComparison(Loc, LHS.get(), RHS.get());
7158 
7159     if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
7160       return ResultTy;
7161   }
7162 
7163   bool LHSIsNull = LHS.get()->isNullPointerConstant(Context,
7164                                               Expr::NPC_ValueDependentIsNull);
7165   bool RHSIsNull = RHS.get()->isNullPointerConstant(Context,
7166                                               Expr::NPC_ValueDependentIsNull);
7167 
7168   // All of the following pointer-related warnings are GCC extensions, except
7169   // when handling null pointer constants.
7170   if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2
7171     QualType LCanPointeeTy =
7172       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
7173     QualType RCanPointeeTy =
7174       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
7175 
7176     if (getLangOpts().CPlusPlus) {
7177       if (LCanPointeeTy == RCanPointeeTy)
7178         return ResultTy;
7179       if (!IsRelational &&
7180           (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7181         // Valid unless comparison between non-null pointer and function pointer
7182         // This is a gcc extension compatibility comparison.
7183         // In a SFINAE context, we treat this as a hard error to maintain
7184         // conformance with the C++ standard.
7185         if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
7186             && !LHSIsNull && !RHSIsNull) {
7187           diagnoseFunctionPointerToVoidComparison(
7188               *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
7189 
7190           if (isSFINAEContext())
7191             return QualType();
7192 
7193           RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
7194           return ResultTy;
7195         }
7196       }
7197 
7198       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
7199         return QualType();
7200       else
7201         return ResultTy;
7202     }
7203     // C99 6.5.9p2 and C99 6.5.8p2
7204     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
7205                                    RCanPointeeTy.getUnqualifiedType())) {
7206       // Valid unless a relational comparison of function pointers
7207       if (IsRelational && LCanPointeeTy->isFunctionType()) {
7208         Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
7209           << LHSType << RHSType << LHS.get()->getSourceRange()
7210           << RHS.get()->getSourceRange();
7211       }
7212     } else if (!IsRelational &&
7213                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7214       // Valid unless comparison between non-null pointer and function pointer
7215       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
7216           && !LHSIsNull && !RHSIsNull)
7217         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
7218                                                 /*isError*/false);
7219     } else {
7220       // Invalid
7221       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
7222     }
7223     if (LCanPointeeTy != RCanPointeeTy) {
7224       if (LHSIsNull && !RHSIsNull)
7225         LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
7226       else
7227         RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
7228     }
7229     return ResultTy;
7230   }
7231 
7232   if (getLangOpts().CPlusPlus) {
7233     // Comparison of nullptr_t with itself.
7234     if (LHSType->isNullPtrType() && RHSType->isNullPtrType())
7235       return ResultTy;
7236 
7237     // Comparison of pointers with null pointer constants and equality
7238     // comparisons of member pointers to null pointer constants.
7239     if (RHSIsNull &&
7240         ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) ||
7241          (!IsRelational &&
7242           (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) {
7243       RHS = ImpCastExprToType(RHS.take(), LHSType,
7244                         LHSType->isMemberPointerType()
7245                           ? CK_NullToMemberPointer
7246                           : CK_NullToPointer);
7247       return ResultTy;
7248     }
7249     if (LHSIsNull &&
7250         ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) ||
7251          (!IsRelational &&
7252           (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) {
7253       LHS = ImpCastExprToType(LHS.take(), RHSType,
7254                         RHSType->isMemberPointerType()
7255                           ? CK_NullToMemberPointer
7256                           : CK_NullToPointer);
7257       return ResultTy;
7258     }
7259 
7260     // Comparison of member pointers.
7261     if (!IsRelational &&
7262         LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) {
7263       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
7264         return QualType();
7265       else
7266         return ResultTy;
7267     }
7268 
7269     // Handle scoped enumeration types specifically, since they don't promote
7270     // to integers.
7271     if (LHS.get()->getType()->isEnumeralType() &&
7272         Context.hasSameUnqualifiedType(LHS.get()->getType(),
7273                                        RHS.get()->getType()))
7274       return ResultTy;
7275   }
7276 
7277   // Handle block pointer types.
7278   if (!IsRelational && LHSType->isBlockPointerType() &&
7279       RHSType->isBlockPointerType()) {
7280     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
7281     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
7282 
7283     if (!LHSIsNull && !RHSIsNull &&
7284         !Context.typesAreCompatible(lpointee, rpointee)) {
7285       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
7286         << LHSType << RHSType << LHS.get()->getSourceRange()
7287         << RHS.get()->getSourceRange();
7288     }
7289     RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
7290     return ResultTy;
7291   }
7292 
7293   // Allow block pointers to be compared with null pointer constants.
7294   if (!IsRelational
7295       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
7296           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
7297     if (!LHSIsNull && !RHSIsNull) {
7298       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
7299              ->getPointeeType()->isVoidType())
7300             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
7301                 ->getPointeeType()->isVoidType())))
7302         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
7303           << LHSType << RHSType << LHS.get()->getSourceRange()
7304           << RHS.get()->getSourceRange();
7305     }
7306     if (LHSIsNull && !RHSIsNull)
7307       LHS = ImpCastExprToType(LHS.take(), RHSType,
7308                               RHSType->isPointerType() ? CK_BitCast
7309                                 : CK_AnyPointerToBlockPointerCast);
7310     else
7311       RHS = ImpCastExprToType(RHS.take(), LHSType,
7312                               LHSType->isPointerType() ? CK_BitCast
7313                                 : CK_AnyPointerToBlockPointerCast);
7314     return ResultTy;
7315   }
7316 
7317   if (LHSType->isObjCObjectPointerType() ||
7318       RHSType->isObjCObjectPointerType()) {
7319     const PointerType *LPT = LHSType->getAs<PointerType>();
7320     const PointerType *RPT = RHSType->getAs<PointerType>();
7321     if (LPT || RPT) {
7322       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
7323       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
7324 
7325       if (!LPtrToVoid && !RPtrToVoid &&
7326           !Context.typesAreCompatible(LHSType, RHSType)) {
7327         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
7328                                           /*isError*/false);
7329       }
7330       if (LHSIsNull && !RHSIsNull)
7331         LHS = ImpCastExprToType(LHS.take(), RHSType,
7332                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
7333       else
7334         RHS = ImpCastExprToType(RHS.take(), LHSType,
7335                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
7336       return ResultTy;
7337     }
7338     if (LHSType->isObjCObjectPointerType() &&
7339         RHSType->isObjCObjectPointerType()) {
7340       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
7341         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
7342                                           /*isError*/false);
7343       if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
7344         diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
7345 
7346       if (LHSIsNull && !RHSIsNull)
7347         LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
7348       else
7349         RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
7350       return ResultTy;
7351     }
7352   }
7353   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
7354       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
7355     unsigned DiagID = 0;
7356     bool isError = false;
7357     if (LangOpts.DebuggerSupport) {
7358       // Under a debugger, allow the comparison of pointers to integers,
7359       // since users tend to want to compare addresses.
7360     } else if ((LHSIsNull && LHSType->isIntegerType()) ||
7361         (RHSIsNull && RHSType->isIntegerType())) {
7362       if (IsRelational && !getLangOpts().CPlusPlus)
7363         DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
7364     } else if (IsRelational && !getLangOpts().CPlusPlus)
7365       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
7366     else if (getLangOpts().CPlusPlus) {
7367       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
7368       isError = true;
7369     } else
7370       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
7371 
7372     if (DiagID) {
7373       Diag(Loc, DiagID)
7374         << LHSType << RHSType << LHS.get()->getSourceRange()
7375         << RHS.get()->getSourceRange();
7376       if (isError)
7377         return QualType();
7378     }
7379 
7380     if (LHSType->isIntegerType())
7381       LHS = ImpCastExprToType(LHS.take(), RHSType,
7382                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
7383     else
7384       RHS = ImpCastExprToType(RHS.take(), LHSType,
7385                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
7386     return ResultTy;
7387   }
7388 
7389   // Handle block pointers.
7390   if (!IsRelational && RHSIsNull
7391       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
7392     RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
7393     return ResultTy;
7394   }
7395   if (!IsRelational && LHSIsNull
7396       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
7397     LHS = ImpCastExprToType(LHS.take(), RHSType, CK_NullToPointer);
7398     return ResultTy;
7399   }
7400 
7401   return InvalidOperands(Loc, LHS, RHS);
7402 }
7403 
7404 
7405 // Return a signed type that is of identical size and number of elements.
7406 // For floating point vectors, return an integer type of identical size
7407 // and number of elements.
7408 QualType Sema::GetSignedVectorType(QualType V) {
7409   const VectorType *VTy = V->getAs<VectorType>();
7410   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
7411   if (TypeSize == Context.getTypeSize(Context.CharTy))
7412     return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
7413   else if (TypeSize == Context.getTypeSize(Context.ShortTy))
7414     return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
7415   else if (TypeSize == Context.getTypeSize(Context.IntTy))
7416     return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
7417   else if (TypeSize == Context.getTypeSize(Context.LongTy))
7418     return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
7419   assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
7420          "Unhandled vector element size in vector compare");
7421   return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
7422 }
7423 
7424 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
7425 /// operates on extended vector types.  Instead of producing an IntTy result,
7426 /// like a scalar comparison, a vector comparison produces a vector of integer
7427 /// types.
7428 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
7429                                           SourceLocation Loc,
7430                                           bool IsRelational) {
7431   // Check to make sure we're operating on vectors of the same type and width,
7432   // Allowing one side to be a scalar of element type.
7433   QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false);
7434   if (vType.isNull())
7435     return vType;
7436 
7437   QualType LHSType = LHS.get()->getType();
7438 
7439   // If AltiVec, the comparison results in a numeric type, i.e.
7440   // bool for C++, int for C
7441   if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
7442     return Context.getLogicalOperationType();
7443 
7444   // For non-floating point types, check for self-comparisons of the form
7445   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
7446   // often indicate logic errors in the program.
7447   if (!LHSType->hasFloatingRepresentation()) {
7448     if (DeclRefExpr* DRL
7449           = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
7450       if (DeclRefExpr* DRR
7451             = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
7452         if (DRL->getDecl() == DRR->getDecl())
7453           DiagRuntimeBehavior(Loc, 0,
7454                               PDiag(diag::warn_comparison_always)
7455                                 << 0 // self-
7456                                 << 2 // "a constant"
7457                               );
7458   }
7459 
7460   // Check for comparisons of floating point operands using != and ==.
7461   if (!IsRelational && LHSType->hasFloatingRepresentation()) {
7462     assert (RHS.get()->getType()->hasFloatingRepresentation());
7463     CheckFloatComparison(Loc, LHS.get(), RHS.get());
7464   }
7465 
7466   // Return a signed type for the vector.
7467   return GetSignedVectorType(LHSType);
7468 }
7469 
7470 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
7471                                           SourceLocation Loc) {
7472   // Ensure that either both operands are of the same vector type, or
7473   // one operand is of a vector type and the other is of its element type.
7474   QualType vType = CheckVectorOperands(LHS, RHS, Loc, false);
7475   if (vType.isNull())
7476     return InvalidOperands(Loc, LHS, RHS);
7477   if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
7478       vType->hasFloatingRepresentation())
7479     return InvalidOperands(Loc, LHS, RHS);
7480 
7481   return GetSignedVectorType(LHS.get()->getType());
7482 }
7483 
7484 inline QualType Sema::CheckBitwiseOperands(
7485   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
7486   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7487 
7488   if (LHS.get()->getType()->isVectorType() ||
7489       RHS.get()->getType()->isVectorType()) {
7490     if (LHS.get()->getType()->hasIntegerRepresentation() &&
7491         RHS.get()->getType()->hasIntegerRepresentation())
7492       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
7493 
7494     return InvalidOperands(Loc, LHS, RHS);
7495   }
7496 
7497   ExprResult LHSResult = Owned(LHS), RHSResult = Owned(RHS);
7498   QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
7499                                                  IsCompAssign);
7500   if (LHSResult.isInvalid() || RHSResult.isInvalid())
7501     return QualType();
7502   LHS = LHSResult.take();
7503   RHS = RHSResult.take();
7504 
7505   if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
7506     return compType;
7507   return InvalidOperands(Loc, LHS, RHS);
7508 }
7509 
7510 inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
7511   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) {
7512 
7513   // Check vector operands differently.
7514   if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
7515     return CheckVectorLogicalOperands(LHS, RHS, Loc);
7516 
7517   // Diagnose cases where the user write a logical and/or but probably meant a
7518   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
7519   // is a constant.
7520   if (LHS.get()->getType()->isIntegerType() &&
7521       !LHS.get()->getType()->isBooleanType() &&
7522       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
7523       // Don't warn in macros or template instantiations.
7524       !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
7525     // If the RHS can be constant folded, and if it constant folds to something
7526     // that isn't 0 or 1 (which indicate a potential logical operation that
7527     // happened to fold to true/false) then warn.
7528     // Parens on the RHS are ignored.
7529     llvm::APSInt Result;
7530     if (RHS.get()->EvaluateAsInt(Result, Context))
7531       if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType()) ||
7532           (Result != 0 && Result != 1)) {
7533         Diag(Loc, diag::warn_logical_instead_of_bitwise)
7534           << RHS.get()->getSourceRange()
7535           << (Opc == BO_LAnd ? "&&" : "||");
7536         // Suggest replacing the logical operator with the bitwise version
7537         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
7538             << (Opc == BO_LAnd ? "&" : "|")
7539             << FixItHint::CreateReplacement(SourceRange(
7540                 Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(),
7541                                                 getLangOpts())),
7542                                             Opc == BO_LAnd ? "&" : "|");
7543         if (Opc == BO_LAnd)
7544           // Suggest replacing "Foo() && kNonZero" with "Foo()"
7545           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
7546               << FixItHint::CreateRemoval(
7547                   SourceRange(
7548                       Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(),
7549                                                  0, getSourceManager(),
7550                                                  getLangOpts()),
7551                       RHS.get()->getLocEnd()));
7552       }
7553   }
7554 
7555   if (!Context.getLangOpts().CPlusPlus) {
7556     // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
7557     // not operate on the built-in scalar and vector float types.
7558     if (Context.getLangOpts().OpenCL &&
7559         Context.getLangOpts().OpenCLVersion < 120) {
7560       if (LHS.get()->getType()->isFloatingType() ||
7561           RHS.get()->getType()->isFloatingType())
7562         return InvalidOperands(Loc, LHS, RHS);
7563     }
7564 
7565     LHS = UsualUnaryConversions(LHS.take());
7566     if (LHS.isInvalid())
7567       return QualType();
7568 
7569     RHS = UsualUnaryConversions(RHS.take());
7570     if (RHS.isInvalid())
7571       return QualType();
7572 
7573     if (!LHS.get()->getType()->isScalarType() ||
7574         !RHS.get()->getType()->isScalarType())
7575       return InvalidOperands(Loc, LHS, RHS);
7576 
7577     return Context.IntTy;
7578   }
7579 
7580   // The following is safe because we only use this method for
7581   // non-overloadable operands.
7582 
7583   // C++ [expr.log.and]p1
7584   // C++ [expr.log.or]p1
7585   // The operands are both contextually converted to type bool.
7586   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
7587   if (LHSRes.isInvalid())
7588     return InvalidOperands(Loc, LHS, RHS);
7589   LHS = LHSRes;
7590 
7591   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
7592   if (RHSRes.isInvalid())
7593     return InvalidOperands(Loc, LHS, RHS);
7594   RHS = RHSRes;
7595 
7596   // C++ [expr.log.and]p2
7597   // C++ [expr.log.or]p2
7598   // The result is a bool.
7599   return Context.BoolTy;
7600 }
7601 
7602 /// IsReadonlyProperty - Verify that otherwise a valid l-value expression
7603 /// is a read-only property; return true if so. A readonly property expression
7604 /// depends on various declarations and thus must be treated specially.
7605 ///
7606 static bool IsReadonlyProperty(Expr *E, Sema &S) {
7607   const ObjCPropertyRefExpr *PropExpr = dyn_cast<ObjCPropertyRefExpr>(E);
7608   if (!PropExpr) return false;
7609   if (PropExpr->isImplicitProperty()) return false;
7610 
7611   ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
7612   QualType BaseType = PropExpr->isSuperReceiver() ?
7613                             PropExpr->getSuperReceiverType() :
7614                             PropExpr->getBase()->getType();
7615 
7616   if (const ObjCObjectPointerType *OPT =
7617       BaseType->getAsObjCInterfacePointerType())
7618     if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
7619       if (S.isPropertyReadonly(PDecl, IFace))
7620         return true;
7621   return false;
7622 }
7623 
7624 static bool IsReadonlyMessage(Expr *E, Sema &S) {
7625   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
7626   if (!ME) return false;
7627   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
7628   ObjCMessageExpr *Base =
7629     dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts());
7630   if (!Base) return false;
7631   return Base->getMethodDecl() != 0;
7632 }
7633 
7634 /// Is the given expression (which must be 'const') a reference to a
7635 /// variable which was originally non-const, but which has become
7636 /// 'const' due to being captured within a block?
7637 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
7638 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
7639   assert(E->isLValue() && E->getType().isConstQualified());
7640   E = E->IgnoreParens();
7641 
7642   // Must be a reference to a declaration from an enclosing scope.
7643   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
7644   if (!DRE) return NCCK_None;
7645   if (!DRE->refersToEnclosingLocal()) return NCCK_None;
7646 
7647   // The declaration must be a variable which is not declared 'const'.
7648   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
7649   if (!var) return NCCK_None;
7650   if (var->getType().isConstQualified()) return NCCK_None;
7651   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
7652 
7653   // Decide whether the first capture was for a block or a lambda.
7654   DeclContext *DC = S.CurContext;
7655   while (DC->getParent() != var->getDeclContext())
7656     DC = DC->getParent();
7657   return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
7658 }
7659 
7660 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
7661 /// emit an error and return true.  If so, return false.
7662 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
7663   assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
7664   SourceLocation OrigLoc = Loc;
7665   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
7666                                                               &Loc);
7667   if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
7668     IsLV = Expr::MLV_ReadonlyProperty;
7669   else if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
7670     IsLV = Expr::MLV_InvalidMessageExpression;
7671   if (IsLV == Expr::MLV_Valid)
7672     return false;
7673 
7674   unsigned Diag = 0;
7675   bool NeedType = false;
7676   switch (IsLV) { // C99 6.5.16p2
7677   case Expr::MLV_ConstQualified:
7678     Diag = diag::err_typecheck_assign_const;
7679 
7680     // Use a specialized diagnostic when we're assigning to an object
7681     // from an enclosing function or block.
7682     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
7683       if (NCCK == NCCK_Block)
7684         Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
7685       else
7686         Diag = diag::err_lambda_decl_ref_not_modifiable_lvalue;
7687       break;
7688     }
7689 
7690     // In ARC, use some specialized diagnostics for occasions where we
7691     // infer 'const'.  These are always pseudo-strong variables.
7692     if (S.getLangOpts().ObjCAutoRefCount) {
7693       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
7694       if (declRef && isa<VarDecl>(declRef->getDecl())) {
7695         VarDecl *var = cast<VarDecl>(declRef->getDecl());
7696 
7697         // Use the normal diagnostic if it's pseudo-__strong but the
7698         // user actually wrote 'const'.
7699         if (var->isARCPseudoStrong() &&
7700             (!var->getTypeSourceInfo() ||
7701              !var->getTypeSourceInfo()->getType().isConstQualified())) {
7702           // There are two pseudo-strong cases:
7703           //  - self
7704           ObjCMethodDecl *method = S.getCurMethodDecl();
7705           if (method && var == method->getSelfDecl())
7706             Diag = method->isClassMethod()
7707               ? diag::err_typecheck_arc_assign_self_class_method
7708               : diag::err_typecheck_arc_assign_self;
7709 
7710           //  - fast enumeration variables
7711           else
7712             Diag = diag::err_typecheck_arr_assign_enumeration;
7713 
7714           SourceRange Assign;
7715           if (Loc != OrigLoc)
7716             Assign = SourceRange(OrigLoc, OrigLoc);
7717           S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
7718           // We need to preserve the AST regardless, so migration tool
7719           // can do its job.
7720           return false;
7721         }
7722       }
7723     }
7724 
7725     break;
7726   case Expr::MLV_ArrayType:
7727   case Expr::MLV_ArrayTemporary:
7728     Diag = diag::err_typecheck_array_not_modifiable_lvalue;
7729     NeedType = true;
7730     break;
7731   case Expr::MLV_NotObjectType:
7732     Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
7733     NeedType = true;
7734     break;
7735   case Expr::MLV_LValueCast:
7736     Diag = diag::err_typecheck_lvalue_casts_not_supported;
7737     break;
7738   case Expr::MLV_Valid:
7739     llvm_unreachable("did not take early return for MLV_Valid");
7740   case Expr::MLV_InvalidExpression:
7741   case Expr::MLV_MemberFunction:
7742   case Expr::MLV_ClassTemporary:
7743     Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
7744     break;
7745   case Expr::MLV_IncompleteType:
7746   case Expr::MLV_IncompleteVoidType:
7747     return S.RequireCompleteType(Loc, E->getType(),
7748              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
7749   case Expr::MLV_DuplicateVectorComponents:
7750     Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
7751     break;
7752   case Expr::MLV_ReadonlyProperty:
7753   case Expr::MLV_NoSetterProperty:
7754     llvm_unreachable("readonly properties should be processed differently");
7755   case Expr::MLV_InvalidMessageExpression:
7756     Diag = diag::error_readonly_message_assignment;
7757     break;
7758   case Expr::MLV_SubObjCPropertySetting:
7759     Diag = diag::error_no_subobject_property_setting;
7760     break;
7761   }
7762 
7763   SourceRange Assign;
7764   if (Loc != OrigLoc)
7765     Assign = SourceRange(OrigLoc, OrigLoc);
7766   if (NeedType)
7767     S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
7768   else
7769     S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
7770   return true;
7771 }
7772 
7773 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
7774                                          SourceLocation Loc,
7775                                          Sema &Sema) {
7776   // C / C++ fields
7777   MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
7778   MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
7779   if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) {
7780     if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))
7781       Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
7782   }
7783 
7784   // Objective-C instance variables
7785   ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
7786   ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
7787   if (OL && OR && OL->getDecl() == OR->getDecl()) {
7788     DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
7789     DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
7790     if (RL && RR && RL->getDecl() == RR->getDecl())
7791       Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
7792   }
7793 }
7794 
7795 // C99 6.5.16.1
7796 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
7797                                        SourceLocation Loc,
7798                                        QualType CompoundType) {
7799   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
7800 
7801   // Verify that LHS is a modifiable lvalue, and emit error if not.
7802   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
7803     return QualType();
7804 
7805   QualType LHSType = LHSExpr->getType();
7806   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
7807                                              CompoundType;
7808   AssignConvertType ConvTy;
7809   if (CompoundType.isNull()) {
7810     Expr *RHSCheck = RHS.get();
7811 
7812     CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
7813 
7814     QualType LHSTy(LHSType);
7815     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
7816     if (RHS.isInvalid())
7817       return QualType();
7818     // Special case of NSObject attributes on c-style pointer types.
7819     if (ConvTy == IncompatiblePointer &&
7820         ((Context.isObjCNSObjectType(LHSType) &&
7821           RHSType->isObjCObjectPointerType()) ||
7822          (Context.isObjCNSObjectType(RHSType) &&
7823           LHSType->isObjCObjectPointerType())))
7824       ConvTy = Compatible;
7825 
7826     if (ConvTy == Compatible &&
7827         LHSType->isObjCObjectType())
7828         Diag(Loc, diag::err_objc_object_assignment)
7829           << LHSType;
7830 
7831     // If the RHS is a unary plus or minus, check to see if they = and + are
7832     // right next to each other.  If so, the user may have typo'd "x =+ 4"
7833     // instead of "x += 4".
7834     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
7835       RHSCheck = ICE->getSubExpr();
7836     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
7837       if ((UO->getOpcode() == UO_Plus ||
7838            UO->getOpcode() == UO_Minus) &&
7839           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
7840           // Only if the two operators are exactly adjacent.
7841           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
7842           // And there is a space or other character before the subexpr of the
7843           // unary +/-.  We don't want to warn on "x=-1".
7844           Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
7845           UO->getSubExpr()->getLocStart().isFileID()) {
7846         Diag(Loc, diag::warn_not_compound_assign)
7847           << (UO->getOpcode() == UO_Plus ? "+" : "-")
7848           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
7849       }
7850     }
7851 
7852     if (ConvTy == Compatible) {
7853       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
7854         // Warn about retain cycles where a block captures the LHS, but
7855         // not if the LHS is a simple variable into which the block is
7856         // being stored...unless that variable can be captured by reference!
7857         const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
7858         const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
7859         if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
7860           checkRetainCycles(LHSExpr, RHS.get());
7861 
7862         // It is safe to assign a weak reference into a strong variable.
7863         // Although this code can still have problems:
7864         //   id x = self.weakProp;
7865         //   id y = self.weakProp;
7866         // we do not warn to warn spuriously when 'x' and 'y' are on separate
7867         // paths through the function. This should be revisited if
7868         // -Wrepeated-use-of-weak is made flow-sensitive.
7869         DiagnosticsEngine::Level Level =
7870           Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
7871                                    RHS.get()->getLocStart());
7872         if (Level != DiagnosticsEngine::Ignored)
7873           getCurFunction()->markSafeWeakUse(RHS.get());
7874 
7875       } else if (getLangOpts().ObjCAutoRefCount) {
7876         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
7877       }
7878     }
7879   } else {
7880     // Compound assignment "x += y"
7881     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
7882   }
7883 
7884   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
7885                                RHS.get(), AA_Assigning))
7886     return QualType();
7887 
7888   CheckForNullPointerDereference(*this, LHSExpr);
7889 
7890   // C99 6.5.16p3: The type of an assignment expression is the type of the
7891   // left operand unless the left operand has qualified type, in which case
7892   // it is the unqualified version of the type of the left operand.
7893   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
7894   // is converted to the type of the assignment expression (above).
7895   // C++ 5.17p1: the type of the assignment expression is that of its left
7896   // operand.
7897   return (getLangOpts().CPlusPlus
7898           ? LHSType : LHSType.getUnqualifiedType());
7899 }
7900 
7901 // C99 6.5.17
7902 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
7903                                    SourceLocation Loc) {
7904   LHS = S.CheckPlaceholderExpr(LHS.take());
7905   RHS = S.CheckPlaceholderExpr(RHS.take());
7906   if (LHS.isInvalid() || RHS.isInvalid())
7907     return QualType();
7908 
7909   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
7910   // operands, but not unary promotions.
7911   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
7912 
7913   // So we treat the LHS as a ignored value, and in C++ we allow the
7914   // containing site to determine what should be done with the RHS.
7915   LHS = S.IgnoredValueConversions(LHS.take());
7916   if (LHS.isInvalid())
7917     return QualType();
7918 
7919   S.DiagnoseUnusedExprResult(LHS.get());
7920 
7921   if (!S.getLangOpts().CPlusPlus) {
7922     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take());
7923     if (RHS.isInvalid())
7924       return QualType();
7925     if (!RHS.get()->getType()->isVoidType())
7926       S.RequireCompleteType(Loc, RHS.get()->getType(),
7927                             diag::err_incomplete_type);
7928   }
7929 
7930   return RHS.get()->getType();
7931 }
7932 
7933 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
7934 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
7935 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
7936                                                ExprValueKind &VK,
7937                                                SourceLocation OpLoc,
7938                                                bool IsInc, bool IsPrefix) {
7939   if (Op->isTypeDependent())
7940     return S.Context.DependentTy;
7941 
7942   QualType ResType = Op->getType();
7943   // Atomic types can be used for increment / decrement where the non-atomic
7944   // versions can, so ignore the _Atomic() specifier for the purpose of
7945   // checking.
7946   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
7947     ResType = ResAtomicType->getValueType();
7948 
7949   assert(!ResType.isNull() && "no type for increment/decrement expression");
7950 
7951   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
7952     // Decrement of bool is not allowed.
7953     if (!IsInc) {
7954       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
7955       return QualType();
7956     }
7957     // Increment of bool sets it to true, but is deprecated.
7958     S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
7959   } else if (ResType->isRealType()) {
7960     // OK!
7961   } else if (ResType->isPointerType()) {
7962     // C99 6.5.2.4p2, 6.5.6p2
7963     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
7964       return QualType();
7965   } else if (ResType->isObjCObjectPointerType()) {
7966     // On modern runtimes, ObjC pointer arithmetic is forbidden.
7967     // Otherwise, we just need a complete type.
7968     if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
7969         checkArithmeticOnObjCPointer(S, OpLoc, Op))
7970       return QualType();
7971   } else if (ResType->isAnyComplexType()) {
7972     // C99 does not support ++/-- on complex types, we allow as an extension.
7973     S.Diag(OpLoc, diag::ext_integer_increment_complex)
7974       << ResType << Op->getSourceRange();
7975   } else if (ResType->isPlaceholderType()) {
7976     ExprResult PR = S.CheckPlaceholderExpr(Op);
7977     if (PR.isInvalid()) return QualType();
7978     return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
7979                                           IsInc, IsPrefix);
7980   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
7981     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
7982   } else {
7983     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
7984       << ResType << int(IsInc) << Op->getSourceRange();
7985     return QualType();
7986   }
7987   // At this point, we know we have a real, complex or pointer type.
7988   // Now make sure the operand is a modifiable lvalue.
7989   if (CheckForModifiableLvalue(Op, OpLoc, S))
7990     return QualType();
7991   // In C++, a prefix increment is the same type as the operand. Otherwise
7992   // (in C or with postfix), the increment is the unqualified type of the
7993   // operand.
7994   if (IsPrefix && S.getLangOpts().CPlusPlus) {
7995     VK = VK_LValue;
7996     return ResType;
7997   } else {
7998     VK = VK_RValue;
7999     return ResType.getUnqualifiedType();
8000   }
8001 }
8002 
8003 
8004 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
8005 /// This routine allows us to typecheck complex/recursive expressions
8006 /// where the declaration is needed for type checking. We only need to
8007 /// handle cases when the expression references a function designator
8008 /// or is an lvalue. Here are some examples:
8009 ///  - &(x) => x
8010 ///  - &*****f => f for f a function designator.
8011 ///  - &s.xx => s
8012 ///  - &s.zz[1].yy -> s, if zz is an array
8013 ///  - *(x + 1) -> x, if x is an array
8014 ///  - &"123"[2] -> 0
8015 ///  - & __real__ x -> x
8016 static ValueDecl *getPrimaryDecl(Expr *E) {
8017   switch (E->getStmtClass()) {
8018   case Stmt::DeclRefExprClass:
8019     return cast<DeclRefExpr>(E)->getDecl();
8020   case Stmt::MemberExprClass:
8021     // If this is an arrow operator, the address is an offset from
8022     // the base's value, so the object the base refers to is
8023     // irrelevant.
8024     if (cast<MemberExpr>(E)->isArrow())
8025       return 0;
8026     // Otherwise, the expression refers to a part of the base
8027     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
8028   case Stmt::ArraySubscriptExprClass: {
8029     // FIXME: This code shouldn't be necessary!  We should catch the implicit
8030     // promotion of register arrays earlier.
8031     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
8032     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
8033       if (ICE->getSubExpr()->getType()->isArrayType())
8034         return getPrimaryDecl(ICE->getSubExpr());
8035     }
8036     return 0;
8037   }
8038   case Stmt::UnaryOperatorClass: {
8039     UnaryOperator *UO = cast<UnaryOperator>(E);
8040 
8041     switch(UO->getOpcode()) {
8042     case UO_Real:
8043     case UO_Imag:
8044     case UO_Extension:
8045       return getPrimaryDecl(UO->getSubExpr());
8046     default:
8047       return 0;
8048     }
8049   }
8050   case Stmt::ParenExprClass:
8051     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
8052   case Stmt::ImplicitCastExprClass:
8053     // If the result of an implicit cast is an l-value, we care about
8054     // the sub-expression; otherwise, the result here doesn't matter.
8055     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
8056   default:
8057     return 0;
8058   }
8059 }
8060 
8061 namespace {
8062   enum {
8063     AO_Bit_Field = 0,
8064     AO_Vector_Element = 1,
8065     AO_Property_Expansion = 2,
8066     AO_Register_Variable = 3,
8067     AO_No_Error = 4
8068   };
8069 }
8070 /// \brief Diagnose invalid operand for address of operations.
8071 ///
8072 /// \param Type The type of operand which cannot have its address taken.
8073 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
8074                                          Expr *E, unsigned Type) {
8075   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
8076 }
8077 
8078 /// CheckAddressOfOperand - The operand of & must be either a function
8079 /// designator or an lvalue designating an object. If it is an lvalue, the
8080 /// object cannot be declared with storage class register or be a bit field.
8081 /// Note: The usual conversions are *not* applied to the operand of the &
8082 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
8083 /// In C++, the operand might be an overloaded function name, in which case
8084 /// we allow the '&' but retain the overloaded-function type.
8085 static QualType CheckAddressOfOperand(Sema &S, ExprResult &OrigOp,
8086                                       SourceLocation OpLoc) {
8087   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
8088     if (PTy->getKind() == BuiltinType::Overload) {
8089       if (!isa<OverloadExpr>(OrigOp.get()->IgnoreParens())) {
8090         assert(cast<UnaryOperator>(OrigOp.get()->IgnoreParens())->getOpcode()
8091                  == UO_AddrOf);
8092         S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
8093           << OrigOp.get()->getSourceRange();
8094         return QualType();
8095       }
8096 
8097       return S.Context.OverloadTy;
8098     }
8099 
8100     if (PTy->getKind() == BuiltinType::UnknownAny)
8101       return S.Context.UnknownAnyTy;
8102 
8103     if (PTy->getKind() == BuiltinType::BoundMember) {
8104       S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
8105         << OrigOp.get()->getSourceRange();
8106       return QualType();
8107     }
8108 
8109     OrigOp = S.CheckPlaceholderExpr(OrigOp.take());
8110     if (OrigOp.isInvalid()) return QualType();
8111   }
8112 
8113   if (OrigOp.get()->isTypeDependent())
8114     return S.Context.DependentTy;
8115 
8116   assert(!OrigOp.get()->getType()->isPlaceholderType());
8117 
8118   // Make sure to ignore parentheses in subsequent checks
8119   Expr *op = OrigOp.get()->IgnoreParens();
8120 
8121   if (S.getLangOpts().C99) {
8122     // Implement C99-only parts of addressof rules.
8123     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
8124       if (uOp->getOpcode() == UO_Deref)
8125         // Per C99 6.5.3.2, the address of a deref always returns a valid result
8126         // (assuming the deref expression is valid).
8127         return uOp->getSubExpr()->getType();
8128     }
8129     // Technically, there should be a check for array subscript
8130     // expressions here, but the result of one is always an lvalue anyway.
8131   }
8132   ValueDecl *dcl = getPrimaryDecl(op);
8133   Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
8134   unsigned AddressOfError = AO_No_Error;
8135 
8136   if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
8137     bool sfinae = (bool)S.isSFINAEContext();
8138     S.Diag(OpLoc, S.isSFINAEContext() ? diag::err_typecheck_addrof_temporary
8139                          : diag::ext_typecheck_addrof_temporary)
8140       << op->getType() << op->getSourceRange();
8141     if (sfinae)
8142       return QualType();
8143   } else if (isa<ObjCSelectorExpr>(op)) {
8144     return S.Context.getPointerType(op->getType());
8145   } else if (lval == Expr::LV_MemberFunction) {
8146     // If it's an instance method, make a member pointer.
8147     // The expression must have exactly the form &A::foo.
8148 
8149     // If the underlying expression isn't a decl ref, give up.
8150     if (!isa<DeclRefExpr>(op)) {
8151       S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
8152         << OrigOp.get()->getSourceRange();
8153       return QualType();
8154     }
8155     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
8156     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
8157 
8158     // The id-expression was parenthesized.
8159     if (OrigOp.get() != DRE) {
8160       S.Diag(OpLoc, diag::err_parens_pointer_member_function)
8161         << OrigOp.get()->getSourceRange();
8162 
8163     // The method was named without a qualifier.
8164     } else if (!DRE->getQualifier()) {
8165       if (MD->getParent()->getName().empty())
8166         S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
8167           << op->getSourceRange();
8168       else {
8169         SmallString<32> Str;
8170         StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
8171         S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
8172           << op->getSourceRange()
8173           << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
8174       }
8175     }
8176 
8177     return S.Context.getMemberPointerType(op->getType(),
8178               S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
8179   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
8180     // C99 6.5.3.2p1
8181     // The operand must be either an l-value or a function designator
8182     if (!op->getType()->isFunctionType()) {
8183       // Use a special diagnostic for loads from property references.
8184       if (isa<PseudoObjectExpr>(op)) {
8185         AddressOfError = AO_Property_Expansion;
8186       } else {
8187         S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
8188           << op->getType() << op->getSourceRange();
8189         return QualType();
8190       }
8191     }
8192   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
8193     // The operand cannot be a bit-field
8194     AddressOfError = AO_Bit_Field;
8195   } else if (op->getObjectKind() == OK_VectorComponent) {
8196     // The operand cannot be an element of a vector
8197     AddressOfError = AO_Vector_Element;
8198   } else if (dcl) { // C99 6.5.3.2p1
8199     // We have an lvalue with a decl. Make sure the decl is not declared
8200     // with the register storage-class specifier.
8201     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
8202       // in C++ it is not error to take address of a register
8203       // variable (c++03 7.1.1P3)
8204       if (vd->getStorageClass() == SC_Register &&
8205           !S.getLangOpts().CPlusPlus) {
8206         AddressOfError = AO_Register_Variable;
8207       }
8208     } else if (isa<FunctionTemplateDecl>(dcl)) {
8209       return S.Context.OverloadTy;
8210     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
8211       // Okay: we can take the address of a field.
8212       // Could be a pointer to member, though, if there is an explicit
8213       // scope qualifier for the class.
8214       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
8215         DeclContext *Ctx = dcl->getDeclContext();
8216         if (Ctx && Ctx->isRecord()) {
8217           if (dcl->getType()->isReferenceType()) {
8218             S.Diag(OpLoc,
8219                    diag::err_cannot_form_pointer_to_member_of_reference_type)
8220               << dcl->getDeclName() << dcl->getType();
8221             return QualType();
8222           }
8223 
8224           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
8225             Ctx = Ctx->getParent();
8226           return S.Context.getMemberPointerType(op->getType(),
8227                 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
8228         }
8229       }
8230     } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl))
8231       llvm_unreachable("Unknown/unexpected decl type");
8232   }
8233 
8234   if (AddressOfError != AO_No_Error) {
8235     diagnoseAddressOfInvalidType(S, OpLoc, op, AddressOfError);
8236     return QualType();
8237   }
8238 
8239   if (lval == Expr::LV_IncompleteVoidType) {
8240     // Taking the address of a void variable is technically illegal, but we
8241     // allow it in cases which are otherwise valid.
8242     // Example: "extern void x; void* y = &x;".
8243     S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
8244   }
8245 
8246   // If the operand has type "type", the result has type "pointer to type".
8247   if (op->getType()->isObjCObjectType())
8248     return S.Context.getObjCObjectPointerType(op->getType());
8249   return S.Context.getPointerType(op->getType());
8250 }
8251 
8252 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
8253 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
8254                                         SourceLocation OpLoc) {
8255   if (Op->isTypeDependent())
8256     return S.Context.DependentTy;
8257 
8258   ExprResult ConvResult = S.UsualUnaryConversions(Op);
8259   if (ConvResult.isInvalid())
8260     return QualType();
8261   Op = ConvResult.take();
8262   QualType OpTy = Op->getType();
8263   QualType Result;
8264 
8265   if (isa<CXXReinterpretCastExpr>(Op)) {
8266     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
8267     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
8268                                      Op->getSourceRange());
8269   }
8270 
8271   // Note that per both C89 and C99, indirection is always legal, even if OpTy
8272   // is an incomplete type or void.  It would be possible to warn about
8273   // dereferencing a void pointer, but it's completely well-defined, and such a
8274   // warning is unlikely to catch any mistakes.
8275   if (const PointerType *PT = OpTy->getAs<PointerType>())
8276     Result = PT->getPointeeType();
8277   else if (const ObjCObjectPointerType *OPT =
8278              OpTy->getAs<ObjCObjectPointerType>())
8279     Result = OPT->getPointeeType();
8280   else {
8281     ExprResult PR = S.CheckPlaceholderExpr(Op);
8282     if (PR.isInvalid()) return QualType();
8283     if (PR.take() != Op)
8284       return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
8285   }
8286 
8287   if (Result.isNull()) {
8288     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
8289       << OpTy << Op->getSourceRange();
8290     return QualType();
8291   }
8292 
8293   // Dereferences are usually l-values...
8294   VK = VK_LValue;
8295 
8296   // ...except that certain expressions are never l-values in C.
8297   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
8298     VK = VK_RValue;
8299 
8300   return Result;
8301 }
8302 
8303 static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
8304   tok::TokenKind Kind) {
8305   BinaryOperatorKind Opc;
8306   switch (Kind) {
8307   default: llvm_unreachable("Unknown binop!");
8308   case tok::periodstar:           Opc = BO_PtrMemD; break;
8309   case tok::arrowstar:            Opc = BO_PtrMemI; break;
8310   case tok::star:                 Opc = BO_Mul; break;
8311   case tok::slash:                Opc = BO_Div; break;
8312   case tok::percent:              Opc = BO_Rem; break;
8313   case tok::plus:                 Opc = BO_Add; break;
8314   case tok::minus:                Opc = BO_Sub; break;
8315   case tok::lessless:             Opc = BO_Shl; break;
8316   case tok::greatergreater:       Opc = BO_Shr; break;
8317   case tok::lessequal:            Opc = BO_LE; break;
8318   case tok::less:                 Opc = BO_LT; break;
8319   case tok::greaterequal:         Opc = BO_GE; break;
8320   case tok::greater:              Opc = BO_GT; break;
8321   case tok::exclaimequal:         Opc = BO_NE; break;
8322   case tok::equalequal:           Opc = BO_EQ; break;
8323   case tok::amp:                  Opc = BO_And; break;
8324   case tok::caret:                Opc = BO_Xor; break;
8325   case tok::pipe:                 Opc = BO_Or; break;
8326   case tok::ampamp:               Opc = BO_LAnd; break;
8327   case tok::pipepipe:             Opc = BO_LOr; break;
8328   case tok::equal:                Opc = BO_Assign; break;
8329   case tok::starequal:            Opc = BO_MulAssign; break;
8330   case tok::slashequal:           Opc = BO_DivAssign; break;
8331   case tok::percentequal:         Opc = BO_RemAssign; break;
8332   case tok::plusequal:            Opc = BO_AddAssign; break;
8333   case tok::minusequal:           Opc = BO_SubAssign; break;
8334   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
8335   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
8336   case tok::ampequal:             Opc = BO_AndAssign; break;
8337   case tok::caretequal:           Opc = BO_XorAssign; break;
8338   case tok::pipeequal:            Opc = BO_OrAssign; break;
8339   case tok::comma:                Opc = BO_Comma; break;
8340   }
8341   return Opc;
8342 }
8343 
8344 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
8345   tok::TokenKind Kind) {
8346   UnaryOperatorKind Opc;
8347   switch (Kind) {
8348   default: llvm_unreachable("Unknown unary op!");
8349   case tok::plusplus:     Opc = UO_PreInc; break;
8350   case tok::minusminus:   Opc = UO_PreDec; break;
8351   case tok::amp:          Opc = UO_AddrOf; break;
8352   case tok::star:         Opc = UO_Deref; break;
8353   case tok::plus:         Opc = UO_Plus; break;
8354   case tok::minus:        Opc = UO_Minus; break;
8355   case tok::tilde:        Opc = UO_Not; break;
8356   case tok::exclaim:      Opc = UO_LNot; break;
8357   case tok::kw___real:    Opc = UO_Real; break;
8358   case tok::kw___imag:    Opc = UO_Imag; break;
8359   case tok::kw___extension__: Opc = UO_Extension; break;
8360   }
8361   return Opc;
8362 }
8363 
8364 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
8365 /// This warning is only emitted for builtin assignment operations. It is also
8366 /// suppressed in the event of macro expansions.
8367 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
8368                                    SourceLocation OpLoc) {
8369   if (!S.ActiveTemplateInstantiations.empty())
8370     return;
8371   if (OpLoc.isInvalid() || OpLoc.isMacroID())
8372     return;
8373   LHSExpr = LHSExpr->IgnoreParenImpCasts();
8374   RHSExpr = RHSExpr->IgnoreParenImpCasts();
8375   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
8376   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
8377   if (!LHSDeclRef || !RHSDeclRef ||
8378       LHSDeclRef->getLocation().isMacroID() ||
8379       RHSDeclRef->getLocation().isMacroID())
8380     return;
8381   const ValueDecl *LHSDecl =
8382     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
8383   const ValueDecl *RHSDecl =
8384     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
8385   if (LHSDecl != RHSDecl)
8386     return;
8387   if (LHSDecl->getType().isVolatileQualified())
8388     return;
8389   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
8390     if (RefTy->getPointeeType().isVolatileQualified())
8391       return;
8392 
8393   S.Diag(OpLoc, diag::warn_self_assignment)
8394       << LHSDeclRef->getType()
8395       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
8396 }
8397 
8398 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
8399 /// operator @p Opc at location @c TokLoc. This routine only supports
8400 /// built-in operations; ActOnBinOp handles overloaded operators.
8401 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
8402                                     BinaryOperatorKind Opc,
8403                                     Expr *LHSExpr, Expr *RHSExpr) {
8404   if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
8405     // The syntax only allows initializer lists on the RHS of assignment,
8406     // so we don't need to worry about accepting invalid code for
8407     // non-assignment operators.
8408     // C++11 5.17p9:
8409     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
8410     //   of x = {} is x = T().
8411     InitializationKind Kind =
8412         InitializationKind::CreateDirectList(RHSExpr->getLocStart());
8413     InitializedEntity Entity =
8414         InitializedEntity::InitializeTemporary(LHSExpr->getType());
8415     InitializationSequence InitSeq(*this, Entity, Kind, &RHSExpr, 1);
8416     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
8417     if (Init.isInvalid())
8418       return Init;
8419     RHSExpr = Init.take();
8420   }
8421 
8422   ExprResult LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
8423   QualType ResultTy;     // Result type of the binary operator.
8424   // The following two variables are used for compound assignment operators
8425   QualType CompLHSTy;    // Type of LHS after promotions for computation
8426   QualType CompResultTy; // Type of computation result
8427   ExprValueKind VK = VK_RValue;
8428   ExprObjectKind OK = OK_Ordinary;
8429 
8430   switch (Opc) {
8431   case BO_Assign:
8432     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
8433     if (getLangOpts().CPlusPlus &&
8434         LHS.get()->getObjectKind() != OK_ObjCProperty) {
8435       VK = LHS.get()->getValueKind();
8436       OK = LHS.get()->getObjectKind();
8437     }
8438     if (!ResultTy.isNull())
8439       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
8440     break;
8441   case BO_PtrMemD:
8442   case BO_PtrMemI:
8443     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
8444                                             Opc == BO_PtrMemI);
8445     break;
8446   case BO_Mul:
8447   case BO_Div:
8448     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
8449                                            Opc == BO_Div);
8450     break;
8451   case BO_Rem:
8452     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
8453     break;
8454   case BO_Add:
8455     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
8456     break;
8457   case BO_Sub:
8458     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
8459     break;
8460   case BO_Shl:
8461   case BO_Shr:
8462     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
8463     break;
8464   case BO_LE:
8465   case BO_LT:
8466   case BO_GE:
8467   case BO_GT:
8468     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
8469     break;
8470   case BO_EQ:
8471   case BO_NE:
8472     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
8473     break;
8474   case BO_And:
8475   case BO_Xor:
8476   case BO_Or:
8477     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc);
8478     break;
8479   case BO_LAnd:
8480   case BO_LOr:
8481     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
8482     break;
8483   case BO_MulAssign:
8484   case BO_DivAssign:
8485     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
8486                                                Opc == BO_DivAssign);
8487     CompLHSTy = CompResultTy;
8488     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8489       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
8490     break;
8491   case BO_RemAssign:
8492     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
8493     CompLHSTy = CompResultTy;
8494     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8495       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
8496     break;
8497   case BO_AddAssign:
8498     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
8499     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8500       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
8501     break;
8502   case BO_SubAssign:
8503     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
8504     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8505       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
8506     break;
8507   case BO_ShlAssign:
8508   case BO_ShrAssign:
8509     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
8510     CompLHSTy = CompResultTy;
8511     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8512       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
8513     break;
8514   case BO_AndAssign:
8515   case BO_XorAssign:
8516   case BO_OrAssign:
8517     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true);
8518     CompLHSTy = CompResultTy;
8519     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8520       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
8521     break;
8522   case BO_Comma:
8523     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
8524     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
8525       VK = RHS.get()->getValueKind();
8526       OK = RHS.get()->getObjectKind();
8527     }
8528     break;
8529   }
8530   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
8531     return ExprError();
8532 
8533   // Check for array bounds violations for both sides of the BinaryOperator
8534   CheckArrayAccess(LHS.get());
8535   CheckArrayAccess(RHS.get());
8536 
8537   if (CompResultTy.isNull())
8538     return Owned(new (Context) BinaryOperator(LHS.take(), RHS.take(), Opc,
8539                                               ResultTy, VK, OK, OpLoc,
8540                                               FPFeatures.fp_contract));
8541   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
8542       OK_ObjCProperty) {
8543     VK = VK_LValue;
8544     OK = LHS.get()->getObjectKind();
8545   }
8546   return Owned(new (Context) CompoundAssignOperator(LHS.take(), RHS.take(), Opc,
8547                                                     ResultTy, VK, OK, CompLHSTy,
8548                                                     CompResultTy, OpLoc,
8549                                                     FPFeatures.fp_contract));
8550 }
8551 
8552 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
8553 /// operators are mixed in a way that suggests that the programmer forgot that
8554 /// comparison operators have higher precedence. The most typical example of
8555 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
8556 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
8557                                       SourceLocation OpLoc, Expr *LHSExpr,
8558                                       Expr *RHSExpr) {
8559   BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
8560   BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
8561 
8562   // Check that one of the sides is a comparison operator.
8563   bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
8564   bool isRightComp = RHSBO && RHSBO->isComparisonOp();
8565   if (!isLeftComp && !isRightComp)
8566     return;
8567 
8568   // Bitwise operations are sometimes used as eager logical ops.
8569   // Don't diagnose this.
8570   bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
8571   bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
8572   if ((isLeftComp || isLeftBitwise) && (isRightComp || isRightBitwise))
8573     return;
8574 
8575   SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
8576                                                    OpLoc)
8577                                      : SourceRange(OpLoc, RHSExpr->getLocEnd());
8578   StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
8579   SourceRange ParensRange = isLeftComp ?
8580       SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd())
8581     : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocStart());
8582 
8583   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
8584     << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
8585   SuggestParentheses(Self, OpLoc,
8586     Self.PDiag(diag::note_precedence_silence) << OpStr,
8587     (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
8588   SuggestParentheses(Self, OpLoc,
8589     Self.PDiag(diag::note_precedence_bitwise_first)
8590       << BinaryOperator::getOpcodeStr(Opc),
8591     ParensRange);
8592 }
8593 
8594 /// \brief It accepts a '&' expr that is inside a '|' one.
8595 /// Emit a diagnostic together with a fixit hint that wraps the '&' expression
8596 /// in parentheses.
8597 static void
8598 EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc,
8599                                        BinaryOperator *Bop) {
8600   assert(Bop->getOpcode() == BO_And);
8601   Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or)
8602       << Bop->getSourceRange() << OpLoc;
8603   SuggestParentheses(Self, Bop->getOperatorLoc(),
8604     Self.PDiag(diag::note_precedence_silence)
8605       << Bop->getOpcodeStr(),
8606     Bop->getSourceRange());
8607 }
8608 
8609 /// \brief It accepts a '&&' expr that is inside a '||' one.
8610 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
8611 /// in parentheses.
8612 static void
8613 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
8614                                        BinaryOperator *Bop) {
8615   assert(Bop->getOpcode() == BO_LAnd);
8616   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
8617       << Bop->getSourceRange() << OpLoc;
8618   SuggestParentheses(Self, Bop->getOperatorLoc(),
8619     Self.PDiag(diag::note_precedence_silence)
8620       << Bop->getOpcodeStr(),
8621     Bop->getSourceRange());
8622 }
8623 
8624 /// \brief Returns true if the given expression can be evaluated as a constant
8625 /// 'true'.
8626 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
8627   bool Res;
8628   return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
8629 }
8630 
8631 /// \brief Returns true if the given expression can be evaluated as a constant
8632 /// 'false'.
8633 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
8634   bool Res;
8635   return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
8636 }
8637 
8638 /// \brief Look for '&&' in the left hand of a '||' expr.
8639 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
8640                                              Expr *LHSExpr, Expr *RHSExpr) {
8641   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
8642     if (Bop->getOpcode() == BO_LAnd) {
8643       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
8644       if (EvaluatesAsFalse(S, RHSExpr))
8645         return;
8646       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
8647       if (!EvaluatesAsTrue(S, Bop->getLHS()))
8648         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
8649     } else if (Bop->getOpcode() == BO_LOr) {
8650       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
8651         // If it's "a || b && 1 || c" we didn't warn earlier for
8652         // "a || b && 1", but warn now.
8653         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
8654           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
8655       }
8656     }
8657   }
8658 }
8659 
8660 /// \brief Look for '&&' in the right hand of a '||' expr.
8661 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
8662                                              Expr *LHSExpr, Expr *RHSExpr) {
8663   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
8664     if (Bop->getOpcode() == BO_LAnd) {
8665       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
8666       if (EvaluatesAsFalse(S, LHSExpr))
8667         return;
8668       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
8669       if (!EvaluatesAsTrue(S, Bop->getRHS()))
8670         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
8671     }
8672   }
8673 }
8674 
8675 /// \brief Look for '&' in the left or right hand of a '|' expr.
8676 static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc,
8677                                              Expr *OrArg) {
8678   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) {
8679     if (Bop->getOpcode() == BO_And)
8680       return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop);
8681   }
8682 }
8683 
8684 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
8685                                     Expr *SubExpr, StringRef Shift) {
8686   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
8687     if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
8688       StringRef Op = Bop->getOpcodeStr();
8689       S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
8690           << Bop->getSourceRange() << OpLoc << Shift << Op;
8691       SuggestParentheses(S, Bop->getOperatorLoc(),
8692           S.PDiag(diag::note_precedence_silence) << Op,
8693           Bop->getSourceRange());
8694     }
8695   }
8696 }
8697 
8698 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
8699 /// precedence.
8700 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
8701                                     SourceLocation OpLoc, Expr *LHSExpr,
8702                                     Expr *RHSExpr){
8703   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
8704   if (BinaryOperator::isBitwiseOp(Opc))
8705     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
8706 
8707   // Diagnose "arg1 & arg2 | arg3"
8708   if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) {
8709     DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr);
8710     DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr);
8711   }
8712 
8713   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
8714   // We don't warn for 'assert(a || b && "bad")' since this is safe.
8715   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
8716     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
8717     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
8718   }
8719 
8720   if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
8721       || Opc == BO_Shr) {
8722     StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
8723     DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
8724     DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
8725   }
8726 }
8727 
8728 // Binary Operators.  'Tok' is the token for the operator.
8729 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
8730                             tok::TokenKind Kind,
8731                             Expr *LHSExpr, Expr *RHSExpr) {
8732   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
8733   assert((LHSExpr != 0) && "ActOnBinOp(): missing left expression");
8734   assert((RHSExpr != 0) && "ActOnBinOp(): missing right expression");
8735 
8736   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
8737   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
8738 
8739   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
8740 }
8741 
8742 /// Build an overloaded binary operator expression in the given scope.
8743 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
8744                                        BinaryOperatorKind Opc,
8745                                        Expr *LHS, Expr *RHS) {
8746   // Find all of the overloaded operators visible from this
8747   // point. We perform both an operator-name lookup from the local
8748   // scope and an argument-dependent lookup based on the types of
8749   // the arguments.
8750   UnresolvedSet<16> Functions;
8751   OverloadedOperatorKind OverOp
8752     = BinaryOperator::getOverloadedOperator(Opc);
8753   if (Sc && OverOp != OO_None)
8754     S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
8755                                    RHS->getType(), Functions);
8756 
8757   // Build the (potentially-overloaded, potentially-dependent)
8758   // binary operation.
8759   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
8760 }
8761 
8762 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
8763                             BinaryOperatorKind Opc,
8764                             Expr *LHSExpr, Expr *RHSExpr) {
8765   // We want to end up calling one of checkPseudoObjectAssignment
8766   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
8767   // both expressions are overloadable or either is type-dependent),
8768   // or CreateBuiltinBinOp (in any other case).  We also want to get
8769   // any placeholder types out of the way.
8770 
8771   // Handle pseudo-objects in the LHS.
8772   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
8773     // Assignments with a pseudo-object l-value need special analysis.
8774     if (pty->getKind() == BuiltinType::PseudoObject &&
8775         BinaryOperator::isAssignmentOp(Opc))
8776       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
8777 
8778     // Don't resolve overloads if the other type is overloadable.
8779     if (pty->getKind() == BuiltinType::Overload) {
8780       // We can't actually test that if we still have a placeholder,
8781       // though.  Fortunately, none of the exceptions we see in that
8782       // code below are valid when the LHS is an overload set.  Note
8783       // that an overload set can be dependently-typed, but it never
8784       // instantiates to having an overloadable type.
8785       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
8786       if (resolvedRHS.isInvalid()) return ExprError();
8787       RHSExpr = resolvedRHS.take();
8788 
8789       if (RHSExpr->isTypeDependent() ||
8790           RHSExpr->getType()->isOverloadableType())
8791         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8792     }
8793 
8794     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
8795     if (LHS.isInvalid()) return ExprError();
8796     LHSExpr = LHS.take();
8797   }
8798 
8799   // Handle pseudo-objects in the RHS.
8800   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
8801     // An overload in the RHS can potentially be resolved by the type
8802     // being assigned to.
8803     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
8804       if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
8805         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8806 
8807       if (LHSExpr->getType()->isOverloadableType())
8808         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8809 
8810       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
8811     }
8812 
8813     // Don't resolve overloads if the other type is overloadable.
8814     if (pty->getKind() == BuiltinType::Overload &&
8815         LHSExpr->getType()->isOverloadableType())
8816       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8817 
8818     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
8819     if (!resolvedRHS.isUsable()) return ExprError();
8820     RHSExpr = resolvedRHS.take();
8821   }
8822 
8823   if (getLangOpts().CPlusPlus) {
8824     // If either expression is type-dependent, always build an
8825     // overloaded op.
8826     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
8827       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8828 
8829     // Otherwise, build an overloaded op if either expression has an
8830     // overloadable type.
8831     if (LHSExpr->getType()->isOverloadableType() ||
8832         RHSExpr->getType()->isOverloadableType())
8833       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8834   }
8835 
8836   // Build a built-in binary operation.
8837   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
8838 }
8839 
8840 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
8841                                       UnaryOperatorKind Opc,
8842                                       Expr *InputExpr) {
8843   ExprResult Input = Owned(InputExpr);
8844   ExprValueKind VK = VK_RValue;
8845   ExprObjectKind OK = OK_Ordinary;
8846   QualType resultType;
8847   switch (Opc) {
8848   case UO_PreInc:
8849   case UO_PreDec:
8850   case UO_PostInc:
8851   case UO_PostDec:
8852     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc,
8853                                                 Opc == UO_PreInc ||
8854                                                 Opc == UO_PostInc,
8855                                                 Opc == UO_PreInc ||
8856                                                 Opc == UO_PreDec);
8857     break;
8858   case UO_AddrOf:
8859     resultType = CheckAddressOfOperand(*this, Input, OpLoc);
8860     break;
8861   case UO_Deref: {
8862     Input = DefaultFunctionArrayLvalueConversion(Input.take());
8863     if (Input.isInvalid()) return ExprError();
8864     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
8865     break;
8866   }
8867   case UO_Plus:
8868   case UO_Minus:
8869     Input = UsualUnaryConversions(Input.take());
8870     if (Input.isInvalid()) return ExprError();
8871     resultType = Input.get()->getType();
8872     if (resultType->isDependentType())
8873       break;
8874     if (resultType->isArithmeticType() || // C99 6.5.3.3p1
8875         resultType->isVectorType())
8876       break;
8877     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6-7
8878              resultType->isEnumeralType())
8879       break;
8880     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
8881              Opc == UO_Plus &&
8882              resultType->isPointerType())
8883       break;
8884 
8885     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
8886       << resultType << Input.get()->getSourceRange());
8887 
8888   case UO_Not: // bitwise complement
8889     Input = UsualUnaryConversions(Input.take());
8890     if (Input.isInvalid())
8891       return ExprError();
8892     resultType = Input.get()->getType();
8893     if (resultType->isDependentType())
8894       break;
8895     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
8896     if (resultType->isComplexType() || resultType->isComplexIntegerType())
8897       // C99 does not support '~' for complex conjugation.
8898       Diag(OpLoc, diag::ext_integer_complement_complex)
8899           << resultType << Input.get()->getSourceRange();
8900     else if (resultType->hasIntegerRepresentation())
8901       break;
8902     else if (resultType->isExtVectorType()) {
8903       if (Context.getLangOpts().OpenCL) {
8904         // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
8905         // on vector float types.
8906         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
8907         if (!T->isIntegerType())
8908           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
8909                            << resultType << Input.get()->getSourceRange());
8910       }
8911       break;
8912     } else {
8913       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
8914                        << resultType << Input.get()->getSourceRange());
8915     }
8916     break;
8917 
8918   case UO_LNot: // logical negation
8919     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
8920     Input = DefaultFunctionArrayLvalueConversion(Input.take());
8921     if (Input.isInvalid()) return ExprError();
8922     resultType = Input.get()->getType();
8923 
8924     // Though we still have to promote half FP to float...
8925     if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
8926       Input = ImpCastExprToType(Input.take(), Context.FloatTy, CK_FloatingCast).take();
8927       resultType = Context.FloatTy;
8928     }
8929 
8930     if (resultType->isDependentType())
8931       break;
8932     if (resultType->isScalarType()) {
8933       // C99 6.5.3.3p1: ok, fallthrough;
8934       if (Context.getLangOpts().CPlusPlus) {
8935         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
8936         // operand contextually converted to bool.
8937         Input = ImpCastExprToType(Input.take(), Context.BoolTy,
8938                                   ScalarTypeToBooleanCastKind(resultType));
8939       } else if (Context.getLangOpts().OpenCL &&
8940                  Context.getLangOpts().OpenCLVersion < 120) {
8941         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
8942         // operate on scalar float types.
8943         if (!resultType->isIntegerType())
8944           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
8945                            << resultType << Input.get()->getSourceRange());
8946       }
8947     } else if (resultType->isExtVectorType()) {
8948       if (Context.getLangOpts().OpenCL &&
8949           Context.getLangOpts().OpenCLVersion < 120) {
8950         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
8951         // operate on vector float types.
8952         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
8953         if (!T->isIntegerType())
8954           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
8955                            << resultType << Input.get()->getSourceRange());
8956       }
8957       // Vector logical not returns the signed variant of the operand type.
8958       resultType = GetSignedVectorType(resultType);
8959       break;
8960     } else {
8961       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
8962         << resultType << Input.get()->getSourceRange());
8963     }
8964 
8965     // LNot always has type int. C99 6.5.3.3p5.
8966     // In C++, it's bool. C++ 5.3.1p8
8967     resultType = Context.getLogicalOperationType();
8968     break;
8969   case UO_Real:
8970   case UO_Imag:
8971     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
8972     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
8973     // complex l-values to ordinary l-values and all other values to r-values.
8974     if (Input.isInvalid()) return ExprError();
8975     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
8976       if (Input.get()->getValueKind() != VK_RValue &&
8977           Input.get()->getObjectKind() == OK_Ordinary)
8978         VK = Input.get()->getValueKind();
8979     } else if (!getLangOpts().CPlusPlus) {
8980       // In C, a volatile scalar is read by __imag. In C++, it is not.
8981       Input = DefaultLvalueConversion(Input.take());
8982     }
8983     break;
8984   case UO_Extension:
8985     resultType = Input.get()->getType();
8986     VK = Input.get()->getValueKind();
8987     OK = Input.get()->getObjectKind();
8988     break;
8989   }
8990   if (resultType.isNull() || Input.isInvalid())
8991     return ExprError();
8992 
8993   // Check for array bounds violations in the operand of the UnaryOperator,
8994   // except for the '*' and '&' operators that have to be handled specially
8995   // by CheckArrayAccess (as there are special cases like &array[arraysize]
8996   // that are explicitly defined as valid by the standard).
8997   if (Opc != UO_AddrOf && Opc != UO_Deref)
8998     CheckArrayAccess(Input.get());
8999 
9000   return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType,
9001                                            VK, OK, OpLoc));
9002 }
9003 
9004 /// \brief Determine whether the given expression is a qualified member
9005 /// access expression, of a form that could be turned into a pointer to member
9006 /// with the address-of operator.
9007 static bool isQualifiedMemberAccess(Expr *E) {
9008   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
9009     if (!DRE->getQualifier())
9010       return false;
9011 
9012     ValueDecl *VD = DRE->getDecl();
9013     if (!VD->isCXXClassMember())
9014       return false;
9015 
9016     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
9017       return true;
9018     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
9019       return Method->isInstance();
9020 
9021     return false;
9022   }
9023 
9024   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
9025     if (!ULE->getQualifier())
9026       return false;
9027 
9028     for (UnresolvedLookupExpr::decls_iterator D = ULE->decls_begin(),
9029                                            DEnd = ULE->decls_end();
9030          D != DEnd; ++D) {
9031       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*D)) {
9032         if (Method->isInstance())
9033           return true;
9034       } else {
9035         // Overload set does not contain methods.
9036         break;
9037       }
9038     }
9039 
9040     return false;
9041   }
9042 
9043   return false;
9044 }
9045 
9046 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
9047                               UnaryOperatorKind Opc, Expr *Input) {
9048   // First things first: handle placeholders so that the
9049   // overloaded-operator check considers the right type.
9050   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
9051     // Increment and decrement of pseudo-object references.
9052     if (pty->getKind() == BuiltinType::PseudoObject &&
9053         UnaryOperator::isIncrementDecrementOp(Opc))
9054       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
9055 
9056     // extension is always a builtin operator.
9057     if (Opc == UO_Extension)
9058       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
9059 
9060     // & gets special logic for several kinds of placeholder.
9061     // The builtin code knows what to do.
9062     if (Opc == UO_AddrOf &&
9063         (pty->getKind() == BuiltinType::Overload ||
9064          pty->getKind() == BuiltinType::UnknownAny ||
9065          pty->getKind() == BuiltinType::BoundMember))
9066       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
9067 
9068     // Anything else needs to be handled now.
9069     ExprResult Result = CheckPlaceholderExpr(Input);
9070     if (Result.isInvalid()) return ExprError();
9071     Input = Result.take();
9072   }
9073 
9074   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
9075       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
9076       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
9077     // Find all of the overloaded operators visible from this
9078     // point. We perform both an operator-name lookup from the local
9079     // scope and an argument-dependent lookup based on the types of
9080     // the arguments.
9081     UnresolvedSet<16> Functions;
9082     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
9083     if (S && OverOp != OO_None)
9084       LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
9085                                    Functions);
9086 
9087     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
9088   }
9089 
9090   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
9091 }
9092 
9093 // Unary Operators.  'Tok' is the token for the operator.
9094 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
9095                               tok::TokenKind Op, Expr *Input) {
9096   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
9097 }
9098 
9099 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
9100 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
9101                                 LabelDecl *TheDecl) {
9102   TheDecl->setUsed();
9103   // Create the AST node.  The address of a label always has type 'void*'.
9104   return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
9105                                        Context.getPointerType(Context.VoidTy)));
9106 }
9107 
9108 /// Given the last statement in a statement-expression, check whether
9109 /// the result is a producing expression (like a call to an
9110 /// ns_returns_retained function) and, if so, rebuild it to hoist the
9111 /// release out of the full-expression.  Otherwise, return null.
9112 /// Cannot fail.
9113 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
9114   // Should always be wrapped with one of these.
9115   ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
9116   if (!cleanups) return 0;
9117 
9118   ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
9119   if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
9120     return 0;
9121 
9122   // Splice out the cast.  This shouldn't modify any interesting
9123   // features of the statement.
9124   Expr *producer = cast->getSubExpr();
9125   assert(producer->getType() == cast->getType());
9126   assert(producer->getValueKind() == cast->getValueKind());
9127   cleanups->setSubExpr(producer);
9128   return cleanups;
9129 }
9130 
9131 void Sema::ActOnStartStmtExpr() {
9132   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
9133 }
9134 
9135 void Sema::ActOnStmtExprError() {
9136   // Note that function is also called by TreeTransform when leaving a
9137   // StmtExpr scope without rebuilding anything.
9138 
9139   DiscardCleanupsInEvaluationContext();
9140   PopExpressionEvaluationContext();
9141 }
9142 
9143 ExprResult
9144 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
9145                     SourceLocation RPLoc) { // "({..})"
9146   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
9147   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
9148 
9149   if (hasAnyUnrecoverableErrorsInThisFunction())
9150     DiscardCleanupsInEvaluationContext();
9151   assert(!ExprNeedsCleanups && "cleanups within StmtExpr not correctly bound!");
9152   PopExpressionEvaluationContext();
9153 
9154   bool isFileScope
9155     = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
9156   if (isFileScope)
9157     return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
9158 
9159   // FIXME: there are a variety of strange constraints to enforce here, for
9160   // example, it is not possible to goto into a stmt expression apparently.
9161   // More semantic analysis is needed.
9162 
9163   // If there are sub stmts in the compound stmt, take the type of the last one
9164   // as the type of the stmtexpr.
9165   QualType Ty = Context.VoidTy;
9166   bool StmtExprMayBindToTemp = false;
9167   if (!Compound->body_empty()) {
9168     Stmt *LastStmt = Compound->body_back();
9169     LabelStmt *LastLabelStmt = 0;
9170     // If LastStmt is a label, skip down through into the body.
9171     while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
9172       LastLabelStmt = Label;
9173       LastStmt = Label->getSubStmt();
9174     }
9175 
9176     if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
9177       // Do function/array conversion on the last expression, but not
9178       // lvalue-to-rvalue.  However, initialize an unqualified type.
9179       ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
9180       if (LastExpr.isInvalid())
9181         return ExprError();
9182       Ty = LastExpr.get()->getType().getUnqualifiedType();
9183 
9184       if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
9185         // In ARC, if the final expression ends in a consume, splice
9186         // the consume out and bind it later.  In the alternate case
9187         // (when dealing with a retainable type), the result
9188         // initialization will create a produce.  In both cases the
9189         // result will be +1, and we'll need to balance that out with
9190         // a bind.
9191         if (Expr *rebuiltLastStmt
9192               = maybeRebuildARCConsumingStmt(LastExpr.get())) {
9193           LastExpr = rebuiltLastStmt;
9194         } else {
9195           LastExpr = PerformCopyInitialization(
9196                             InitializedEntity::InitializeResult(LPLoc,
9197                                                                 Ty,
9198                                                                 false),
9199                                                    SourceLocation(),
9200                                                LastExpr);
9201         }
9202 
9203         if (LastExpr.isInvalid())
9204           return ExprError();
9205         if (LastExpr.get() != 0) {
9206           if (!LastLabelStmt)
9207             Compound->setLastStmt(LastExpr.take());
9208           else
9209             LastLabelStmt->setSubStmt(LastExpr.take());
9210           StmtExprMayBindToTemp = true;
9211         }
9212       }
9213     }
9214   }
9215 
9216   // FIXME: Check that expression type is complete/non-abstract; statement
9217   // expressions are not lvalues.
9218   Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
9219   if (StmtExprMayBindToTemp)
9220     return MaybeBindToTemporary(ResStmtExpr);
9221   return Owned(ResStmtExpr);
9222 }
9223 
9224 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
9225                                       TypeSourceInfo *TInfo,
9226                                       OffsetOfComponent *CompPtr,
9227                                       unsigned NumComponents,
9228                                       SourceLocation RParenLoc) {
9229   QualType ArgTy = TInfo->getType();
9230   bool Dependent = ArgTy->isDependentType();
9231   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
9232 
9233   // We must have at least one component that refers to the type, and the first
9234   // one is known to be a field designator.  Verify that the ArgTy represents
9235   // a struct/union/class.
9236   if (!Dependent && !ArgTy->isRecordType())
9237     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
9238                        << ArgTy << TypeRange);
9239 
9240   // Type must be complete per C99 7.17p3 because a declaring a variable
9241   // with an incomplete type would be ill-formed.
9242   if (!Dependent
9243       && RequireCompleteType(BuiltinLoc, ArgTy,
9244                              diag::err_offsetof_incomplete_type, TypeRange))
9245     return ExprError();
9246 
9247   // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
9248   // GCC extension, diagnose them.
9249   // FIXME: This diagnostic isn't actually visible because the location is in
9250   // a system header!
9251   if (NumComponents != 1)
9252     Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
9253       << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
9254 
9255   bool DidWarnAboutNonPOD = false;
9256   QualType CurrentType = ArgTy;
9257   typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
9258   SmallVector<OffsetOfNode, 4> Comps;
9259   SmallVector<Expr*, 4> Exprs;
9260   for (unsigned i = 0; i != NumComponents; ++i) {
9261     const OffsetOfComponent &OC = CompPtr[i];
9262     if (OC.isBrackets) {
9263       // Offset of an array sub-field.  TODO: Should we allow vector elements?
9264       if (!CurrentType->isDependentType()) {
9265         const ArrayType *AT = Context.getAsArrayType(CurrentType);
9266         if(!AT)
9267           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
9268                            << CurrentType);
9269         CurrentType = AT->getElementType();
9270       } else
9271         CurrentType = Context.DependentTy;
9272 
9273       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
9274       if (IdxRval.isInvalid())
9275         return ExprError();
9276       Expr *Idx = IdxRval.take();
9277 
9278       // The expression must be an integral expression.
9279       // FIXME: An integral constant expression?
9280       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
9281           !Idx->getType()->isIntegerType())
9282         return ExprError(Diag(Idx->getLocStart(),
9283                               diag::err_typecheck_subscript_not_integer)
9284                          << Idx->getSourceRange());
9285 
9286       // Record this array index.
9287       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
9288       Exprs.push_back(Idx);
9289       continue;
9290     }
9291 
9292     // Offset of a field.
9293     if (CurrentType->isDependentType()) {
9294       // We have the offset of a field, but we can't look into the dependent
9295       // type. Just record the identifier of the field.
9296       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
9297       CurrentType = Context.DependentTy;
9298       continue;
9299     }
9300 
9301     // We need to have a complete type to look into.
9302     if (RequireCompleteType(OC.LocStart, CurrentType,
9303                             diag::err_offsetof_incomplete_type))
9304       return ExprError();
9305 
9306     // Look for the designated field.
9307     const RecordType *RC = CurrentType->getAs<RecordType>();
9308     if (!RC)
9309       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
9310                        << CurrentType);
9311     RecordDecl *RD = RC->getDecl();
9312 
9313     // C++ [lib.support.types]p5:
9314     //   The macro offsetof accepts a restricted set of type arguments in this
9315     //   International Standard. type shall be a POD structure or a POD union
9316     //   (clause 9).
9317     // C++11 [support.types]p4:
9318     //   If type is not a standard-layout class (Clause 9), the results are
9319     //   undefined.
9320     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
9321       bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
9322       unsigned DiagID =
9323         LangOpts.CPlusPlus11? diag::warn_offsetof_non_standardlayout_type
9324                             : diag::warn_offsetof_non_pod_type;
9325 
9326       if (!IsSafe && !DidWarnAboutNonPOD &&
9327           DiagRuntimeBehavior(BuiltinLoc, 0,
9328                               PDiag(DiagID)
9329                               << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
9330                               << CurrentType))
9331         DidWarnAboutNonPOD = true;
9332     }
9333 
9334     // Look for the field.
9335     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
9336     LookupQualifiedName(R, RD);
9337     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
9338     IndirectFieldDecl *IndirectMemberDecl = 0;
9339     if (!MemberDecl) {
9340       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
9341         MemberDecl = IndirectMemberDecl->getAnonField();
9342     }
9343 
9344     if (!MemberDecl)
9345       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
9346                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
9347                                                               OC.LocEnd));
9348 
9349     // C99 7.17p3:
9350     //   (If the specified member is a bit-field, the behavior is undefined.)
9351     //
9352     // We diagnose this as an error.
9353     if (MemberDecl->isBitField()) {
9354       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
9355         << MemberDecl->getDeclName()
9356         << SourceRange(BuiltinLoc, RParenLoc);
9357       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
9358       return ExprError();
9359     }
9360 
9361     RecordDecl *Parent = MemberDecl->getParent();
9362     if (IndirectMemberDecl)
9363       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
9364 
9365     // If the member was found in a base class, introduce OffsetOfNodes for
9366     // the base class indirections.
9367     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
9368                        /*DetectVirtual=*/false);
9369     if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
9370       CXXBasePath &Path = Paths.front();
9371       for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
9372            B != BEnd; ++B)
9373         Comps.push_back(OffsetOfNode(B->Base));
9374     }
9375 
9376     if (IndirectMemberDecl) {
9377       for (IndirectFieldDecl::chain_iterator FI =
9378            IndirectMemberDecl->chain_begin(),
9379            FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
9380         assert(isa<FieldDecl>(*FI));
9381         Comps.push_back(OffsetOfNode(OC.LocStart,
9382                                      cast<FieldDecl>(*FI), OC.LocEnd));
9383       }
9384     } else
9385       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
9386 
9387     CurrentType = MemberDecl->getType().getNonReferenceType();
9388   }
9389 
9390   return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
9391                                     TInfo, Comps, Exprs, RParenLoc));
9392 }
9393 
9394 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
9395                                       SourceLocation BuiltinLoc,
9396                                       SourceLocation TypeLoc,
9397                                       ParsedType ParsedArgTy,
9398                                       OffsetOfComponent *CompPtr,
9399                                       unsigned NumComponents,
9400                                       SourceLocation RParenLoc) {
9401 
9402   TypeSourceInfo *ArgTInfo;
9403   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
9404   if (ArgTy.isNull())
9405     return ExprError();
9406 
9407   if (!ArgTInfo)
9408     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
9409 
9410   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
9411                               RParenLoc);
9412 }
9413 
9414 
9415 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
9416                                  Expr *CondExpr,
9417                                  Expr *LHSExpr, Expr *RHSExpr,
9418                                  SourceLocation RPLoc) {
9419   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
9420 
9421   ExprValueKind VK = VK_RValue;
9422   ExprObjectKind OK = OK_Ordinary;
9423   QualType resType;
9424   bool ValueDependent = false;
9425   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
9426     resType = Context.DependentTy;
9427     ValueDependent = true;
9428   } else {
9429     // The conditional expression is required to be a constant expression.
9430     llvm::APSInt condEval(32);
9431     ExprResult CondICE
9432       = VerifyIntegerConstantExpression(CondExpr, &condEval,
9433           diag::err_typecheck_choose_expr_requires_constant, false);
9434     if (CondICE.isInvalid())
9435       return ExprError();
9436     CondExpr = CondICE.take();
9437 
9438     // If the condition is > zero, then the AST type is the same as the LSHExpr.
9439     Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
9440 
9441     resType = ActiveExpr->getType();
9442     ValueDependent = ActiveExpr->isValueDependent();
9443     VK = ActiveExpr->getValueKind();
9444     OK = ActiveExpr->getObjectKind();
9445   }
9446 
9447   return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
9448                                         resType, VK, OK, RPLoc,
9449                                         resType->isDependentType(),
9450                                         ValueDependent));
9451 }
9452 
9453 //===----------------------------------------------------------------------===//
9454 // Clang Extensions.
9455 //===----------------------------------------------------------------------===//
9456 
9457 /// ActOnBlockStart - This callback is invoked when a block literal is started.
9458 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
9459   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
9460   PushBlockScope(CurScope, Block);
9461   CurContext->addDecl(Block);
9462   if (CurScope)
9463     PushDeclContext(CurScope, Block);
9464   else
9465     CurContext = Block;
9466 
9467   getCurBlock()->HasImplicitReturnType = true;
9468 
9469   // Enter a new evaluation context to insulate the block from any
9470   // cleanups from the enclosing full-expression.
9471   PushExpressionEvaluationContext(PotentiallyEvaluated);
9472 }
9473 
9474 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
9475                                Scope *CurScope) {
9476   assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
9477   assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
9478   BlockScopeInfo *CurBlock = getCurBlock();
9479 
9480   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
9481   QualType T = Sig->getType();
9482 
9483   // FIXME: We should allow unexpanded parameter packs here, but that would,
9484   // in turn, make the block expression contain unexpanded parameter packs.
9485   if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
9486     // Drop the parameters.
9487     FunctionProtoType::ExtProtoInfo EPI;
9488     EPI.HasTrailingReturn = false;
9489     EPI.TypeQuals |= DeclSpec::TQ_const;
9490     T = Context.getFunctionType(Context.DependentTy, ArrayRef<QualType>(), EPI);
9491     Sig = Context.getTrivialTypeSourceInfo(T);
9492   }
9493 
9494   // GetTypeForDeclarator always produces a function type for a block
9495   // literal signature.  Furthermore, it is always a FunctionProtoType
9496   // unless the function was written with a typedef.
9497   assert(T->isFunctionType() &&
9498          "GetTypeForDeclarator made a non-function block signature");
9499 
9500   // Look for an explicit signature in that function type.
9501   FunctionProtoTypeLoc ExplicitSignature;
9502 
9503   TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
9504   if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) {
9505 
9506     // Check whether that explicit signature was synthesized by
9507     // GetTypeForDeclarator.  If so, don't save that as part of the
9508     // written signature.
9509     if (ExplicitSignature.getLocalRangeBegin() ==
9510         ExplicitSignature.getLocalRangeEnd()) {
9511       // This would be much cheaper if we stored TypeLocs instead of
9512       // TypeSourceInfos.
9513       TypeLoc Result = ExplicitSignature.getResultLoc();
9514       unsigned Size = Result.getFullDataSize();
9515       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
9516       Sig->getTypeLoc().initializeFullCopy(Result, Size);
9517 
9518       ExplicitSignature = FunctionProtoTypeLoc();
9519     }
9520   }
9521 
9522   CurBlock->TheDecl->setSignatureAsWritten(Sig);
9523   CurBlock->FunctionType = T;
9524 
9525   const FunctionType *Fn = T->getAs<FunctionType>();
9526   QualType RetTy = Fn->getResultType();
9527   bool isVariadic =
9528     (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
9529 
9530   CurBlock->TheDecl->setIsVariadic(isVariadic);
9531 
9532   // Don't allow returning a objc interface by value.
9533   if (RetTy->isObjCObjectType()) {
9534     Diag(ParamInfo.getLocStart(),
9535          diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
9536     return;
9537   }
9538 
9539   // Context.DependentTy is used as a placeholder for a missing block
9540   // return type.  TODO:  what should we do with declarators like:
9541   //   ^ * { ... }
9542   // If the answer is "apply template argument deduction"....
9543   if (RetTy != Context.DependentTy) {
9544     CurBlock->ReturnType = RetTy;
9545     CurBlock->TheDecl->setBlockMissingReturnType(false);
9546     CurBlock->HasImplicitReturnType = false;
9547   }
9548 
9549   // Push block parameters from the declarator if we had them.
9550   SmallVector<ParmVarDecl*, 8> Params;
9551   if (ExplicitSignature) {
9552     for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
9553       ParmVarDecl *Param = ExplicitSignature.getArg(I);
9554       if (Param->getIdentifier() == 0 &&
9555           !Param->isImplicit() &&
9556           !Param->isInvalidDecl() &&
9557           !getLangOpts().CPlusPlus)
9558         Diag(Param->getLocation(), diag::err_parameter_name_omitted);
9559       Params.push_back(Param);
9560     }
9561 
9562   // Fake up parameter variables if we have a typedef, like
9563   //   ^ fntype { ... }
9564   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
9565     for (FunctionProtoType::arg_type_iterator
9566            I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
9567       ParmVarDecl *Param =
9568         BuildParmVarDeclForTypedef(CurBlock->TheDecl,
9569                                    ParamInfo.getLocStart(),
9570                                    *I);
9571       Params.push_back(Param);
9572     }
9573   }
9574 
9575   // Set the parameters on the block decl.
9576   if (!Params.empty()) {
9577     CurBlock->TheDecl->setParams(Params);
9578     CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
9579                              CurBlock->TheDecl->param_end(),
9580                              /*CheckParameterNames=*/false);
9581   }
9582 
9583   // Finally we can process decl attributes.
9584   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
9585 
9586   // Put the parameter variables in scope.  We can bail out immediately
9587   // if we don't have any.
9588   if (Params.empty())
9589     return;
9590 
9591   for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
9592          E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
9593     (*AI)->setOwningFunction(CurBlock->TheDecl);
9594 
9595     // If this has an identifier, add it to the scope stack.
9596     if ((*AI)->getIdentifier()) {
9597       CheckShadow(CurBlock->TheScope, *AI);
9598 
9599       PushOnScopeChains(*AI, CurBlock->TheScope);
9600     }
9601   }
9602 }
9603 
9604 /// ActOnBlockError - If there is an error parsing a block, this callback
9605 /// is invoked to pop the information about the block from the action impl.
9606 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
9607   // Leave the expression-evaluation context.
9608   DiscardCleanupsInEvaluationContext();
9609   PopExpressionEvaluationContext();
9610 
9611   // Pop off CurBlock, handle nested blocks.
9612   PopDeclContext();
9613   PopFunctionScopeInfo();
9614 }
9615 
9616 /// ActOnBlockStmtExpr - This is called when the body of a block statement
9617 /// literal was successfully completed.  ^(int x){...}
9618 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
9619                                     Stmt *Body, Scope *CurScope) {
9620   // If blocks are disabled, emit an error.
9621   if (!LangOpts.Blocks)
9622     Diag(CaretLoc, diag::err_blocks_disable);
9623 
9624   // Leave the expression-evaluation context.
9625   if (hasAnyUnrecoverableErrorsInThisFunction())
9626     DiscardCleanupsInEvaluationContext();
9627   assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!");
9628   PopExpressionEvaluationContext();
9629 
9630   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
9631 
9632   if (BSI->HasImplicitReturnType)
9633     deduceClosureReturnType(*BSI);
9634 
9635   PopDeclContext();
9636 
9637   QualType RetTy = Context.VoidTy;
9638   if (!BSI->ReturnType.isNull())
9639     RetTy = BSI->ReturnType;
9640 
9641   bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
9642   QualType BlockTy;
9643 
9644   // Set the captured variables on the block.
9645   // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
9646   SmallVector<BlockDecl::Capture, 4> Captures;
9647   for (unsigned i = 0, e = BSI->Captures.size(); i != e; i++) {
9648     CapturingScopeInfo::Capture &Cap = BSI->Captures[i];
9649     if (Cap.isThisCapture())
9650       continue;
9651     BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
9652                               Cap.isNested(), Cap.getCopyExpr());
9653     Captures.push_back(NewCap);
9654   }
9655   BSI->TheDecl->setCaptures(Context, Captures.begin(), Captures.end(),
9656                             BSI->CXXThisCaptureIndex != 0);
9657 
9658   // If the user wrote a function type in some form, try to use that.
9659   if (!BSI->FunctionType.isNull()) {
9660     const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
9661 
9662     FunctionType::ExtInfo Ext = FTy->getExtInfo();
9663     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
9664 
9665     // Turn protoless block types into nullary block types.
9666     if (isa<FunctionNoProtoType>(FTy)) {
9667       FunctionProtoType::ExtProtoInfo EPI;
9668       EPI.ExtInfo = Ext;
9669       BlockTy = Context.getFunctionType(RetTy, ArrayRef<QualType>(), EPI);
9670 
9671     // Otherwise, if we don't need to change anything about the function type,
9672     // preserve its sugar structure.
9673     } else if (FTy->getResultType() == RetTy &&
9674                (!NoReturn || FTy->getNoReturnAttr())) {
9675       BlockTy = BSI->FunctionType;
9676 
9677     // Otherwise, make the minimal modifications to the function type.
9678     } else {
9679       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
9680       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9681       EPI.TypeQuals = 0; // FIXME: silently?
9682       EPI.ExtInfo = Ext;
9683       BlockTy =
9684         Context.getFunctionType(RetTy,
9685                                 ArrayRef<QualType>(FPT->arg_type_begin(),
9686                                                    FPT->getNumArgs()),
9687                                 EPI);
9688     }
9689 
9690   // If we don't have a function type, just build one from nothing.
9691   } else {
9692     FunctionProtoType::ExtProtoInfo EPI;
9693     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
9694     BlockTy = Context.getFunctionType(RetTy, ArrayRef<QualType>(), EPI);
9695   }
9696 
9697   DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
9698                            BSI->TheDecl->param_end());
9699   BlockTy = Context.getBlockPointerType(BlockTy);
9700 
9701   // If needed, diagnose invalid gotos and switches in the block.
9702   if (getCurFunction()->NeedsScopeChecking() &&
9703       !hasAnyUnrecoverableErrorsInThisFunction() &&
9704       !PP.isCodeCompletionEnabled())
9705     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
9706 
9707   BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
9708 
9709   // Try to apply the named return value optimization. We have to check again
9710   // if we can do this, though, because blocks keep return statements around
9711   // to deduce an implicit return type.
9712   if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
9713       !BSI->TheDecl->isDependentContext())
9714     computeNRVO(Body, getCurBlock());
9715 
9716   BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
9717   const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy();
9718   PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
9719 
9720   // If the block isn't obviously global, i.e. it captures anything at
9721   // all, then we need to do a few things in the surrounding context:
9722   if (Result->getBlockDecl()->hasCaptures()) {
9723     // First, this expression has a new cleanup object.
9724     ExprCleanupObjects.push_back(Result->getBlockDecl());
9725     ExprNeedsCleanups = true;
9726 
9727     // It also gets a branch-protected scope if any of the captured
9728     // variables needs destruction.
9729     for (BlockDecl::capture_const_iterator
9730            ci = Result->getBlockDecl()->capture_begin(),
9731            ce = Result->getBlockDecl()->capture_end(); ci != ce; ++ci) {
9732       const VarDecl *var = ci->getVariable();
9733       if (var->getType().isDestructedType() != QualType::DK_none) {
9734         getCurFunction()->setHasBranchProtectedScope();
9735         break;
9736       }
9737     }
9738   }
9739 
9740   return Owned(Result);
9741 }
9742 
9743 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
9744                                         Expr *E, ParsedType Ty,
9745                                         SourceLocation RPLoc) {
9746   TypeSourceInfo *TInfo;
9747   GetTypeFromParser(Ty, &TInfo);
9748   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
9749 }
9750 
9751 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
9752                                 Expr *E, TypeSourceInfo *TInfo,
9753                                 SourceLocation RPLoc) {
9754   Expr *OrigExpr = E;
9755 
9756   // Get the va_list type
9757   QualType VaListType = Context.getBuiltinVaListType();
9758   if (VaListType->isArrayType()) {
9759     // Deal with implicit array decay; for example, on x86-64,
9760     // va_list is an array, but it's supposed to decay to
9761     // a pointer for va_arg.
9762     VaListType = Context.getArrayDecayedType(VaListType);
9763     // Make sure the input expression also decays appropriately.
9764     ExprResult Result = UsualUnaryConversions(E);
9765     if (Result.isInvalid())
9766       return ExprError();
9767     E = Result.take();
9768   } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
9769     // If va_list is a record type and we are compiling in C++ mode,
9770     // check the argument using reference binding.
9771     InitializedEntity Entity
9772       = InitializedEntity::InitializeParameter(Context,
9773           Context.getLValueReferenceType(VaListType), false);
9774     ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
9775     if (Init.isInvalid())
9776       return ExprError();
9777     E = Init.takeAs<Expr>();
9778   } else {
9779     // Otherwise, the va_list argument must be an l-value because
9780     // it is modified by va_arg.
9781     if (!E->isTypeDependent() &&
9782         CheckForModifiableLvalue(E, BuiltinLoc, *this))
9783       return ExprError();
9784   }
9785 
9786   if (!E->isTypeDependent() &&
9787       !Context.hasSameType(VaListType, E->getType())) {
9788     return ExprError(Diag(E->getLocStart(),
9789                          diag::err_first_argument_to_va_arg_not_of_type_va_list)
9790       << OrigExpr->getType() << E->getSourceRange());
9791   }
9792 
9793   if (!TInfo->getType()->isDependentType()) {
9794     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
9795                             diag::err_second_parameter_to_va_arg_incomplete,
9796                             TInfo->getTypeLoc()))
9797       return ExprError();
9798 
9799     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
9800                                TInfo->getType(),
9801                                diag::err_second_parameter_to_va_arg_abstract,
9802                                TInfo->getTypeLoc()))
9803       return ExprError();
9804 
9805     if (!TInfo->getType().isPODType(Context)) {
9806       Diag(TInfo->getTypeLoc().getBeginLoc(),
9807            TInfo->getType()->isObjCLifetimeType()
9808              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
9809              : diag::warn_second_parameter_to_va_arg_not_pod)
9810         << TInfo->getType()
9811         << TInfo->getTypeLoc().getSourceRange();
9812     }
9813 
9814     // Check for va_arg where arguments of the given type will be promoted
9815     // (i.e. this va_arg is guaranteed to have undefined behavior).
9816     QualType PromoteType;
9817     if (TInfo->getType()->isPromotableIntegerType()) {
9818       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
9819       if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
9820         PromoteType = QualType();
9821     }
9822     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
9823       PromoteType = Context.DoubleTy;
9824     if (!PromoteType.isNull())
9825       DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
9826                   PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
9827                           << TInfo->getType()
9828                           << PromoteType
9829                           << TInfo->getTypeLoc().getSourceRange());
9830   }
9831 
9832   QualType T = TInfo->getType().getNonLValueExprType(Context);
9833   return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
9834 }
9835 
9836 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
9837   // The type of __null will be int or long, depending on the size of
9838   // pointers on the target.
9839   QualType Ty;
9840   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
9841   if (pw == Context.getTargetInfo().getIntWidth())
9842     Ty = Context.IntTy;
9843   else if (pw == Context.getTargetInfo().getLongWidth())
9844     Ty = Context.LongTy;
9845   else if (pw == Context.getTargetInfo().getLongLongWidth())
9846     Ty = Context.LongLongTy;
9847   else {
9848     llvm_unreachable("I don't know size of pointer!");
9849   }
9850 
9851   return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
9852 }
9853 
9854 static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
9855                                            Expr *SrcExpr, FixItHint &Hint) {
9856   if (!SemaRef.getLangOpts().ObjC1)
9857     return;
9858 
9859   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
9860   if (!PT)
9861     return;
9862 
9863   // Check if the destination is of type 'id'.
9864   if (!PT->isObjCIdType()) {
9865     // Check if the destination is the 'NSString' interface.
9866     const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
9867     if (!ID || !ID->getIdentifier()->isStr("NSString"))
9868       return;
9869   }
9870 
9871   // Ignore any parens, implicit casts (should only be
9872   // array-to-pointer decays), and not-so-opaque values.  The last is
9873   // important for making this trigger for property assignments.
9874   SrcExpr = SrcExpr->IgnoreParenImpCasts();
9875   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
9876     if (OV->getSourceExpr())
9877       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
9878 
9879   StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
9880   if (!SL || !SL->isAscii())
9881     return;
9882 
9883   Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
9884 }
9885 
9886 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
9887                                     SourceLocation Loc,
9888                                     QualType DstType, QualType SrcType,
9889                                     Expr *SrcExpr, AssignmentAction Action,
9890                                     bool *Complained) {
9891   if (Complained)
9892     *Complained = false;
9893 
9894   // Decode the result (notice that AST's are still created for extensions).
9895   bool CheckInferredResultType = false;
9896   bool isInvalid = false;
9897   unsigned DiagKind = 0;
9898   FixItHint Hint;
9899   ConversionFixItGenerator ConvHints;
9900   bool MayHaveConvFixit = false;
9901   bool MayHaveFunctionDiff = false;
9902 
9903   switch (ConvTy) {
9904   case Compatible:
9905       DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
9906       return false;
9907 
9908   case PointerToInt:
9909     DiagKind = diag::ext_typecheck_convert_pointer_int;
9910     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9911     MayHaveConvFixit = true;
9912     break;
9913   case IntToPointer:
9914     DiagKind = diag::ext_typecheck_convert_int_pointer;
9915     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9916     MayHaveConvFixit = true;
9917     break;
9918   case IncompatiblePointer:
9919     MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
9920     DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
9921     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
9922       SrcType->isObjCObjectPointerType();
9923     if (Hint.isNull() && !CheckInferredResultType) {
9924       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9925     }
9926     MayHaveConvFixit = true;
9927     break;
9928   case IncompatiblePointerSign:
9929     DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
9930     break;
9931   case FunctionVoidPointer:
9932     DiagKind = diag::ext_typecheck_convert_pointer_void_func;
9933     break;
9934   case IncompatiblePointerDiscardsQualifiers: {
9935     // Perform array-to-pointer decay if necessary.
9936     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
9937 
9938     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
9939     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
9940     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
9941       DiagKind = diag::err_typecheck_incompatible_address_space;
9942       break;
9943 
9944 
9945     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
9946       DiagKind = diag::err_typecheck_incompatible_ownership;
9947       break;
9948     }
9949 
9950     llvm_unreachable("unknown error case for discarding qualifiers!");
9951     // fallthrough
9952   }
9953   case CompatiblePointerDiscardsQualifiers:
9954     // If the qualifiers lost were because we were applying the
9955     // (deprecated) C++ conversion from a string literal to a char*
9956     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
9957     // Ideally, this check would be performed in
9958     // checkPointerTypesForAssignment. However, that would require a
9959     // bit of refactoring (so that the second argument is an
9960     // expression, rather than a type), which should be done as part
9961     // of a larger effort to fix checkPointerTypesForAssignment for
9962     // C++ semantics.
9963     if (getLangOpts().CPlusPlus &&
9964         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
9965       return false;
9966     DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
9967     break;
9968   case IncompatibleNestedPointerQualifiers:
9969     DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
9970     break;
9971   case IntToBlockPointer:
9972     DiagKind = diag::err_int_to_block_pointer;
9973     break;
9974   case IncompatibleBlockPointer:
9975     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
9976     break;
9977   case IncompatibleObjCQualifiedId:
9978     // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
9979     // it can give a more specific diagnostic.
9980     DiagKind = diag::warn_incompatible_qualified_id;
9981     break;
9982   case IncompatibleVectors:
9983     DiagKind = diag::warn_incompatible_vectors;
9984     break;
9985   case IncompatibleObjCWeakRef:
9986     DiagKind = diag::err_arc_weak_unavailable_assign;
9987     break;
9988   case Incompatible:
9989     DiagKind = diag::err_typecheck_convert_incompatible;
9990     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9991     MayHaveConvFixit = true;
9992     isInvalid = true;
9993     MayHaveFunctionDiff = true;
9994     break;
9995   }
9996 
9997   QualType FirstType, SecondType;
9998   switch (Action) {
9999   case AA_Assigning:
10000   case AA_Initializing:
10001     // The destination type comes first.
10002     FirstType = DstType;
10003     SecondType = SrcType;
10004     break;
10005 
10006   case AA_Returning:
10007   case AA_Passing:
10008   case AA_Converting:
10009   case AA_Sending:
10010   case AA_Casting:
10011     // The source type comes first.
10012     FirstType = SrcType;
10013     SecondType = DstType;
10014     break;
10015   }
10016 
10017   PartialDiagnostic FDiag = PDiag(DiagKind);
10018   FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
10019 
10020   // If we can fix the conversion, suggest the FixIts.
10021   assert(ConvHints.isNull() || Hint.isNull());
10022   if (!ConvHints.isNull()) {
10023     for (std::vector<FixItHint>::iterator HI = ConvHints.Hints.begin(),
10024          HE = ConvHints.Hints.end(); HI != HE; ++HI)
10025       FDiag << *HI;
10026   } else {
10027     FDiag << Hint;
10028   }
10029   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
10030 
10031   if (MayHaveFunctionDiff)
10032     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
10033 
10034   Diag(Loc, FDiag);
10035 
10036   if (SecondType == Context.OverloadTy)
10037     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
10038                               FirstType);
10039 
10040   if (CheckInferredResultType)
10041     EmitRelatedResultTypeNote(SrcExpr);
10042 
10043   if (Action == AA_Returning && ConvTy == IncompatiblePointer)
10044     EmitRelatedResultTypeNoteForReturn(DstType);
10045 
10046   if (Complained)
10047     *Complained = true;
10048   return isInvalid;
10049 }
10050 
10051 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
10052                                                  llvm::APSInt *Result) {
10053   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
10054   public:
10055     virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
10056       S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
10057     }
10058   } Diagnoser;
10059 
10060   return VerifyIntegerConstantExpression(E, Result, Diagnoser);
10061 }
10062 
10063 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
10064                                                  llvm::APSInt *Result,
10065                                                  unsigned DiagID,
10066                                                  bool AllowFold) {
10067   class IDDiagnoser : public VerifyICEDiagnoser {
10068     unsigned DiagID;
10069 
10070   public:
10071     IDDiagnoser(unsigned DiagID)
10072       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
10073 
10074     virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
10075       S.Diag(Loc, DiagID) << SR;
10076     }
10077   } Diagnoser(DiagID);
10078 
10079   return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
10080 }
10081 
10082 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
10083                                             SourceRange SR) {
10084   S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
10085 }
10086 
10087 ExprResult
10088 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
10089                                       VerifyICEDiagnoser &Diagnoser,
10090                                       bool AllowFold) {
10091   SourceLocation DiagLoc = E->getLocStart();
10092 
10093   if (getLangOpts().CPlusPlus11) {
10094     // C++11 [expr.const]p5:
10095     //   If an expression of literal class type is used in a context where an
10096     //   integral constant expression is required, then that class type shall
10097     //   have a single non-explicit conversion function to an integral or
10098     //   unscoped enumeration type
10099     ExprResult Converted;
10100     if (!Diagnoser.Suppress) {
10101       class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
10102       public:
10103         CXX11ConvertDiagnoser() : ICEConvertDiagnoser(false, true) { }
10104 
10105         virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
10106                                                  QualType T) {
10107           return S.Diag(Loc, diag::err_ice_not_integral) << T;
10108         }
10109 
10110         virtual DiagnosticBuilder diagnoseIncomplete(Sema &S,
10111                                                      SourceLocation Loc,
10112                                                      QualType T) {
10113           return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
10114         }
10115 
10116         virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S,
10117                                                        SourceLocation Loc,
10118                                                        QualType T,
10119                                                        QualType ConvTy) {
10120           return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
10121         }
10122 
10123         virtual DiagnosticBuilder noteExplicitConv(Sema &S,
10124                                                    CXXConversionDecl *Conv,
10125                                                    QualType ConvTy) {
10126           return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
10127                    << ConvTy->isEnumeralType() << ConvTy;
10128         }
10129 
10130         virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
10131                                                     QualType T) {
10132           return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
10133         }
10134 
10135         virtual DiagnosticBuilder noteAmbiguous(Sema &S,
10136                                                 CXXConversionDecl *Conv,
10137                                                 QualType ConvTy) {
10138           return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
10139                    << ConvTy->isEnumeralType() << ConvTy;
10140         }
10141 
10142         virtual DiagnosticBuilder diagnoseConversion(Sema &S,
10143                                                      SourceLocation Loc,
10144                                                      QualType T,
10145                                                      QualType ConvTy) {
10146           return DiagnosticBuilder::getEmpty();
10147         }
10148       } ConvertDiagnoser;
10149 
10150       Converted = ConvertToIntegralOrEnumerationType(DiagLoc, E,
10151                                                      ConvertDiagnoser,
10152                                              /*AllowScopedEnumerations*/ false);
10153     } else {
10154       // The caller wants to silently enquire whether this is an ICE. Don't
10155       // produce any diagnostics if it isn't.
10156       class SilentICEConvertDiagnoser : public ICEConvertDiagnoser {
10157       public:
10158         SilentICEConvertDiagnoser() : ICEConvertDiagnoser(true, true) { }
10159 
10160         virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
10161                                                  QualType T) {
10162           return DiagnosticBuilder::getEmpty();
10163         }
10164 
10165         virtual DiagnosticBuilder diagnoseIncomplete(Sema &S,
10166                                                      SourceLocation Loc,
10167                                                      QualType T) {
10168           return DiagnosticBuilder::getEmpty();
10169         }
10170 
10171         virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S,
10172                                                        SourceLocation Loc,
10173                                                        QualType T,
10174                                                        QualType ConvTy) {
10175           return DiagnosticBuilder::getEmpty();
10176         }
10177 
10178         virtual DiagnosticBuilder noteExplicitConv(Sema &S,
10179                                                    CXXConversionDecl *Conv,
10180                                                    QualType ConvTy) {
10181           return DiagnosticBuilder::getEmpty();
10182         }
10183 
10184         virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
10185                                                     QualType T) {
10186           return DiagnosticBuilder::getEmpty();
10187         }
10188 
10189         virtual DiagnosticBuilder noteAmbiguous(Sema &S,
10190                                                 CXXConversionDecl *Conv,
10191                                                 QualType ConvTy) {
10192           return DiagnosticBuilder::getEmpty();
10193         }
10194 
10195         virtual DiagnosticBuilder diagnoseConversion(Sema &S,
10196                                                      SourceLocation Loc,
10197                                                      QualType T,
10198                                                      QualType ConvTy) {
10199           return DiagnosticBuilder::getEmpty();
10200         }
10201       } ConvertDiagnoser;
10202 
10203       Converted = ConvertToIntegralOrEnumerationType(DiagLoc, E,
10204                                                      ConvertDiagnoser, false);
10205     }
10206     if (Converted.isInvalid())
10207       return Converted;
10208     E = Converted.take();
10209     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
10210       return ExprError();
10211   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
10212     // An ICE must be of integral or unscoped enumeration type.
10213     if (!Diagnoser.Suppress)
10214       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
10215     return ExprError();
10216   }
10217 
10218   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
10219   // in the non-ICE case.
10220   if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
10221     if (Result)
10222       *Result = E->EvaluateKnownConstInt(Context);
10223     return Owned(E);
10224   }
10225 
10226   Expr::EvalResult EvalResult;
10227   SmallVector<PartialDiagnosticAt, 8> Notes;
10228   EvalResult.Diag = &Notes;
10229 
10230   // Try to evaluate the expression, and produce diagnostics explaining why it's
10231   // not a constant expression as a side-effect.
10232   bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
10233                 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
10234 
10235   // In C++11, we can rely on diagnostics being produced for any expression
10236   // which is not a constant expression. If no diagnostics were produced, then
10237   // this is a constant expression.
10238   if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
10239     if (Result)
10240       *Result = EvalResult.Val.getInt();
10241     return Owned(E);
10242   }
10243 
10244   // If our only note is the usual "invalid subexpression" note, just point
10245   // the caret at its location rather than producing an essentially
10246   // redundant note.
10247   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
10248         diag::note_invalid_subexpr_in_const_expr) {
10249     DiagLoc = Notes[0].first;
10250     Notes.clear();
10251   }
10252 
10253   if (!Folded || !AllowFold) {
10254     if (!Diagnoser.Suppress) {
10255       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
10256       for (unsigned I = 0, N = Notes.size(); I != N; ++I)
10257         Diag(Notes[I].first, Notes[I].second);
10258     }
10259 
10260     return ExprError();
10261   }
10262 
10263   Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
10264   for (unsigned I = 0, N = Notes.size(); I != N; ++I)
10265     Diag(Notes[I].first, Notes[I].second);
10266 
10267   if (Result)
10268     *Result = EvalResult.Val.getInt();
10269   return Owned(E);
10270 }
10271 
10272 namespace {
10273   // Handle the case where we conclude a expression which we speculatively
10274   // considered to be unevaluated is actually evaluated.
10275   class TransformToPE : public TreeTransform<TransformToPE> {
10276     typedef TreeTransform<TransformToPE> BaseTransform;
10277 
10278   public:
10279     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
10280 
10281     // Make sure we redo semantic analysis
10282     bool AlwaysRebuild() { return true; }
10283 
10284     // Make sure we handle LabelStmts correctly.
10285     // FIXME: This does the right thing, but maybe we need a more general
10286     // fix to TreeTransform?
10287     StmtResult TransformLabelStmt(LabelStmt *S) {
10288       S->getDecl()->setStmt(0);
10289       return BaseTransform::TransformLabelStmt(S);
10290     }
10291 
10292     // We need to special-case DeclRefExprs referring to FieldDecls which
10293     // are not part of a member pointer formation; normal TreeTransforming
10294     // doesn't catch this case because of the way we represent them in the AST.
10295     // FIXME: This is a bit ugly; is it really the best way to handle this
10296     // case?
10297     //
10298     // Error on DeclRefExprs referring to FieldDecls.
10299     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
10300       if (isa<FieldDecl>(E->getDecl()) &&
10301           !SemaRef.isUnevaluatedContext())
10302         return SemaRef.Diag(E->getLocation(),
10303                             diag::err_invalid_non_static_member_use)
10304             << E->getDecl() << E->getSourceRange();
10305 
10306       return BaseTransform::TransformDeclRefExpr(E);
10307     }
10308 
10309     // Exception: filter out member pointer formation
10310     ExprResult TransformUnaryOperator(UnaryOperator *E) {
10311       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
10312         return E;
10313 
10314       return BaseTransform::TransformUnaryOperator(E);
10315     }
10316 
10317     ExprResult TransformLambdaExpr(LambdaExpr *E) {
10318       // Lambdas never need to be transformed.
10319       return E;
10320     }
10321   };
10322 }
10323 
10324 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
10325   assert(ExprEvalContexts.back().Context == Unevaluated &&
10326          "Should only transform unevaluated expressions");
10327   ExprEvalContexts.back().Context =
10328       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
10329   if (ExprEvalContexts.back().Context == Unevaluated)
10330     return E;
10331   return TransformToPE(*this).TransformExpr(E);
10332 }
10333 
10334 void
10335 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
10336                                       Decl *LambdaContextDecl,
10337                                       bool IsDecltype) {
10338   ExprEvalContexts.push_back(
10339              ExpressionEvaluationContextRecord(NewContext,
10340                                                ExprCleanupObjects.size(),
10341                                                ExprNeedsCleanups,
10342                                                LambdaContextDecl,
10343                                                IsDecltype));
10344   ExprNeedsCleanups = false;
10345   if (!MaybeODRUseExprs.empty())
10346     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
10347 }
10348 
10349 void
10350 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
10351                                       ReuseLambdaContextDecl_t,
10352                                       bool IsDecltype) {
10353   Decl *LambdaContextDecl = ExprEvalContexts.back().LambdaContextDecl;
10354   PushExpressionEvaluationContext(NewContext, LambdaContextDecl, IsDecltype);
10355 }
10356 
10357 void Sema::PopExpressionEvaluationContext() {
10358   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
10359 
10360   if (!Rec.Lambdas.empty()) {
10361     if (Rec.Context == Unevaluated) {
10362       // C++11 [expr.prim.lambda]p2:
10363       //   A lambda-expression shall not appear in an unevaluated operand
10364       //   (Clause 5).
10365       for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I)
10366         Diag(Rec.Lambdas[I]->getLocStart(),
10367              diag::err_lambda_unevaluated_operand);
10368     } else {
10369       // Mark the capture expressions odr-used. This was deferred
10370       // during lambda expression creation.
10371       for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I) {
10372         LambdaExpr *Lambda = Rec.Lambdas[I];
10373         for (LambdaExpr::capture_init_iterator
10374                   C = Lambda->capture_init_begin(),
10375                CEnd = Lambda->capture_init_end();
10376              C != CEnd; ++C) {
10377           MarkDeclarationsReferencedInExpr(*C);
10378         }
10379       }
10380     }
10381   }
10382 
10383   // When are coming out of an unevaluated context, clear out any
10384   // temporaries that we may have created as part of the evaluation of
10385   // the expression in that context: they aren't relevant because they
10386   // will never be constructed.
10387   if (Rec.Context == Unevaluated || Rec.Context == ConstantEvaluated) {
10388     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
10389                              ExprCleanupObjects.end());
10390     ExprNeedsCleanups = Rec.ParentNeedsCleanups;
10391     CleanupVarDeclMarking();
10392     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
10393   // Otherwise, merge the contexts together.
10394   } else {
10395     ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
10396     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
10397                             Rec.SavedMaybeODRUseExprs.end());
10398   }
10399 
10400   // Pop the current expression evaluation context off the stack.
10401   ExprEvalContexts.pop_back();
10402 }
10403 
10404 void Sema::DiscardCleanupsInEvaluationContext() {
10405   ExprCleanupObjects.erase(
10406          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
10407          ExprCleanupObjects.end());
10408   ExprNeedsCleanups = false;
10409   MaybeODRUseExprs.clear();
10410 }
10411 
10412 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
10413   if (!E->getType()->isVariablyModifiedType())
10414     return E;
10415   return TransformToPotentiallyEvaluated(E);
10416 }
10417 
10418 static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) {
10419   // Do not mark anything as "used" within a dependent context; wait for
10420   // an instantiation.
10421   if (SemaRef.CurContext->isDependentContext())
10422     return false;
10423 
10424   switch (SemaRef.ExprEvalContexts.back().Context) {
10425     case Sema::Unevaluated:
10426       // We are in an expression that is not potentially evaluated; do nothing.
10427       // (Depending on how you read the standard, we actually do need to do
10428       // something here for null pointer constants, but the standard's
10429       // definition of a null pointer constant is completely crazy.)
10430       return false;
10431 
10432     case Sema::ConstantEvaluated:
10433     case Sema::PotentiallyEvaluated:
10434       // We are in a potentially evaluated expression (or a constant-expression
10435       // in C++03); we need to do implicit template instantiation, implicitly
10436       // define class members, and mark most declarations as used.
10437       return true;
10438 
10439     case Sema::PotentiallyEvaluatedIfUsed:
10440       // Referenced declarations will only be used if the construct in the
10441       // containing expression is used.
10442       return false;
10443   }
10444   llvm_unreachable("Invalid context");
10445 }
10446 
10447 /// \brief Mark a function referenced, and check whether it is odr-used
10448 /// (C++ [basic.def.odr]p2, C99 6.9p3)
10449 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func) {
10450   assert(Func && "No function?");
10451 
10452   Func->setReferenced();
10453 
10454   // C++11 [basic.def.odr]p3:
10455   //   A function whose name appears as a potentially-evaluated expression is
10456   //   odr-used if it is the unique lookup result or the selected member of a
10457   //   set of overloaded functions [...].
10458   //
10459   // We (incorrectly) mark overload resolution as an unevaluated context, so we
10460   // can just check that here. Skip the rest of this function if we've already
10461   // marked the function as used.
10462   if (Func->isUsed(false) || !IsPotentiallyEvaluatedContext(*this)) {
10463     // C++11 [temp.inst]p3:
10464     //   Unless a function template specialization has been explicitly
10465     //   instantiated or explicitly specialized, the function template
10466     //   specialization is implicitly instantiated when the specialization is
10467     //   referenced in a context that requires a function definition to exist.
10468     //
10469     // We consider constexpr function templates to be referenced in a context
10470     // that requires a definition to exist whenever they are referenced.
10471     //
10472     // FIXME: This instantiates constexpr functions too frequently. If this is
10473     // really an unevaluated context (and we're not just in the definition of a
10474     // function template or overload resolution or other cases which we
10475     // incorrectly consider to be unevaluated contexts), and we're not in a
10476     // subexpression which we actually need to evaluate (for instance, a
10477     // template argument, array bound or an expression in a braced-init-list),
10478     // we are not permitted to instantiate this constexpr function definition.
10479     //
10480     // FIXME: This also implicitly defines special members too frequently. They
10481     // are only supposed to be implicitly defined if they are odr-used, but they
10482     // are not odr-used from constant expressions in unevaluated contexts.
10483     // However, they cannot be referenced if they are deleted, and they are
10484     // deleted whenever the implicit definition of the special member would
10485     // fail.
10486     if (!Func->isConstexpr() || Func->getBody())
10487       return;
10488     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
10489     if (!Func->isImplicitlyInstantiable() && (!MD || MD->isUserProvided()))
10490       return;
10491   }
10492 
10493   // Note that this declaration has been used.
10494   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
10495     if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
10496       if (Constructor->isDefaultConstructor()) {
10497         if (Constructor->isTrivial())
10498           return;
10499         if (!Constructor->isUsed(false))
10500           DefineImplicitDefaultConstructor(Loc, Constructor);
10501       } else if (Constructor->isCopyConstructor()) {
10502         if (!Constructor->isUsed(false))
10503           DefineImplicitCopyConstructor(Loc, Constructor);
10504       } else if (Constructor->isMoveConstructor()) {
10505         if (!Constructor->isUsed(false))
10506           DefineImplicitMoveConstructor(Loc, Constructor);
10507       }
10508     } else if (Constructor->getInheritedConstructor()) {
10509       if (!Constructor->isUsed(false))
10510         DefineInheritingConstructor(Loc, Constructor);
10511     }
10512 
10513     MarkVTableUsed(Loc, Constructor->getParent());
10514   } else if (CXXDestructorDecl *Destructor =
10515                  dyn_cast<CXXDestructorDecl>(Func)) {
10516     if (Destructor->isDefaulted() && !Destructor->isDeleted() &&
10517         !Destructor->isUsed(false))
10518       DefineImplicitDestructor(Loc, Destructor);
10519     if (Destructor->isVirtual())
10520       MarkVTableUsed(Loc, Destructor->getParent());
10521   } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
10522     if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted() &&
10523         MethodDecl->isOverloadedOperator() &&
10524         MethodDecl->getOverloadedOperator() == OO_Equal) {
10525       if (!MethodDecl->isUsed(false)) {
10526         if (MethodDecl->isCopyAssignmentOperator())
10527           DefineImplicitCopyAssignment(Loc, MethodDecl);
10528         else
10529           DefineImplicitMoveAssignment(Loc, MethodDecl);
10530       }
10531     } else if (isa<CXXConversionDecl>(MethodDecl) &&
10532                MethodDecl->getParent()->isLambda()) {
10533       CXXConversionDecl *Conversion = cast<CXXConversionDecl>(MethodDecl);
10534       if (Conversion->isLambdaToBlockPointerConversion())
10535         DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
10536       else
10537         DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
10538     } else if (MethodDecl->isVirtual())
10539       MarkVTableUsed(Loc, MethodDecl->getParent());
10540   }
10541 
10542   // Recursive functions should be marked when used from another function.
10543   // FIXME: Is this really right?
10544   if (CurContext == Func) return;
10545 
10546   // Resolve the exception specification for any function which is
10547   // used: CodeGen will need it.
10548   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
10549   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
10550     ResolveExceptionSpec(Loc, FPT);
10551 
10552   // Implicit instantiation of function templates and member functions of
10553   // class templates.
10554   if (Func->isImplicitlyInstantiable()) {
10555     bool AlreadyInstantiated = false;
10556     SourceLocation PointOfInstantiation = Loc;
10557     if (FunctionTemplateSpecializationInfo *SpecInfo
10558                               = Func->getTemplateSpecializationInfo()) {
10559       if (SpecInfo->getPointOfInstantiation().isInvalid())
10560         SpecInfo->setPointOfInstantiation(Loc);
10561       else if (SpecInfo->getTemplateSpecializationKind()
10562                  == TSK_ImplicitInstantiation) {
10563         AlreadyInstantiated = true;
10564         PointOfInstantiation = SpecInfo->getPointOfInstantiation();
10565       }
10566     } else if (MemberSpecializationInfo *MSInfo
10567                                 = Func->getMemberSpecializationInfo()) {
10568       if (MSInfo->getPointOfInstantiation().isInvalid())
10569         MSInfo->setPointOfInstantiation(Loc);
10570       else if (MSInfo->getTemplateSpecializationKind()
10571                  == TSK_ImplicitInstantiation) {
10572         AlreadyInstantiated = true;
10573         PointOfInstantiation = MSInfo->getPointOfInstantiation();
10574       }
10575     }
10576 
10577     if (!AlreadyInstantiated || Func->isConstexpr()) {
10578       if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
10579           cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass())
10580         PendingLocalImplicitInstantiations.push_back(
10581             std::make_pair(Func, PointOfInstantiation));
10582       else if (Func->isConstexpr())
10583         // Do not defer instantiations of constexpr functions, to avoid the
10584         // expression evaluator needing to call back into Sema if it sees a
10585         // call to such a function.
10586         InstantiateFunctionDefinition(PointOfInstantiation, Func);
10587       else {
10588         PendingInstantiations.push_back(std::make_pair(Func,
10589                                                        PointOfInstantiation));
10590         // Notify the consumer that a function was implicitly instantiated.
10591         Consumer.HandleCXXImplicitFunctionInstantiation(Func);
10592       }
10593     }
10594   } else {
10595     // Walk redefinitions, as some of them may be instantiable.
10596     for (FunctionDecl::redecl_iterator i(Func->redecls_begin()),
10597          e(Func->redecls_end()); i != e; ++i) {
10598       if (!i->isUsed(false) && i->isImplicitlyInstantiable())
10599         MarkFunctionReferenced(Loc, *i);
10600     }
10601   }
10602 
10603   // Keep track of used but undefined functions.
10604   if (!Func->isDefined()) {
10605     if (mightHaveNonExternalLinkage(Func))
10606       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
10607     else if (Func->getMostRecentDecl()->isInlined() &&
10608              (LangOpts.CPlusPlus || !LangOpts.GNUInline) &&
10609              !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
10610       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
10611   }
10612 
10613   // Normally the must current decl is marked used while processing the use and
10614   // any subsequent decls are marked used by decl merging. This fails with
10615   // template instantiation since marking can happen at the end of the file
10616   // and, because of the two phase lookup, this function is called with at
10617   // decl in the middle of a decl chain. We loop to maintain the invariant
10618   // that once a decl is used, all decls after it are also used.
10619   for (FunctionDecl *F = Func->getMostRecentDecl();; F = F->getPreviousDecl()) {
10620     F->setUsed(true);
10621     if (F == Func)
10622       break;
10623   }
10624 }
10625 
10626 static void
10627 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
10628                                    VarDecl *var, DeclContext *DC) {
10629   DeclContext *VarDC = var->getDeclContext();
10630 
10631   //  If the parameter still belongs to the translation unit, then
10632   //  we're actually just using one parameter in the declaration of
10633   //  the next.
10634   if (isa<ParmVarDecl>(var) &&
10635       isa<TranslationUnitDecl>(VarDC))
10636     return;
10637 
10638   // For C code, don't diagnose about capture if we're not actually in code
10639   // right now; it's impossible to write a non-constant expression outside of
10640   // function context, so we'll get other (more useful) diagnostics later.
10641   //
10642   // For C++, things get a bit more nasty... it would be nice to suppress this
10643   // diagnostic for certain cases like using a local variable in an array bound
10644   // for a member of a local class, but the correct predicate is not obvious.
10645   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
10646     return;
10647 
10648   if (isa<CXXMethodDecl>(VarDC) &&
10649       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
10650     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda)
10651       << var->getIdentifier();
10652   } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) {
10653     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
10654       << var->getIdentifier() << fn->getDeclName();
10655   } else if (isa<BlockDecl>(VarDC)) {
10656     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block)
10657       << var->getIdentifier();
10658   } else {
10659     // FIXME: Is there any other context where a local variable can be
10660     // declared?
10661     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context)
10662       << var->getIdentifier();
10663   }
10664 
10665   S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
10666     << var->getIdentifier();
10667 
10668   // FIXME: Add additional diagnostic info about class etc. which prevents
10669   // capture.
10670 }
10671 
10672 /// \brief Capture the given variable in the given lambda expression.
10673 static ExprResult captureInLambda(Sema &S, LambdaScopeInfo *LSI,
10674                                   VarDecl *Var, QualType FieldType,
10675                                   QualType DeclRefType,
10676                                   SourceLocation Loc,
10677                                   bool RefersToEnclosingLocal) {
10678   CXXRecordDecl *Lambda = LSI->Lambda;
10679 
10680   // Build the non-static data member.
10681   FieldDecl *Field
10682     = FieldDecl::Create(S.Context, Lambda, Loc, Loc, 0, FieldType,
10683                         S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
10684                         0, false, ICIS_NoInit);
10685   Field->setImplicit(true);
10686   Field->setAccess(AS_private);
10687   Lambda->addDecl(Field);
10688 
10689   // C++11 [expr.prim.lambda]p21:
10690   //   When the lambda-expression is evaluated, the entities that
10691   //   are captured by copy are used to direct-initialize each
10692   //   corresponding non-static data member of the resulting closure
10693   //   object. (For array members, the array elements are
10694   //   direct-initialized in increasing subscript order.) These
10695   //   initializations are performed in the (unspecified) order in
10696   //   which the non-static data members are declared.
10697 
10698   // Introduce a new evaluation context for the initialization, so
10699   // that temporaries introduced as part of the capture are retained
10700   // to be re-"exported" from the lambda expression itself.
10701   S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
10702 
10703   // C++ [expr.prim.labda]p12:
10704   //   An entity captured by a lambda-expression is odr-used (3.2) in
10705   //   the scope containing the lambda-expression.
10706   Expr *Ref = new (S.Context) DeclRefExpr(Var, RefersToEnclosingLocal,
10707                                           DeclRefType, VK_LValue, Loc);
10708   Var->setReferenced(true);
10709   Var->setUsed(true);
10710 
10711   // When the field has array type, create index variables for each
10712   // dimension of the array. We use these index variables to subscript
10713   // the source array, and other clients (e.g., CodeGen) will perform
10714   // the necessary iteration with these index variables.
10715   SmallVector<VarDecl *, 4> IndexVariables;
10716   QualType BaseType = FieldType;
10717   QualType SizeType = S.Context.getSizeType();
10718   LSI->ArrayIndexStarts.push_back(LSI->ArrayIndexVars.size());
10719   while (const ConstantArrayType *Array
10720                         = S.Context.getAsConstantArrayType(BaseType)) {
10721     // Create the iteration variable for this array index.
10722     IdentifierInfo *IterationVarName = 0;
10723     {
10724       SmallString<8> Str;
10725       llvm::raw_svector_ostream OS(Str);
10726       OS << "__i" << IndexVariables.size();
10727       IterationVarName = &S.Context.Idents.get(OS.str());
10728     }
10729     VarDecl *IterationVar
10730       = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
10731                         IterationVarName, SizeType,
10732                         S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
10733                         SC_None, SC_None);
10734     IndexVariables.push_back(IterationVar);
10735     LSI->ArrayIndexVars.push_back(IterationVar);
10736 
10737     // Create a reference to the iteration variable.
10738     ExprResult IterationVarRef
10739       = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
10740     assert(!IterationVarRef.isInvalid() &&
10741            "Reference to invented variable cannot fail!");
10742     IterationVarRef = S.DefaultLvalueConversion(IterationVarRef.take());
10743     assert(!IterationVarRef.isInvalid() &&
10744            "Conversion of invented variable cannot fail!");
10745 
10746     // Subscript the array with this iteration variable.
10747     ExprResult Subscript = S.CreateBuiltinArraySubscriptExpr(
10748                              Ref, Loc, IterationVarRef.take(), Loc);
10749     if (Subscript.isInvalid()) {
10750       S.CleanupVarDeclMarking();
10751       S.DiscardCleanupsInEvaluationContext();
10752       S.PopExpressionEvaluationContext();
10753       return ExprError();
10754     }
10755 
10756     Ref = Subscript.take();
10757     BaseType = Array->getElementType();
10758   }
10759 
10760   // Construct the entity that we will be initializing. For an array, this
10761   // will be first element in the array, which may require several levels
10762   // of array-subscript entities.
10763   SmallVector<InitializedEntity, 4> Entities;
10764   Entities.reserve(1 + IndexVariables.size());
10765   Entities.push_back(
10766     InitializedEntity::InitializeLambdaCapture(Var, Field, Loc));
10767   for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
10768     Entities.push_back(InitializedEntity::InitializeElement(S.Context,
10769                                                             0,
10770                                                             Entities.back()));
10771 
10772   InitializationKind InitKind
10773     = InitializationKind::CreateDirect(Loc, Loc, Loc);
10774   InitializationSequence Init(S, Entities.back(), InitKind, &Ref, 1);
10775   ExprResult Result(true);
10776   if (!Init.Diagnose(S, Entities.back(), InitKind, &Ref, 1))
10777     Result = Init.Perform(S, Entities.back(), InitKind, Ref);
10778 
10779   // If this initialization requires any cleanups (e.g., due to a
10780   // default argument to a copy constructor), note that for the
10781   // lambda.
10782   if (S.ExprNeedsCleanups)
10783     LSI->ExprNeedsCleanups = true;
10784 
10785   // Exit the expression evaluation context used for the capture.
10786   S.CleanupVarDeclMarking();
10787   S.DiscardCleanupsInEvaluationContext();
10788   S.PopExpressionEvaluationContext();
10789   return Result;
10790 }
10791 
10792 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
10793                               TryCaptureKind Kind, SourceLocation EllipsisLoc,
10794                               bool BuildAndDiagnose,
10795                               QualType &CaptureType,
10796                               QualType &DeclRefType) {
10797   bool Nested = false;
10798 
10799   DeclContext *DC = CurContext;
10800   if (Var->getDeclContext() == DC) return true;
10801   if (!Var->hasLocalStorage()) return true;
10802 
10803   bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
10804 
10805   // Walk up the stack to determine whether we can capture the variable,
10806   // performing the "simple" checks that don't depend on type. We stop when
10807   // we've either hit the declared scope of the variable or find an existing
10808   // capture of that variable.
10809   CaptureType = Var->getType();
10810   DeclRefType = CaptureType.getNonReferenceType();
10811   bool Explicit = (Kind != TryCapture_Implicit);
10812   unsigned FunctionScopesIndex = FunctionScopes.size() - 1;
10813   do {
10814     // Only block literals and lambda expressions can capture; other
10815     // scopes don't work.
10816     DeclContext *ParentDC;
10817     if (isa<BlockDecl>(DC))
10818       ParentDC = DC->getParent();
10819     else if (isa<CXXMethodDecl>(DC) &&
10820              cast<CXXMethodDecl>(DC)->getOverloadedOperator() == OO_Call &&
10821              cast<CXXRecordDecl>(DC->getParent())->isLambda())
10822       ParentDC = DC->getParent()->getParent();
10823     else {
10824       if (BuildAndDiagnose)
10825         diagnoseUncapturableValueReference(*this, Loc, Var, DC);
10826       return true;
10827     }
10828 
10829     CapturingScopeInfo *CSI =
10830       cast<CapturingScopeInfo>(FunctionScopes[FunctionScopesIndex]);
10831 
10832     // Check whether we've already captured it.
10833     if (CSI->CaptureMap.count(Var)) {
10834       // If we found a capture, any subcaptures are nested.
10835       Nested = true;
10836 
10837       // Retrieve the capture type for this variable.
10838       CaptureType = CSI->getCapture(Var).getCaptureType();
10839 
10840       // Compute the type of an expression that refers to this variable.
10841       DeclRefType = CaptureType.getNonReferenceType();
10842 
10843       const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var);
10844       if (Cap.isCopyCapture() &&
10845           !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable))
10846         DeclRefType.addConst();
10847       break;
10848     }
10849 
10850     bool IsBlock = isa<BlockScopeInfo>(CSI);
10851     bool IsLambda = !IsBlock;
10852 
10853     // Lambdas are not allowed to capture unnamed variables
10854     // (e.g. anonymous unions).
10855     // FIXME: The C++11 rule don't actually state this explicitly, but I'm
10856     // assuming that's the intent.
10857     if (IsLambda && !Var->getDeclName()) {
10858       if (BuildAndDiagnose) {
10859         Diag(Loc, diag::err_lambda_capture_anonymous_var);
10860         Diag(Var->getLocation(), diag::note_declared_at);
10861       }
10862       return true;
10863     }
10864 
10865     // Prohibit variably-modified types; they're difficult to deal with.
10866     if (Var->getType()->isVariablyModifiedType()) {
10867       if (BuildAndDiagnose) {
10868         if (IsBlock)
10869           Diag(Loc, diag::err_ref_vm_type);
10870         else
10871           Diag(Loc, diag::err_lambda_capture_vm_type) << Var->getDeclName();
10872         Diag(Var->getLocation(), diag::note_previous_decl)
10873           << Var->getDeclName();
10874       }
10875       return true;
10876     }
10877     // Prohibit structs with flexible array members too.
10878     // We cannot capture what is in the tail end of the struct.
10879     if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
10880       if (VTTy->getDecl()->hasFlexibleArrayMember()) {
10881         if (BuildAndDiagnose) {
10882           if (IsBlock)
10883             Diag(Loc, diag::err_ref_flexarray_type);
10884           else
10885             Diag(Loc, diag::err_lambda_capture_flexarray_type)
10886               << Var->getDeclName();
10887           Diag(Var->getLocation(), diag::note_previous_decl)
10888             << Var->getDeclName();
10889         }
10890         return true;
10891       }
10892     }
10893     // Lambdas are not allowed to capture __block variables; they don't
10894     // support the expected semantics.
10895     if (IsLambda && HasBlocksAttr) {
10896       if (BuildAndDiagnose) {
10897         Diag(Loc, diag::err_lambda_capture_block)
10898           << Var->getDeclName();
10899         Diag(Var->getLocation(), diag::note_previous_decl)
10900           << Var->getDeclName();
10901       }
10902       return true;
10903     }
10904 
10905     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
10906       // No capture-default
10907       if (BuildAndDiagnose) {
10908         Diag(Loc, diag::err_lambda_impcap) << Var->getDeclName();
10909         Diag(Var->getLocation(), diag::note_previous_decl)
10910           << Var->getDeclName();
10911         Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
10912              diag::note_lambda_decl);
10913       }
10914       return true;
10915     }
10916 
10917     FunctionScopesIndex--;
10918     DC = ParentDC;
10919     Explicit = false;
10920   } while (!Var->getDeclContext()->Equals(DC));
10921 
10922   // Walk back down the scope stack, computing the type of the capture at
10923   // each step, checking type-specific requirements, and adding captures if
10924   // requested.
10925   for (unsigned I = ++FunctionScopesIndex, N = FunctionScopes.size(); I != N;
10926        ++I) {
10927     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
10928 
10929     // Compute the type of the capture and of a reference to the capture within
10930     // this scope.
10931     if (isa<BlockScopeInfo>(CSI)) {
10932       Expr *CopyExpr = 0;
10933       bool ByRef = false;
10934 
10935       // Blocks are not allowed to capture arrays.
10936       if (CaptureType->isArrayType()) {
10937         if (BuildAndDiagnose) {
10938           Diag(Loc, diag::err_ref_array_type);
10939           Diag(Var->getLocation(), diag::note_previous_decl)
10940           << Var->getDeclName();
10941         }
10942         return true;
10943       }
10944 
10945       // Forbid the block-capture of autoreleasing variables.
10946       if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
10947         if (BuildAndDiagnose) {
10948           Diag(Loc, diag::err_arc_autoreleasing_capture)
10949             << /*block*/ 0;
10950           Diag(Var->getLocation(), diag::note_previous_decl)
10951             << Var->getDeclName();
10952         }
10953         return true;
10954       }
10955 
10956       if (HasBlocksAttr || CaptureType->isReferenceType()) {
10957         // Block capture by reference does not change the capture or
10958         // declaration reference types.
10959         ByRef = true;
10960       } else {
10961         // Block capture by copy introduces 'const'.
10962         CaptureType = CaptureType.getNonReferenceType().withConst();
10963         DeclRefType = CaptureType;
10964 
10965         if (getLangOpts().CPlusPlus && BuildAndDiagnose) {
10966           if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
10967             // The capture logic needs the destructor, so make sure we mark it.
10968             // Usually this is unnecessary because most local variables have
10969             // their destructors marked at declaration time, but parameters are
10970             // an exception because it's technically only the call site that
10971             // actually requires the destructor.
10972             if (isa<ParmVarDecl>(Var))
10973               FinalizeVarWithDestructor(Var, Record);
10974 
10975             // According to the blocks spec, the capture of a variable from
10976             // the stack requires a const copy constructor.  This is not true
10977             // of the copy/move done to move a __block variable to the heap.
10978             Expr *DeclRef = new (Context) DeclRefExpr(Var, Nested,
10979                                                       DeclRefType.withConst(),
10980                                                       VK_LValue, Loc);
10981 
10982             ExprResult Result
10983               = PerformCopyInitialization(
10984                   InitializedEntity::InitializeBlock(Var->getLocation(),
10985                                                      CaptureType, false),
10986                   Loc, Owned(DeclRef));
10987 
10988             // Build a full-expression copy expression if initialization
10989             // succeeded and used a non-trivial constructor.  Recover from
10990             // errors by pretending that the copy isn't necessary.
10991             if (!Result.isInvalid() &&
10992                 !cast<CXXConstructExpr>(Result.get())->getConstructor()
10993                    ->isTrivial()) {
10994               Result = MaybeCreateExprWithCleanups(Result);
10995               CopyExpr = Result.take();
10996             }
10997           }
10998         }
10999       }
11000 
11001       // Actually capture the variable.
11002       if (BuildAndDiagnose)
11003         CSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
11004                         SourceLocation(), CaptureType, CopyExpr);
11005       Nested = true;
11006       continue;
11007     }
11008 
11009     LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
11010 
11011     // Determine whether we are capturing by reference or by value.
11012     bool ByRef = false;
11013     if (I == N - 1 && Kind != TryCapture_Implicit) {
11014       ByRef = (Kind == TryCapture_ExplicitByRef);
11015     } else {
11016       ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
11017     }
11018 
11019     // Compute the type of the field that will capture this variable.
11020     if (ByRef) {
11021       // C++11 [expr.prim.lambda]p15:
11022       //   An entity is captured by reference if it is implicitly or
11023       //   explicitly captured but not captured by copy. It is
11024       //   unspecified whether additional unnamed non-static data
11025       //   members are declared in the closure type for entities
11026       //   captured by reference.
11027       //
11028       // FIXME: It is not clear whether we want to build an lvalue reference
11029       // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
11030       // to do the former, while EDG does the latter. Core issue 1249 will
11031       // clarify, but for now we follow GCC because it's a more permissive and
11032       // easily defensible position.
11033       CaptureType = Context.getLValueReferenceType(DeclRefType);
11034     } else {
11035       // C++11 [expr.prim.lambda]p14:
11036       //   For each entity captured by copy, an unnamed non-static
11037       //   data member is declared in the closure type. The
11038       //   declaration order of these members is unspecified. The type
11039       //   of such a data member is the type of the corresponding
11040       //   captured entity if the entity is not a reference to an
11041       //   object, or the referenced type otherwise. [Note: If the
11042       //   captured entity is a reference to a function, the
11043       //   corresponding data member is also a reference to a
11044       //   function. - end note ]
11045       if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
11046         if (!RefType->getPointeeType()->isFunctionType())
11047           CaptureType = RefType->getPointeeType();
11048       }
11049 
11050       // Forbid the lambda copy-capture of autoreleasing variables.
11051       if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
11052         if (BuildAndDiagnose) {
11053           Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
11054           Diag(Var->getLocation(), diag::note_previous_decl)
11055             << Var->getDeclName();
11056         }
11057         return true;
11058       }
11059     }
11060 
11061     // Capture this variable in the lambda.
11062     Expr *CopyExpr = 0;
11063     if (BuildAndDiagnose) {
11064       ExprResult Result = captureInLambda(*this, LSI, Var, CaptureType,
11065                                           DeclRefType, Loc,
11066                                           Nested);
11067       if (!Result.isInvalid())
11068         CopyExpr = Result.take();
11069     }
11070 
11071     // Compute the type of a reference to this captured variable.
11072     if (ByRef)
11073       DeclRefType = CaptureType.getNonReferenceType();
11074     else {
11075       // C++ [expr.prim.lambda]p5:
11076       //   The closure type for a lambda-expression has a public inline
11077       //   function call operator [...]. This function call operator is
11078       //   declared const (9.3.1) if and only if the lambda-expression’s
11079       //   parameter-declaration-clause is not followed by mutable.
11080       DeclRefType = CaptureType.getNonReferenceType();
11081       if (!LSI->Mutable && !CaptureType->isReferenceType())
11082         DeclRefType.addConst();
11083     }
11084 
11085     // Add the capture.
11086     if (BuildAndDiagnose)
11087       CSI->addCapture(Var, /*IsBlock=*/false, ByRef, Nested, Loc,
11088                       EllipsisLoc, CaptureType, CopyExpr);
11089     Nested = true;
11090   }
11091 
11092   return false;
11093 }
11094 
11095 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
11096                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {
11097   QualType CaptureType;
11098   QualType DeclRefType;
11099   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
11100                             /*BuildAndDiagnose=*/true, CaptureType,
11101                             DeclRefType);
11102 }
11103 
11104 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
11105   QualType CaptureType;
11106   QualType DeclRefType;
11107 
11108   // Determine whether we can capture this variable.
11109   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
11110                          /*BuildAndDiagnose=*/false, CaptureType, DeclRefType))
11111     return QualType();
11112 
11113   return DeclRefType;
11114 }
11115 
11116 static void MarkVarDeclODRUsed(Sema &SemaRef, VarDecl *Var,
11117                                SourceLocation Loc) {
11118   // Keep track of used but undefined variables.
11119   // FIXME: We shouldn't suppress this warning for static data members.
11120   if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
11121       Var->getLinkage() != ExternalLinkage &&
11122       !(Var->isStaticDataMember() && Var->hasInit())) {
11123     SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()];
11124     if (old.isInvalid()) old = Loc;
11125   }
11126 
11127   SemaRef.tryCaptureVariable(Var, Loc);
11128 
11129   Var->setUsed(true);
11130 }
11131 
11132 void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
11133   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
11134   // an object that satisfies the requirements for appearing in a
11135   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
11136   // is immediately applied."  This function handles the lvalue-to-rvalue
11137   // conversion part.
11138   MaybeODRUseExprs.erase(E->IgnoreParens());
11139 }
11140 
11141 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
11142   if (!Res.isUsable())
11143     return Res;
11144 
11145   // If a constant-expression is a reference to a variable where we delay
11146   // deciding whether it is an odr-use, just assume we will apply the
11147   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
11148   // (a non-type template argument), we have special handling anyway.
11149   UpdateMarkingForLValueToRValue(Res.get());
11150   return Res;
11151 }
11152 
11153 void Sema::CleanupVarDeclMarking() {
11154   for (llvm::SmallPtrSetIterator<Expr*> i = MaybeODRUseExprs.begin(),
11155                                         e = MaybeODRUseExprs.end();
11156        i != e; ++i) {
11157     VarDecl *Var;
11158     SourceLocation Loc;
11159     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(*i)) {
11160       Var = cast<VarDecl>(DRE->getDecl());
11161       Loc = DRE->getLocation();
11162     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(*i)) {
11163       Var = cast<VarDecl>(ME->getMemberDecl());
11164       Loc = ME->getMemberLoc();
11165     } else {
11166       llvm_unreachable("Unexpcted expression");
11167     }
11168 
11169     MarkVarDeclODRUsed(*this, Var, Loc);
11170   }
11171 
11172   MaybeODRUseExprs.clear();
11173 }
11174 
11175 // Mark a VarDecl referenced, and perform the necessary handling to compute
11176 // odr-uses.
11177 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
11178                                     VarDecl *Var, Expr *E) {
11179   Var->setReferenced();
11180 
11181   if (!IsPotentiallyEvaluatedContext(SemaRef))
11182     return;
11183 
11184   // Implicit instantiation of static data members of class templates.
11185   if (Var->isStaticDataMember() && Var->getInstantiatedFromStaticDataMember()) {
11186     MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
11187     assert(MSInfo && "Missing member specialization information?");
11188     bool AlreadyInstantiated = !MSInfo->getPointOfInstantiation().isInvalid();
11189     if (MSInfo->getTemplateSpecializationKind() == TSK_ImplicitInstantiation &&
11190         (!AlreadyInstantiated ||
11191          Var->isUsableInConstantExpressions(SemaRef.Context))) {
11192       if (!AlreadyInstantiated) {
11193         // This is a modification of an existing AST node. Notify listeners.
11194         if (ASTMutationListener *L = SemaRef.getASTMutationListener())
11195           L->StaticDataMemberInstantiated(Var);
11196         MSInfo->setPointOfInstantiation(Loc);
11197       }
11198       SourceLocation PointOfInstantiation = MSInfo->getPointOfInstantiation();
11199       if (Var->isUsableInConstantExpressions(SemaRef.Context))
11200         // Do not defer instantiations of variables which could be used in a
11201         // constant expression.
11202         SemaRef.InstantiateStaticDataMemberDefinition(PointOfInstantiation,Var);
11203       else
11204         SemaRef.PendingInstantiations.push_back(
11205             std::make_pair(Var, PointOfInstantiation));
11206     }
11207   }
11208 
11209   // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies
11210   // the requirements for appearing in a constant expression (5.19) and, if
11211   // it is an object, the lvalue-to-rvalue conversion (4.1)
11212   // is immediately applied."  We check the first part here, and
11213   // Sema::UpdateMarkingForLValueToRValue deals with the second part.
11214   // Note that we use the C++11 definition everywhere because nothing in
11215   // C++03 depends on whether we get the C++03 version correct. The second
11216   // part does not apply to references, since they are not objects.
11217   const VarDecl *DefVD;
11218   if (E && !isa<ParmVarDecl>(Var) &&
11219       Var->isUsableInConstantExpressions(SemaRef.Context) &&
11220       Var->getAnyInitializer(DefVD) && DefVD->checkInitIsICE()) {
11221     if (!Var->getType()->isReferenceType())
11222       SemaRef.MaybeODRUseExprs.insert(E);
11223   } else
11224     MarkVarDeclODRUsed(SemaRef, Var, Loc);
11225 }
11226 
11227 /// \brief Mark a variable referenced, and check whether it is odr-used
11228 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
11229 /// used directly for normal expressions referring to VarDecl.
11230 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
11231   DoMarkVarDeclReferenced(*this, Loc, Var, 0);
11232 }
11233 
11234 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
11235                                Decl *D, Expr *E, bool OdrUse) {
11236   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
11237     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
11238     return;
11239   }
11240 
11241   SemaRef.MarkAnyDeclReferenced(Loc, D, OdrUse);
11242 
11243   // If this is a call to a method via a cast, also mark the method in the
11244   // derived class used in case codegen can devirtualize the call.
11245   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
11246   if (!ME)
11247     return;
11248   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
11249   if (!MD)
11250     return;
11251   const Expr *Base = ME->getBase();
11252   const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
11253   if (!MostDerivedClassDecl)
11254     return;
11255   CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl);
11256   if (!DM || DM->isPure())
11257     return;
11258   SemaRef.MarkAnyDeclReferenced(Loc, DM, OdrUse);
11259 }
11260 
11261 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
11262 void Sema::MarkDeclRefReferenced(DeclRefExpr *E) {
11263   // TODO: update this with DR# once a defect report is filed.
11264   // C++11 defect. The address of a pure member should not be an ODR use, even
11265   // if it's a qualified reference.
11266   bool OdrUse = true;
11267   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
11268     if (Method->isVirtual())
11269       OdrUse = false;
11270   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
11271 }
11272 
11273 /// \brief Perform reference-marking and odr-use handling for a MemberExpr.
11274 void Sema::MarkMemberReferenced(MemberExpr *E) {
11275   // C++11 [basic.def.odr]p2:
11276   //   A non-overloaded function whose name appears as a potentially-evaluated
11277   //   expression or a member of a set of candidate functions, if selected by
11278   //   overload resolution when referred to from a potentially-evaluated
11279   //   expression, is odr-used, unless it is a pure virtual function and its
11280   //   name is not explicitly qualified.
11281   bool OdrUse = true;
11282   if (!E->hasQualifier()) {
11283     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
11284       if (Method->isPure())
11285         OdrUse = false;
11286   }
11287   SourceLocation Loc = E->getMemberLoc().isValid() ?
11288                             E->getMemberLoc() : E->getLocStart();
11289   MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, OdrUse);
11290 }
11291 
11292 /// \brief Perform marking for a reference to an arbitrary declaration.  It
11293 /// marks the declaration referenced, and performs odr-use checking for functions
11294 /// and variables. This method should not be used when building an normal
11295 /// expression which refers to a variable.
11296 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool OdrUse) {
11297   if (OdrUse) {
11298     if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
11299       MarkVariableReferenced(Loc, VD);
11300       return;
11301     }
11302     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
11303       MarkFunctionReferenced(Loc, FD);
11304       return;
11305     }
11306   }
11307   D->setReferenced();
11308 }
11309 
11310 namespace {
11311   // Mark all of the declarations referenced
11312   // FIXME: Not fully implemented yet! We need to have a better understanding
11313   // of when we're entering
11314   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
11315     Sema &S;
11316     SourceLocation Loc;
11317 
11318   public:
11319     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
11320 
11321     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
11322 
11323     bool TraverseTemplateArgument(const TemplateArgument &Arg);
11324     bool TraverseRecordType(RecordType *T);
11325   };
11326 }
11327 
11328 bool MarkReferencedDecls::TraverseTemplateArgument(
11329   const TemplateArgument &Arg) {
11330   if (Arg.getKind() == TemplateArgument::Declaration) {
11331     if (Decl *D = Arg.getAsDecl())
11332       S.MarkAnyDeclReferenced(Loc, D, true);
11333   }
11334 
11335   return Inherited::TraverseTemplateArgument(Arg);
11336 }
11337 
11338 bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
11339   if (ClassTemplateSpecializationDecl *Spec
11340                   = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
11341     const TemplateArgumentList &Args = Spec->getTemplateArgs();
11342     return TraverseTemplateArguments(Args.data(), Args.size());
11343   }
11344 
11345   return true;
11346 }
11347 
11348 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
11349   MarkReferencedDecls Marker(*this, Loc);
11350   Marker.TraverseType(Context.getCanonicalType(T));
11351 }
11352 
11353 namespace {
11354   /// \brief Helper class that marks all of the declarations referenced by
11355   /// potentially-evaluated subexpressions as "referenced".
11356   class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
11357     Sema &S;
11358     bool SkipLocalVariables;
11359 
11360   public:
11361     typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
11362 
11363     EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
11364       : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
11365 
11366     void VisitDeclRefExpr(DeclRefExpr *E) {
11367       // If we were asked not to visit local variables, don't.
11368       if (SkipLocalVariables) {
11369         if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
11370           if (VD->hasLocalStorage())
11371             return;
11372       }
11373 
11374       S.MarkDeclRefReferenced(E);
11375     }
11376 
11377     void VisitMemberExpr(MemberExpr *E) {
11378       S.MarkMemberReferenced(E);
11379       Inherited::VisitMemberExpr(E);
11380     }
11381 
11382     void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
11383       S.MarkFunctionReferenced(E->getLocStart(),
11384             const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
11385       Visit(E->getSubExpr());
11386     }
11387 
11388     void VisitCXXNewExpr(CXXNewExpr *E) {
11389       if (E->getOperatorNew())
11390         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
11391       if (E->getOperatorDelete())
11392         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
11393       Inherited::VisitCXXNewExpr(E);
11394     }
11395 
11396     void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
11397       if (E->getOperatorDelete())
11398         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
11399       QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
11400       if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
11401         CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
11402         S.MarkFunctionReferenced(E->getLocStart(),
11403                                     S.LookupDestructor(Record));
11404       }
11405 
11406       Inherited::VisitCXXDeleteExpr(E);
11407     }
11408 
11409     void VisitCXXConstructExpr(CXXConstructExpr *E) {
11410       S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
11411       Inherited::VisitCXXConstructExpr(E);
11412     }
11413 
11414     void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
11415       Visit(E->getExpr());
11416     }
11417 
11418     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
11419       Inherited::VisitImplicitCastExpr(E);
11420 
11421       if (E->getCastKind() == CK_LValueToRValue)
11422         S.UpdateMarkingForLValueToRValue(E->getSubExpr());
11423     }
11424   };
11425 }
11426 
11427 /// \brief Mark any declarations that appear within this expression or any
11428 /// potentially-evaluated subexpressions as "referenced".
11429 ///
11430 /// \param SkipLocalVariables If true, don't mark local variables as
11431 /// 'referenced'.
11432 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
11433                                             bool SkipLocalVariables) {
11434   EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
11435 }
11436 
11437 /// \brief Emit a diagnostic that describes an effect on the run-time behavior
11438 /// of the program being compiled.
11439 ///
11440 /// This routine emits the given diagnostic when the code currently being
11441 /// type-checked is "potentially evaluated", meaning that there is a
11442 /// possibility that the code will actually be executable. Code in sizeof()
11443 /// expressions, code used only during overload resolution, etc., are not
11444 /// potentially evaluated. This routine will suppress such diagnostics or,
11445 /// in the absolutely nutty case of potentially potentially evaluated
11446 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
11447 /// later.
11448 ///
11449 /// This routine should be used for all diagnostics that describe the run-time
11450 /// behavior of a program, such as passing a non-POD value through an ellipsis.
11451 /// Failure to do so will likely result in spurious diagnostics or failures
11452 /// during overload resolution or within sizeof/alignof/typeof/typeid.
11453 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
11454                                const PartialDiagnostic &PD) {
11455   switch (ExprEvalContexts.back().Context) {
11456   case Unevaluated:
11457     // The argument will never be evaluated, so don't complain.
11458     break;
11459 
11460   case ConstantEvaluated:
11461     // Relevant diagnostics should be produced by constant evaluation.
11462     break;
11463 
11464   case PotentiallyEvaluated:
11465   case PotentiallyEvaluatedIfUsed:
11466     if (Statement && getCurFunctionOrMethodDecl()) {
11467       FunctionScopes.back()->PossiblyUnreachableDiags.
11468         push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
11469     }
11470     else
11471       Diag(Loc, PD);
11472 
11473     return true;
11474   }
11475 
11476   return false;
11477 }
11478 
11479 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
11480                                CallExpr *CE, FunctionDecl *FD) {
11481   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
11482     return false;
11483 
11484   // If we're inside a decltype's expression, don't check for a valid return
11485   // type or construct temporaries until we know whether this is the last call.
11486   if (ExprEvalContexts.back().IsDecltype) {
11487     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
11488     return false;
11489   }
11490 
11491   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
11492     FunctionDecl *FD;
11493     CallExpr *CE;
11494 
11495   public:
11496     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
11497       : FD(FD), CE(CE) { }
11498 
11499     virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
11500       if (!FD) {
11501         S.Diag(Loc, diag::err_call_incomplete_return)
11502           << T << CE->getSourceRange();
11503         return;
11504       }
11505 
11506       S.Diag(Loc, diag::err_call_function_incomplete_return)
11507         << CE->getSourceRange() << FD->getDeclName() << T;
11508       S.Diag(FD->getLocation(),
11509              diag::note_function_with_incomplete_return_type_declared_here)
11510         << FD->getDeclName();
11511     }
11512   } Diagnoser(FD, CE);
11513 
11514   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
11515     return true;
11516 
11517   return false;
11518 }
11519 
11520 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
11521 // will prevent this condition from triggering, which is what we want.
11522 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
11523   SourceLocation Loc;
11524 
11525   unsigned diagnostic = diag::warn_condition_is_assignment;
11526   bool IsOrAssign = false;
11527 
11528   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
11529     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
11530       return;
11531 
11532     IsOrAssign = Op->getOpcode() == BO_OrAssign;
11533 
11534     // Greylist some idioms by putting them into a warning subcategory.
11535     if (ObjCMessageExpr *ME
11536           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
11537       Selector Sel = ME->getSelector();
11538 
11539       // self = [<foo> init...]
11540       if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init"))
11541         diagnostic = diag::warn_condition_is_idiomatic_assignment;
11542 
11543       // <foo> = [<bar> nextObject]
11544       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
11545         diagnostic = diag::warn_condition_is_idiomatic_assignment;
11546     }
11547 
11548     Loc = Op->getOperatorLoc();
11549   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
11550     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
11551       return;
11552 
11553     IsOrAssign = Op->getOperator() == OO_PipeEqual;
11554     Loc = Op->getOperatorLoc();
11555   } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
11556     return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
11557   else {
11558     // Not an assignment.
11559     return;
11560   }
11561 
11562   Diag(Loc, diagnostic) << E->getSourceRange();
11563 
11564   SourceLocation Open = E->getLocStart();
11565   SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
11566   Diag(Loc, diag::note_condition_assign_silence)
11567         << FixItHint::CreateInsertion(Open, "(")
11568         << FixItHint::CreateInsertion(Close, ")");
11569 
11570   if (IsOrAssign)
11571     Diag(Loc, diag::note_condition_or_assign_to_comparison)
11572       << FixItHint::CreateReplacement(Loc, "!=");
11573   else
11574     Diag(Loc, diag::note_condition_assign_to_comparison)
11575       << FixItHint::CreateReplacement(Loc, "==");
11576 }
11577 
11578 /// \brief Redundant parentheses over an equality comparison can indicate
11579 /// that the user intended an assignment used as condition.
11580 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
11581   // Don't warn if the parens came from a macro.
11582   SourceLocation parenLoc = ParenE->getLocStart();
11583   if (parenLoc.isInvalid() || parenLoc.isMacroID())
11584     return;
11585   // Don't warn for dependent expressions.
11586   if (ParenE->isTypeDependent())
11587     return;
11588 
11589   Expr *E = ParenE->IgnoreParens();
11590 
11591   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
11592     if (opE->getOpcode() == BO_EQ &&
11593         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
11594                                                            == Expr::MLV_Valid) {
11595       SourceLocation Loc = opE->getOperatorLoc();
11596 
11597       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
11598       SourceRange ParenERange = ParenE->getSourceRange();
11599       Diag(Loc, diag::note_equality_comparison_silence)
11600         << FixItHint::CreateRemoval(ParenERange.getBegin())
11601         << FixItHint::CreateRemoval(ParenERange.getEnd());
11602       Diag(Loc, diag::note_equality_comparison_to_assign)
11603         << FixItHint::CreateReplacement(Loc, "=");
11604     }
11605 }
11606 
11607 ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
11608   DiagnoseAssignmentAsCondition(E);
11609   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
11610     DiagnoseEqualityWithExtraParens(parenE);
11611 
11612   ExprResult result = CheckPlaceholderExpr(E);
11613   if (result.isInvalid()) return ExprError();
11614   E = result.take();
11615 
11616   if (!E->isTypeDependent()) {
11617     if (getLangOpts().CPlusPlus)
11618       return CheckCXXBooleanCondition(E); // C++ 6.4p4
11619 
11620     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
11621     if (ERes.isInvalid())
11622       return ExprError();
11623     E = ERes.take();
11624 
11625     QualType T = E->getType();
11626     if (!T->isScalarType()) { // C99 6.8.4.1p1
11627       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
11628         << T << E->getSourceRange();
11629       return ExprError();
11630     }
11631   }
11632 
11633   return Owned(E);
11634 }
11635 
11636 ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
11637                                        Expr *SubExpr) {
11638   if (!SubExpr)
11639     return ExprError();
11640 
11641   return CheckBooleanCondition(SubExpr, Loc);
11642 }
11643 
11644 namespace {
11645   /// A visitor for rebuilding a call to an __unknown_any expression
11646   /// to have an appropriate type.
11647   struct RebuildUnknownAnyFunction
11648     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
11649 
11650     Sema &S;
11651 
11652     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
11653 
11654     ExprResult VisitStmt(Stmt *S) {
11655       llvm_unreachable("unexpected statement!");
11656     }
11657 
11658     ExprResult VisitExpr(Expr *E) {
11659       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
11660         << E->getSourceRange();
11661       return ExprError();
11662     }
11663 
11664     /// Rebuild an expression which simply semantically wraps another
11665     /// expression which it shares the type and value kind of.
11666     template <class T> ExprResult rebuildSugarExpr(T *E) {
11667       ExprResult SubResult = Visit(E->getSubExpr());
11668       if (SubResult.isInvalid()) return ExprError();
11669 
11670       Expr *SubExpr = SubResult.take();
11671       E->setSubExpr(SubExpr);
11672       E->setType(SubExpr->getType());
11673       E->setValueKind(SubExpr->getValueKind());
11674       assert(E->getObjectKind() == OK_Ordinary);
11675       return E;
11676     }
11677 
11678     ExprResult VisitParenExpr(ParenExpr *E) {
11679       return rebuildSugarExpr(E);
11680     }
11681 
11682     ExprResult VisitUnaryExtension(UnaryOperator *E) {
11683       return rebuildSugarExpr(E);
11684     }
11685 
11686     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
11687       ExprResult SubResult = Visit(E->getSubExpr());
11688       if (SubResult.isInvalid()) return ExprError();
11689 
11690       Expr *SubExpr = SubResult.take();
11691       E->setSubExpr(SubExpr);
11692       E->setType(S.Context.getPointerType(SubExpr->getType()));
11693       assert(E->getValueKind() == VK_RValue);
11694       assert(E->getObjectKind() == OK_Ordinary);
11695       return E;
11696     }
11697 
11698     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
11699       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
11700 
11701       E->setType(VD->getType());
11702 
11703       assert(E->getValueKind() == VK_RValue);
11704       if (S.getLangOpts().CPlusPlus &&
11705           !(isa<CXXMethodDecl>(VD) &&
11706             cast<CXXMethodDecl>(VD)->isInstance()))
11707         E->setValueKind(VK_LValue);
11708 
11709       return E;
11710     }
11711 
11712     ExprResult VisitMemberExpr(MemberExpr *E) {
11713       return resolveDecl(E, E->getMemberDecl());
11714     }
11715 
11716     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
11717       return resolveDecl(E, E->getDecl());
11718     }
11719   };
11720 }
11721 
11722 /// Given a function expression of unknown-any type, try to rebuild it
11723 /// to have a function type.
11724 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
11725   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
11726   if (Result.isInvalid()) return ExprError();
11727   return S.DefaultFunctionArrayConversion(Result.take());
11728 }
11729 
11730 namespace {
11731   /// A visitor for rebuilding an expression of type __unknown_anytype
11732   /// into one which resolves the type directly on the referring
11733   /// expression.  Strict preservation of the original source
11734   /// structure is not a goal.
11735   struct RebuildUnknownAnyExpr
11736     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
11737 
11738     Sema &S;
11739 
11740     /// The current destination type.
11741     QualType DestType;
11742 
11743     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
11744       : S(S), DestType(CastType) {}
11745 
11746     ExprResult VisitStmt(Stmt *S) {
11747       llvm_unreachable("unexpected statement!");
11748     }
11749 
11750     ExprResult VisitExpr(Expr *E) {
11751       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
11752         << E->getSourceRange();
11753       return ExprError();
11754     }
11755 
11756     ExprResult VisitCallExpr(CallExpr *E);
11757     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
11758 
11759     /// Rebuild an expression which simply semantically wraps another
11760     /// expression which it shares the type and value kind of.
11761     template <class T> ExprResult rebuildSugarExpr(T *E) {
11762       ExprResult SubResult = Visit(E->getSubExpr());
11763       if (SubResult.isInvalid()) return ExprError();
11764       Expr *SubExpr = SubResult.take();
11765       E->setSubExpr(SubExpr);
11766       E->setType(SubExpr->getType());
11767       E->setValueKind(SubExpr->getValueKind());
11768       assert(E->getObjectKind() == OK_Ordinary);
11769       return E;
11770     }
11771 
11772     ExprResult VisitParenExpr(ParenExpr *E) {
11773       return rebuildSugarExpr(E);
11774     }
11775 
11776     ExprResult VisitUnaryExtension(UnaryOperator *E) {
11777       return rebuildSugarExpr(E);
11778     }
11779 
11780     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
11781       const PointerType *Ptr = DestType->getAs<PointerType>();
11782       if (!Ptr) {
11783         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
11784           << E->getSourceRange();
11785         return ExprError();
11786       }
11787       assert(E->getValueKind() == VK_RValue);
11788       assert(E->getObjectKind() == OK_Ordinary);
11789       E->setType(DestType);
11790 
11791       // Build the sub-expression as if it were an object of the pointee type.
11792       DestType = Ptr->getPointeeType();
11793       ExprResult SubResult = Visit(E->getSubExpr());
11794       if (SubResult.isInvalid()) return ExprError();
11795       E->setSubExpr(SubResult.take());
11796       return E;
11797     }
11798 
11799     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
11800 
11801     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
11802 
11803     ExprResult VisitMemberExpr(MemberExpr *E) {
11804       return resolveDecl(E, E->getMemberDecl());
11805     }
11806 
11807     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
11808       return resolveDecl(E, E->getDecl());
11809     }
11810   };
11811 }
11812 
11813 /// Rebuilds a call expression which yielded __unknown_anytype.
11814 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
11815   Expr *CalleeExpr = E->getCallee();
11816 
11817   enum FnKind {
11818     FK_MemberFunction,
11819     FK_FunctionPointer,
11820     FK_BlockPointer
11821   };
11822 
11823   FnKind Kind;
11824   QualType CalleeType = CalleeExpr->getType();
11825   if (CalleeType == S.Context.BoundMemberTy) {
11826     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
11827     Kind = FK_MemberFunction;
11828     CalleeType = Expr::findBoundMemberType(CalleeExpr);
11829   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
11830     CalleeType = Ptr->getPointeeType();
11831     Kind = FK_FunctionPointer;
11832   } else {
11833     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
11834     Kind = FK_BlockPointer;
11835   }
11836   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
11837 
11838   // Verify that this is a legal result type of a function.
11839   if (DestType->isArrayType() || DestType->isFunctionType()) {
11840     unsigned diagID = diag::err_func_returning_array_function;
11841     if (Kind == FK_BlockPointer)
11842       diagID = diag::err_block_returning_array_function;
11843 
11844     S.Diag(E->getExprLoc(), diagID)
11845       << DestType->isFunctionType() << DestType;
11846     return ExprError();
11847   }
11848 
11849   // Otherwise, go ahead and set DestType as the call's result.
11850   E->setType(DestType.getNonLValueExprType(S.Context));
11851   E->setValueKind(Expr::getValueKindForType(DestType));
11852   assert(E->getObjectKind() == OK_Ordinary);
11853 
11854   // Rebuild the function type, replacing the result type with DestType.
11855   if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType))
11856     DestType =
11857       S.Context.getFunctionType(DestType,
11858                                 ArrayRef<QualType>(Proto->arg_type_begin(),
11859                                                    Proto->getNumArgs()),
11860                                 Proto->getExtProtoInfo());
11861   else
11862     DestType = S.Context.getFunctionNoProtoType(DestType,
11863                                                 FnType->getExtInfo());
11864 
11865   // Rebuild the appropriate pointer-to-function type.
11866   switch (Kind) {
11867   case FK_MemberFunction:
11868     // Nothing to do.
11869     break;
11870 
11871   case FK_FunctionPointer:
11872     DestType = S.Context.getPointerType(DestType);
11873     break;
11874 
11875   case FK_BlockPointer:
11876     DestType = S.Context.getBlockPointerType(DestType);
11877     break;
11878   }
11879 
11880   // Finally, we can recurse.
11881   ExprResult CalleeResult = Visit(CalleeExpr);
11882   if (!CalleeResult.isUsable()) return ExprError();
11883   E->setCallee(CalleeResult.take());
11884 
11885   // Bind a temporary if necessary.
11886   return S.MaybeBindToTemporary(E);
11887 }
11888 
11889 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
11890   // Verify that this is a legal result type of a call.
11891   if (DestType->isArrayType() || DestType->isFunctionType()) {
11892     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
11893       << DestType->isFunctionType() << DestType;
11894     return ExprError();
11895   }
11896 
11897   // Rewrite the method result type if available.
11898   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
11899     assert(Method->getResultType() == S.Context.UnknownAnyTy);
11900     Method->setResultType(DestType);
11901   }
11902 
11903   // Change the type of the message.
11904   E->setType(DestType.getNonReferenceType());
11905   E->setValueKind(Expr::getValueKindForType(DestType));
11906 
11907   return S.MaybeBindToTemporary(E);
11908 }
11909 
11910 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
11911   // The only case we should ever see here is a function-to-pointer decay.
11912   if (E->getCastKind() == CK_FunctionToPointerDecay) {
11913     assert(E->getValueKind() == VK_RValue);
11914     assert(E->getObjectKind() == OK_Ordinary);
11915 
11916     E->setType(DestType);
11917 
11918     // Rebuild the sub-expression as the pointee (function) type.
11919     DestType = DestType->castAs<PointerType>()->getPointeeType();
11920 
11921     ExprResult Result = Visit(E->getSubExpr());
11922     if (!Result.isUsable()) return ExprError();
11923 
11924     E->setSubExpr(Result.take());
11925     return S.Owned(E);
11926   } else if (E->getCastKind() == CK_LValueToRValue) {
11927     assert(E->getValueKind() == VK_RValue);
11928     assert(E->getObjectKind() == OK_Ordinary);
11929 
11930     assert(isa<BlockPointerType>(E->getType()));
11931 
11932     E->setType(DestType);
11933 
11934     // The sub-expression has to be a lvalue reference, so rebuild it as such.
11935     DestType = S.Context.getLValueReferenceType(DestType);
11936 
11937     ExprResult Result = Visit(E->getSubExpr());
11938     if (!Result.isUsable()) return ExprError();
11939 
11940     E->setSubExpr(Result.take());
11941     return S.Owned(E);
11942   } else {
11943     llvm_unreachable("Unhandled cast type!");
11944   }
11945 }
11946 
11947 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
11948   ExprValueKind ValueKind = VK_LValue;
11949   QualType Type = DestType;
11950 
11951   // We know how to make this work for certain kinds of decls:
11952 
11953   //  - functions
11954   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
11955     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
11956       DestType = Ptr->getPointeeType();
11957       ExprResult Result = resolveDecl(E, VD);
11958       if (Result.isInvalid()) return ExprError();
11959       return S.ImpCastExprToType(Result.take(), Type,
11960                                  CK_FunctionToPointerDecay, VK_RValue);
11961     }
11962 
11963     if (!Type->isFunctionType()) {
11964       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
11965         << VD << E->getSourceRange();
11966       return ExprError();
11967     }
11968 
11969     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
11970       if (MD->isInstance()) {
11971         ValueKind = VK_RValue;
11972         Type = S.Context.BoundMemberTy;
11973       }
11974 
11975     // Function references aren't l-values in C.
11976     if (!S.getLangOpts().CPlusPlus)
11977       ValueKind = VK_RValue;
11978 
11979   //  - variables
11980   } else if (isa<VarDecl>(VD)) {
11981     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
11982       Type = RefTy->getPointeeType();
11983     } else if (Type->isFunctionType()) {
11984       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
11985         << VD << E->getSourceRange();
11986       return ExprError();
11987     }
11988 
11989   //  - nothing else
11990   } else {
11991     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
11992       << VD << E->getSourceRange();
11993     return ExprError();
11994   }
11995 
11996   VD->setType(DestType);
11997   E->setType(Type);
11998   E->setValueKind(ValueKind);
11999   return S.Owned(E);
12000 }
12001 
12002 /// Check a cast of an unknown-any type.  We intentionally only
12003 /// trigger this for C-style casts.
12004 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
12005                                      Expr *CastExpr, CastKind &CastKind,
12006                                      ExprValueKind &VK, CXXCastPath &Path) {
12007   // Rewrite the casted expression from scratch.
12008   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
12009   if (!result.isUsable()) return ExprError();
12010 
12011   CastExpr = result.take();
12012   VK = CastExpr->getValueKind();
12013   CastKind = CK_NoOp;
12014 
12015   return CastExpr;
12016 }
12017 
12018 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
12019   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
12020 }
12021 
12022 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
12023                                     Expr *arg, QualType &paramType) {
12024   // If the syntactic form of the argument is not an explicit cast of
12025   // any sort, just do default argument promotion.
12026   ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
12027   if (!castArg) {
12028     ExprResult result = DefaultArgumentPromotion(arg);
12029     if (result.isInvalid()) return ExprError();
12030     paramType = result.get()->getType();
12031     return result;
12032   }
12033 
12034   // Otherwise, use the type that was written in the explicit cast.
12035   assert(!arg->hasPlaceholderType());
12036   paramType = castArg->getTypeAsWritten();
12037 
12038   // Copy-initialize a parameter of that type.
12039   InitializedEntity entity =
12040     InitializedEntity::InitializeParameter(Context, paramType,
12041                                            /*consumed*/ false);
12042   return PerformCopyInitialization(entity, callLoc, Owned(arg));
12043 }
12044 
12045 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
12046   Expr *orig = E;
12047   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
12048   while (true) {
12049     E = E->IgnoreParenImpCasts();
12050     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
12051       E = call->getCallee();
12052       diagID = diag::err_uncasted_call_of_unknown_any;
12053     } else {
12054       break;
12055     }
12056   }
12057 
12058   SourceLocation loc;
12059   NamedDecl *d;
12060   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
12061     loc = ref->getLocation();
12062     d = ref->getDecl();
12063   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
12064     loc = mem->getMemberLoc();
12065     d = mem->getMemberDecl();
12066   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
12067     diagID = diag::err_uncasted_call_of_unknown_any;
12068     loc = msg->getSelectorStartLoc();
12069     d = msg->getMethodDecl();
12070     if (!d) {
12071       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
12072         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
12073         << orig->getSourceRange();
12074       return ExprError();
12075     }
12076   } else {
12077     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
12078       << E->getSourceRange();
12079     return ExprError();
12080   }
12081 
12082   S.Diag(loc, diagID) << d << orig->getSourceRange();
12083 
12084   // Never recoverable.
12085   return ExprError();
12086 }
12087 
12088 /// Check for operands with placeholder types and complain if found.
12089 /// Returns true if there was an error and no recovery was possible.
12090 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
12091   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
12092   if (!placeholderType) return Owned(E);
12093 
12094   switch (placeholderType->getKind()) {
12095 
12096   // Overloaded expressions.
12097   case BuiltinType::Overload: {
12098     // Try to resolve a single function template specialization.
12099     // This is obligatory.
12100     ExprResult result = Owned(E);
12101     if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) {
12102       return result;
12103 
12104     // If that failed, try to recover with a call.
12105     } else {
12106       tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable),
12107                            /*complain*/ true);
12108       return result;
12109     }
12110   }
12111 
12112   // Bound member functions.
12113   case BuiltinType::BoundMember: {
12114     ExprResult result = Owned(E);
12115     tryToRecoverWithCall(result, PDiag(diag::err_bound_member_function),
12116                          /*complain*/ true);
12117     return result;
12118   }
12119 
12120   // ARC unbridged casts.
12121   case BuiltinType::ARCUnbridgedCast: {
12122     Expr *realCast = stripARCUnbridgedCast(E);
12123     diagnoseARCUnbridgedCast(realCast);
12124     return Owned(realCast);
12125   }
12126 
12127   // Expressions of unknown type.
12128   case BuiltinType::UnknownAny:
12129     return diagnoseUnknownAnyExpr(*this, E);
12130 
12131   // Pseudo-objects.
12132   case BuiltinType::PseudoObject:
12133     return checkPseudoObjectRValue(E);
12134 
12135   case BuiltinType::BuiltinFn:
12136     Diag(E->getLocStart(), diag::err_builtin_fn_use);
12137     return ExprError();
12138 
12139   // Everything else should be impossible.
12140 #define BUILTIN_TYPE(Id, SingletonId) \
12141   case BuiltinType::Id:
12142 #define PLACEHOLDER_TYPE(Id, SingletonId)
12143 #include "clang/AST/BuiltinTypes.def"
12144     break;
12145   }
12146 
12147   llvm_unreachable("invalid placeholder type!");
12148 }
12149 
12150 bool Sema::CheckCaseExpression(Expr *E) {
12151   if (E->isTypeDependent())
12152     return true;
12153   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
12154     return E->getType()->isIntegralOrEnumerationType();
12155   return false;
12156 }
12157 
12158 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
12159 ExprResult
12160 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
12161   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
12162          "Unknown Objective-C Boolean value!");
12163   QualType BoolT = Context.ObjCBuiltinBoolTy;
12164   if (!Context.getBOOLDecl()) {
12165     LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
12166                         Sema::LookupOrdinaryName);
12167     if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
12168       NamedDecl *ND = Result.getFoundDecl();
12169       if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
12170         Context.setBOOLDecl(TD);
12171     }
12172   }
12173   if (Context.getBOOLDecl())
12174     BoolT = Context.getBOOLType();
12175   return Owned(new (Context) ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes,
12176                                         BoolT, OpLoc));
12177 }
12178