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/ASTLambda.h"
19 #include "clang/AST/ASTMutationListener.h"
20 #include "clang/AST/CXXInheritance.h"
21 #include "clang/AST/DeclObjC.h"
22 #include "clang/AST/DeclTemplate.h"
23 #include "clang/AST/EvaluatedExprVisitor.h"
24 #include "clang/AST/Expr.h"
25 #include "clang/AST/ExprCXX.h"
26 #include "clang/AST/ExprObjC.h"
27 #include "clang/AST/RecursiveASTVisitor.h"
28 #include "clang/AST/TypeLoc.h"
29 #include "clang/Basic/PartialDiagnostic.h"
30 #include "clang/Basic/SourceManager.h"
31 #include "clang/Basic/TargetInfo.h"
32 #include "clang/Lex/LiteralSupport.h"
33 #include "clang/Lex/Preprocessor.h"
34 #include "clang/Sema/AnalysisBasedWarnings.h"
35 #include "clang/Sema/DeclSpec.h"
36 #include "clang/Sema/DelayedDiagnostic.h"
37 #include "clang/Sema/Designator.h"
38 #include "clang/Sema/Initialization.h"
39 #include "clang/Sema/Lookup.h"
40 #include "clang/Sema/ParsedTemplate.h"
41 #include "clang/Sema/Scope.h"
42 #include "clang/Sema/ScopeInfo.h"
43 #include "clang/Sema/SemaFixItUtils.h"
44 #include "clang/Sema/Template.h"
45 using namespace clang;
46 using namespace sema;
47 
48 /// \brief Determine whether the use of this declaration is valid, without
49 /// emitting diagnostics.
50 bool Sema::CanUseDecl(NamedDecl *D) {
51   // See if this is an auto-typed variable whose initializer we are parsing.
52   if (ParsingInitForAutoVars.count(D))
53     return false;
54 
55   // See if this is a deleted function.
56   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
57     if (FD->isDeleted())
58       return false;
59 
60     // If the function has a deduced return type, and we can't deduce it,
61     // then we can't use it either.
62     if (getLangOpts().CPlusPlus1y && FD->getReturnType()->isUndeducedType() &&
63         DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
64       return false;
65   }
66 
67   // See if this function is unavailable.
68   if (D->getAvailability() == AR_Unavailable &&
69       cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
70     return false;
71 
72   return true;
73 }
74 
75 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
76   // Warn if this is used but marked unused.
77   if (D->hasAttr<UnusedAttr>()) {
78     const Decl *DC = cast<Decl>(S.getCurObjCLexicalContext());
79     if (!DC->hasAttr<UnusedAttr>())
80       S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
81   }
82 }
83 
84 static AvailabilityResult DiagnoseAvailabilityOfDecl(Sema &S,
85                               NamedDecl *D, SourceLocation Loc,
86                               const ObjCInterfaceDecl *UnknownObjCClass) {
87   // See if this declaration is unavailable or deprecated.
88   std::string Message;
89   AvailabilityResult Result = D->getAvailability(&Message);
90   if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D))
91     if (Result == AR_Available) {
92       const DeclContext *DC = ECD->getDeclContext();
93       if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC))
94         Result = TheEnumDecl->getAvailability(&Message);
95     }
96 
97   const ObjCPropertyDecl *ObjCPDecl = 0;
98   if (Result == AR_Deprecated || Result == AR_Unavailable) {
99     if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
100       if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) {
101         AvailabilityResult PDeclResult = PD->getAvailability(0);
102         if (PDeclResult == Result)
103           ObjCPDecl = PD;
104       }
105     }
106   }
107 
108   switch (Result) {
109     case AR_Available:
110     case AR_NotYetIntroduced:
111       break;
112 
113     case AR_Deprecated:
114       if (S.getCurContextAvailability() != AR_Deprecated)
115         S.EmitAvailabilityWarning(Sema::AD_Deprecation,
116                                   D, Message, Loc, UnknownObjCClass, ObjCPDecl);
117       break;
118 
119     case AR_Unavailable:
120       if (S.getCurContextAvailability() != AR_Unavailable)
121         S.EmitAvailabilityWarning(Sema::AD_Unavailable,
122                                   D, Message, Loc, UnknownObjCClass, ObjCPDecl);
123       break;
124 
125     }
126     return Result;
127 }
128 
129 /// \brief Emit a note explaining that this function is deleted.
130 void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
131   assert(Decl->isDeleted());
132 
133   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
134 
135   if (Method && Method->isDeleted() && Method->isDefaulted()) {
136     // If the method was explicitly defaulted, point at that declaration.
137     if (!Method->isImplicit())
138       Diag(Decl->getLocation(), diag::note_implicitly_deleted);
139 
140     // Try to diagnose why this special member function was implicitly
141     // deleted. This might fail, if that reason no longer applies.
142     CXXSpecialMember CSM = getSpecialMember(Method);
143     if (CSM != CXXInvalid)
144       ShouldDeleteSpecialMember(Method, CSM, /*Diagnose=*/true);
145 
146     return;
147   }
148 
149   if (CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Decl)) {
150     if (CXXConstructorDecl *BaseCD =
151             const_cast<CXXConstructorDecl*>(CD->getInheritedConstructor())) {
152       Diag(Decl->getLocation(), diag::note_inherited_deleted_here);
153       if (BaseCD->isDeleted()) {
154         NoteDeletedFunction(BaseCD);
155       } else {
156         // FIXME: An explanation of why exactly it can't be inherited
157         // would be nice.
158         Diag(BaseCD->getLocation(), diag::note_cannot_inherit);
159       }
160       return;
161     }
162   }
163 
164   Diag(Decl->getLocation(), diag::note_availability_specified_here)
165     << Decl << true;
166 }
167 
168 /// \brief Determine whether a FunctionDecl was ever declared with an
169 /// explicit storage class.
170 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
171   for (FunctionDecl::redecl_iterator I = D->redecls_begin(),
172                                      E = D->redecls_end();
173        I != E; ++I) {
174     if (I->getStorageClass() != SC_None)
175       return true;
176   }
177   return false;
178 }
179 
180 /// \brief Check whether we're in an extern inline function and referring to a
181 /// variable or function with internal linkage (C11 6.7.4p3).
182 ///
183 /// This is only a warning because we used to silently accept this code, but
184 /// in many cases it will not behave correctly. This is not enabled in C++ mode
185 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
186 /// and so while there may still be user mistakes, most of the time we can't
187 /// prove that there are errors.
188 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
189                                                       const NamedDecl *D,
190                                                       SourceLocation Loc) {
191   // This is disabled under C++; there are too many ways for this to fire in
192   // contexts where the warning is a false positive, or where it is technically
193   // correct but benign.
194   if (S.getLangOpts().CPlusPlus)
195     return;
196 
197   // Check if this is an inlined function or method.
198   FunctionDecl *Current = S.getCurFunctionDecl();
199   if (!Current)
200     return;
201   if (!Current->isInlined())
202     return;
203   if (!Current->isExternallyVisible())
204     return;
205 
206   // Check if the decl has internal linkage.
207   if (D->getFormalLinkage() != InternalLinkage)
208     return;
209 
210   // Downgrade from ExtWarn to Extension if
211   //  (1) the supposedly external inline function is in the main file,
212   //      and probably won't be included anywhere else.
213   //  (2) the thing we're referencing is a pure function.
214   //  (3) the thing we're referencing is another inline function.
215   // This last can give us false negatives, but it's better than warning on
216   // wrappers for simple C library functions.
217   const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
218   bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
219   if (!DowngradeWarning && UsedFn)
220     DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
221 
222   S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline
223                                : diag::warn_internal_in_extern_inline)
224     << /*IsVar=*/!UsedFn << D;
225 
226   S.MaybeSuggestAddingStaticToDecl(Current);
227 
228   S.Diag(D->getCanonicalDecl()->getLocation(),
229          diag::note_internal_decl_declared_here)
230     << D;
231 }
232 
233 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
234   const FunctionDecl *First = Cur->getFirstDecl();
235 
236   // Suggest "static" on the function, if possible.
237   if (!hasAnyExplicitStorageClass(First)) {
238     SourceLocation DeclBegin = First->getSourceRange().getBegin();
239     Diag(DeclBegin, diag::note_convert_inline_to_static)
240       << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
241   }
242 }
243 
244 /// \brief Determine whether the use of this declaration is valid, and
245 /// emit any corresponding diagnostics.
246 ///
247 /// This routine diagnoses various problems with referencing
248 /// declarations that can occur when using a declaration. For example,
249 /// it might warn if a deprecated or unavailable declaration is being
250 /// used, or produce an error (and return true) if a C++0x deleted
251 /// function is being used.
252 ///
253 /// \returns true if there was an error (this declaration cannot be
254 /// referenced), false otherwise.
255 ///
256 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
257                              const ObjCInterfaceDecl *UnknownObjCClass) {
258   if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
259     // If there were any diagnostics suppressed by template argument deduction,
260     // emit them now.
261     SuppressedDiagnosticsMap::iterator
262       Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
263     if (Pos != SuppressedDiagnostics.end()) {
264       SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second;
265       for (unsigned I = 0, N = Suppressed.size(); I != N; ++I)
266         Diag(Suppressed[I].first, Suppressed[I].second);
267 
268       // Clear out the list of suppressed diagnostics, so that we don't emit
269       // them again for this specialization. However, we don't obsolete this
270       // entry from the table, because we want to avoid ever emitting these
271       // diagnostics again.
272       Suppressed.clear();
273     }
274 
275     // C++ [basic.start.main]p3:
276     //   The function 'main' shall not be used within a program.
277     if (cast<FunctionDecl>(D)->isMain())
278       Diag(Loc, diag::ext_main_used);
279   }
280 
281   // See if this is an auto-typed variable whose initializer we are parsing.
282   if (ParsingInitForAutoVars.count(D)) {
283     Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
284       << D->getDeclName();
285     return true;
286   }
287 
288   // See if this is a deleted function.
289   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
290     if (FD->isDeleted()) {
291       Diag(Loc, diag::err_deleted_function_use);
292       NoteDeletedFunction(FD);
293       return true;
294     }
295 
296     // If the function has a deduced return type, and we can't deduce it,
297     // then we can't use it either.
298     if (getLangOpts().CPlusPlus1y && FD->getReturnType()->isUndeducedType() &&
299         DeduceReturnType(FD, Loc))
300       return true;
301   }
302   DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass);
303 
304   DiagnoseUnusedOfDecl(*this, D, Loc);
305 
306   diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
307 
308   return false;
309 }
310 
311 /// \brief Retrieve the message suffix that should be added to a
312 /// diagnostic complaining about the given function being deleted or
313 /// unavailable.
314 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
315   std::string Message;
316   if (FD->getAvailability(&Message))
317     return ": " + Message;
318 
319   return std::string();
320 }
321 
322 /// DiagnoseSentinelCalls - This routine checks whether a call or
323 /// message-send is to a declaration with the sentinel attribute, and
324 /// if so, it checks that the requirements of the sentinel are
325 /// satisfied.
326 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
327                                  ArrayRef<Expr *> Args) {
328   const SentinelAttr *attr = D->getAttr<SentinelAttr>();
329   if (!attr)
330     return;
331 
332   // The number of formal parameters of the declaration.
333   unsigned numFormalParams;
334 
335   // The kind of declaration.  This is also an index into a %select in
336   // the diagnostic.
337   enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
338 
339   if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
340     numFormalParams = MD->param_size();
341     calleeType = CT_Method;
342   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
343     numFormalParams = FD->param_size();
344     calleeType = CT_Function;
345   } else if (isa<VarDecl>(D)) {
346     QualType type = cast<ValueDecl>(D)->getType();
347     const FunctionType *fn = 0;
348     if (const PointerType *ptr = type->getAs<PointerType>()) {
349       fn = ptr->getPointeeType()->getAs<FunctionType>();
350       if (!fn) return;
351       calleeType = CT_Function;
352     } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
353       fn = ptr->getPointeeType()->castAs<FunctionType>();
354       calleeType = CT_Block;
355     } else {
356       return;
357     }
358 
359     if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
360       numFormalParams = proto->getNumParams();
361     } else {
362       numFormalParams = 0;
363     }
364   } else {
365     return;
366   }
367 
368   // "nullPos" is the number of formal parameters at the end which
369   // effectively count as part of the variadic arguments.  This is
370   // useful if you would prefer to not have *any* formal parameters,
371   // but the language forces you to have at least one.
372   unsigned nullPos = attr->getNullPos();
373   assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
374   numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
375 
376   // The number of arguments which should follow the sentinel.
377   unsigned numArgsAfterSentinel = attr->getSentinel();
378 
379   // If there aren't enough arguments for all the formal parameters,
380   // the sentinel, and the args after the sentinel, complain.
381   if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
382     Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
383     Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
384     return;
385   }
386 
387   // Otherwise, find the sentinel expression.
388   Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
389   if (!sentinelExpr) return;
390   if (sentinelExpr->isValueDependent()) return;
391   if (Context.isSentinelNullExpr(sentinelExpr)) return;
392 
393   // Pick a reasonable string to insert.  Optimistically use 'nil' or
394   // 'NULL' if those are actually defined in the context.  Only use
395   // 'nil' for ObjC methods, where it's much more likely that the
396   // variadic arguments form a list of object pointers.
397   SourceLocation MissingNilLoc
398     = PP.getLocForEndOfToken(sentinelExpr->getLocEnd());
399   std::string NullValue;
400   if (calleeType == CT_Method &&
401       PP.getIdentifierInfo("nil")->hasMacroDefinition())
402     NullValue = "nil";
403   else if (PP.getIdentifierInfo("NULL")->hasMacroDefinition())
404     NullValue = "NULL";
405   else
406     NullValue = "(void*) 0";
407 
408   if (MissingNilLoc.isInvalid())
409     Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
410   else
411     Diag(MissingNilLoc, diag::warn_missing_sentinel)
412       << int(calleeType)
413       << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
414   Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
415 }
416 
417 SourceRange Sema::getExprRange(Expr *E) const {
418   return E ? E->getSourceRange() : SourceRange();
419 }
420 
421 //===----------------------------------------------------------------------===//
422 //  Standard Promotions and Conversions
423 //===----------------------------------------------------------------------===//
424 
425 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
426 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) {
427   // Handle any placeholder expressions which made it here.
428   if (E->getType()->isPlaceholderType()) {
429     ExprResult result = CheckPlaceholderExpr(E);
430     if (result.isInvalid()) return ExprError();
431     E = result.take();
432   }
433 
434   QualType Ty = E->getType();
435   assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
436 
437   if (Ty->isFunctionType())
438     E = ImpCastExprToType(E, Context.getPointerType(Ty),
439                           CK_FunctionToPointerDecay).take();
440   else if (Ty->isArrayType()) {
441     // In C90 mode, arrays only promote to pointers if the array expression is
442     // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
443     // type 'array of type' is converted to an expression that has type 'pointer
444     // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
445     // that has type 'array of type' ...".  The relevant change is "an lvalue"
446     // (C90) to "an expression" (C99).
447     //
448     // C++ 4.2p1:
449     // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
450     // T" can be converted to an rvalue of type "pointer to T".
451     //
452     if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
453       E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
454                             CK_ArrayToPointerDecay).take();
455   }
456   return Owned(E);
457 }
458 
459 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
460   // Check to see if we are dereferencing a null pointer.  If so,
461   // and if not volatile-qualified, this is undefined behavior that the
462   // optimizer will delete, so warn about it.  People sometimes try to use this
463   // to get a deterministic trap and are surprised by clang's behavior.  This
464   // only handles the pattern "*null", which is a very syntactic check.
465   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
466     if (UO->getOpcode() == UO_Deref &&
467         UO->getSubExpr()->IgnoreParenCasts()->
468           isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
469         !UO->getType().isVolatileQualified()) {
470     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
471                           S.PDiag(diag::warn_indirection_through_null)
472                             << UO->getSubExpr()->getSourceRange());
473     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
474                         S.PDiag(diag::note_indirection_through_null));
475   }
476 }
477 
478 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
479                                     SourceLocation AssignLoc,
480                                     const Expr* RHS) {
481   const ObjCIvarDecl *IV = OIRE->getDecl();
482   if (!IV)
483     return;
484 
485   DeclarationName MemberName = IV->getDeclName();
486   IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
487   if (!Member || !Member->isStr("isa"))
488     return;
489 
490   const Expr *Base = OIRE->getBase();
491   QualType BaseType = Base->getType();
492   if (OIRE->isArrow())
493     BaseType = BaseType->getPointeeType();
494   if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
495     if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
496       ObjCInterfaceDecl *ClassDeclared = 0;
497       ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
498       if (!ClassDeclared->getSuperClass()
499           && (*ClassDeclared->ivar_begin()) == IV) {
500         if (RHS) {
501           NamedDecl *ObjectSetClass =
502             S.LookupSingleName(S.TUScope,
503                                &S.Context.Idents.get("object_setClass"),
504                                SourceLocation(), S.LookupOrdinaryName);
505           if (ObjectSetClass) {
506             SourceLocation RHSLocEnd = S.PP.getLocForEndOfToken(RHS->getLocEnd());
507             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) <<
508             FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") <<
509             FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(),
510                                                      AssignLoc), ",") <<
511             FixItHint::CreateInsertion(RHSLocEnd, ")");
512           }
513           else
514             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
515         } else {
516           NamedDecl *ObjectGetClass =
517             S.LookupSingleName(S.TUScope,
518                                &S.Context.Idents.get("object_getClass"),
519                                SourceLocation(), S.LookupOrdinaryName);
520           if (ObjectGetClass)
521             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) <<
522             FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") <<
523             FixItHint::CreateReplacement(
524                                          SourceRange(OIRE->getOpLoc(),
525                                                      OIRE->getLocEnd()), ")");
526           else
527             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
528         }
529         S.Diag(IV->getLocation(), diag::note_ivar_decl);
530       }
531     }
532 }
533 
534 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
535   // Handle any placeholder expressions which made it here.
536   if (E->getType()->isPlaceholderType()) {
537     ExprResult result = CheckPlaceholderExpr(E);
538     if (result.isInvalid()) return ExprError();
539     E = result.take();
540   }
541 
542   // C++ [conv.lval]p1:
543   //   A glvalue of a non-function, non-array type T can be
544   //   converted to a prvalue.
545   if (!E->isGLValue()) return Owned(E);
546 
547   QualType T = E->getType();
548   assert(!T.isNull() && "r-value conversion on typeless expression?");
549 
550   // We don't want to throw lvalue-to-rvalue casts on top of
551   // expressions of certain types in C++.
552   if (getLangOpts().CPlusPlus &&
553       (E->getType() == Context.OverloadTy ||
554        T->isDependentType() ||
555        T->isRecordType()))
556     return Owned(E);
557 
558   // The C standard is actually really unclear on this point, and
559   // DR106 tells us what the result should be but not why.  It's
560   // generally best to say that void types just doesn't undergo
561   // lvalue-to-rvalue at all.  Note that expressions of unqualified
562   // 'void' type are never l-values, but qualified void can be.
563   if (T->isVoidType())
564     return Owned(E);
565 
566   // OpenCL usually rejects direct accesses to values of 'half' type.
567   if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16 &&
568       T->isHalfType()) {
569     Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
570       << 0 << T;
571     return ExprError();
572   }
573 
574   CheckForNullPointerDereference(*this, E);
575   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
576     NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
577                                      &Context.Idents.get("object_getClass"),
578                                      SourceLocation(), LookupOrdinaryName);
579     if (ObjectGetClass)
580       Diag(E->getExprLoc(), diag::warn_objc_isa_use) <<
581         FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") <<
582         FixItHint::CreateReplacement(
583                     SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
584     else
585       Diag(E->getExprLoc(), diag::warn_objc_isa_use);
586   }
587   else if (const ObjCIvarRefExpr *OIRE =
588             dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
589     DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/0);
590 
591   // C++ [conv.lval]p1:
592   //   [...] If T is a non-class type, the type of the prvalue is the
593   //   cv-unqualified version of T. Otherwise, the type of the
594   //   rvalue is T.
595   //
596   // C99 6.3.2.1p2:
597   //   If the lvalue has qualified type, the value has the unqualified
598   //   version of the type of the lvalue; otherwise, the value has the
599   //   type of the lvalue.
600   if (T.hasQualifiers())
601     T = T.getUnqualifiedType();
602 
603   UpdateMarkingForLValueToRValue(E);
604 
605   // Loading a __weak object implicitly retains the value, so we need a cleanup to
606   // balance that.
607   if (getLangOpts().ObjCAutoRefCount &&
608       E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
609     ExprNeedsCleanups = true;
610 
611   ExprResult Res = Owned(ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
612                                                   E, 0, VK_RValue));
613 
614   // C11 6.3.2.1p2:
615   //   ... if the lvalue has atomic type, the value has the non-atomic version
616   //   of the type of the lvalue ...
617   if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
618     T = Atomic->getValueType().getUnqualifiedType();
619     Res = Owned(ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic,
620                                          Res.get(), 0, VK_RValue));
621   }
622 
623   return Res;
624 }
625 
626 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) {
627   ExprResult Res = DefaultFunctionArrayConversion(E);
628   if (Res.isInvalid())
629     return ExprError();
630   Res = DefaultLvalueConversion(Res.take());
631   if (Res.isInvalid())
632     return ExprError();
633   return Res;
634 }
635 
636 
637 /// UsualUnaryConversions - Performs various conversions that are common to most
638 /// operators (C99 6.3). The conversions of array and function types are
639 /// sometimes suppressed. For example, the array->pointer conversion doesn't
640 /// apply if the array is an argument to the sizeof or address (&) operators.
641 /// In these instances, this routine should *not* be called.
642 ExprResult Sema::UsualUnaryConversions(Expr *E) {
643   // First, convert to an r-value.
644   ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
645   if (Res.isInvalid())
646     return ExprError();
647   E = Res.take();
648 
649   QualType Ty = E->getType();
650   assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
651 
652   // Half FP have to be promoted to float unless it is natively supported
653   if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
654     return ImpCastExprToType(Res.take(), Context.FloatTy, CK_FloatingCast);
655 
656   // Try to perform integral promotions if the object has a theoretically
657   // promotable type.
658   if (Ty->isIntegralOrUnscopedEnumerationType()) {
659     // C99 6.3.1.1p2:
660     //
661     //   The following may be used in an expression wherever an int or
662     //   unsigned int may be used:
663     //     - an object or expression with an integer type whose integer
664     //       conversion rank is less than or equal to the rank of int
665     //       and unsigned int.
666     //     - A bit-field of type _Bool, int, signed int, or unsigned int.
667     //
668     //   If an int can represent all values of the original type, the
669     //   value is converted to an int; otherwise, it is converted to an
670     //   unsigned int. These are called the integer promotions. All
671     //   other types are unchanged by the integer promotions.
672 
673     QualType PTy = Context.isPromotableBitField(E);
674     if (!PTy.isNull()) {
675       E = ImpCastExprToType(E, PTy, CK_IntegralCast).take();
676       return Owned(E);
677     }
678     if (Ty->isPromotableIntegerType()) {
679       QualType PT = Context.getPromotedIntegerType(Ty);
680       E = ImpCastExprToType(E, PT, CK_IntegralCast).take();
681       return Owned(E);
682     }
683   }
684   return Owned(E);
685 }
686 
687 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
688 /// do not have a prototype. Arguments that have type float or __fp16
689 /// are promoted to double. All other argument types are converted by
690 /// UsualUnaryConversions().
691 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
692   QualType Ty = E->getType();
693   assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
694 
695   ExprResult Res = UsualUnaryConversions(E);
696   if (Res.isInvalid())
697     return ExprError();
698   E = Res.take();
699 
700   // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to
701   // double.
702   const BuiltinType *BTy = Ty->getAs<BuiltinType>();
703   if (BTy && (BTy->getKind() == BuiltinType::Half ||
704               BTy->getKind() == BuiltinType::Float))
705     E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).take();
706 
707   // C++ performs lvalue-to-rvalue conversion as a default argument
708   // promotion, even on class types, but note:
709   //   C++11 [conv.lval]p2:
710   //     When an lvalue-to-rvalue conversion occurs in an unevaluated
711   //     operand or a subexpression thereof the value contained in the
712   //     referenced object is not accessed. Otherwise, if the glvalue
713   //     has a class type, the conversion copy-initializes a temporary
714   //     of type T from the glvalue and the result of the conversion
715   //     is a prvalue for the temporary.
716   // FIXME: add some way to gate this entire thing for correctness in
717   // potentially potentially evaluated contexts.
718   if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
719     ExprResult Temp = PerformCopyInitialization(
720                        InitializedEntity::InitializeTemporary(E->getType()),
721                                                 E->getExprLoc(),
722                                                 Owned(E));
723     if (Temp.isInvalid())
724       return ExprError();
725     E = Temp.get();
726   }
727 
728   return Owned(E);
729 }
730 
731 /// Determine the degree of POD-ness for an expression.
732 /// Incomplete types are considered POD, since this check can be performed
733 /// when we're in an unevaluated context.
734 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
735   if (Ty->isIncompleteType()) {
736     // C++11 [expr.call]p7:
737     //   After these conversions, if the argument does not have arithmetic,
738     //   enumeration, pointer, pointer to member, or class type, the program
739     //   is ill-formed.
740     //
741     // Since we've already performed array-to-pointer and function-to-pointer
742     // decay, the only such type in C++ is cv void. This also handles
743     // initializer lists as variadic arguments.
744     if (Ty->isVoidType())
745       return VAK_Invalid;
746 
747     if (Ty->isObjCObjectType())
748       return VAK_Invalid;
749     return VAK_Valid;
750   }
751 
752   if (Ty.isCXX98PODType(Context))
753     return VAK_Valid;
754 
755   // C++11 [expr.call]p7:
756   //   Passing a potentially-evaluated argument of class type (Clause 9)
757   //   having a non-trivial copy constructor, a non-trivial move constructor,
758   //   or a non-trivial destructor, with no corresponding parameter,
759   //   is conditionally-supported with implementation-defined semantics.
760   if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
761     if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
762       if (!Record->hasNonTrivialCopyConstructor() &&
763           !Record->hasNonTrivialMoveConstructor() &&
764           !Record->hasNonTrivialDestructor())
765         return VAK_ValidInCXX11;
766 
767   if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
768     return VAK_Valid;
769 
770   if (Ty->isObjCObjectType())
771     return VAK_Invalid;
772 
773   // FIXME: In C++11, these cases are conditionally-supported, meaning we're
774   // permitted to reject them. We should consider doing so.
775   return VAK_Undefined;
776 }
777 
778 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
779   // Don't allow one to pass an Objective-C interface to a vararg.
780   const QualType &Ty = E->getType();
781   VarArgKind VAK = isValidVarArgType(Ty);
782 
783   // Complain about passing non-POD types through varargs.
784   switch (VAK) {
785   case VAK_Valid:
786     break;
787 
788   case VAK_ValidInCXX11:
789     DiagRuntimeBehavior(
790         E->getLocStart(), 0,
791         PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
792           << E->getType() << CT);
793     break;
794 
795   case VAK_Undefined:
796     DiagRuntimeBehavior(
797         E->getLocStart(), 0,
798         PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
799           << getLangOpts().CPlusPlus11 << Ty << CT);
800     break;
801 
802   case VAK_Invalid:
803     if (Ty->isObjCObjectType())
804       DiagRuntimeBehavior(
805           E->getLocStart(), 0,
806           PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
807             << Ty << CT);
808     else
809       Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg)
810         << isa<InitListExpr>(E) << Ty << CT;
811     break;
812   }
813 }
814 
815 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
816 /// will create a trap if the resulting type is not a POD type.
817 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
818                                                   FunctionDecl *FDecl) {
819   if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
820     // Strip the unbridged-cast placeholder expression off, if applicable.
821     if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
822         (CT == VariadicMethod ||
823          (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
824       E = stripARCUnbridgedCast(E);
825 
826     // Otherwise, do normal placeholder checking.
827     } else {
828       ExprResult ExprRes = CheckPlaceholderExpr(E);
829       if (ExprRes.isInvalid())
830         return ExprError();
831       E = ExprRes.take();
832     }
833   }
834 
835   ExprResult ExprRes = DefaultArgumentPromotion(E);
836   if (ExprRes.isInvalid())
837     return ExprError();
838   E = ExprRes.take();
839 
840   // Diagnostics regarding non-POD argument types are
841   // emitted along with format string checking in Sema::CheckFunctionCall().
842   if (isValidVarArgType(E->getType()) == VAK_Undefined) {
843     // Turn this into a trap.
844     CXXScopeSpec SS;
845     SourceLocation TemplateKWLoc;
846     UnqualifiedId Name;
847     Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
848                        E->getLocStart());
849     ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
850                                           Name, true, false);
851     if (TrapFn.isInvalid())
852       return ExprError();
853 
854     ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(),
855                                     E->getLocStart(), None,
856                                     E->getLocEnd());
857     if (Call.isInvalid())
858       return ExprError();
859 
860     ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
861                                   Call.get(), E);
862     if (Comma.isInvalid())
863       return ExprError();
864     return Comma.get();
865   }
866 
867   if (!getLangOpts().CPlusPlus &&
868       RequireCompleteType(E->getExprLoc(), E->getType(),
869                           diag::err_call_incomplete_argument))
870     return ExprError();
871 
872   return Owned(E);
873 }
874 
875 /// \brief Converts an integer to complex float type.  Helper function of
876 /// UsualArithmeticConversions()
877 ///
878 /// \return false if the integer expression is an integer type and is
879 /// successfully converted to the complex type.
880 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
881                                                   ExprResult &ComplexExpr,
882                                                   QualType IntTy,
883                                                   QualType ComplexTy,
884                                                   bool SkipCast) {
885   if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
886   if (SkipCast) return false;
887   if (IntTy->isIntegerType()) {
888     QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
889     IntExpr = S.ImpCastExprToType(IntExpr.take(), fpTy, CK_IntegralToFloating);
890     IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
891                                   CK_FloatingRealToComplex);
892   } else {
893     assert(IntTy->isComplexIntegerType());
894     IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
895                                   CK_IntegralComplexToFloatingComplex);
896   }
897   return false;
898 }
899 
900 /// \brief Takes two complex float types and converts them to the same type.
901 /// Helper function of UsualArithmeticConversions()
902 static QualType
903 handleComplexFloatToComplexFloatConverstion(Sema &S, ExprResult &LHS,
904                                             ExprResult &RHS, QualType LHSType,
905                                             QualType RHSType,
906                                             bool IsCompAssign) {
907   int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
908 
909   if (order < 0) {
910     // _Complex float -> _Complex double
911     if (!IsCompAssign)
912       LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingComplexCast);
913     return RHSType;
914   }
915   if (order > 0)
916     // _Complex float -> _Complex double
917     RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingComplexCast);
918   return LHSType;
919 }
920 
921 /// \brief Converts otherExpr to complex float and promotes complexExpr if
922 /// necessary.  Helper function of UsualArithmeticConversions()
923 static QualType handleOtherComplexFloatConversion(Sema &S,
924                                                   ExprResult &ComplexExpr,
925                                                   ExprResult &OtherExpr,
926                                                   QualType ComplexTy,
927                                                   QualType OtherTy,
928                                                   bool ConvertComplexExpr,
929                                                   bool ConvertOtherExpr) {
930   int order = S.Context.getFloatingTypeOrder(ComplexTy, OtherTy);
931 
932   // If just the complexExpr is complex, the otherExpr needs to be converted,
933   // and the complexExpr might need to be promoted.
934   if (order > 0) { // complexExpr is wider
935     // float -> _Complex double
936     if (ConvertOtherExpr) {
937       QualType fp = cast<ComplexType>(ComplexTy)->getElementType();
938       OtherExpr = S.ImpCastExprToType(OtherExpr.take(), fp, CK_FloatingCast);
939       OtherExpr = S.ImpCastExprToType(OtherExpr.take(), ComplexTy,
940                                       CK_FloatingRealToComplex);
941     }
942     return ComplexTy;
943   }
944 
945   // otherTy is at least as wide.  Find its corresponding complex type.
946   QualType result = (order == 0 ? ComplexTy :
947                                   S.Context.getComplexType(OtherTy));
948 
949   // double -> _Complex double
950   if (ConvertOtherExpr)
951     OtherExpr = S.ImpCastExprToType(OtherExpr.take(), result,
952                                     CK_FloatingRealToComplex);
953 
954   // _Complex float -> _Complex double
955   if (ConvertComplexExpr && order < 0)
956     ComplexExpr = S.ImpCastExprToType(ComplexExpr.take(), result,
957                                       CK_FloatingComplexCast);
958 
959   return result;
960 }
961 
962 /// \brief Handle arithmetic conversion with complex types.  Helper function of
963 /// UsualArithmeticConversions()
964 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
965                                              ExprResult &RHS, QualType LHSType,
966                                              QualType RHSType,
967                                              bool IsCompAssign) {
968   // if we have an integer operand, the result is the complex type.
969   if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
970                                              /*skipCast*/false))
971     return LHSType;
972   if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
973                                              /*skipCast*/IsCompAssign))
974     return RHSType;
975 
976   // This handles complex/complex, complex/float, or float/complex.
977   // When both operands are complex, the shorter operand is converted to the
978   // type of the longer, and that is the type of the result. This corresponds
979   // to what is done when combining two real floating-point operands.
980   // The fun begins when size promotion occur across type domains.
981   // From H&S 6.3.4: When one operand is complex and the other is a real
982   // floating-point type, the less precise type is converted, within it's
983   // real or complex domain, to the precision of the other type. For example,
984   // when combining a "long double" with a "double _Complex", the
985   // "double _Complex" is promoted to "long double _Complex".
986 
987   bool LHSComplexFloat = LHSType->isComplexType();
988   bool RHSComplexFloat = RHSType->isComplexType();
989 
990   // If both are complex, just cast to the more precise type.
991   if (LHSComplexFloat && RHSComplexFloat)
992     return handleComplexFloatToComplexFloatConverstion(S, LHS, RHS,
993                                                        LHSType, RHSType,
994                                                        IsCompAssign);
995 
996   // If only one operand is complex, promote it if necessary and convert the
997   // other operand to complex.
998   if (LHSComplexFloat)
999     return handleOtherComplexFloatConversion(
1000         S, LHS, RHS, LHSType, RHSType, /*convertComplexExpr*/!IsCompAssign,
1001         /*convertOtherExpr*/ true);
1002 
1003   assert(RHSComplexFloat);
1004   return handleOtherComplexFloatConversion(
1005       S, RHS, LHS, RHSType, LHSType, /*convertComplexExpr*/true,
1006       /*convertOtherExpr*/ !IsCompAssign);
1007 }
1008 
1009 /// \brief Hande arithmetic conversion from integer to float.  Helper function
1010 /// of UsualArithmeticConversions()
1011 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1012                                            ExprResult &IntExpr,
1013                                            QualType FloatTy, QualType IntTy,
1014                                            bool ConvertFloat, bool ConvertInt) {
1015   if (IntTy->isIntegerType()) {
1016     if (ConvertInt)
1017       // Convert intExpr to the lhs floating point type.
1018       IntExpr = S.ImpCastExprToType(IntExpr.take(), FloatTy,
1019                                     CK_IntegralToFloating);
1020     return FloatTy;
1021   }
1022 
1023   // Convert both sides to the appropriate complex float.
1024   assert(IntTy->isComplexIntegerType());
1025   QualType result = S.Context.getComplexType(FloatTy);
1026 
1027   // _Complex int -> _Complex float
1028   if (ConvertInt)
1029     IntExpr = S.ImpCastExprToType(IntExpr.take(), result,
1030                                   CK_IntegralComplexToFloatingComplex);
1031 
1032   // float -> _Complex float
1033   if (ConvertFloat)
1034     FloatExpr = S.ImpCastExprToType(FloatExpr.take(), result,
1035                                     CK_FloatingRealToComplex);
1036 
1037   return result;
1038 }
1039 
1040 /// \brief Handle arithmethic conversion with floating point types.  Helper
1041 /// function of UsualArithmeticConversions()
1042 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1043                                       ExprResult &RHS, QualType LHSType,
1044                                       QualType RHSType, bool IsCompAssign) {
1045   bool LHSFloat = LHSType->isRealFloatingType();
1046   bool RHSFloat = RHSType->isRealFloatingType();
1047 
1048   // If we have two real floating types, convert the smaller operand
1049   // to the bigger result.
1050   if (LHSFloat && RHSFloat) {
1051     int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1052     if (order > 0) {
1053       RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingCast);
1054       return LHSType;
1055     }
1056 
1057     assert(order < 0 && "illegal float comparison");
1058     if (!IsCompAssign)
1059       LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingCast);
1060     return RHSType;
1061   }
1062 
1063   if (LHSFloat)
1064     return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1065                                       /*convertFloat=*/!IsCompAssign,
1066                                       /*convertInt=*/ true);
1067   assert(RHSFloat);
1068   return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1069                                     /*convertInt=*/ true,
1070                                     /*convertFloat=*/!IsCompAssign);
1071 }
1072 
1073 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1074 
1075 namespace {
1076 /// These helper callbacks are placed in an anonymous namespace to
1077 /// permit their use as function template parameters.
1078 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1079   return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1080 }
1081 
1082 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1083   return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1084                              CK_IntegralComplexCast);
1085 }
1086 }
1087 
1088 /// \brief Handle integer arithmetic conversions.  Helper function of
1089 /// UsualArithmeticConversions()
1090 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1091 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1092                                         ExprResult &RHS, QualType LHSType,
1093                                         QualType RHSType, bool IsCompAssign) {
1094   // The rules for this case are in C99 6.3.1.8
1095   int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1096   bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1097   bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1098   if (LHSSigned == RHSSigned) {
1099     // Same signedness; use the higher-ranked type
1100     if (order >= 0) {
1101       RHS = (*doRHSCast)(S, RHS.take(), LHSType);
1102       return LHSType;
1103     } else if (!IsCompAssign)
1104       LHS = (*doLHSCast)(S, LHS.take(), RHSType);
1105     return RHSType;
1106   } else if (order != (LHSSigned ? 1 : -1)) {
1107     // The unsigned type has greater than or equal rank to the
1108     // signed type, so use the unsigned type
1109     if (RHSSigned) {
1110       RHS = (*doRHSCast)(S, RHS.take(), LHSType);
1111       return LHSType;
1112     } else if (!IsCompAssign)
1113       LHS = (*doLHSCast)(S, LHS.take(), RHSType);
1114     return RHSType;
1115   } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1116     // The two types are different widths; if we are here, that
1117     // means the signed type is larger than the unsigned type, so
1118     // use the signed type.
1119     if (LHSSigned) {
1120       RHS = (*doRHSCast)(S, RHS.take(), LHSType);
1121       return LHSType;
1122     } else if (!IsCompAssign)
1123       LHS = (*doLHSCast)(S, LHS.take(), RHSType);
1124     return RHSType;
1125   } else {
1126     // The signed type is higher-ranked than the unsigned type,
1127     // but isn't actually any bigger (like unsigned int and long
1128     // on most 32-bit systems).  Use the unsigned type corresponding
1129     // to the signed type.
1130     QualType result =
1131       S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1132     RHS = (*doRHSCast)(S, RHS.take(), result);
1133     if (!IsCompAssign)
1134       LHS = (*doLHSCast)(S, LHS.take(), result);
1135     return result;
1136   }
1137 }
1138 
1139 /// \brief Handle conversions with GCC complex int extension.  Helper function
1140 /// of UsualArithmeticConversions()
1141 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1142                                            ExprResult &RHS, QualType LHSType,
1143                                            QualType RHSType,
1144                                            bool IsCompAssign) {
1145   const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1146   const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1147 
1148   if (LHSComplexInt && RHSComplexInt) {
1149     QualType LHSEltType = LHSComplexInt->getElementType();
1150     QualType RHSEltType = RHSComplexInt->getElementType();
1151     QualType ScalarType =
1152       handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1153         (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1154 
1155     return S.Context.getComplexType(ScalarType);
1156   }
1157 
1158   if (LHSComplexInt) {
1159     QualType LHSEltType = LHSComplexInt->getElementType();
1160     QualType ScalarType =
1161       handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1162         (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1163     QualType ComplexType = S.Context.getComplexType(ScalarType);
1164     RHS = S.ImpCastExprToType(RHS.take(), ComplexType,
1165                               CK_IntegralRealToComplex);
1166 
1167     return ComplexType;
1168   }
1169 
1170   assert(RHSComplexInt);
1171 
1172   QualType RHSEltType = RHSComplexInt->getElementType();
1173   QualType ScalarType =
1174     handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1175       (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1176   QualType ComplexType = S.Context.getComplexType(ScalarType);
1177 
1178   if (!IsCompAssign)
1179     LHS = S.ImpCastExprToType(LHS.take(), ComplexType,
1180                               CK_IntegralRealToComplex);
1181   return ComplexType;
1182 }
1183 
1184 /// UsualArithmeticConversions - Performs various conversions that are common to
1185 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1186 /// routine returns the first non-arithmetic type found. The client is
1187 /// responsible for emitting appropriate error diagnostics.
1188 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1189                                           bool IsCompAssign) {
1190   if (!IsCompAssign) {
1191     LHS = UsualUnaryConversions(LHS.take());
1192     if (LHS.isInvalid())
1193       return QualType();
1194   }
1195 
1196   RHS = UsualUnaryConversions(RHS.take());
1197   if (RHS.isInvalid())
1198     return QualType();
1199 
1200   // For conversion purposes, we ignore any qualifiers.
1201   // For example, "const float" and "float" are equivalent.
1202   QualType LHSType =
1203     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1204   QualType RHSType =
1205     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1206 
1207   // For conversion purposes, we ignore any atomic qualifier on the LHS.
1208   if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1209     LHSType = AtomicLHS->getValueType();
1210 
1211   // If both types are identical, no conversion is needed.
1212   if (LHSType == RHSType)
1213     return LHSType;
1214 
1215   // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1216   // The caller can deal with this (e.g. pointer + int).
1217   if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1218     return QualType();
1219 
1220   // Apply unary and bitfield promotions to the LHS's type.
1221   QualType LHSUnpromotedType = LHSType;
1222   if (LHSType->isPromotableIntegerType())
1223     LHSType = Context.getPromotedIntegerType(LHSType);
1224   QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1225   if (!LHSBitfieldPromoteTy.isNull())
1226     LHSType = LHSBitfieldPromoteTy;
1227   if (LHSType != LHSUnpromotedType && !IsCompAssign)
1228     LHS = ImpCastExprToType(LHS.take(), LHSType, CK_IntegralCast);
1229 
1230   // If both types are identical, no conversion is needed.
1231   if (LHSType == RHSType)
1232     return LHSType;
1233 
1234   // At this point, we have two different arithmetic types.
1235 
1236   // Handle complex types first (C99 6.3.1.8p1).
1237   if (LHSType->isComplexType() || RHSType->isComplexType())
1238     return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1239                                         IsCompAssign);
1240 
1241   // Now handle "real" floating types (i.e. float, double, long double).
1242   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1243     return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1244                                  IsCompAssign);
1245 
1246   // Handle GCC complex int extension.
1247   if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1248     return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1249                                       IsCompAssign);
1250 
1251   // Finally, we have two differing integer types.
1252   return handleIntegerConversion<doIntegralCast, doIntegralCast>
1253            (*this, LHS, RHS, LHSType, RHSType, IsCompAssign);
1254 }
1255 
1256 
1257 //===----------------------------------------------------------------------===//
1258 //  Semantic Analysis for various Expression Types
1259 //===----------------------------------------------------------------------===//
1260 
1261 
1262 ExprResult
1263 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1264                                 SourceLocation DefaultLoc,
1265                                 SourceLocation RParenLoc,
1266                                 Expr *ControllingExpr,
1267                                 ArrayRef<ParsedType> ArgTypes,
1268                                 ArrayRef<Expr *> ArgExprs) {
1269   unsigned NumAssocs = ArgTypes.size();
1270   assert(NumAssocs == ArgExprs.size());
1271 
1272   TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1273   for (unsigned i = 0; i < NumAssocs; ++i) {
1274     if (ArgTypes[i])
1275       (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1276     else
1277       Types[i] = 0;
1278   }
1279 
1280   ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1281                                              ControllingExpr,
1282                                              llvm::makeArrayRef(Types, NumAssocs),
1283                                              ArgExprs);
1284   delete [] Types;
1285   return ER;
1286 }
1287 
1288 ExprResult
1289 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1290                                  SourceLocation DefaultLoc,
1291                                  SourceLocation RParenLoc,
1292                                  Expr *ControllingExpr,
1293                                  ArrayRef<TypeSourceInfo *> Types,
1294                                  ArrayRef<Expr *> Exprs) {
1295   unsigned NumAssocs = Types.size();
1296   assert(NumAssocs == Exprs.size());
1297   if (ControllingExpr->getType()->isPlaceholderType()) {
1298     ExprResult result = CheckPlaceholderExpr(ControllingExpr);
1299     if (result.isInvalid()) return ExprError();
1300     ControllingExpr = result.take();
1301   }
1302 
1303   bool TypeErrorFound = false,
1304        IsResultDependent = ControllingExpr->isTypeDependent(),
1305        ContainsUnexpandedParameterPack
1306          = ControllingExpr->containsUnexpandedParameterPack();
1307 
1308   for (unsigned i = 0; i < NumAssocs; ++i) {
1309     if (Exprs[i]->containsUnexpandedParameterPack())
1310       ContainsUnexpandedParameterPack = true;
1311 
1312     if (Types[i]) {
1313       if (Types[i]->getType()->containsUnexpandedParameterPack())
1314         ContainsUnexpandedParameterPack = true;
1315 
1316       if (Types[i]->getType()->isDependentType()) {
1317         IsResultDependent = true;
1318       } else {
1319         // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1320         // complete object type other than a variably modified type."
1321         unsigned D = 0;
1322         if (Types[i]->getType()->isIncompleteType())
1323           D = diag::err_assoc_type_incomplete;
1324         else if (!Types[i]->getType()->isObjectType())
1325           D = diag::err_assoc_type_nonobject;
1326         else if (Types[i]->getType()->isVariablyModifiedType())
1327           D = diag::err_assoc_type_variably_modified;
1328 
1329         if (D != 0) {
1330           Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1331             << Types[i]->getTypeLoc().getSourceRange()
1332             << Types[i]->getType();
1333           TypeErrorFound = true;
1334         }
1335 
1336         // C11 6.5.1.1p2 "No two generic associations in the same generic
1337         // selection shall specify compatible types."
1338         for (unsigned j = i+1; j < NumAssocs; ++j)
1339           if (Types[j] && !Types[j]->getType()->isDependentType() &&
1340               Context.typesAreCompatible(Types[i]->getType(),
1341                                          Types[j]->getType())) {
1342             Diag(Types[j]->getTypeLoc().getBeginLoc(),
1343                  diag::err_assoc_compatible_types)
1344               << Types[j]->getTypeLoc().getSourceRange()
1345               << Types[j]->getType()
1346               << Types[i]->getType();
1347             Diag(Types[i]->getTypeLoc().getBeginLoc(),
1348                  diag::note_compat_assoc)
1349               << Types[i]->getTypeLoc().getSourceRange()
1350               << Types[i]->getType();
1351             TypeErrorFound = true;
1352           }
1353       }
1354     }
1355   }
1356   if (TypeErrorFound)
1357     return ExprError();
1358 
1359   // If we determined that the generic selection is result-dependent, don't
1360   // try to compute the result expression.
1361   if (IsResultDependent)
1362     return Owned(new (Context) GenericSelectionExpr(
1363                    Context, KeyLoc, ControllingExpr,
1364                    Types, Exprs,
1365                    DefaultLoc, RParenLoc, ContainsUnexpandedParameterPack));
1366 
1367   SmallVector<unsigned, 1> CompatIndices;
1368   unsigned DefaultIndex = -1U;
1369   for (unsigned i = 0; i < NumAssocs; ++i) {
1370     if (!Types[i])
1371       DefaultIndex = i;
1372     else if (Context.typesAreCompatible(ControllingExpr->getType(),
1373                                         Types[i]->getType()))
1374       CompatIndices.push_back(i);
1375   }
1376 
1377   // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1378   // type compatible with at most one of the types named in its generic
1379   // association list."
1380   if (CompatIndices.size() > 1) {
1381     // We strip parens here because the controlling expression is typically
1382     // parenthesized in macro definitions.
1383     ControllingExpr = ControllingExpr->IgnoreParens();
1384     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1385       << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1386       << (unsigned) CompatIndices.size();
1387     for (SmallVectorImpl<unsigned>::iterator I = CompatIndices.begin(),
1388          E = CompatIndices.end(); I != E; ++I) {
1389       Diag(Types[*I]->getTypeLoc().getBeginLoc(),
1390            diag::note_compat_assoc)
1391         << Types[*I]->getTypeLoc().getSourceRange()
1392         << Types[*I]->getType();
1393     }
1394     return ExprError();
1395   }
1396 
1397   // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1398   // its controlling expression shall have type compatible with exactly one of
1399   // the types named in its generic association list."
1400   if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1401     // We strip parens here because the controlling expression is typically
1402     // parenthesized in macro definitions.
1403     ControllingExpr = ControllingExpr->IgnoreParens();
1404     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1405       << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1406     return ExprError();
1407   }
1408 
1409   // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1410   // type name that is compatible with the type of the controlling expression,
1411   // then the result expression of the generic selection is the expression
1412   // in that generic association. Otherwise, the result expression of the
1413   // generic selection is the expression in the default generic association."
1414   unsigned ResultIndex =
1415     CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1416 
1417   return Owned(new (Context) GenericSelectionExpr(
1418                  Context, KeyLoc, ControllingExpr,
1419                  Types, Exprs,
1420                  DefaultLoc, RParenLoc, ContainsUnexpandedParameterPack,
1421                  ResultIndex));
1422 }
1423 
1424 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1425 /// location of the token and the offset of the ud-suffix within it.
1426 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1427                                      unsigned Offset) {
1428   return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1429                                         S.getLangOpts());
1430 }
1431 
1432 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1433 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1434 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1435                                                  IdentifierInfo *UDSuffix,
1436                                                  SourceLocation UDSuffixLoc,
1437                                                  ArrayRef<Expr*> Args,
1438                                                  SourceLocation LitEndLoc) {
1439   assert(Args.size() <= 2 && "too many arguments for literal operator");
1440 
1441   QualType ArgTy[2];
1442   for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1443     ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1444     if (ArgTy[ArgIdx]->isArrayType())
1445       ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1446   }
1447 
1448   DeclarationName OpName =
1449     S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1450   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1451   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1452 
1453   LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1454   if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1455                               /*AllowRaw*/false, /*AllowTemplate*/false,
1456                               /*AllowStringTemplate*/false) == Sema::LOLR_Error)
1457     return ExprError();
1458 
1459   return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1460 }
1461 
1462 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1463 /// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
1464 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1465 /// multiple tokens.  However, the common case is that StringToks points to one
1466 /// string.
1467 ///
1468 ExprResult
1469 Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks,
1470                          Scope *UDLScope) {
1471   assert(NumStringToks && "Must have at least one string!");
1472 
1473   StringLiteralParser Literal(StringToks, NumStringToks, PP);
1474   if (Literal.hadError)
1475     return ExprError();
1476 
1477   SmallVector<SourceLocation, 4> StringTokLocs;
1478   for (unsigned i = 0; i != NumStringToks; ++i)
1479     StringTokLocs.push_back(StringToks[i].getLocation());
1480 
1481   QualType CharTy = Context.CharTy;
1482   StringLiteral::StringKind Kind = StringLiteral::Ascii;
1483   if (Literal.isWide()) {
1484     CharTy = Context.getWideCharType();
1485     Kind = StringLiteral::Wide;
1486   } else if (Literal.isUTF8()) {
1487     Kind = StringLiteral::UTF8;
1488   } else if (Literal.isUTF16()) {
1489     CharTy = Context.Char16Ty;
1490     Kind = StringLiteral::UTF16;
1491   } else if (Literal.isUTF32()) {
1492     CharTy = Context.Char32Ty;
1493     Kind = StringLiteral::UTF32;
1494   } else if (Literal.isPascal()) {
1495     CharTy = Context.UnsignedCharTy;
1496   }
1497 
1498   QualType CharTyConst = CharTy;
1499   // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
1500   if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
1501     CharTyConst.addConst();
1502 
1503   // Get an array type for the string, according to C99 6.4.5.  This includes
1504   // the nul terminator character as well as the string length for pascal
1505   // strings.
1506   QualType StrTy = Context.getConstantArrayType(CharTyConst,
1507                                  llvm::APInt(32, Literal.GetNumStringChars()+1),
1508                                  ArrayType::Normal, 0);
1509 
1510   // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
1511   if (getLangOpts().OpenCL) {
1512     StrTy = Context.getAddrSpaceQualType(StrTy, LangAS::opencl_constant);
1513   }
1514 
1515   // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1516   StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1517                                              Kind, Literal.Pascal, StrTy,
1518                                              &StringTokLocs[0],
1519                                              StringTokLocs.size());
1520   if (Literal.getUDSuffix().empty())
1521     return Owned(Lit);
1522 
1523   // We're building a user-defined literal.
1524   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1525   SourceLocation UDSuffixLoc =
1526     getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1527                    Literal.getUDSuffixOffset());
1528 
1529   // Make sure we're allowed user-defined literals here.
1530   if (!UDLScope)
1531     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1532 
1533   // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1534   //   operator "" X (str, len)
1535   QualType SizeType = Context.getSizeType();
1536 
1537   DeclarationName OpName =
1538     Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1539   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1540   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1541 
1542   QualType ArgTy[] = {
1543     Context.getArrayDecayedType(StrTy), SizeType
1544   };
1545 
1546   LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1547   switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1548                                 /*AllowRaw*/false, /*AllowTemplate*/false,
1549                                 /*AllowStringTemplate*/true)) {
1550 
1551   case LOLR_Cooked: {
1552     llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1553     IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1554                                                     StringTokLocs[0]);
1555     Expr *Args[] = { Lit, LenArg };
1556 
1557     return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1558   }
1559 
1560   case LOLR_StringTemplate: {
1561     TemplateArgumentListInfo ExplicitArgs;
1562 
1563     unsigned CharBits = Context.getIntWidth(CharTy);
1564     bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1565     llvm::APSInt Value(CharBits, CharIsUnsigned);
1566 
1567     TemplateArgument TypeArg(CharTy);
1568     TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1569     ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1570 
1571     for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1572       Value = Lit->getCodeUnit(I);
1573       TemplateArgument Arg(Context, Value, CharTy);
1574       TemplateArgumentLocInfo ArgInfo;
1575       ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1576     }
1577     return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1578                                     &ExplicitArgs);
1579   }
1580   case LOLR_Raw:
1581   case LOLR_Template:
1582     llvm_unreachable("unexpected literal operator lookup result");
1583   case LOLR_Error:
1584     return ExprError();
1585   }
1586   llvm_unreachable("unexpected literal operator lookup result");
1587 }
1588 
1589 ExprResult
1590 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1591                        SourceLocation Loc,
1592                        const CXXScopeSpec *SS) {
1593   DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1594   return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1595 }
1596 
1597 /// BuildDeclRefExpr - Build an expression that references a
1598 /// declaration that does not require a closure capture.
1599 ExprResult
1600 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1601                        const DeclarationNameInfo &NameInfo,
1602                        const CXXScopeSpec *SS, NamedDecl *FoundD,
1603                        const TemplateArgumentListInfo *TemplateArgs) {
1604   if (getLangOpts().CUDA)
1605     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
1606       if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) {
1607         CUDAFunctionTarget CallerTarget = IdentifyCUDATarget(Caller),
1608                            CalleeTarget = IdentifyCUDATarget(Callee);
1609         if (CheckCUDATarget(CallerTarget, CalleeTarget)) {
1610           Diag(NameInfo.getLoc(), diag::err_ref_bad_target)
1611             << CalleeTarget << D->getIdentifier() << CallerTarget;
1612           Diag(D->getLocation(), diag::note_previous_decl)
1613             << D->getIdentifier();
1614           return ExprError();
1615         }
1616       }
1617 
1618   bool refersToEnclosingScope =
1619     (CurContext != D->getDeclContext() &&
1620      D->getDeclContext()->isFunctionOrMethod()) ||
1621     (isa<VarDecl>(D) &&
1622      cast<VarDecl>(D)->isInitCapture());
1623 
1624   DeclRefExpr *E;
1625   if (isa<VarTemplateSpecializationDecl>(D)) {
1626     VarTemplateSpecializationDecl *VarSpec =
1627         cast<VarTemplateSpecializationDecl>(D);
1628 
1629     E = DeclRefExpr::Create(
1630         Context,
1631         SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(),
1632         VarSpec->getTemplateKeywordLoc(), D, refersToEnclosingScope,
1633         NameInfo.getLoc(), Ty, VK, FoundD, TemplateArgs);
1634   } else {
1635     assert(!TemplateArgs && "No template arguments for non-variable"
1636                             " template specialization references");
1637     E = DeclRefExpr::Create(
1638         Context,
1639         SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(),
1640         SourceLocation(), D, refersToEnclosingScope, NameInfo, Ty, VK, FoundD);
1641   }
1642 
1643   MarkDeclRefReferenced(E);
1644 
1645   if (getLangOpts().ObjCARCWeak && isa<VarDecl>(D) &&
1646       Ty.getObjCLifetime() == Qualifiers::OCL_Weak) {
1647     DiagnosticsEngine::Level Level =
1648       Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
1649                                E->getLocStart());
1650     if (Level != DiagnosticsEngine::Ignored)
1651       recordUseOfEvaluatedWeak(E);
1652   }
1653 
1654   // Just in case we're building an illegal pointer-to-member.
1655   FieldDecl *FD = dyn_cast<FieldDecl>(D);
1656   if (FD && FD->isBitField())
1657     E->setObjectKind(OK_BitField);
1658 
1659   return Owned(E);
1660 }
1661 
1662 /// Decomposes the given name into a DeclarationNameInfo, its location, and
1663 /// possibly a list of template arguments.
1664 ///
1665 /// If this produces template arguments, it is permitted to call
1666 /// DecomposeTemplateName.
1667 ///
1668 /// This actually loses a lot of source location information for
1669 /// non-standard name kinds; we should consider preserving that in
1670 /// some way.
1671 void
1672 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1673                              TemplateArgumentListInfo &Buffer,
1674                              DeclarationNameInfo &NameInfo,
1675                              const TemplateArgumentListInfo *&TemplateArgs) {
1676   if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1677     Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1678     Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1679 
1680     ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
1681                                        Id.TemplateId->NumArgs);
1682     translateTemplateArguments(TemplateArgsPtr, Buffer);
1683 
1684     TemplateName TName = Id.TemplateId->Template.get();
1685     SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1686     NameInfo = Context.getNameForTemplate(TName, TNameLoc);
1687     TemplateArgs = &Buffer;
1688   } else {
1689     NameInfo = GetNameFromUnqualifiedId(Id);
1690     TemplateArgs = 0;
1691   }
1692 }
1693 
1694 /// Diagnose an empty lookup.
1695 ///
1696 /// \return false if new lookup candidates were found
1697 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1698                                CorrectionCandidateCallback &CCC,
1699                                TemplateArgumentListInfo *ExplicitTemplateArgs,
1700                                ArrayRef<Expr *> Args) {
1701   DeclarationName Name = R.getLookupName();
1702 
1703   unsigned diagnostic = diag::err_undeclared_var_use;
1704   unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
1705   if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1706       Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
1707       Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
1708     diagnostic = diag::err_undeclared_use;
1709     diagnostic_suggest = diag::err_undeclared_use_suggest;
1710   }
1711 
1712   // If the original lookup was an unqualified lookup, fake an
1713   // unqualified lookup.  This is useful when (for example) the
1714   // original lookup would not have found something because it was a
1715   // dependent name.
1716   DeclContext *DC = (SS.isEmpty() && !CallsUndergoingInstantiation.empty())
1717     ? CurContext : 0;
1718   while (DC) {
1719     if (isa<CXXRecordDecl>(DC)) {
1720       LookupQualifiedName(R, DC);
1721 
1722       if (!R.empty()) {
1723         // Don't give errors about ambiguities in this lookup.
1724         R.suppressDiagnostics();
1725 
1726         // During a default argument instantiation the CurContext points
1727         // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1728         // function parameter list, hence add an explicit check.
1729         bool isDefaultArgument = !ActiveTemplateInstantiations.empty() &&
1730                               ActiveTemplateInstantiations.back().Kind ==
1731             ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
1732         CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1733         bool isInstance = CurMethod &&
1734                           CurMethod->isInstance() &&
1735                           DC == CurMethod->getParent() && !isDefaultArgument;
1736 
1737 
1738         // Give a code modification hint to insert 'this->'.
1739         // TODO: fixit for inserting 'Base<T>::' in the other cases.
1740         // Actually quite difficult!
1741         if (getLangOpts().MSVCCompat)
1742           diagnostic = diag::warn_found_via_dependent_bases_lookup;
1743         if (isInstance) {
1744           Diag(R.getNameLoc(), diagnostic) << Name
1745             << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1746           UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1747               CallsUndergoingInstantiation.back()->getCallee());
1748 
1749           CXXMethodDecl *DepMethod;
1750           if (CurMethod->isDependentContext())
1751             DepMethod = CurMethod;
1752           else if (CurMethod->getTemplatedKind() ==
1753               FunctionDecl::TK_FunctionTemplateSpecialization)
1754             DepMethod = cast<CXXMethodDecl>(CurMethod->getPrimaryTemplate()->
1755                 getInstantiatedFromMemberTemplate()->getTemplatedDecl());
1756           else
1757             DepMethod = cast<CXXMethodDecl>(
1758                 CurMethod->getInstantiatedFromMemberFunction());
1759           assert(DepMethod && "No template pattern found");
1760 
1761           QualType DepThisType = DepMethod->getThisType(Context);
1762           CheckCXXThisCapture(R.getNameLoc());
1763           CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1764                                      R.getNameLoc(), DepThisType, false);
1765           TemplateArgumentListInfo TList;
1766           if (ULE->hasExplicitTemplateArgs())
1767             ULE->copyTemplateArgumentsInto(TList);
1768 
1769           CXXScopeSpec SS;
1770           SS.Adopt(ULE->getQualifierLoc());
1771           CXXDependentScopeMemberExpr *DepExpr =
1772               CXXDependentScopeMemberExpr::Create(
1773                   Context, DepThis, DepThisType, true, SourceLocation(),
1774                   SS.getWithLocInContext(Context),
1775                   ULE->getTemplateKeywordLoc(), 0,
1776                   R.getLookupNameInfo(),
1777                   ULE->hasExplicitTemplateArgs() ? &TList : 0);
1778           CallsUndergoingInstantiation.back()->setCallee(DepExpr);
1779         } else {
1780           Diag(R.getNameLoc(), diagnostic) << Name;
1781         }
1782 
1783         // Do we really want to note all of these?
1784         for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1785           Diag((*I)->getLocation(), diag::note_dependent_var_use);
1786 
1787         // Return true if we are inside a default argument instantiation
1788         // and the found name refers to an instance member function, otherwise
1789         // the function calling DiagnoseEmptyLookup will try to create an
1790         // implicit member call and this is wrong for default argument.
1791         if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1792           Diag(R.getNameLoc(), diag::err_member_call_without_object);
1793           return true;
1794         }
1795 
1796         // Tell the callee to try to recover.
1797         return false;
1798       }
1799 
1800       R.clear();
1801     }
1802 
1803     // In Microsoft mode, if we are performing lookup from within a friend
1804     // function definition declared at class scope then we must set
1805     // DC to the lexical parent to be able to search into the parent
1806     // class.
1807     if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) &&
1808         cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1809         DC->getLexicalParent()->isRecord())
1810       DC = DC->getLexicalParent();
1811     else
1812       DC = DC->getParent();
1813   }
1814 
1815   // We didn't find anything, so try to correct for a typo.
1816   TypoCorrection Corrected;
1817   if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
1818                                     S, &SS, CCC))) {
1819     std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1820     bool DroppedSpecifier =
1821         Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
1822     R.setLookupName(Corrected.getCorrection());
1823 
1824     bool AcceptableWithRecovery = false;
1825     bool AcceptableWithoutRecovery = false;
1826     NamedDecl *ND = Corrected.getCorrectionDecl();
1827     if (ND) {
1828       if (Corrected.isOverloaded()) {
1829         OverloadCandidateSet OCS(R.getNameLoc());
1830         OverloadCandidateSet::iterator Best;
1831         for (TypoCorrection::decl_iterator CD = Corrected.begin(),
1832                                         CDEnd = Corrected.end();
1833              CD != CDEnd; ++CD) {
1834           if (FunctionTemplateDecl *FTD =
1835                    dyn_cast<FunctionTemplateDecl>(*CD))
1836             AddTemplateOverloadCandidate(
1837                 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
1838                 Args, OCS);
1839           else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
1840             if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1841               AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
1842                                    Args, OCS);
1843         }
1844         switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1845         case OR_Success:
1846           ND = Best->Function;
1847           Corrected.setCorrectionDecl(ND);
1848           break;
1849         default:
1850           // FIXME: Arbitrarily pick the first declaration for the note.
1851           Corrected.setCorrectionDecl(ND);
1852           break;
1853         }
1854       }
1855       R.addDecl(ND);
1856 
1857       AcceptableWithRecovery =
1858           isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND);
1859       // FIXME: If we ended up with a typo for a type name or
1860       // Objective-C class name, we're in trouble because the parser
1861       // is in the wrong place to recover. Suggest the typo
1862       // correction, but don't make it a fix-it since we're not going
1863       // to recover well anyway.
1864       AcceptableWithoutRecovery =
1865           isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
1866     } else {
1867       // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
1868       // because we aren't able to recover.
1869       AcceptableWithoutRecovery = true;
1870     }
1871 
1872     if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
1873       unsigned NoteID = (Corrected.getCorrectionDecl() &&
1874                          isa<ImplicitParamDecl>(Corrected.getCorrectionDecl()))
1875                             ? diag::note_implicit_param_decl
1876                             : diag::note_previous_decl;
1877       if (SS.isEmpty())
1878         diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
1879                      PDiag(NoteID), AcceptableWithRecovery);
1880       else
1881         diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
1882                                   << Name << computeDeclContext(SS, false)
1883                                   << DroppedSpecifier << SS.getRange(),
1884                      PDiag(NoteID), AcceptableWithRecovery);
1885 
1886       // Tell the callee whether to try to recover.
1887       return !AcceptableWithRecovery;
1888     }
1889   }
1890   R.clear();
1891 
1892   // Emit a special diagnostic for failed member lookups.
1893   // FIXME: computing the declaration context might fail here (?)
1894   if (!SS.isEmpty()) {
1895     Diag(R.getNameLoc(), diag::err_no_member)
1896       << Name << computeDeclContext(SS, false)
1897       << SS.getRange();
1898     return true;
1899   }
1900 
1901   // Give up, we can't recover.
1902   Diag(R.getNameLoc(), diagnostic) << Name;
1903   return true;
1904 }
1905 
1906 ExprResult Sema::ActOnIdExpression(Scope *S,
1907                                    CXXScopeSpec &SS,
1908                                    SourceLocation TemplateKWLoc,
1909                                    UnqualifiedId &Id,
1910                                    bool HasTrailingLParen,
1911                                    bool IsAddressOfOperand,
1912                                    CorrectionCandidateCallback *CCC,
1913                                    bool IsInlineAsmIdentifier) {
1914   assert(!(IsAddressOfOperand && HasTrailingLParen) &&
1915          "cannot be direct & operand and have a trailing lparen");
1916   if (SS.isInvalid())
1917     return ExprError();
1918 
1919   TemplateArgumentListInfo TemplateArgsBuffer;
1920 
1921   // Decompose the UnqualifiedId into the following data.
1922   DeclarationNameInfo NameInfo;
1923   const TemplateArgumentListInfo *TemplateArgs;
1924   DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
1925 
1926   DeclarationName Name = NameInfo.getName();
1927   IdentifierInfo *II = Name.getAsIdentifierInfo();
1928   SourceLocation NameLoc = NameInfo.getLoc();
1929 
1930   // C++ [temp.dep.expr]p3:
1931   //   An id-expression is type-dependent if it contains:
1932   //     -- an identifier that was declared with a dependent type,
1933   //        (note: handled after lookup)
1934   //     -- a template-id that is dependent,
1935   //        (note: handled in BuildTemplateIdExpr)
1936   //     -- a conversion-function-id that specifies a dependent type,
1937   //     -- a nested-name-specifier that contains a class-name that
1938   //        names a dependent type.
1939   // Determine whether this is a member of an unknown specialization;
1940   // we need to handle these differently.
1941   bool DependentID = false;
1942   if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1943       Name.getCXXNameType()->isDependentType()) {
1944     DependentID = true;
1945   } else if (SS.isSet()) {
1946     if (DeclContext *DC = computeDeclContext(SS, false)) {
1947       if (RequireCompleteDeclContext(SS, DC))
1948         return ExprError();
1949     } else {
1950       DependentID = true;
1951     }
1952   }
1953 
1954   if (DependentID)
1955     return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1956                                       IsAddressOfOperand, TemplateArgs);
1957 
1958   // Perform the required lookup.
1959   LookupResult R(*this, NameInfo,
1960                  (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
1961                   ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
1962   if (TemplateArgs) {
1963     // Lookup the template name again to correctly establish the context in
1964     // which it was found. This is really unfortunate as we already did the
1965     // lookup to determine that it was a template name in the first place. If
1966     // this becomes a performance hit, we can work harder to preserve those
1967     // results until we get here but it's likely not worth it.
1968     bool MemberOfUnknownSpecialization;
1969     LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1970                        MemberOfUnknownSpecialization);
1971 
1972     if (MemberOfUnknownSpecialization ||
1973         (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
1974       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1975                                         IsAddressOfOperand, TemplateArgs);
1976   } else {
1977     bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
1978     LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
1979 
1980     // If the result might be in a dependent base class, this is a dependent
1981     // id-expression.
1982     if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
1983       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1984                                         IsAddressOfOperand, TemplateArgs);
1985 
1986     // If this reference is in an Objective-C method, then we need to do
1987     // some special Objective-C lookup, too.
1988     if (IvarLookupFollowUp) {
1989       ExprResult E(LookupInObjCMethod(R, S, II, true));
1990       if (E.isInvalid())
1991         return ExprError();
1992 
1993       if (Expr *Ex = E.takeAs<Expr>())
1994         return Owned(Ex);
1995     }
1996   }
1997 
1998   if (R.isAmbiguous())
1999     return ExprError();
2000 
2001   // Determine whether this name might be a candidate for
2002   // argument-dependent lookup.
2003   bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2004 
2005   if (R.empty() && !ADL) {
2006 
2007     // Otherwise, this could be an implicitly declared function reference (legal
2008     // in C90, extension in C99, forbidden in C++).
2009     if (HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2010       NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2011       if (D) R.addDecl(D);
2012     }
2013 
2014     // If this name wasn't predeclared and if this is not a function
2015     // call, diagnose the problem.
2016     if (R.empty()) {
2017       // In Microsoft mode, if we are inside a template class member function
2018       // whose parent class has dependent base classes, and we can't resolve
2019       // an identifier, then assume the identifier is a member of a dependent
2020       // base class.  The goal is to postpone name lookup to instantiation time
2021       // to be able to search into the type dependent base classes.
2022       // FIXME: If we want 100% compatibility with MSVC, we will have delay all
2023       // unqualified name lookup.  Any name lookup during template parsing means
2024       // clang might find something that MSVC doesn't.  For now, we only handle
2025       // the common case of members of a dependent base class.
2026       if (getLangOpts().MSVCCompat) {
2027         CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext);
2028         if (MD && MD->isInstance() && MD->getParent()->hasAnyDependentBases()) {
2029           assert(SS.isEmpty() && "qualifiers should be already handled");
2030           QualType ThisType = MD->getThisType(Context);
2031           // Since the 'this' expression is synthesized, we don't need to
2032           // perform the double-lookup check.
2033           NamedDecl *FirstQualifierInScope = 0;
2034           return Owned(CXXDependentScopeMemberExpr::Create(
2035               Context, /*This=*/0, ThisType, /*IsArrow=*/true,
2036               /*Op=*/SourceLocation(), SS.getWithLocInContext(Context),
2037               TemplateKWLoc, FirstQualifierInScope, NameInfo, TemplateArgs));
2038         }
2039       }
2040 
2041       // Don't diagnose an empty lookup for inline assmebly.
2042       if (IsInlineAsmIdentifier)
2043         return ExprError();
2044 
2045       CorrectionCandidateCallback DefaultValidator;
2046       if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator))
2047         return ExprError();
2048 
2049       assert(!R.empty() &&
2050              "DiagnoseEmptyLookup returned false but added no results");
2051 
2052       // If we found an Objective-C instance variable, let
2053       // LookupInObjCMethod build the appropriate expression to
2054       // reference the ivar.
2055       if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2056         R.clear();
2057         ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2058         // In a hopelessly buggy code, Objective-C instance variable
2059         // lookup fails and no expression will be built to reference it.
2060         if (!E.isInvalid() && !E.get())
2061           return ExprError();
2062         return E;
2063       }
2064     }
2065   }
2066 
2067   // This is guaranteed from this point on.
2068   assert(!R.empty() || ADL);
2069 
2070   // Check whether this might be a C++ implicit instance member access.
2071   // C++ [class.mfct.non-static]p3:
2072   //   When an id-expression that is not part of a class member access
2073   //   syntax and not used to form a pointer to member is used in the
2074   //   body of a non-static member function of class X, if name lookup
2075   //   resolves the name in the id-expression to a non-static non-type
2076   //   member of some class C, the id-expression is transformed into a
2077   //   class member access expression using (*this) as the
2078   //   postfix-expression to the left of the . operator.
2079   //
2080   // But we don't actually need to do this for '&' operands if R
2081   // resolved to a function or overloaded function set, because the
2082   // expression is ill-formed if it actually works out to be a
2083   // non-static member function:
2084   //
2085   // C++ [expr.ref]p4:
2086   //   Otherwise, if E1.E2 refers to a non-static member function. . .
2087   //   [t]he expression can be used only as the left-hand operand of a
2088   //   member function call.
2089   //
2090   // There are other safeguards against such uses, but it's important
2091   // to get this right here so that we don't end up making a
2092   // spuriously dependent expression if we're inside a dependent
2093   // instance method.
2094   if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2095     bool MightBeImplicitMember;
2096     if (!IsAddressOfOperand)
2097       MightBeImplicitMember = true;
2098     else if (!SS.isEmpty())
2099       MightBeImplicitMember = false;
2100     else if (R.isOverloadedResult())
2101       MightBeImplicitMember = false;
2102     else if (R.isUnresolvableResult())
2103       MightBeImplicitMember = true;
2104     else
2105       MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2106                               isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2107                               isa<MSPropertyDecl>(R.getFoundDecl());
2108 
2109     if (MightBeImplicitMember)
2110       return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2111                                              R, TemplateArgs);
2112   }
2113 
2114   if (TemplateArgs || TemplateKWLoc.isValid()) {
2115 
2116     // In C++1y, if this is a variable template id, then check it
2117     // in BuildTemplateIdExpr().
2118     // The single lookup result must be a variable template declaration.
2119     if (Id.getKind() == UnqualifiedId::IK_TemplateId && Id.TemplateId &&
2120         Id.TemplateId->Kind == TNK_Var_template) {
2121       assert(R.getAsSingle<VarTemplateDecl>() &&
2122              "There should only be one declaration found.");
2123     }
2124 
2125     return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2126   }
2127 
2128   return BuildDeclarationNameExpr(SS, R, ADL);
2129 }
2130 
2131 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2132 /// declaration name, generally during template instantiation.
2133 /// There's a large number of things which don't need to be done along
2134 /// this path.
2135 ExprResult
2136 Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
2137                                         const DeclarationNameInfo &NameInfo,
2138                                         bool IsAddressOfOperand) {
2139   DeclContext *DC = computeDeclContext(SS, false);
2140   if (!DC)
2141     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2142                                      NameInfo, /*TemplateArgs=*/0);
2143 
2144   if (RequireCompleteDeclContext(SS, DC))
2145     return ExprError();
2146 
2147   LookupResult R(*this, NameInfo, LookupOrdinaryName);
2148   LookupQualifiedName(R, DC);
2149 
2150   if (R.isAmbiguous())
2151     return ExprError();
2152 
2153   if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2154     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2155                                      NameInfo, /*TemplateArgs=*/0);
2156 
2157   if (R.empty()) {
2158     Diag(NameInfo.getLoc(), diag::err_no_member)
2159       << NameInfo.getName() << DC << SS.getRange();
2160     return ExprError();
2161   }
2162 
2163   // Defend against this resolving to an implicit member access. We usually
2164   // won't get here if this might be a legitimate a class member (we end up in
2165   // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2166   // a pointer-to-member or in an unevaluated context in C++11.
2167   if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2168     return BuildPossibleImplicitMemberExpr(SS,
2169                                            /*TemplateKWLoc=*/SourceLocation(),
2170                                            R, /*TemplateArgs=*/0);
2171 
2172   return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2173 }
2174 
2175 /// LookupInObjCMethod - The parser has read a name in, and Sema has
2176 /// detected that we're currently inside an ObjC method.  Perform some
2177 /// additional lookup.
2178 ///
2179 /// Ideally, most of this would be done by lookup, but there's
2180 /// actually quite a lot of extra work involved.
2181 ///
2182 /// Returns a null sentinel to indicate trivial success.
2183 ExprResult
2184 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2185                          IdentifierInfo *II, bool AllowBuiltinCreation) {
2186   SourceLocation Loc = Lookup.getNameLoc();
2187   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2188 
2189   // Check for error condition which is already reported.
2190   if (!CurMethod)
2191     return ExprError();
2192 
2193   // There are two cases to handle here.  1) scoped lookup could have failed,
2194   // in which case we should look for an ivar.  2) scoped lookup could have
2195   // found a decl, but that decl is outside the current instance method (i.e.
2196   // a global variable).  In these two cases, we do a lookup for an ivar with
2197   // this name, if the lookup sucedes, we replace it our current decl.
2198 
2199   // If we're in a class method, we don't normally want to look for
2200   // ivars.  But if we don't find anything else, and there's an
2201   // ivar, that's an error.
2202   bool IsClassMethod = CurMethod->isClassMethod();
2203 
2204   bool LookForIvars;
2205   if (Lookup.empty())
2206     LookForIvars = true;
2207   else if (IsClassMethod)
2208     LookForIvars = false;
2209   else
2210     LookForIvars = (Lookup.isSingleResult() &&
2211                     Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2212   ObjCInterfaceDecl *IFace = 0;
2213   if (LookForIvars) {
2214     IFace = CurMethod->getClassInterface();
2215     ObjCInterfaceDecl *ClassDeclared;
2216     ObjCIvarDecl *IV = 0;
2217     if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2218       // Diagnose using an ivar in a class method.
2219       if (IsClassMethod)
2220         return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
2221                          << IV->getDeclName());
2222 
2223       // If we're referencing an invalid decl, just return this as a silent
2224       // error node.  The error diagnostic was already emitted on the decl.
2225       if (IV->isInvalidDecl())
2226         return ExprError();
2227 
2228       // Check if referencing a field with __attribute__((deprecated)).
2229       if (DiagnoseUseOfDecl(IV, Loc))
2230         return ExprError();
2231 
2232       // Diagnose the use of an ivar outside of the declaring class.
2233       if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2234           !declaresSameEntity(ClassDeclared, IFace) &&
2235           !getLangOpts().DebuggerSupport)
2236         Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
2237 
2238       // FIXME: This should use a new expr for a direct reference, don't
2239       // turn this into Self->ivar, just return a BareIVarExpr or something.
2240       IdentifierInfo &II = Context.Idents.get("self");
2241       UnqualifiedId SelfName;
2242       SelfName.setIdentifier(&II, SourceLocation());
2243       SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
2244       CXXScopeSpec SelfScopeSpec;
2245       SourceLocation TemplateKWLoc;
2246       ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
2247                                               SelfName, false, false);
2248       if (SelfExpr.isInvalid())
2249         return ExprError();
2250 
2251       SelfExpr = DefaultLvalueConversion(SelfExpr.take());
2252       if (SelfExpr.isInvalid())
2253         return ExprError();
2254 
2255       MarkAnyDeclReferenced(Loc, IV, true);
2256 
2257       ObjCMethodFamily MF = CurMethod->getMethodFamily();
2258       if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2259           !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2260         Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2261 
2262       ObjCIvarRefExpr *Result = new (Context) ObjCIvarRefExpr(IV, IV->getType(),
2263                                                               Loc, IV->getLocation(),
2264                                                               SelfExpr.take(),
2265                                                               true, true);
2266 
2267       if (getLangOpts().ObjCAutoRefCount) {
2268         if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2269           DiagnosticsEngine::Level Level =
2270             Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, Loc);
2271           if (Level != DiagnosticsEngine::Ignored)
2272             recordUseOfEvaluatedWeak(Result);
2273         }
2274         if (CurContext->isClosure())
2275           Diag(Loc, diag::warn_implicitly_retains_self)
2276             << FixItHint::CreateInsertion(Loc, "self->");
2277       }
2278 
2279       return Owned(Result);
2280     }
2281   } else if (CurMethod->isInstanceMethod()) {
2282     // We should warn if a local variable hides an ivar.
2283     if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2284       ObjCInterfaceDecl *ClassDeclared;
2285       if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2286         if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2287             declaresSameEntity(IFace, ClassDeclared))
2288           Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2289       }
2290     }
2291   } else if (Lookup.isSingleResult() &&
2292              Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2293     // If accessing a stand-alone ivar in a class method, this is an error.
2294     if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
2295       return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
2296                        << IV->getDeclName());
2297   }
2298 
2299   if (Lookup.empty() && II && AllowBuiltinCreation) {
2300     // FIXME. Consolidate this with similar code in LookupName.
2301     if (unsigned BuiltinID = II->getBuiltinID()) {
2302       if (!(getLangOpts().CPlusPlus &&
2303             Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2304         NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2305                                            S, Lookup.isForRedeclaration(),
2306                                            Lookup.getNameLoc());
2307         if (D) Lookup.addDecl(D);
2308       }
2309     }
2310   }
2311   // Sentinel value saying that we didn't do anything special.
2312   return Owned((Expr*) 0);
2313 }
2314 
2315 /// \brief Cast a base object to a member's actual type.
2316 ///
2317 /// Logically this happens in three phases:
2318 ///
2319 /// * First we cast from the base type to the naming class.
2320 ///   The naming class is the class into which we were looking
2321 ///   when we found the member;  it's the qualifier type if a
2322 ///   qualifier was provided, and otherwise it's the base type.
2323 ///
2324 /// * Next we cast from the naming class to the declaring class.
2325 ///   If the member we found was brought into a class's scope by
2326 ///   a using declaration, this is that class;  otherwise it's
2327 ///   the class declaring the member.
2328 ///
2329 /// * Finally we cast from the declaring class to the "true"
2330 ///   declaring class of the member.  This conversion does not
2331 ///   obey access control.
2332 ExprResult
2333 Sema::PerformObjectMemberConversion(Expr *From,
2334                                     NestedNameSpecifier *Qualifier,
2335                                     NamedDecl *FoundDecl,
2336                                     NamedDecl *Member) {
2337   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2338   if (!RD)
2339     return Owned(From);
2340 
2341   QualType DestRecordType;
2342   QualType DestType;
2343   QualType FromRecordType;
2344   QualType FromType = From->getType();
2345   bool PointerConversions = false;
2346   if (isa<FieldDecl>(Member)) {
2347     DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2348 
2349     if (FromType->getAs<PointerType>()) {
2350       DestType = Context.getPointerType(DestRecordType);
2351       FromRecordType = FromType->getPointeeType();
2352       PointerConversions = true;
2353     } else {
2354       DestType = DestRecordType;
2355       FromRecordType = FromType;
2356     }
2357   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2358     if (Method->isStatic())
2359       return Owned(From);
2360 
2361     DestType = Method->getThisType(Context);
2362     DestRecordType = DestType->getPointeeType();
2363 
2364     if (FromType->getAs<PointerType>()) {
2365       FromRecordType = FromType->getPointeeType();
2366       PointerConversions = true;
2367     } else {
2368       FromRecordType = FromType;
2369       DestType = DestRecordType;
2370     }
2371   } else {
2372     // No conversion necessary.
2373     return Owned(From);
2374   }
2375 
2376   if (DestType->isDependentType() || FromType->isDependentType())
2377     return Owned(From);
2378 
2379   // If the unqualified types are the same, no conversion is necessary.
2380   if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2381     return Owned(From);
2382 
2383   SourceRange FromRange = From->getSourceRange();
2384   SourceLocation FromLoc = FromRange.getBegin();
2385 
2386   ExprValueKind VK = From->getValueKind();
2387 
2388   // C++ [class.member.lookup]p8:
2389   //   [...] Ambiguities can often be resolved by qualifying a name with its
2390   //   class name.
2391   //
2392   // If the member was a qualified name and the qualified referred to a
2393   // specific base subobject type, we'll cast to that intermediate type
2394   // first and then to the object in which the member is declared. That allows
2395   // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2396   //
2397   //   class Base { public: int x; };
2398   //   class Derived1 : public Base { };
2399   //   class Derived2 : public Base { };
2400   //   class VeryDerived : public Derived1, public Derived2 { void f(); };
2401   //
2402   //   void VeryDerived::f() {
2403   //     x = 17; // error: ambiguous base subobjects
2404   //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
2405   //   }
2406   if (Qualifier && Qualifier->getAsType()) {
2407     QualType QType = QualType(Qualifier->getAsType(), 0);
2408     assert(QType->isRecordType() && "lookup done with non-record type");
2409 
2410     QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2411 
2412     // In C++98, the qualifier type doesn't actually have to be a base
2413     // type of the object type, in which case we just ignore it.
2414     // Otherwise build the appropriate casts.
2415     if (IsDerivedFrom(FromRecordType, QRecordType)) {
2416       CXXCastPath BasePath;
2417       if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2418                                        FromLoc, FromRange, &BasePath))
2419         return ExprError();
2420 
2421       if (PointerConversions)
2422         QType = Context.getPointerType(QType);
2423       From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2424                                VK, &BasePath).take();
2425 
2426       FromType = QType;
2427       FromRecordType = QRecordType;
2428 
2429       // If the qualifier type was the same as the destination type,
2430       // we're done.
2431       if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2432         return Owned(From);
2433     }
2434   }
2435 
2436   bool IgnoreAccess = false;
2437 
2438   // If we actually found the member through a using declaration, cast
2439   // down to the using declaration's type.
2440   //
2441   // Pointer equality is fine here because only one declaration of a
2442   // class ever has member declarations.
2443   if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2444     assert(isa<UsingShadowDecl>(FoundDecl));
2445     QualType URecordType = Context.getTypeDeclType(
2446                            cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2447 
2448     // We only need to do this if the naming-class to declaring-class
2449     // conversion is non-trivial.
2450     if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2451       assert(IsDerivedFrom(FromRecordType, URecordType));
2452       CXXCastPath BasePath;
2453       if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2454                                        FromLoc, FromRange, &BasePath))
2455         return ExprError();
2456 
2457       QualType UType = URecordType;
2458       if (PointerConversions)
2459         UType = Context.getPointerType(UType);
2460       From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2461                                VK, &BasePath).take();
2462       FromType = UType;
2463       FromRecordType = URecordType;
2464     }
2465 
2466     // We don't do access control for the conversion from the
2467     // declaring class to the true declaring class.
2468     IgnoreAccess = true;
2469   }
2470 
2471   CXXCastPath BasePath;
2472   if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2473                                    FromLoc, FromRange, &BasePath,
2474                                    IgnoreAccess))
2475     return ExprError();
2476 
2477   return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2478                            VK, &BasePath);
2479 }
2480 
2481 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2482                                       const LookupResult &R,
2483                                       bool HasTrailingLParen) {
2484   // Only when used directly as the postfix-expression of a call.
2485   if (!HasTrailingLParen)
2486     return false;
2487 
2488   // Never if a scope specifier was provided.
2489   if (SS.isSet())
2490     return false;
2491 
2492   // Only in C++ or ObjC++.
2493   if (!getLangOpts().CPlusPlus)
2494     return false;
2495 
2496   // Turn off ADL when we find certain kinds of declarations during
2497   // normal lookup:
2498   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2499     NamedDecl *D = *I;
2500 
2501     // C++0x [basic.lookup.argdep]p3:
2502     //     -- a declaration of a class member
2503     // Since using decls preserve this property, we check this on the
2504     // original decl.
2505     if (D->isCXXClassMember())
2506       return false;
2507 
2508     // C++0x [basic.lookup.argdep]p3:
2509     //     -- a block-scope function declaration that is not a
2510     //        using-declaration
2511     // NOTE: we also trigger this for function templates (in fact, we
2512     // don't check the decl type at all, since all other decl types
2513     // turn off ADL anyway).
2514     if (isa<UsingShadowDecl>(D))
2515       D = cast<UsingShadowDecl>(D)->getTargetDecl();
2516     else if (D->getLexicalDeclContext()->isFunctionOrMethod())
2517       return false;
2518 
2519     // C++0x [basic.lookup.argdep]p3:
2520     //     -- a declaration that is neither a function or a function
2521     //        template
2522     // And also for builtin functions.
2523     if (isa<FunctionDecl>(D)) {
2524       FunctionDecl *FDecl = cast<FunctionDecl>(D);
2525 
2526       // But also builtin functions.
2527       if (FDecl->getBuiltinID() && FDecl->isImplicit())
2528         return false;
2529     } else if (!isa<FunctionTemplateDecl>(D))
2530       return false;
2531   }
2532 
2533   return true;
2534 }
2535 
2536 
2537 /// Diagnoses obvious problems with the use of the given declaration
2538 /// as an expression.  This is only actually called for lookups that
2539 /// were not overloaded, and it doesn't promise that the declaration
2540 /// will in fact be used.
2541 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2542   if (isa<TypedefNameDecl>(D)) {
2543     S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2544     return true;
2545   }
2546 
2547   if (isa<ObjCInterfaceDecl>(D)) {
2548     S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2549     return true;
2550   }
2551 
2552   if (isa<NamespaceDecl>(D)) {
2553     S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2554     return true;
2555   }
2556 
2557   return false;
2558 }
2559 
2560 ExprResult
2561 Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2562                                LookupResult &R,
2563                                bool NeedsADL) {
2564   // If this is a single, fully-resolved result and we don't need ADL,
2565   // just build an ordinary singleton decl ref.
2566   if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
2567     return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
2568                                     R.getRepresentativeDecl());
2569 
2570   // We only need to check the declaration if there's exactly one
2571   // result, because in the overloaded case the results can only be
2572   // functions and function templates.
2573   if (R.isSingleResult() &&
2574       CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
2575     return ExprError();
2576 
2577   // Otherwise, just build an unresolved lookup expression.  Suppress
2578   // any lookup-related diagnostics; we'll hash these out later, when
2579   // we've picked a target.
2580   R.suppressDiagnostics();
2581 
2582   UnresolvedLookupExpr *ULE
2583     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2584                                    SS.getWithLocInContext(Context),
2585                                    R.getLookupNameInfo(),
2586                                    NeedsADL, R.isOverloadedResult(),
2587                                    R.begin(), R.end());
2588 
2589   return Owned(ULE);
2590 }
2591 
2592 /// \brief Complete semantic analysis for a reference to the given declaration.
2593 ExprResult Sema::BuildDeclarationNameExpr(
2594     const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
2595     NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs) {
2596   assert(D && "Cannot refer to a NULL declaration");
2597   assert(!isa<FunctionTemplateDecl>(D) &&
2598          "Cannot refer unambiguously to a function template");
2599 
2600   SourceLocation Loc = NameInfo.getLoc();
2601   if (CheckDeclInExpr(*this, Loc, D))
2602     return ExprError();
2603 
2604   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2605     // Specifically diagnose references to class templates that are missing
2606     // a template argument list.
2607     Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0)
2608                                            << Template << SS.getRange();
2609     Diag(Template->getLocation(), diag::note_template_decl_here);
2610     return ExprError();
2611   }
2612 
2613   // Make sure that we're referring to a value.
2614   ValueDecl *VD = dyn_cast<ValueDecl>(D);
2615   if (!VD) {
2616     Diag(Loc, diag::err_ref_non_value)
2617       << D << SS.getRange();
2618     Diag(D->getLocation(), diag::note_declared_at);
2619     return ExprError();
2620   }
2621 
2622   // Check whether this declaration can be used. Note that we suppress
2623   // this check when we're going to perform argument-dependent lookup
2624   // on this function name, because this might not be the function
2625   // that overload resolution actually selects.
2626   if (DiagnoseUseOfDecl(VD, Loc))
2627     return ExprError();
2628 
2629   // Only create DeclRefExpr's for valid Decl's.
2630   if (VD->isInvalidDecl())
2631     return ExprError();
2632 
2633   // Handle members of anonymous structs and unions.  If we got here,
2634   // and the reference is to a class member indirect field, then this
2635   // must be the subject of a pointer-to-member expression.
2636   if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2637     if (!indirectField->isCXXClassMember())
2638       return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2639                                                       indirectField);
2640 
2641   {
2642     QualType type = VD->getType();
2643     ExprValueKind valueKind = VK_RValue;
2644 
2645     switch (D->getKind()) {
2646     // Ignore all the non-ValueDecl kinds.
2647 #define ABSTRACT_DECL(kind)
2648 #define VALUE(type, base)
2649 #define DECL(type, base) \
2650     case Decl::type:
2651 #include "clang/AST/DeclNodes.inc"
2652       llvm_unreachable("invalid value decl kind");
2653 
2654     // These shouldn't make it here.
2655     case Decl::ObjCAtDefsField:
2656     case Decl::ObjCIvar:
2657       llvm_unreachable("forming non-member reference to ivar?");
2658 
2659     // Enum constants are always r-values and never references.
2660     // Unresolved using declarations are dependent.
2661     case Decl::EnumConstant:
2662     case Decl::UnresolvedUsingValue:
2663       valueKind = VK_RValue;
2664       break;
2665 
2666     // Fields and indirect fields that got here must be for
2667     // pointer-to-member expressions; we just call them l-values for
2668     // internal consistency, because this subexpression doesn't really
2669     // exist in the high-level semantics.
2670     case Decl::Field:
2671     case Decl::IndirectField:
2672       assert(getLangOpts().CPlusPlus &&
2673              "building reference to field in C?");
2674 
2675       // These can't have reference type in well-formed programs, but
2676       // for internal consistency we do this anyway.
2677       type = type.getNonReferenceType();
2678       valueKind = VK_LValue;
2679       break;
2680 
2681     // Non-type template parameters are either l-values or r-values
2682     // depending on the type.
2683     case Decl::NonTypeTemplateParm: {
2684       if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2685         type = reftype->getPointeeType();
2686         valueKind = VK_LValue; // even if the parameter is an r-value reference
2687         break;
2688       }
2689 
2690       // For non-references, we need to strip qualifiers just in case
2691       // the template parameter was declared as 'const int' or whatever.
2692       valueKind = VK_RValue;
2693       type = type.getUnqualifiedType();
2694       break;
2695     }
2696 
2697     case Decl::Var:
2698     case Decl::VarTemplateSpecialization:
2699     case Decl::VarTemplatePartialSpecialization:
2700       // In C, "extern void blah;" is valid and is an r-value.
2701       if (!getLangOpts().CPlusPlus &&
2702           !type.hasQualifiers() &&
2703           type->isVoidType()) {
2704         valueKind = VK_RValue;
2705         break;
2706       }
2707       // fallthrough
2708 
2709     case Decl::ImplicitParam:
2710     case Decl::ParmVar: {
2711       // These are always l-values.
2712       valueKind = VK_LValue;
2713       type = type.getNonReferenceType();
2714 
2715       // FIXME: Does the addition of const really only apply in
2716       // potentially-evaluated contexts? Since the variable isn't actually
2717       // captured in an unevaluated context, it seems that the answer is no.
2718       if (!isUnevaluatedContext()) {
2719         QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
2720         if (!CapturedType.isNull())
2721           type = CapturedType;
2722       }
2723 
2724       break;
2725     }
2726 
2727     case Decl::Function: {
2728       if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
2729         if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
2730           type = Context.BuiltinFnTy;
2731           valueKind = VK_RValue;
2732           break;
2733         }
2734       }
2735 
2736       const FunctionType *fty = type->castAs<FunctionType>();
2737 
2738       // If we're referring to a function with an __unknown_anytype
2739       // result type, make the entire expression __unknown_anytype.
2740       if (fty->getReturnType() == Context.UnknownAnyTy) {
2741         type = Context.UnknownAnyTy;
2742         valueKind = VK_RValue;
2743         break;
2744       }
2745 
2746       // Functions are l-values in C++.
2747       if (getLangOpts().CPlusPlus) {
2748         valueKind = VK_LValue;
2749         break;
2750       }
2751 
2752       // C99 DR 316 says that, if a function type comes from a
2753       // function definition (without a prototype), that type is only
2754       // used for checking compatibility. Therefore, when referencing
2755       // the function, we pretend that we don't have the full function
2756       // type.
2757       if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2758           isa<FunctionProtoType>(fty))
2759         type = Context.getFunctionNoProtoType(fty->getReturnType(),
2760                                               fty->getExtInfo());
2761 
2762       // Functions are r-values in C.
2763       valueKind = VK_RValue;
2764       break;
2765     }
2766 
2767     case Decl::MSProperty:
2768       valueKind = VK_LValue;
2769       break;
2770 
2771     case Decl::CXXMethod:
2772       // If we're referring to a method with an __unknown_anytype
2773       // result type, make the entire expression __unknown_anytype.
2774       // This should only be possible with a type written directly.
2775       if (const FunctionProtoType *proto
2776             = dyn_cast<FunctionProtoType>(VD->getType()))
2777         if (proto->getReturnType() == Context.UnknownAnyTy) {
2778           type = Context.UnknownAnyTy;
2779           valueKind = VK_RValue;
2780           break;
2781         }
2782 
2783       // C++ methods are l-values if static, r-values if non-static.
2784       if (cast<CXXMethodDecl>(VD)->isStatic()) {
2785         valueKind = VK_LValue;
2786         break;
2787       }
2788       // fallthrough
2789 
2790     case Decl::CXXConversion:
2791     case Decl::CXXDestructor:
2792     case Decl::CXXConstructor:
2793       valueKind = VK_RValue;
2794       break;
2795     }
2796 
2797     return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
2798                             TemplateArgs);
2799   }
2800 }
2801 
2802 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
2803                                      PredefinedExpr::IdentType IT) {
2804   // Pick the current block, lambda, captured statement or function.
2805   Decl *currentDecl = 0;
2806   if (const BlockScopeInfo *BSI = getCurBlock())
2807     currentDecl = BSI->TheDecl;
2808   else if (const LambdaScopeInfo *LSI = getCurLambda())
2809     currentDecl = LSI->CallOperator;
2810   else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
2811     currentDecl = CSI->TheCapturedDecl;
2812   else
2813     currentDecl = getCurFunctionOrMethodDecl();
2814 
2815   if (!currentDecl) {
2816     Diag(Loc, diag::ext_predef_outside_function);
2817     currentDecl = Context.getTranslationUnitDecl();
2818   }
2819 
2820   QualType ResTy;
2821   if (cast<DeclContext>(currentDecl)->isDependentContext())
2822     ResTy = Context.DependentTy;
2823   else {
2824     // Pre-defined identifiers are of type char[x], where x is the length of
2825     // the string.
2826     unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
2827 
2828     llvm::APInt LengthI(32, Length + 1);
2829     if (IT == PredefinedExpr::LFunction)
2830       ResTy = Context.WideCharTy.withConst();
2831     else
2832       ResTy = Context.CharTy.withConst();
2833     ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2834   }
2835 
2836   return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
2837 }
2838 
2839 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
2840   PredefinedExpr::IdentType IT;
2841 
2842   switch (Kind) {
2843   default: llvm_unreachable("Unknown simple primary expr!");
2844   case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2845   case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
2846   case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS]
2847   case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break;
2848   case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
2849   }
2850 
2851   return BuildPredefinedExpr(Loc, IT);
2852 }
2853 
2854 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
2855   SmallString<16> CharBuffer;
2856   bool Invalid = false;
2857   StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
2858   if (Invalid)
2859     return ExprError();
2860 
2861   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
2862                             PP, Tok.getKind());
2863   if (Literal.hadError())
2864     return ExprError();
2865 
2866   QualType Ty;
2867   if (Literal.isWide())
2868     Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
2869   else if (Literal.isUTF16())
2870     Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
2871   else if (Literal.isUTF32())
2872     Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
2873   else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
2874     Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
2875   else
2876     Ty = Context.CharTy;  // 'x' -> char in C++
2877 
2878   CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
2879   if (Literal.isWide())
2880     Kind = CharacterLiteral::Wide;
2881   else if (Literal.isUTF16())
2882     Kind = CharacterLiteral::UTF16;
2883   else if (Literal.isUTF32())
2884     Kind = CharacterLiteral::UTF32;
2885 
2886   Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
2887                                              Tok.getLocation());
2888 
2889   if (Literal.getUDSuffix().empty())
2890     return Owned(Lit);
2891 
2892   // We're building a user-defined literal.
2893   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2894   SourceLocation UDSuffixLoc =
2895     getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
2896 
2897   // Make sure we're allowed user-defined literals here.
2898   if (!UDLScope)
2899     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
2900 
2901   // C++11 [lex.ext]p6: The literal L is treated as a call of the form
2902   //   operator "" X (ch)
2903   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
2904                                         Lit, Tok.getLocation());
2905 }
2906 
2907 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
2908   unsigned IntSize = Context.getTargetInfo().getIntWidth();
2909   return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
2910                                       Context.IntTy, Loc));
2911 }
2912 
2913 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
2914                                   QualType Ty, SourceLocation Loc) {
2915   const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
2916 
2917   using llvm::APFloat;
2918   APFloat Val(Format);
2919 
2920   APFloat::opStatus result = Literal.GetFloatValue(Val);
2921 
2922   // Overflow is always an error, but underflow is only an error if
2923   // we underflowed to zero (APFloat reports denormals as underflow).
2924   if ((result & APFloat::opOverflow) ||
2925       ((result & APFloat::opUnderflow) && Val.isZero())) {
2926     unsigned diagnostic;
2927     SmallString<20> buffer;
2928     if (result & APFloat::opOverflow) {
2929       diagnostic = diag::warn_float_overflow;
2930       APFloat::getLargest(Format).toString(buffer);
2931     } else {
2932       diagnostic = diag::warn_float_underflow;
2933       APFloat::getSmallest(Format).toString(buffer);
2934     }
2935 
2936     S.Diag(Loc, diagnostic)
2937       << Ty
2938       << StringRef(buffer.data(), buffer.size());
2939   }
2940 
2941   bool isExact = (result == APFloat::opOK);
2942   return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
2943 }
2944 
2945 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
2946   // Fast path for a single digit (which is quite common).  A single digit
2947   // cannot have a trigraph, escaped newline, radix prefix, or suffix.
2948   if (Tok.getLength() == 1) {
2949     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
2950     return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
2951   }
2952 
2953   SmallString<128> SpellingBuffer;
2954   // NumericLiteralParser wants to overread by one character.  Add padding to
2955   // the buffer in case the token is copied to the buffer.  If getSpelling()
2956   // returns a StringRef to the memory buffer, it should have a null char at
2957   // the EOF, so it is also safe.
2958   SpellingBuffer.resize(Tok.getLength() + 1);
2959 
2960   // Get the spelling of the token, which eliminates trigraphs, etc.
2961   bool Invalid = false;
2962   StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
2963   if (Invalid)
2964     return ExprError();
2965 
2966   NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
2967   if (Literal.hadError)
2968     return ExprError();
2969 
2970   if (Literal.hasUDSuffix()) {
2971     // We're building a user-defined literal.
2972     IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2973     SourceLocation UDSuffixLoc =
2974       getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
2975 
2976     // Make sure we're allowed user-defined literals here.
2977     if (!UDLScope)
2978       return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
2979 
2980     QualType CookedTy;
2981     if (Literal.isFloatingLiteral()) {
2982       // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
2983       // long double, the literal is treated as a call of the form
2984       //   operator "" X (f L)
2985       CookedTy = Context.LongDoubleTy;
2986     } else {
2987       // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
2988       // unsigned long long, the literal is treated as a call of the form
2989       //   operator "" X (n ULL)
2990       CookedTy = Context.UnsignedLongLongTy;
2991     }
2992 
2993     DeclarationName OpName =
2994       Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
2995     DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
2996     OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
2997 
2998     SourceLocation TokLoc = Tok.getLocation();
2999 
3000     // Perform literal operator lookup to determine if we're building a raw
3001     // literal or a cooked one.
3002     LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3003     switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3004                                   /*AllowRaw*/true, /*AllowTemplate*/true,
3005                                   /*AllowStringTemplate*/false)) {
3006     case LOLR_Error:
3007       return ExprError();
3008 
3009     case LOLR_Cooked: {
3010       Expr *Lit;
3011       if (Literal.isFloatingLiteral()) {
3012         Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3013       } else {
3014         llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3015         if (Literal.GetIntegerValue(ResultVal))
3016           Diag(Tok.getLocation(), diag::err_integer_too_large);
3017         Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3018                                      Tok.getLocation());
3019       }
3020       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3021     }
3022 
3023     case LOLR_Raw: {
3024       // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3025       // literal is treated as a call of the form
3026       //   operator "" X ("n")
3027       unsigned Length = Literal.getUDSuffixOffset();
3028       QualType StrTy = Context.getConstantArrayType(
3029           Context.CharTy.withConst(), llvm::APInt(32, Length + 1),
3030           ArrayType::Normal, 0);
3031       Expr *Lit = StringLiteral::Create(
3032           Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3033           /*Pascal*/false, StrTy, &TokLoc, 1);
3034       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3035     }
3036 
3037     case LOLR_Template: {
3038       // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3039       // template), L is treated as a call fo the form
3040       //   operator "" X <'c1', 'c2', ... 'ck'>()
3041       // where n is the source character sequence c1 c2 ... ck.
3042       TemplateArgumentListInfo ExplicitArgs;
3043       unsigned CharBits = Context.getIntWidth(Context.CharTy);
3044       bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3045       llvm::APSInt Value(CharBits, CharIsUnsigned);
3046       for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3047         Value = TokSpelling[I];
3048         TemplateArgument Arg(Context, Value, Context.CharTy);
3049         TemplateArgumentLocInfo ArgInfo;
3050         ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3051       }
3052       return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3053                                       &ExplicitArgs);
3054     }
3055     case LOLR_StringTemplate:
3056       llvm_unreachable("unexpected literal operator lookup result");
3057     }
3058   }
3059 
3060   Expr *Res;
3061 
3062   if (Literal.isFloatingLiteral()) {
3063     QualType Ty;
3064     if (Literal.isFloat)
3065       Ty = Context.FloatTy;
3066     else if (!Literal.isLong)
3067       Ty = Context.DoubleTy;
3068     else
3069       Ty = Context.LongDoubleTy;
3070 
3071     Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3072 
3073     if (Ty == Context.DoubleTy) {
3074       if (getLangOpts().SinglePrecisionConstants) {
3075         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
3076       } else if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
3077         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3078         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
3079       }
3080     }
3081   } else if (!Literal.isIntegerLiteral()) {
3082     return ExprError();
3083   } else {
3084     QualType Ty;
3085 
3086     // 'long long' is a C99 or C++11 feature.
3087     if (!getLangOpts().C99 && Literal.isLongLong) {
3088       if (getLangOpts().CPlusPlus)
3089         Diag(Tok.getLocation(),
3090              getLangOpts().CPlusPlus11 ?
3091              diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3092       else
3093         Diag(Tok.getLocation(), diag::ext_c99_longlong);
3094     }
3095 
3096     // Get the value in the widest-possible width.
3097     unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3098     // The microsoft literal suffix extensions support 128-bit literals, which
3099     // may be wider than [u]intmax_t.
3100     // FIXME: Actually, they don't. We seem to have accidentally invented the
3101     //        i128 suffix.
3102     if (Literal.isMicrosoftInteger && MaxWidth < 128 &&
3103         PP.getTargetInfo().hasInt128Type())
3104       MaxWidth = 128;
3105     llvm::APInt ResultVal(MaxWidth, 0);
3106 
3107     if (Literal.GetIntegerValue(ResultVal)) {
3108       // If this value didn't fit into uintmax_t, error and force to ull.
3109       Diag(Tok.getLocation(), diag::err_integer_too_large);
3110       Ty = Context.UnsignedLongLongTy;
3111       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3112              "long long is not intmax_t?");
3113     } else {
3114       // If this value fits into a ULL, try to figure out what else it fits into
3115       // according to the rules of C99 6.4.4.1p5.
3116 
3117       // Octal, Hexadecimal, and integers with a U suffix are allowed to
3118       // be an unsigned int.
3119       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3120 
3121       // Check from smallest to largest, picking the smallest type we can.
3122       unsigned Width = 0;
3123       if (!Literal.isLong && !Literal.isLongLong) {
3124         // Are int/unsigned possibilities?
3125         unsigned IntSize = Context.getTargetInfo().getIntWidth();
3126 
3127         // Does it fit in a unsigned int?
3128         if (ResultVal.isIntN(IntSize)) {
3129           // Does it fit in a signed int?
3130           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3131             Ty = Context.IntTy;
3132           else if (AllowUnsigned)
3133             Ty = Context.UnsignedIntTy;
3134           Width = IntSize;
3135         }
3136       }
3137 
3138       // Are long/unsigned long possibilities?
3139       if (Ty.isNull() && !Literal.isLongLong) {
3140         unsigned LongSize = Context.getTargetInfo().getLongWidth();
3141 
3142         // Does it fit in a unsigned long?
3143         if (ResultVal.isIntN(LongSize)) {
3144           // Does it fit in a signed long?
3145           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3146             Ty = Context.LongTy;
3147           else if (AllowUnsigned)
3148             Ty = Context.UnsignedLongTy;
3149           Width = LongSize;
3150         }
3151       }
3152 
3153       // Check long long if needed.
3154       if (Ty.isNull()) {
3155         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3156 
3157         // Does it fit in a unsigned long long?
3158         if (ResultVal.isIntN(LongLongSize)) {
3159           // Does it fit in a signed long long?
3160           // To be compatible with MSVC, hex integer literals ending with the
3161           // LL or i64 suffix are always signed in Microsoft mode.
3162           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3163               (getLangOpts().MicrosoftExt && Literal.isLongLong)))
3164             Ty = Context.LongLongTy;
3165           else if (AllowUnsigned)
3166             Ty = Context.UnsignedLongLongTy;
3167           Width = LongLongSize;
3168         }
3169       }
3170 
3171       // If it doesn't fit in unsigned long long, and we're using Microsoft
3172       // extensions, then its a 128-bit integer literal.
3173       if (Ty.isNull() && Literal.isMicrosoftInteger &&
3174           PP.getTargetInfo().hasInt128Type()) {
3175         if (Literal.isUnsigned)
3176           Ty = Context.UnsignedInt128Ty;
3177         else
3178           Ty = Context.Int128Ty;
3179         Width = 128;
3180       }
3181 
3182       // If we still couldn't decide a type, we probably have something that
3183       // does not fit in a signed long long, but has no U suffix.
3184       if (Ty.isNull()) {
3185         Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
3186         Ty = Context.UnsignedLongLongTy;
3187         Width = Context.getTargetInfo().getLongLongWidth();
3188       }
3189 
3190       if (ResultVal.getBitWidth() != Width)
3191         ResultVal = ResultVal.trunc(Width);
3192     }
3193     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3194   }
3195 
3196   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3197   if (Literal.isImaginary)
3198     Res = new (Context) ImaginaryLiteral(Res,
3199                                         Context.getComplexType(Res->getType()));
3200 
3201   return Owned(Res);
3202 }
3203 
3204 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
3205   assert((E != 0) && "ActOnParenExpr() missing expr");
3206   return Owned(new (Context) ParenExpr(L, R, E));
3207 }
3208 
3209 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3210                                          SourceLocation Loc,
3211                                          SourceRange ArgRange) {
3212   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3213   // scalar or vector data type argument..."
3214   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3215   // type (C99 6.2.5p18) or void.
3216   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3217     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3218       << T << ArgRange;
3219     return true;
3220   }
3221 
3222   assert((T->isVoidType() || !T->isIncompleteType()) &&
3223          "Scalar types should always be complete");
3224   return false;
3225 }
3226 
3227 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3228                                            SourceLocation Loc,
3229                                            SourceRange ArgRange,
3230                                            UnaryExprOrTypeTrait TraitKind) {
3231   // Invalid types must be hard errors for SFINAE in C++.
3232   if (S.LangOpts.CPlusPlus)
3233     return true;
3234 
3235   // C99 6.5.3.4p1:
3236   if (T->isFunctionType() &&
3237       (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) {
3238     // sizeof(function)/alignof(function) is allowed as an extension.
3239     S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3240       << TraitKind << ArgRange;
3241     return false;
3242   }
3243 
3244   // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
3245   // this is an error (OpenCL v1.1 s6.3.k)
3246   if (T->isVoidType()) {
3247     unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
3248                                         : diag::ext_sizeof_alignof_void_type;
3249     S.Diag(Loc, DiagID) << TraitKind << ArgRange;
3250     return false;
3251   }
3252 
3253   return true;
3254 }
3255 
3256 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
3257                                              SourceLocation Loc,
3258                                              SourceRange ArgRange,
3259                                              UnaryExprOrTypeTrait TraitKind) {
3260   // Reject sizeof(interface) and sizeof(interface<proto>) if the
3261   // runtime doesn't allow it.
3262   if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
3263     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3264       << T << (TraitKind == UETT_SizeOf)
3265       << ArgRange;
3266     return true;
3267   }
3268 
3269   return false;
3270 }
3271 
3272 /// \brief Check whether E is a pointer from a decayed array type (the decayed
3273 /// pointer type is equal to T) and emit a warning if it is.
3274 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
3275                                      Expr *E) {
3276   // Don't warn if the operation changed the type.
3277   if (T != E->getType())
3278     return;
3279 
3280   // Now look for array decays.
3281   ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
3282   if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
3283     return;
3284 
3285   S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
3286                                              << ICE->getType()
3287                                              << ICE->getSubExpr()->getType();
3288 }
3289 
3290 /// \brief Check the constraints on expression operands to unary type expression
3291 /// and type traits.
3292 ///
3293 /// Completes any types necessary and validates the constraints on the operand
3294 /// expression. The logic mostly mirrors the type-based overload, but may modify
3295 /// the expression as it completes the type for that expression through template
3296 /// instantiation, etc.
3297 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
3298                                             UnaryExprOrTypeTrait ExprKind) {
3299   QualType ExprTy = E->getType();
3300   assert(!ExprTy->isReferenceType());
3301 
3302   if (ExprKind == UETT_VecStep)
3303     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
3304                                         E->getSourceRange());
3305 
3306   // Whitelist some types as extensions
3307   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
3308                                       E->getSourceRange(), ExprKind))
3309     return false;
3310 
3311   if (RequireCompleteExprType(E,
3312                               diag::err_sizeof_alignof_incomplete_type,
3313                               ExprKind, E->getSourceRange()))
3314     return true;
3315 
3316   // Completing the expression's type may have changed it.
3317   ExprTy = E->getType();
3318   assert(!ExprTy->isReferenceType());
3319 
3320   if (ExprTy->isFunctionType()) {
3321     Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
3322       << ExprKind << E->getSourceRange();
3323     return true;
3324   }
3325 
3326   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
3327                                        E->getSourceRange(), ExprKind))
3328     return true;
3329 
3330   if (ExprKind == UETT_SizeOf) {
3331     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
3332       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
3333         QualType OType = PVD->getOriginalType();
3334         QualType Type = PVD->getType();
3335         if (Type->isPointerType() && OType->isArrayType()) {
3336           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
3337             << Type << OType;
3338           Diag(PVD->getLocation(), diag::note_declared_at);
3339         }
3340       }
3341     }
3342 
3343     // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
3344     // decays into a pointer and returns an unintended result. This is most
3345     // likely a typo for "sizeof(array) op x".
3346     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
3347       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3348                                BO->getLHS());
3349       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3350                                BO->getRHS());
3351     }
3352   }
3353 
3354   return false;
3355 }
3356 
3357 /// \brief Check the constraints on operands to unary expression and type
3358 /// traits.
3359 ///
3360 /// This will complete any types necessary, and validate the various constraints
3361 /// on those operands.
3362 ///
3363 /// The UsualUnaryConversions() function is *not* called by this routine.
3364 /// C99 6.3.2.1p[2-4] all state:
3365 ///   Except when it is the operand of the sizeof operator ...
3366 ///
3367 /// C++ [expr.sizeof]p4
3368 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3369 ///   standard conversions are not applied to the operand of sizeof.
3370 ///
3371 /// This policy is followed for all of the unary trait expressions.
3372 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
3373                                             SourceLocation OpLoc,
3374                                             SourceRange ExprRange,
3375                                             UnaryExprOrTypeTrait ExprKind) {
3376   if (ExprType->isDependentType())
3377     return false;
3378 
3379   // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
3380   //   the result is the size of the referenced type."
3381   // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
3382   //   result shall be the alignment of the referenced type."
3383   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3384     ExprType = Ref->getPointeeType();
3385 
3386   if (ExprKind == UETT_VecStep)
3387     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
3388 
3389   // Whitelist some types as extensions
3390   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
3391                                       ExprKind))
3392     return false;
3393 
3394   if (RequireCompleteType(OpLoc, ExprType,
3395                           diag::err_sizeof_alignof_incomplete_type,
3396                           ExprKind, ExprRange))
3397     return true;
3398 
3399   if (ExprType->isFunctionType()) {
3400     Diag(OpLoc, diag::err_sizeof_alignof_function_type)
3401       << ExprKind << ExprRange;
3402     return true;
3403   }
3404 
3405   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
3406                                        ExprKind))
3407     return true;
3408 
3409   return false;
3410 }
3411 
3412 static bool CheckAlignOfExpr(Sema &S, Expr *E) {
3413   E = E->IgnoreParens();
3414 
3415   // Cannot know anything else if the expression is dependent.
3416   if (E->isTypeDependent())
3417     return false;
3418 
3419   if (E->getObjectKind() == OK_BitField) {
3420     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield)
3421        << 1 << E->getSourceRange();
3422     return true;
3423   }
3424 
3425   ValueDecl *D = 0;
3426   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3427     D = DRE->getDecl();
3428   } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3429     D = ME->getMemberDecl();
3430   }
3431 
3432   // If it's a field, require the containing struct to have a
3433   // complete definition so that we can compute the layout.
3434   //
3435   // This requires a very particular set of circumstances.  For a
3436   // field to be contained within an incomplete type, we must in the
3437   // process of parsing that type.  To have an expression refer to a
3438   // field, it must be an id-expression or a member-expression, but
3439   // the latter are always ill-formed when the base type is
3440   // incomplete, including only being partially complete.  An
3441   // id-expression can never refer to a field in C because fields
3442   // are not in the ordinary namespace.  In C++, an id-expression
3443   // can implicitly be a member access, but only if there's an
3444   // implicit 'this' value, and all such contexts are subject to
3445   // delayed parsing --- except for trailing return types in C++11.
3446   // And if an id-expression referring to a field occurs in a
3447   // context that lacks a 'this' value, it's ill-formed --- except,
3448   // again, in C++11, where such references are allowed in an
3449   // unevaluated context.  So C++11 introduces some new complexity.
3450   //
3451   // For the record, since __alignof__ on expressions is a GCC
3452   // extension, GCC seems to permit this but always gives the
3453   // nonsensical answer 0.
3454   //
3455   // We don't really need the layout here --- we could instead just
3456   // directly check for all the appropriate alignment-lowing
3457   // attributes --- but that would require duplicating a lot of
3458   // logic that just isn't worth duplicating for such a marginal
3459   // use-case.
3460   if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
3461     // Fast path this check, since we at least know the record has a
3462     // definition if we can find a member of it.
3463     if (!FD->getParent()->isCompleteDefinition()) {
3464       S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
3465         << E->getSourceRange();
3466       return true;
3467     }
3468 
3469     // Otherwise, if it's a field, and the field doesn't have
3470     // reference type, then it must have a complete type (or be a
3471     // flexible array member, which we explicitly want to
3472     // white-list anyway), which makes the following checks trivial.
3473     if (!FD->getType()->isReferenceType())
3474       return false;
3475   }
3476 
3477   return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
3478 }
3479 
3480 bool Sema::CheckVecStepExpr(Expr *E) {
3481   E = E->IgnoreParens();
3482 
3483   // Cannot know anything else if the expression is dependent.
3484   if (E->isTypeDependent())
3485     return false;
3486 
3487   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
3488 }
3489 
3490 /// \brief Build a sizeof or alignof expression given a type operand.
3491 ExprResult
3492 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3493                                      SourceLocation OpLoc,
3494                                      UnaryExprOrTypeTrait ExprKind,
3495                                      SourceRange R) {
3496   if (!TInfo)
3497     return ExprError();
3498 
3499   QualType T = TInfo->getType();
3500 
3501   if (!T->isDependentType() &&
3502       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
3503     return ExprError();
3504 
3505   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
3506   return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo,
3507                                                       Context.getSizeType(),
3508                                                       OpLoc, R.getEnd()));
3509 }
3510 
3511 /// \brief Build a sizeof or alignof expression given an expression
3512 /// operand.
3513 ExprResult
3514 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
3515                                      UnaryExprOrTypeTrait ExprKind) {
3516   ExprResult PE = CheckPlaceholderExpr(E);
3517   if (PE.isInvalid())
3518     return ExprError();
3519 
3520   E = PE.get();
3521 
3522   // Verify that the operand is valid.
3523   bool isInvalid = false;
3524   if (E->isTypeDependent()) {
3525     // Delay type-checking for type-dependent expressions.
3526   } else if (ExprKind == UETT_AlignOf) {
3527     isInvalid = CheckAlignOfExpr(*this, E);
3528   } else if (ExprKind == UETT_VecStep) {
3529     isInvalid = CheckVecStepExpr(E);
3530   } else if (E->refersToBitField()) {  // C99 6.5.3.4p1.
3531     Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0;
3532     isInvalid = true;
3533   } else {
3534     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
3535   }
3536 
3537   if (isInvalid)
3538     return ExprError();
3539 
3540   if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
3541     PE = TransformToPotentiallyEvaluated(E);
3542     if (PE.isInvalid()) return ExprError();
3543     E = PE.take();
3544   }
3545 
3546   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
3547   return Owned(new (Context) UnaryExprOrTypeTraitExpr(
3548       ExprKind, E, Context.getSizeType(), OpLoc,
3549       E->getSourceRange().getEnd()));
3550 }
3551 
3552 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
3553 /// expr and the same for @c alignof and @c __alignof
3554 /// Note that the ArgRange is invalid if isType is false.
3555 ExprResult
3556 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
3557                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
3558                                     void *TyOrEx, const SourceRange &ArgRange) {
3559   // If error parsing type, ignore.
3560   if (TyOrEx == 0) return ExprError();
3561 
3562   if (IsType) {
3563     TypeSourceInfo *TInfo;
3564     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
3565     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
3566   }
3567 
3568   Expr *ArgEx = (Expr *)TyOrEx;
3569   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
3570   return Result;
3571 }
3572 
3573 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
3574                                      bool IsReal) {
3575   if (V.get()->isTypeDependent())
3576     return S.Context.DependentTy;
3577 
3578   // _Real and _Imag are only l-values for normal l-values.
3579   if (V.get()->getObjectKind() != OK_Ordinary) {
3580     V = S.DefaultLvalueConversion(V.take());
3581     if (V.isInvalid())
3582       return QualType();
3583   }
3584 
3585   // These operators return the element type of a complex type.
3586   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
3587     return CT->getElementType();
3588 
3589   // Otherwise they pass through real integer and floating point types here.
3590   if (V.get()->getType()->isArithmeticType())
3591     return V.get()->getType();
3592 
3593   // Test for placeholders.
3594   ExprResult PR = S.CheckPlaceholderExpr(V.get());
3595   if (PR.isInvalid()) return QualType();
3596   if (PR.get() != V.get()) {
3597     V = PR;
3598     return CheckRealImagOperand(S, V, Loc, IsReal);
3599   }
3600 
3601   // Reject anything else.
3602   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
3603     << (IsReal ? "__real" : "__imag");
3604   return QualType();
3605 }
3606 
3607 
3608 
3609 ExprResult
3610 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
3611                           tok::TokenKind Kind, Expr *Input) {
3612   UnaryOperatorKind Opc;
3613   switch (Kind) {
3614   default: llvm_unreachable("Unknown unary op!");
3615   case tok::plusplus:   Opc = UO_PostInc; break;
3616   case tok::minusminus: Opc = UO_PostDec; break;
3617   }
3618 
3619   // Since this might is a postfix expression, get rid of ParenListExprs.
3620   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
3621   if (Result.isInvalid()) return ExprError();
3622   Input = Result.take();
3623 
3624   return BuildUnaryOp(S, OpLoc, Opc, Input);
3625 }
3626 
3627 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal.
3628 ///
3629 /// \return true on error
3630 static bool checkArithmeticOnObjCPointer(Sema &S,
3631                                          SourceLocation opLoc,
3632                                          Expr *op) {
3633   assert(op->getType()->isObjCObjectPointerType());
3634   if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
3635       !S.LangOpts.ObjCSubscriptingLegacyRuntime)
3636     return false;
3637 
3638   S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
3639     << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
3640     << op->getSourceRange();
3641   return true;
3642 }
3643 
3644 ExprResult
3645 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
3646                               Expr *idx, SourceLocation rbLoc) {
3647   // Since this might be a postfix expression, get rid of ParenListExprs.
3648   if (isa<ParenListExpr>(base)) {
3649     ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
3650     if (result.isInvalid()) return ExprError();
3651     base = result.take();
3652   }
3653 
3654   // Handle any non-overload placeholder types in the base and index
3655   // expressions.  We can't handle overloads here because the other
3656   // operand might be an overloadable type, in which case the overload
3657   // resolution for the operator overload should get the first crack
3658   // at the overload.
3659   if (base->getType()->isNonOverloadPlaceholderType()) {
3660     ExprResult result = CheckPlaceholderExpr(base);
3661     if (result.isInvalid()) return ExprError();
3662     base = result.take();
3663   }
3664   if (idx->getType()->isNonOverloadPlaceholderType()) {
3665     ExprResult result = CheckPlaceholderExpr(idx);
3666     if (result.isInvalid()) return ExprError();
3667     idx = result.take();
3668   }
3669 
3670   // Build an unanalyzed expression if either operand is type-dependent.
3671   if (getLangOpts().CPlusPlus &&
3672       (base->isTypeDependent() || idx->isTypeDependent())) {
3673     return Owned(new (Context) ArraySubscriptExpr(base, idx,
3674                                                   Context.DependentTy,
3675                                                   VK_LValue, OK_Ordinary,
3676                                                   rbLoc));
3677   }
3678 
3679   // Use C++ overloaded-operator rules if either operand has record
3680   // type.  The spec says to do this if either type is *overloadable*,
3681   // but enum types can't declare subscript operators or conversion
3682   // operators, so there's nothing interesting for overload resolution
3683   // to do if there aren't any record types involved.
3684   //
3685   // ObjC pointers have their own subscripting logic that is not tied
3686   // to overload resolution and so should not take this path.
3687   if (getLangOpts().CPlusPlus &&
3688       (base->getType()->isRecordType() ||
3689        (!base->getType()->isObjCObjectPointerType() &&
3690         idx->getType()->isRecordType()))) {
3691     return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
3692   }
3693 
3694   return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
3695 }
3696 
3697 ExprResult
3698 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
3699                                       Expr *Idx, SourceLocation RLoc) {
3700   Expr *LHSExp = Base;
3701   Expr *RHSExp = Idx;
3702 
3703   // Perform default conversions.
3704   if (!LHSExp->getType()->getAs<VectorType>()) {
3705     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
3706     if (Result.isInvalid())
3707       return ExprError();
3708     LHSExp = Result.take();
3709   }
3710   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
3711   if (Result.isInvalid())
3712     return ExprError();
3713   RHSExp = Result.take();
3714 
3715   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
3716   ExprValueKind VK = VK_LValue;
3717   ExprObjectKind OK = OK_Ordinary;
3718 
3719   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
3720   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
3721   // in the subscript position. As a result, we need to derive the array base
3722   // and index from the expression types.
3723   Expr *BaseExpr, *IndexExpr;
3724   QualType ResultType;
3725   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3726     BaseExpr = LHSExp;
3727     IndexExpr = RHSExp;
3728     ResultType = Context.DependentTy;
3729   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
3730     BaseExpr = LHSExp;
3731     IndexExpr = RHSExp;
3732     ResultType = PTy->getPointeeType();
3733   } else if (const ObjCObjectPointerType *PTy =
3734                LHSTy->getAs<ObjCObjectPointerType>()) {
3735     BaseExpr = LHSExp;
3736     IndexExpr = RHSExp;
3737 
3738     // Use custom logic if this should be the pseudo-object subscript
3739     // expression.
3740     if (!LangOpts.isSubscriptPointerArithmetic())
3741       return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, 0, 0);
3742 
3743     ResultType = PTy->getPointeeType();
3744   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
3745      // Handle the uncommon case of "123[Ptr]".
3746     BaseExpr = RHSExp;
3747     IndexExpr = LHSExp;
3748     ResultType = PTy->getPointeeType();
3749   } else if (const ObjCObjectPointerType *PTy =
3750                RHSTy->getAs<ObjCObjectPointerType>()) {
3751      // Handle the uncommon case of "123[Ptr]".
3752     BaseExpr = RHSExp;
3753     IndexExpr = LHSExp;
3754     ResultType = PTy->getPointeeType();
3755     if (!LangOpts.isSubscriptPointerArithmetic()) {
3756       Diag(LLoc, diag::err_subscript_nonfragile_interface)
3757         << ResultType << BaseExpr->getSourceRange();
3758       return ExprError();
3759     }
3760   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
3761     BaseExpr = LHSExp;    // vectors: V[123]
3762     IndexExpr = RHSExp;
3763     VK = LHSExp->getValueKind();
3764     if (VK != VK_RValue)
3765       OK = OK_VectorComponent;
3766 
3767     // FIXME: need to deal with const...
3768     ResultType = VTy->getElementType();
3769   } else if (LHSTy->isArrayType()) {
3770     // If we see an array that wasn't promoted by
3771     // DefaultFunctionArrayLvalueConversion, it must be an array that
3772     // wasn't promoted because of the C90 rule that doesn't
3773     // allow promoting non-lvalue arrays.  Warn, then
3774     // force the promotion here.
3775     Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3776         LHSExp->getSourceRange();
3777     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
3778                                CK_ArrayToPointerDecay).take();
3779     LHSTy = LHSExp->getType();
3780 
3781     BaseExpr = LHSExp;
3782     IndexExpr = RHSExp;
3783     ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
3784   } else if (RHSTy->isArrayType()) {
3785     // Same as previous, except for 123[f().a] case
3786     Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3787         RHSExp->getSourceRange();
3788     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
3789                                CK_ArrayToPointerDecay).take();
3790     RHSTy = RHSExp->getType();
3791 
3792     BaseExpr = RHSExp;
3793     IndexExpr = LHSExp;
3794     ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
3795   } else {
3796     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3797        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
3798   }
3799   // C99 6.5.2.1p1
3800   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
3801     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3802                      << IndexExpr->getSourceRange());
3803 
3804   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
3805        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3806          && !IndexExpr->isTypeDependent())
3807     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3808 
3809   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
3810   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3811   // type. Note that Functions are not objects, and that (in C99 parlance)
3812   // incomplete types are not object types.
3813   if (ResultType->isFunctionType()) {
3814     Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3815       << ResultType << BaseExpr->getSourceRange();
3816     return ExprError();
3817   }
3818 
3819   if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
3820     // GNU extension: subscripting on pointer to void
3821     Diag(LLoc, diag::ext_gnu_subscript_void_type)
3822       << BaseExpr->getSourceRange();
3823 
3824     // C forbids expressions of unqualified void type from being l-values.
3825     // See IsCForbiddenLValueType.
3826     if (!ResultType.hasQualifiers()) VK = VK_RValue;
3827   } else if (!ResultType->isDependentType() &&
3828       RequireCompleteType(LLoc, ResultType,
3829                           diag::err_subscript_incomplete_type, BaseExpr))
3830     return ExprError();
3831 
3832   assert(VK == VK_RValue || LangOpts.CPlusPlus ||
3833          !ResultType.isCForbiddenLValueType());
3834 
3835   return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
3836                                                 ResultType, VK, OK, RLoc));
3837 }
3838 
3839 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
3840                                         FunctionDecl *FD,
3841                                         ParmVarDecl *Param) {
3842   if (Param->hasUnparsedDefaultArg()) {
3843     Diag(CallLoc,
3844          diag::err_use_of_default_argument_to_function_declared_later) <<
3845       FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
3846     Diag(UnparsedDefaultArgLocs[Param],
3847          diag::note_default_argument_declared_here);
3848     return ExprError();
3849   }
3850 
3851   if (Param->hasUninstantiatedDefaultArg()) {
3852     Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
3853 
3854     EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated,
3855                                                  Param);
3856 
3857     // Instantiate the expression.
3858     MultiLevelTemplateArgumentList MutiLevelArgList
3859       = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
3860 
3861     InstantiatingTemplate Inst(*this, CallLoc, Param,
3862                                MutiLevelArgList.getInnermost());
3863     if (Inst.isInvalid())
3864       return ExprError();
3865 
3866     ExprResult Result;
3867     {
3868       // C++ [dcl.fct.default]p5:
3869       //   The names in the [default argument] expression are bound, and
3870       //   the semantic constraints are checked, at the point where the
3871       //   default argument expression appears.
3872       ContextRAII SavedContext(*this, FD);
3873       LocalInstantiationScope Local(*this);
3874       Result = SubstExpr(UninstExpr, MutiLevelArgList);
3875     }
3876     if (Result.isInvalid())
3877       return ExprError();
3878 
3879     // Check the expression as an initializer for the parameter.
3880     InitializedEntity Entity
3881       = InitializedEntity::InitializeParameter(Context, Param);
3882     InitializationKind Kind
3883       = InitializationKind::CreateCopy(Param->getLocation(),
3884              /*FIXME:EqualLoc*/UninstExpr->getLocStart());
3885     Expr *ResultE = Result.takeAs<Expr>();
3886 
3887     InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
3888     Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
3889     if (Result.isInvalid())
3890       return ExprError();
3891 
3892     Expr *Arg = Result.takeAs<Expr>();
3893     CheckCompletedExpr(Arg, Param->getOuterLocStart());
3894     // Build the default argument expression.
3895     return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param, Arg));
3896   }
3897 
3898   // If the default expression creates temporaries, we need to
3899   // push them to the current stack of expression temporaries so they'll
3900   // be properly destroyed.
3901   // FIXME: We should really be rebuilding the default argument with new
3902   // bound temporaries; see the comment in PR5810.
3903   // We don't need to do that with block decls, though, because
3904   // blocks in default argument expression can never capture anything.
3905   if (isa<ExprWithCleanups>(Param->getInit())) {
3906     // Set the "needs cleanups" bit regardless of whether there are
3907     // any explicit objects.
3908     ExprNeedsCleanups = true;
3909 
3910     // Append all the objects to the cleanup list.  Right now, this
3911     // should always be a no-op, because blocks in default argument
3912     // expressions should never be able to capture anything.
3913     assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() &&
3914            "default argument expression has capturing blocks?");
3915   }
3916 
3917   // We already type-checked the argument, so we know it works.
3918   // Just mark all of the declarations in this potentially-evaluated expression
3919   // as being "referenced".
3920   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
3921                                    /*SkipLocalVariables=*/true);
3922   return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
3923 }
3924 
3925 
3926 Sema::VariadicCallType
3927 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
3928                           Expr *Fn) {
3929   if (Proto && Proto->isVariadic()) {
3930     if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
3931       return VariadicConstructor;
3932     else if (Fn && Fn->getType()->isBlockPointerType())
3933       return VariadicBlock;
3934     else if (FDecl) {
3935       if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3936         if (Method->isInstance())
3937           return VariadicMethod;
3938     } else if (Fn && Fn->getType() == Context.BoundMemberTy)
3939       return VariadicMethod;
3940     return VariadicFunction;
3941   }
3942   return VariadicDoesNotApply;
3943 }
3944 
3945 namespace {
3946 class FunctionCallCCC : public FunctionCallFilterCCC {
3947 public:
3948   FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
3949                   unsigned NumArgs, bool HasExplicitTemplateArgs)
3950       : FunctionCallFilterCCC(SemaRef, NumArgs, HasExplicitTemplateArgs),
3951         FunctionName(FuncName) {}
3952 
3953   virtual bool ValidateCandidate(const TypoCorrection &candidate) {
3954     if (!candidate.getCorrectionSpecifier() ||
3955         candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
3956       return false;
3957     }
3958 
3959     return FunctionCallFilterCCC::ValidateCandidate(candidate);
3960   }
3961 
3962 private:
3963   const IdentifierInfo *const FunctionName;
3964 };
3965 }
3966 
3967 static TypoCorrection TryTypoCorrectionForCall(Sema &S,
3968                                                DeclarationNameInfo FuncName,
3969                                                ArrayRef<Expr *> Args) {
3970   FunctionCallCCC CCC(S, FuncName.getName().getAsIdentifierInfo(),
3971                       Args.size(), false);
3972   if (TypoCorrection Corrected =
3973           S.CorrectTypo(FuncName, Sema::LookupOrdinaryName,
3974                         S.getScopeForContext(S.CurContext), NULL, CCC)) {
3975     if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
3976       if (Corrected.isOverloaded()) {
3977         OverloadCandidateSet OCS(FuncName.getLoc());
3978         OverloadCandidateSet::iterator Best;
3979         for (TypoCorrection::decl_iterator CD = Corrected.begin(),
3980                                            CDEnd = Corrected.end();
3981              CD != CDEnd; ++CD) {
3982           if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
3983             S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
3984                                    OCS);
3985         }
3986         switch (OCS.BestViableFunction(S, FuncName.getLoc(), Best)) {
3987         case OR_Success:
3988           ND = Best->Function;
3989           Corrected.setCorrectionDecl(ND);
3990           break;
3991         default:
3992           break;
3993         }
3994       }
3995       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
3996         return Corrected;
3997       }
3998     }
3999   }
4000   return TypoCorrection();
4001 }
4002 
4003 /// ConvertArgumentsForCall - Converts the arguments specified in
4004 /// Args/NumArgs to the parameter types of the function FDecl with
4005 /// function prototype Proto. Call is the call expression itself, and
4006 /// Fn is the function expression. For a C++ member function, this
4007 /// routine does not attempt to convert the object argument. Returns
4008 /// true if the call is ill-formed.
4009 bool
4010 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
4011                               FunctionDecl *FDecl,
4012                               const FunctionProtoType *Proto,
4013                               ArrayRef<Expr *> Args,
4014                               SourceLocation RParenLoc,
4015                               bool IsExecConfig) {
4016   // Bail out early if calling a builtin with custom typechecking.
4017   // We don't need to do this in the
4018   if (FDecl)
4019     if (unsigned ID = FDecl->getBuiltinID())
4020       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
4021         return false;
4022 
4023   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
4024   // assignment, to the types of the corresponding parameter, ...
4025   unsigned NumParams = Proto->getNumParams();
4026   bool Invalid = false;
4027   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
4028   unsigned FnKind = Fn->getType()->isBlockPointerType()
4029                        ? 1 /* block */
4030                        : (IsExecConfig ? 3 /* kernel function (exec config) */
4031                                        : 0 /* function */);
4032 
4033   // If too few arguments are available (and we don't have default
4034   // arguments for the remaining parameters), don't make the call.
4035   if (Args.size() < NumParams) {
4036     if (Args.size() < MinArgs) {
4037       MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
4038       TypoCorrection TC;
4039       if (FDecl && (TC = TryTypoCorrectionForCall(
4040                         *this, DeclarationNameInfo(FDecl->getDeclName(),
4041                                                    (ME ? ME->getMemberLoc()
4042                                                        : Fn->getLocStart())),
4043                         Args))) {
4044         unsigned diag_id =
4045             MinArgs == NumParams && !Proto->isVariadic()
4046                 ? diag::err_typecheck_call_too_few_args_suggest
4047                 : diag::err_typecheck_call_too_few_args_at_least_suggest;
4048         diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
4049                                         << static_cast<unsigned>(Args.size())
4050                                         << TC.getCorrectionRange());
4051       } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
4052         Diag(RParenLoc,
4053              MinArgs == NumParams && !Proto->isVariadic()
4054                  ? diag::err_typecheck_call_too_few_args_one
4055                  : diag::err_typecheck_call_too_few_args_at_least_one)
4056             << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
4057       else
4058         Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
4059                             ? diag::err_typecheck_call_too_few_args
4060                             : diag::err_typecheck_call_too_few_args_at_least)
4061             << FnKind << MinArgs << static_cast<unsigned>(Args.size())
4062             << Fn->getSourceRange();
4063 
4064       // Emit the location of the prototype.
4065       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4066         Diag(FDecl->getLocStart(), diag::note_callee_decl)
4067           << FDecl;
4068 
4069       return true;
4070     }
4071     Call->setNumArgs(Context, NumParams);
4072   }
4073 
4074   // If too many are passed and not variadic, error on the extras and drop
4075   // them.
4076   if (Args.size() > NumParams) {
4077     if (!Proto->isVariadic()) {
4078       MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
4079       TypoCorrection TC;
4080       if (FDecl && (TC = TryTypoCorrectionForCall(
4081                         *this, DeclarationNameInfo(FDecl->getDeclName(),
4082                                                    (ME ? ME->getMemberLoc()
4083                                                        : Fn->getLocStart())),
4084                         Args))) {
4085         unsigned diag_id =
4086             MinArgs == NumParams && !Proto->isVariadic()
4087                 ? diag::err_typecheck_call_too_many_args_suggest
4088                 : diag::err_typecheck_call_too_many_args_at_most_suggest;
4089         diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
4090                                         << static_cast<unsigned>(Args.size())
4091                                         << TC.getCorrectionRange());
4092       } else if (NumParams == 1 && FDecl &&
4093                  FDecl->getParamDecl(0)->getDeclName())
4094         Diag(Args[NumParams]->getLocStart(),
4095              MinArgs == NumParams
4096                  ? diag::err_typecheck_call_too_many_args_one
4097                  : diag::err_typecheck_call_too_many_args_at_most_one)
4098             << FnKind << FDecl->getParamDecl(0)
4099             << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
4100             << SourceRange(Args[NumParams]->getLocStart(),
4101                            Args.back()->getLocEnd());
4102       else
4103         Diag(Args[NumParams]->getLocStart(),
4104              MinArgs == NumParams
4105                  ? diag::err_typecheck_call_too_many_args
4106                  : diag::err_typecheck_call_too_many_args_at_most)
4107             << FnKind << NumParams << static_cast<unsigned>(Args.size())
4108             << Fn->getSourceRange()
4109             << SourceRange(Args[NumParams]->getLocStart(),
4110                            Args.back()->getLocEnd());
4111 
4112       // Emit the location of the prototype.
4113       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4114         Diag(FDecl->getLocStart(), diag::note_callee_decl)
4115           << FDecl;
4116 
4117       // This deletes the extra arguments.
4118       Call->setNumArgs(Context, NumParams);
4119       return true;
4120     }
4121   }
4122   SmallVector<Expr *, 8> AllArgs;
4123   VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
4124 
4125   Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
4126                                    Proto, 0, Args, AllArgs, CallType);
4127   if (Invalid)
4128     return true;
4129   unsigned TotalNumArgs = AllArgs.size();
4130   for (unsigned i = 0; i < TotalNumArgs; ++i)
4131     Call->setArg(i, AllArgs[i]);
4132 
4133   return false;
4134 }
4135 
4136 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
4137                                   const FunctionProtoType *Proto,
4138                                   unsigned FirstParam, ArrayRef<Expr *> Args,
4139                                   SmallVectorImpl<Expr *> &AllArgs,
4140                                   VariadicCallType CallType, bool AllowExplicit,
4141                                   bool IsListInitialization) {
4142   unsigned NumParams = Proto->getNumParams();
4143   unsigned NumArgsToCheck = Args.size();
4144   bool Invalid = false;
4145   if (Args.size() != NumParams)
4146     // Use default arguments for missing arguments
4147     NumArgsToCheck = NumParams;
4148   unsigned ArgIx = 0;
4149   // Continue to check argument types (even if we have too few/many args).
4150   for (unsigned i = FirstParam; i != NumArgsToCheck; i++) {
4151     QualType ProtoArgType = Proto->getParamType(i);
4152 
4153     Expr *Arg;
4154     ParmVarDecl *Param;
4155     if (ArgIx < Args.size()) {
4156       Arg = Args[ArgIx++];
4157 
4158       if (RequireCompleteType(Arg->getLocStart(),
4159                               ProtoArgType,
4160                               diag::err_call_incomplete_argument, Arg))
4161         return true;
4162 
4163       // Pass the argument
4164       Param = 0;
4165       if (FDecl && i < FDecl->getNumParams())
4166         Param = FDecl->getParamDecl(i);
4167 
4168       // Strip the unbridged-cast placeholder expression off, if applicable.
4169       bool CFAudited = false;
4170       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
4171           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4172           (!Param || !Param->hasAttr<CFConsumedAttr>()))
4173         Arg = stripARCUnbridgedCast(Arg);
4174       else if (getLangOpts().ObjCAutoRefCount &&
4175                FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4176                (!Param || !Param->hasAttr<CFConsumedAttr>()))
4177         CFAudited = true;
4178 
4179       InitializedEntity Entity =
4180           Param ? InitializedEntity::InitializeParameter(Context, Param,
4181                                                          ProtoArgType)
4182                 : InitializedEntity::InitializeParameter(
4183                       Context, ProtoArgType, Proto->isParamConsumed(i));
4184 
4185       // Remember that parameter belongs to a CF audited API.
4186       if (CFAudited)
4187         Entity.setParameterCFAudited();
4188 
4189       ExprResult ArgE = PerformCopyInitialization(Entity,
4190                                                   SourceLocation(),
4191                                                   Owned(Arg),
4192                                                   IsListInitialization,
4193                                                   AllowExplicit);
4194       if (ArgE.isInvalid())
4195         return true;
4196 
4197       Arg = ArgE.takeAs<Expr>();
4198     } else {
4199       assert(FDecl && "can't use default arguments without a known callee");
4200       Param = FDecl->getParamDecl(i);
4201 
4202       ExprResult ArgExpr =
4203         BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
4204       if (ArgExpr.isInvalid())
4205         return true;
4206 
4207       Arg = ArgExpr.takeAs<Expr>();
4208     }
4209 
4210     // Check for array bounds violations for each argument to the call. This
4211     // check only triggers warnings when the argument isn't a more complex Expr
4212     // with its own checking, such as a BinaryOperator.
4213     CheckArrayAccess(Arg);
4214 
4215     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
4216     CheckStaticArrayArgument(CallLoc, Param, Arg);
4217 
4218     AllArgs.push_back(Arg);
4219   }
4220 
4221   // If this is a variadic call, handle args passed through "...".
4222   if (CallType != VariadicDoesNotApply) {
4223     // Assume that extern "C" functions with variadic arguments that
4224     // return __unknown_anytype aren't *really* variadic.
4225     if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
4226         FDecl->isExternC()) {
4227       for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) {
4228         QualType paramType; // ignored
4229         ExprResult arg = checkUnknownAnyArg(CallLoc, Args[i], paramType);
4230         Invalid |= arg.isInvalid();
4231         AllArgs.push_back(arg.take());
4232       }
4233 
4234     // Otherwise do argument promotion, (C99 6.5.2.2p7).
4235     } else {
4236       for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) {
4237         ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType,
4238                                                           FDecl);
4239         Invalid |= Arg.isInvalid();
4240         AllArgs.push_back(Arg.take());
4241       }
4242     }
4243 
4244     // Check for array bounds violations.
4245     for (unsigned i = ArgIx, e = Args.size(); i != e; ++i)
4246       CheckArrayAccess(Args[i]);
4247   }
4248   return Invalid;
4249 }
4250 
4251 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
4252   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
4253   if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
4254     TL = DTL.getOriginalLoc();
4255   if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
4256     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
4257       << ATL.getLocalSourceRange();
4258 }
4259 
4260 /// CheckStaticArrayArgument - If the given argument corresponds to a static
4261 /// array parameter, check that it is non-null, and that if it is formed by
4262 /// array-to-pointer decay, the underlying array is sufficiently large.
4263 ///
4264 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
4265 /// array type derivation, then for each call to the function, the value of the
4266 /// corresponding actual argument shall provide access to the first element of
4267 /// an array with at least as many elements as specified by the size expression.
4268 void
4269 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
4270                                ParmVarDecl *Param,
4271                                const Expr *ArgExpr) {
4272   // Static array parameters are not supported in C++.
4273   if (!Param || getLangOpts().CPlusPlus)
4274     return;
4275 
4276   QualType OrigTy = Param->getOriginalType();
4277 
4278   const ArrayType *AT = Context.getAsArrayType(OrigTy);
4279   if (!AT || AT->getSizeModifier() != ArrayType::Static)
4280     return;
4281 
4282   if (ArgExpr->isNullPointerConstant(Context,
4283                                      Expr::NPC_NeverValueDependent)) {
4284     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
4285     DiagnoseCalleeStaticArrayParam(*this, Param);
4286     return;
4287   }
4288 
4289   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
4290   if (!CAT)
4291     return;
4292 
4293   const ConstantArrayType *ArgCAT =
4294     Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
4295   if (!ArgCAT)
4296     return;
4297 
4298   if (ArgCAT->getSize().ult(CAT->getSize())) {
4299     Diag(CallLoc, diag::warn_static_array_too_small)
4300       << ArgExpr->getSourceRange()
4301       << (unsigned) ArgCAT->getSize().getZExtValue()
4302       << (unsigned) CAT->getSize().getZExtValue();
4303     DiagnoseCalleeStaticArrayParam(*this, Param);
4304   }
4305 }
4306 
4307 /// Given a function expression of unknown-any type, try to rebuild it
4308 /// to have a function type.
4309 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
4310 
4311 /// Is the given type a placeholder that we need to lower out
4312 /// immediately during argument processing?
4313 static bool isPlaceholderToRemoveAsArg(QualType type) {
4314   // Placeholders are never sugared.
4315   const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
4316   if (!placeholder) return false;
4317 
4318   switch (placeholder->getKind()) {
4319   // Ignore all the non-placeholder types.
4320 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
4321 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
4322 #include "clang/AST/BuiltinTypes.def"
4323     return false;
4324 
4325   // We cannot lower out overload sets; they might validly be resolved
4326   // by the call machinery.
4327   case BuiltinType::Overload:
4328     return false;
4329 
4330   // Unbridged casts in ARC can be handled in some call positions and
4331   // should be left in place.
4332   case BuiltinType::ARCUnbridgedCast:
4333     return false;
4334 
4335   // Pseudo-objects should be converted as soon as possible.
4336   case BuiltinType::PseudoObject:
4337     return true;
4338 
4339   // The debugger mode could theoretically but currently does not try
4340   // to resolve unknown-typed arguments based on known parameter types.
4341   case BuiltinType::UnknownAny:
4342     return true;
4343 
4344   // These are always invalid as call arguments and should be reported.
4345   case BuiltinType::BoundMember:
4346   case BuiltinType::BuiltinFn:
4347     return true;
4348   }
4349   llvm_unreachable("bad builtin type kind");
4350 }
4351 
4352 /// Check an argument list for placeholders that we won't try to
4353 /// handle later.
4354 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
4355   // Apply this processing to all the arguments at once instead of
4356   // dying at the first failure.
4357   bool hasInvalid = false;
4358   for (size_t i = 0, e = args.size(); i != e; i++) {
4359     if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
4360       ExprResult result = S.CheckPlaceholderExpr(args[i]);
4361       if (result.isInvalid()) hasInvalid = true;
4362       else args[i] = result.take();
4363     }
4364   }
4365   return hasInvalid;
4366 }
4367 
4368 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
4369 /// This provides the location of the left/right parens and a list of comma
4370 /// locations.
4371 ExprResult
4372 Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
4373                     MultiExprArg ArgExprs, SourceLocation RParenLoc,
4374                     Expr *ExecConfig, bool IsExecConfig) {
4375   // Since this might be a postfix expression, get rid of ParenListExprs.
4376   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
4377   if (Result.isInvalid()) return ExprError();
4378   Fn = Result.take();
4379 
4380   if (checkArgsForPlaceholders(*this, ArgExprs))
4381     return ExprError();
4382 
4383   if (getLangOpts().CPlusPlus) {
4384     // If this is a pseudo-destructor expression, build the call immediately.
4385     if (isa<CXXPseudoDestructorExpr>(Fn)) {
4386       if (!ArgExprs.empty()) {
4387         // Pseudo-destructor calls should not have any arguments.
4388         Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
4389           << FixItHint::CreateRemoval(
4390                                     SourceRange(ArgExprs[0]->getLocStart(),
4391                                                 ArgExprs.back()->getLocEnd()));
4392       }
4393 
4394       return Owned(new (Context) CallExpr(Context, Fn, None,
4395                                           Context.VoidTy, VK_RValue,
4396                                           RParenLoc));
4397     }
4398     if (Fn->getType() == Context.PseudoObjectTy) {
4399       ExprResult result = CheckPlaceholderExpr(Fn);
4400       if (result.isInvalid()) return ExprError();
4401       Fn = result.take();
4402     }
4403 
4404     // Determine whether this is a dependent call inside a C++ template,
4405     // in which case we won't do any semantic analysis now.
4406     // FIXME: Will need to cache the results of name lookup (including ADL) in
4407     // Fn.
4408     bool Dependent = false;
4409     if (Fn->isTypeDependent())
4410       Dependent = true;
4411     else if (Expr::hasAnyTypeDependentArguments(ArgExprs))
4412       Dependent = true;
4413 
4414     if (Dependent) {
4415       if (ExecConfig) {
4416         return Owned(new (Context) CUDAKernelCallExpr(
4417             Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
4418             Context.DependentTy, VK_RValue, RParenLoc));
4419       } else {
4420         return Owned(new (Context) CallExpr(Context, Fn, ArgExprs,
4421                                             Context.DependentTy, VK_RValue,
4422                                             RParenLoc));
4423       }
4424     }
4425 
4426     // Determine whether this is a call to an object (C++ [over.call.object]).
4427     if (Fn->getType()->isRecordType())
4428       return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc,
4429                                                 ArgExprs, RParenLoc));
4430 
4431     if (Fn->getType() == Context.UnknownAnyTy) {
4432       ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
4433       if (result.isInvalid()) return ExprError();
4434       Fn = result.take();
4435     }
4436 
4437     if (Fn->getType() == Context.BoundMemberTy) {
4438       return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs, RParenLoc);
4439     }
4440   }
4441 
4442   // Check for overloaded calls.  This can happen even in C due to extensions.
4443   if (Fn->getType() == Context.OverloadTy) {
4444     OverloadExpr::FindResult find = OverloadExpr::find(Fn);
4445 
4446     // We aren't supposed to apply this logic for if there's an '&' involved.
4447     if (!find.HasFormOfMemberPointer) {
4448       OverloadExpr *ovl = find.Expression;
4449       if (isa<UnresolvedLookupExpr>(ovl)) {
4450         UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
4451         return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, ArgExprs,
4452                                        RParenLoc, ExecConfig);
4453       } else {
4454         return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs,
4455                                          RParenLoc);
4456       }
4457     }
4458   }
4459 
4460   // If we're directly calling a function, get the appropriate declaration.
4461   if (Fn->getType() == Context.UnknownAnyTy) {
4462     ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
4463     if (result.isInvalid()) return ExprError();
4464     Fn = result.take();
4465   }
4466 
4467   Expr *NakedFn = Fn->IgnoreParens();
4468 
4469   NamedDecl *NDecl = 0;
4470   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
4471     if (UnOp->getOpcode() == UO_AddrOf)
4472       NakedFn = UnOp->getSubExpr()->IgnoreParens();
4473 
4474   if (isa<DeclRefExpr>(NakedFn))
4475     NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
4476   else if (isa<MemberExpr>(NakedFn))
4477     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
4478 
4479   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
4480     if (FD->hasAttr<EnableIfAttr>()) {
4481       if (const EnableIfAttr *Attr = CheckEnableIf(FD, ArgExprs, true)) {
4482         Diag(Fn->getLocStart(),
4483              isa<CXXMethodDecl>(FD) ?
4484                  diag::err_ovl_no_viable_member_function_in_call :
4485                  diag::err_ovl_no_viable_function_in_call)
4486           << FD << FD->getSourceRange();
4487         Diag(FD->getLocation(),
4488              diag::note_ovl_candidate_disabled_by_enable_if_attr)
4489             << Attr->getCond()->getSourceRange() << Attr->getMessage();
4490       }
4491     }
4492   }
4493 
4494   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
4495                                ExecConfig, IsExecConfig);
4496 }
4497 
4498 ExprResult
4499 Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
4500                               MultiExprArg ExecConfig, SourceLocation GGGLoc) {
4501   FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
4502   if (!ConfigDecl)
4503     return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
4504                           << "cudaConfigureCall");
4505   QualType ConfigQTy = ConfigDecl->getType();
4506 
4507   DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
4508       ConfigDecl, false, ConfigQTy, VK_LValue, LLLLoc);
4509   MarkFunctionReferenced(LLLLoc, ConfigDecl);
4510 
4511   return ActOnCallExpr(S, ConfigDR, LLLLoc, ExecConfig, GGGLoc, 0,
4512                        /*IsExecConfig=*/true);
4513 }
4514 
4515 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
4516 ///
4517 /// __builtin_astype( value, dst type )
4518 ///
4519 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
4520                                  SourceLocation BuiltinLoc,
4521                                  SourceLocation RParenLoc) {
4522   ExprValueKind VK = VK_RValue;
4523   ExprObjectKind OK = OK_Ordinary;
4524   QualType DstTy = GetTypeFromParser(ParsedDestTy);
4525   QualType SrcTy = E->getType();
4526   if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
4527     return ExprError(Diag(BuiltinLoc,
4528                           diag::err_invalid_astype_of_different_size)
4529                      << DstTy
4530                      << SrcTy
4531                      << E->getSourceRange());
4532   return Owned(new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc,
4533                RParenLoc));
4534 }
4535 
4536 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
4537 /// provided arguments.
4538 ///
4539 /// __builtin_convertvector( value, dst type )
4540 ///
4541 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
4542                                         SourceLocation BuiltinLoc,
4543                                         SourceLocation RParenLoc) {
4544   TypeSourceInfo *TInfo;
4545   GetTypeFromParser(ParsedDestTy, &TInfo);
4546   return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
4547 }
4548 
4549 /// BuildResolvedCallExpr - Build a call to a resolved expression,
4550 /// i.e. an expression not of \p OverloadTy.  The expression should
4551 /// unary-convert to an expression of function-pointer or
4552 /// block-pointer type.
4553 ///
4554 /// \param NDecl the declaration being called, if available
4555 ExprResult
4556 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
4557                             SourceLocation LParenLoc,
4558                             ArrayRef<Expr *> Args,
4559                             SourceLocation RParenLoc,
4560                             Expr *Config, bool IsExecConfig) {
4561   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
4562   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
4563 
4564   // Promote the function operand.
4565   // We special-case function promotion here because we only allow promoting
4566   // builtin functions to function pointers in the callee of a call.
4567   ExprResult Result;
4568   if (BuiltinID &&
4569       Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
4570     Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()),
4571                                CK_BuiltinFnToFnPtr).take();
4572   } else {
4573     Result = UsualUnaryConversions(Fn);
4574   }
4575   if (Result.isInvalid())
4576     return ExprError();
4577   Fn = Result.take();
4578 
4579   // Make the call expr early, before semantic checks.  This guarantees cleanup
4580   // of arguments and function on error.
4581   CallExpr *TheCall;
4582   if (Config)
4583     TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
4584                                                cast<CallExpr>(Config), Args,
4585                                                Context.BoolTy, VK_RValue,
4586                                                RParenLoc);
4587   else
4588     TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy,
4589                                      VK_RValue, RParenLoc);
4590 
4591   // Bail out early if calling a builtin with custom typechecking.
4592   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
4593     return CheckBuiltinFunctionCall(BuiltinID, TheCall);
4594 
4595  retry:
4596   const FunctionType *FuncT;
4597   if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
4598     // C99 6.5.2.2p1 - "The expression that denotes the called function shall
4599     // have type pointer to function".
4600     FuncT = PT->getPointeeType()->getAs<FunctionType>();
4601     if (FuncT == 0)
4602       return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4603                          << Fn->getType() << Fn->getSourceRange());
4604   } else if (const BlockPointerType *BPT =
4605                Fn->getType()->getAs<BlockPointerType>()) {
4606     FuncT = BPT->getPointeeType()->castAs<FunctionType>();
4607   } else {
4608     // Handle calls to expressions of unknown-any type.
4609     if (Fn->getType() == Context.UnknownAnyTy) {
4610       ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
4611       if (rewrite.isInvalid()) return ExprError();
4612       Fn = rewrite.take();
4613       TheCall->setCallee(Fn);
4614       goto retry;
4615     }
4616 
4617     return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4618       << Fn->getType() << Fn->getSourceRange());
4619   }
4620 
4621   if (getLangOpts().CUDA) {
4622     if (Config) {
4623       // CUDA: Kernel calls must be to global functions
4624       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
4625         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
4626             << FDecl->getName() << Fn->getSourceRange());
4627 
4628       // CUDA: Kernel function must have 'void' return type
4629       if (!FuncT->getReturnType()->isVoidType())
4630         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
4631             << Fn->getType() << Fn->getSourceRange());
4632     } else {
4633       // CUDA: Calls to global functions must be configured
4634       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
4635         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
4636             << FDecl->getName() << Fn->getSourceRange());
4637     }
4638   }
4639 
4640   // Check for a valid return type
4641   if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall,
4642                           FDecl))
4643     return ExprError();
4644 
4645   // We know the result type of the call, set it.
4646   TheCall->setType(FuncT->getCallResultType(Context));
4647   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
4648 
4649   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
4650   if (Proto) {
4651     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
4652                                 IsExecConfig))
4653       return ExprError();
4654   } else {
4655     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
4656 
4657     if (FDecl) {
4658       // Check if we have too few/too many template arguments, based
4659       // on our knowledge of the function definition.
4660       const FunctionDecl *Def = 0;
4661       if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
4662         Proto = Def->getType()->getAs<FunctionProtoType>();
4663        if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
4664           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
4665           << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
4666       }
4667 
4668       // If the function we're calling isn't a function prototype, but we have
4669       // a function prototype from a prior declaratiom, use that prototype.
4670       if (!FDecl->hasPrototype())
4671         Proto = FDecl->getType()->getAs<FunctionProtoType>();
4672     }
4673 
4674     // Promote the arguments (C99 6.5.2.2p6).
4675     for (unsigned i = 0, e = Args.size(); i != e; i++) {
4676       Expr *Arg = Args[i];
4677 
4678       if (Proto && i < Proto->getNumParams()) {
4679         InitializedEntity Entity = InitializedEntity::InitializeParameter(
4680             Context, Proto->getParamType(i), Proto->isParamConsumed(i));
4681         ExprResult ArgE = PerformCopyInitialization(Entity,
4682                                                     SourceLocation(),
4683                                                     Owned(Arg));
4684         if (ArgE.isInvalid())
4685           return true;
4686 
4687         Arg = ArgE.takeAs<Expr>();
4688 
4689       } else {
4690         ExprResult ArgE = DefaultArgumentPromotion(Arg);
4691 
4692         if (ArgE.isInvalid())
4693           return true;
4694 
4695         Arg = ArgE.takeAs<Expr>();
4696       }
4697 
4698       if (RequireCompleteType(Arg->getLocStart(),
4699                               Arg->getType(),
4700                               diag::err_call_incomplete_argument, Arg))
4701         return ExprError();
4702 
4703       TheCall->setArg(i, Arg);
4704     }
4705   }
4706 
4707   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4708     if (!Method->isStatic())
4709       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
4710         << Fn->getSourceRange());
4711 
4712   // Check for sentinels
4713   if (NDecl)
4714     DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
4715 
4716   // Do special checking on direct calls to functions.
4717   if (FDecl) {
4718     if (CheckFunctionCall(FDecl, TheCall, Proto))
4719       return ExprError();
4720 
4721     if (BuiltinID)
4722       return CheckBuiltinFunctionCall(BuiltinID, TheCall);
4723   } else if (NDecl) {
4724     if (CheckPointerCall(NDecl, TheCall, Proto))
4725       return ExprError();
4726   } else {
4727     if (CheckOtherCall(TheCall, Proto))
4728       return ExprError();
4729   }
4730 
4731   return MaybeBindToTemporary(TheCall);
4732 }
4733 
4734 ExprResult
4735 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
4736                            SourceLocation RParenLoc, Expr *InitExpr) {
4737   assert(Ty && "ActOnCompoundLiteral(): missing type");
4738   // FIXME: put back this assert when initializers are worked out.
4739   //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
4740 
4741   TypeSourceInfo *TInfo;
4742   QualType literalType = GetTypeFromParser(Ty, &TInfo);
4743   if (!TInfo)
4744     TInfo = Context.getTrivialTypeSourceInfo(literalType);
4745 
4746   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
4747 }
4748 
4749 ExprResult
4750 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
4751                                SourceLocation RParenLoc, Expr *LiteralExpr) {
4752   QualType literalType = TInfo->getType();
4753 
4754   if (literalType->isArrayType()) {
4755     if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
4756           diag::err_illegal_decl_array_incomplete_type,
4757           SourceRange(LParenLoc,
4758                       LiteralExpr->getSourceRange().getEnd())))
4759       return ExprError();
4760     if (literalType->isVariableArrayType())
4761       return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
4762         << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
4763   } else if (!literalType->isDependentType() &&
4764              RequireCompleteType(LParenLoc, literalType,
4765                diag::err_typecheck_decl_incomplete_type,
4766                SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
4767     return ExprError();
4768 
4769   InitializedEntity Entity
4770     = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
4771   InitializationKind Kind
4772     = InitializationKind::CreateCStyleCast(LParenLoc,
4773                                            SourceRange(LParenLoc, RParenLoc),
4774                                            /*InitList=*/true);
4775   InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
4776   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
4777                                       &literalType);
4778   if (Result.isInvalid())
4779     return ExprError();
4780   LiteralExpr = Result.get();
4781 
4782   bool isFileScope = getCurFunctionOrMethodDecl() == 0;
4783   if (isFileScope &&
4784       !LiteralExpr->isTypeDependent() &&
4785       !LiteralExpr->isValueDependent() &&
4786       !literalType->isDependentType()) { // 6.5.2.5p3
4787     if (CheckForConstantInitializer(LiteralExpr, literalType))
4788       return ExprError();
4789   }
4790 
4791   // In C, compound literals are l-values for some reason.
4792   ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue;
4793 
4794   return MaybeBindToTemporary(
4795            new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
4796                                              VK, LiteralExpr, isFileScope));
4797 }
4798 
4799 ExprResult
4800 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
4801                     SourceLocation RBraceLoc) {
4802   // Immediately handle non-overload placeholders.  Overloads can be
4803   // resolved contextually, but everything else here can't.
4804   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
4805     if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
4806       ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
4807 
4808       // Ignore failures; dropping the entire initializer list because
4809       // of one failure would be terrible for indexing/etc.
4810       if (result.isInvalid()) continue;
4811 
4812       InitArgList[I] = result.take();
4813     }
4814   }
4815 
4816   // Semantic analysis for initializers is done by ActOnDeclarator() and
4817   // CheckInitializer() - it requires knowledge of the object being intialized.
4818 
4819   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
4820                                                RBraceLoc);
4821   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
4822   return Owned(E);
4823 }
4824 
4825 /// Do an explicit extend of the given block pointer if we're in ARC.
4826 static void maybeExtendBlockObject(Sema &S, ExprResult &E) {
4827   assert(E.get()->getType()->isBlockPointerType());
4828   assert(E.get()->isRValue());
4829 
4830   // Only do this in an r-value context.
4831   if (!S.getLangOpts().ObjCAutoRefCount) return;
4832 
4833   E = ImplicitCastExpr::Create(S.Context, E.get()->getType(),
4834                                CK_ARCExtendBlockObject, E.get(),
4835                                /*base path*/ 0, VK_RValue);
4836   S.ExprNeedsCleanups = true;
4837 }
4838 
4839 /// Prepare a conversion of the given expression to an ObjC object
4840 /// pointer type.
4841 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
4842   QualType type = E.get()->getType();
4843   if (type->isObjCObjectPointerType()) {
4844     return CK_BitCast;
4845   } else if (type->isBlockPointerType()) {
4846     maybeExtendBlockObject(*this, E);
4847     return CK_BlockPointerToObjCPointerCast;
4848   } else {
4849     assert(type->isPointerType());
4850     return CK_CPointerToObjCPointerCast;
4851   }
4852 }
4853 
4854 /// Prepares for a scalar cast, performing all the necessary stages
4855 /// except the final cast and returning the kind required.
4856 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
4857   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
4858   // Also, callers should have filtered out the invalid cases with
4859   // pointers.  Everything else should be possible.
4860 
4861   QualType SrcTy = Src.get()->getType();
4862   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
4863     return CK_NoOp;
4864 
4865   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
4866   case Type::STK_MemberPointer:
4867     llvm_unreachable("member pointer type in C");
4868 
4869   case Type::STK_CPointer:
4870   case Type::STK_BlockPointer:
4871   case Type::STK_ObjCObjectPointer:
4872     switch (DestTy->getScalarTypeKind()) {
4873     case Type::STK_CPointer: {
4874       unsigned SrcAS = SrcTy->getPointeeType().getAddressSpace();
4875       unsigned DestAS = DestTy->getPointeeType().getAddressSpace();
4876       if (SrcAS != DestAS)
4877         return CK_AddressSpaceConversion;
4878       return CK_BitCast;
4879     }
4880     case Type::STK_BlockPointer:
4881       return (SrcKind == Type::STK_BlockPointer
4882                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
4883     case Type::STK_ObjCObjectPointer:
4884       if (SrcKind == Type::STK_ObjCObjectPointer)
4885         return CK_BitCast;
4886       if (SrcKind == Type::STK_CPointer)
4887         return CK_CPointerToObjCPointerCast;
4888       maybeExtendBlockObject(*this, Src);
4889       return CK_BlockPointerToObjCPointerCast;
4890     case Type::STK_Bool:
4891       return CK_PointerToBoolean;
4892     case Type::STK_Integral:
4893       return CK_PointerToIntegral;
4894     case Type::STK_Floating:
4895     case Type::STK_FloatingComplex:
4896     case Type::STK_IntegralComplex:
4897     case Type::STK_MemberPointer:
4898       llvm_unreachable("illegal cast from pointer");
4899     }
4900     llvm_unreachable("Should have returned before this");
4901 
4902   case Type::STK_Bool: // casting from bool is like casting from an integer
4903   case Type::STK_Integral:
4904     switch (DestTy->getScalarTypeKind()) {
4905     case Type::STK_CPointer:
4906     case Type::STK_ObjCObjectPointer:
4907     case Type::STK_BlockPointer:
4908       if (Src.get()->isNullPointerConstant(Context,
4909                                            Expr::NPC_ValueDependentIsNull))
4910         return CK_NullToPointer;
4911       return CK_IntegralToPointer;
4912     case Type::STK_Bool:
4913       return CK_IntegralToBoolean;
4914     case Type::STK_Integral:
4915       return CK_IntegralCast;
4916     case Type::STK_Floating:
4917       return CK_IntegralToFloating;
4918     case Type::STK_IntegralComplex:
4919       Src = ImpCastExprToType(Src.take(),
4920                               DestTy->castAs<ComplexType>()->getElementType(),
4921                               CK_IntegralCast);
4922       return CK_IntegralRealToComplex;
4923     case Type::STK_FloatingComplex:
4924       Src = ImpCastExprToType(Src.take(),
4925                               DestTy->castAs<ComplexType>()->getElementType(),
4926                               CK_IntegralToFloating);
4927       return CK_FloatingRealToComplex;
4928     case Type::STK_MemberPointer:
4929       llvm_unreachable("member pointer type in C");
4930     }
4931     llvm_unreachable("Should have returned before this");
4932 
4933   case Type::STK_Floating:
4934     switch (DestTy->getScalarTypeKind()) {
4935     case Type::STK_Floating:
4936       return CK_FloatingCast;
4937     case Type::STK_Bool:
4938       return CK_FloatingToBoolean;
4939     case Type::STK_Integral:
4940       return CK_FloatingToIntegral;
4941     case Type::STK_FloatingComplex:
4942       Src = ImpCastExprToType(Src.take(),
4943                               DestTy->castAs<ComplexType>()->getElementType(),
4944                               CK_FloatingCast);
4945       return CK_FloatingRealToComplex;
4946     case Type::STK_IntegralComplex:
4947       Src = ImpCastExprToType(Src.take(),
4948                               DestTy->castAs<ComplexType>()->getElementType(),
4949                               CK_FloatingToIntegral);
4950       return CK_IntegralRealToComplex;
4951     case Type::STK_CPointer:
4952     case Type::STK_ObjCObjectPointer:
4953     case Type::STK_BlockPointer:
4954       llvm_unreachable("valid float->pointer cast?");
4955     case Type::STK_MemberPointer:
4956       llvm_unreachable("member pointer type in C");
4957     }
4958     llvm_unreachable("Should have returned before this");
4959 
4960   case Type::STK_FloatingComplex:
4961     switch (DestTy->getScalarTypeKind()) {
4962     case Type::STK_FloatingComplex:
4963       return CK_FloatingComplexCast;
4964     case Type::STK_IntegralComplex:
4965       return CK_FloatingComplexToIntegralComplex;
4966     case Type::STK_Floating: {
4967       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
4968       if (Context.hasSameType(ET, DestTy))
4969         return CK_FloatingComplexToReal;
4970       Src = ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal);
4971       return CK_FloatingCast;
4972     }
4973     case Type::STK_Bool:
4974       return CK_FloatingComplexToBoolean;
4975     case Type::STK_Integral:
4976       Src = ImpCastExprToType(Src.take(),
4977                               SrcTy->castAs<ComplexType>()->getElementType(),
4978                               CK_FloatingComplexToReal);
4979       return CK_FloatingToIntegral;
4980     case Type::STK_CPointer:
4981     case Type::STK_ObjCObjectPointer:
4982     case Type::STK_BlockPointer:
4983       llvm_unreachable("valid complex float->pointer cast?");
4984     case Type::STK_MemberPointer:
4985       llvm_unreachable("member pointer type in C");
4986     }
4987     llvm_unreachable("Should have returned before this");
4988 
4989   case Type::STK_IntegralComplex:
4990     switch (DestTy->getScalarTypeKind()) {
4991     case Type::STK_FloatingComplex:
4992       return CK_IntegralComplexToFloatingComplex;
4993     case Type::STK_IntegralComplex:
4994       return CK_IntegralComplexCast;
4995     case Type::STK_Integral: {
4996       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
4997       if (Context.hasSameType(ET, DestTy))
4998         return CK_IntegralComplexToReal;
4999       Src = ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal);
5000       return CK_IntegralCast;
5001     }
5002     case Type::STK_Bool:
5003       return CK_IntegralComplexToBoolean;
5004     case Type::STK_Floating:
5005       Src = ImpCastExprToType(Src.take(),
5006                               SrcTy->castAs<ComplexType>()->getElementType(),
5007                               CK_IntegralComplexToReal);
5008       return CK_IntegralToFloating;
5009     case Type::STK_CPointer:
5010     case Type::STK_ObjCObjectPointer:
5011     case Type::STK_BlockPointer:
5012       llvm_unreachable("valid complex int->pointer cast?");
5013     case Type::STK_MemberPointer:
5014       llvm_unreachable("member pointer type in C");
5015     }
5016     llvm_unreachable("Should have returned before this");
5017   }
5018 
5019   llvm_unreachable("Unhandled scalar cast");
5020 }
5021 
5022 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
5023                            CastKind &Kind) {
5024   assert(VectorTy->isVectorType() && "Not a vector type!");
5025 
5026   if (Ty->isVectorType() || Ty->isIntegerType()) {
5027     if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
5028       return Diag(R.getBegin(),
5029                   Ty->isVectorType() ?
5030                   diag::err_invalid_conversion_between_vectors :
5031                   diag::err_invalid_conversion_between_vector_and_integer)
5032         << VectorTy << Ty << R;
5033   } else
5034     return Diag(R.getBegin(),
5035                 diag::err_invalid_conversion_between_vector_and_scalar)
5036       << VectorTy << Ty << R;
5037 
5038   Kind = CK_BitCast;
5039   return false;
5040 }
5041 
5042 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
5043                                     Expr *CastExpr, CastKind &Kind) {
5044   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
5045 
5046   QualType SrcTy = CastExpr->getType();
5047 
5048   // If SrcTy is a VectorType, the total size must match to explicitly cast to
5049   // an ExtVectorType.
5050   // In OpenCL, casts between vectors of different types are not allowed.
5051   // (See OpenCL 6.2).
5052   if (SrcTy->isVectorType()) {
5053     if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)
5054         || (getLangOpts().OpenCL &&
5055             (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
5056       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
5057         << DestTy << SrcTy << R;
5058       return ExprError();
5059     }
5060     Kind = CK_BitCast;
5061     return Owned(CastExpr);
5062   }
5063 
5064   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
5065   // conversion will take place first from scalar to elt type, and then
5066   // splat from elt type to vector.
5067   if (SrcTy->isPointerType())
5068     return Diag(R.getBegin(),
5069                 diag::err_invalid_conversion_between_vector_and_scalar)
5070       << DestTy << SrcTy << R;
5071 
5072   QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
5073   ExprResult CastExprRes = Owned(CastExpr);
5074   CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy);
5075   if (CastExprRes.isInvalid())
5076     return ExprError();
5077   CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take();
5078 
5079   Kind = CK_VectorSplat;
5080   return Owned(CastExpr);
5081 }
5082 
5083 ExprResult
5084 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
5085                     Declarator &D, ParsedType &Ty,
5086                     SourceLocation RParenLoc, Expr *CastExpr) {
5087   assert(!D.isInvalidType() && (CastExpr != 0) &&
5088          "ActOnCastExpr(): missing type or expr");
5089 
5090   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
5091   if (D.isInvalidType())
5092     return ExprError();
5093 
5094   if (getLangOpts().CPlusPlus) {
5095     // Check that there are no default arguments (C++ only).
5096     CheckExtraCXXDefaultArguments(D);
5097   }
5098 
5099   checkUnusedDeclAttributes(D);
5100 
5101   QualType castType = castTInfo->getType();
5102   Ty = CreateParsedType(castType, castTInfo);
5103 
5104   bool isVectorLiteral = false;
5105 
5106   // Check for an altivec or OpenCL literal,
5107   // i.e. all the elements are integer constants.
5108   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
5109   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
5110   if ((getLangOpts().AltiVec || getLangOpts().OpenCL)
5111        && castType->isVectorType() && (PE || PLE)) {
5112     if (PLE && PLE->getNumExprs() == 0) {
5113       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
5114       return ExprError();
5115     }
5116     if (PE || PLE->getNumExprs() == 1) {
5117       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
5118       if (!E->getType()->isVectorType())
5119         isVectorLiteral = true;
5120     }
5121     else
5122       isVectorLiteral = true;
5123   }
5124 
5125   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
5126   // then handle it as such.
5127   if (isVectorLiteral)
5128     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
5129 
5130   // If the Expr being casted is a ParenListExpr, handle it specially.
5131   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
5132   // sequence of BinOp comma operators.
5133   if (isa<ParenListExpr>(CastExpr)) {
5134     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
5135     if (Result.isInvalid()) return ExprError();
5136     CastExpr = Result.take();
5137   }
5138 
5139   if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
5140       !getSourceManager().isInSystemMacro(LParenLoc))
5141     Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
5142 
5143   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
5144 }
5145 
5146 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
5147                                     SourceLocation RParenLoc, Expr *E,
5148                                     TypeSourceInfo *TInfo) {
5149   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
5150          "Expected paren or paren list expression");
5151 
5152   Expr **exprs;
5153   unsigned numExprs;
5154   Expr *subExpr;
5155   SourceLocation LiteralLParenLoc, LiteralRParenLoc;
5156   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
5157     LiteralLParenLoc = PE->getLParenLoc();
5158     LiteralRParenLoc = PE->getRParenLoc();
5159     exprs = PE->getExprs();
5160     numExprs = PE->getNumExprs();
5161   } else { // isa<ParenExpr> by assertion at function entrance
5162     LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
5163     LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
5164     subExpr = cast<ParenExpr>(E)->getSubExpr();
5165     exprs = &subExpr;
5166     numExprs = 1;
5167   }
5168 
5169   QualType Ty = TInfo->getType();
5170   assert(Ty->isVectorType() && "Expected vector type");
5171 
5172   SmallVector<Expr *, 8> initExprs;
5173   const VectorType *VTy = Ty->getAs<VectorType>();
5174   unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
5175 
5176   // '(...)' form of vector initialization in AltiVec: the number of
5177   // initializers must be one or must match the size of the vector.
5178   // If a single value is specified in the initializer then it will be
5179   // replicated to all the components of the vector
5180   if (VTy->getVectorKind() == VectorType::AltiVecVector) {
5181     // The number of initializers must be one or must match the size of the
5182     // vector. If a single value is specified in the initializer then it will
5183     // be replicated to all the components of the vector
5184     if (numExprs == 1) {
5185       QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
5186       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
5187       if (Literal.isInvalid())
5188         return ExprError();
5189       Literal = ImpCastExprToType(Literal.take(), ElemTy,
5190                                   PrepareScalarCast(Literal, ElemTy));
5191       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
5192     }
5193     else if (numExprs < numElems) {
5194       Diag(E->getExprLoc(),
5195            diag::err_incorrect_number_of_vector_initializers);
5196       return ExprError();
5197     }
5198     else
5199       initExprs.append(exprs, exprs + numExprs);
5200   }
5201   else {
5202     // For OpenCL, when the number of initializers is a single value,
5203     // it will be replicated to all components of the vector.
5204     if (getLangOpts().OpenCL &&
5205         VTy->getVectorKind() == VectorType::GenericVector &&
5206         numExprs == 1) {
5207         QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
5208         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
5209         if (Literal.isInvalid())
5210           return ExprError();
5211         Literal = ImpCastExprToType(Literal.take(), ElemTy,
5212                                     PrepareScalarCast(Literal, ElemTy));
5213         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
5214     }
5215 
5216     initExprs.append(exprs, exprs + numExprs);
5217   }
5218   // FIXME: This means that pretty-printing the final AST will produce curly
5219   // braces instead of the original commas.
5220   InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
5221                                                    initExprs, LiteralRParenLoc);
5222   initE->setType(Ty);
5223   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
5224 }
5225 
5226 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
5227 /// the ParenListExpr into a sequence of comma binary operators.
5228 ExprResult
5229 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
5230   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
5231   if (!E)
5232     return Owned(OrigExpr);
5233 
5234   ExprResult Result(E->getExpr(0));
5235 
5236   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
5237     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
5238                         E->getExpr(i));
5239 
5240   if (Result.isInvalid()) return ExprError();
5241 
5242   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
5243 }
5244 
5245 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
5246                                     SourceLocation R,
5247                                     MultiExprArg Val) {
5248   Expr *expr = new (Context) ParenListExpr(Context, L, Val, R);
5249   return Owned(expr);
5250 }
5251 
5252 /// \brief Emit a specialized diagnostic when one expression is a null pointer
5253 /// constant and the other is not a pointer.  Returns true if a diagnostic is
5254 /// emitted.
5255 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
5256                                       SourceLocation QuestionLoc) {
5257   Expr *NullExpr = LHSExpr;
5258   Expr *NonPointerExpr = RHSExpr;
5259   Expr::NullPointerConstantKind NullKind =
5260       NullExpr->isNullPointerConstant(Context,
5261                                       Expr::NPC_ValueDependentIsNotNull);
5262 
5263   if (NullKind == Expr::NPCK_NotNull) {
5264     NullExpr = RHSExpr;
5265     NonPointerExpr = LHSExpr;
5266     NullKind =
5267         NullExpr->isNullPointerConstant(Context,
5268                                         Expr::NPC_ValueDependentIsNotNull);
5269   }
5270 
5271   if (NullKind == Expr::NPCK_NotNull)
5272     return false;
5273 
5274   if (NullKind == Expr::NPCK_ZeroExpression)
5275     return false;
5276 
5277   if (NullKind == Expr::NPCK_ZeroLiteral) {
5278     // In this case, check to make sure that we got here from a "NULL"
5279     // string in the source code.
5280     NullExpr = NullExpr->IgnoreParenImpCasts();
5281     SourceLocation loc = NullExpr->getExprLoc();
5282     if (!findMacroSpelling(loc, "NULL"))
5283       return false;
5284   }
5285 
5286   int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
5287   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
5288       << NonPointerExpr->getType() << DiagType
5289       << NonPointerExpr->getSourceRange();
5290   return true;
5291 }
5292 
5293 /// \brief Return false if the condition expression is valid, true otherwise.
5294 static bool checkCondition(Sema &S, Expr *Cond) {
5295   QualType CondTy = Cond->getType();
5296 
5297   // C99 6.5.15p2
5298   if (CondTy->isScalarType()) return false;
5299 
5300   // OpenCL v1.1 s6.3.i says the condition is allowed to be a vector or scalar.
5301   if (S.getLangOpts().OpenCL && CondTy->isVectorType())
5302     return false;
5303 
5304   // Emit the proper error message.
5305   S.Diag(Cond->getLocStart(), S.getLangOpts().OpenCL ?
5306                               diag::err_typecheck_cond_expect_scalar :
5307                               diag::err_typecheck_cond_expect_scalar_or_vector)
5308     << CondTy;
5309   return true;
5310 }
5311 
5312 /// \brief Return false if the two expressions can be converted to a vector,
5313 /// true otherwise
5314 static bool checkConditionalConvertScalarsToVectors(Sema &S, ExprResult &LHS,
5315                                                     ExprResult &RHS,
5316                                                     QualType CondTy) {
5317   // Both operands should be of scalar type.
5318   if (!LHS.get()->getType()->isScalarType()) {
5319     S.Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
5320       << CondTy;
5321     return true;
5322   }
5323   if (!RHS.get()->getType()->isScalarType()) {
5324     S.Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
5325       << CondTy;
5326     return true;
5327   }
5328 
5329   // Implicity convert these scalars to the type of the condition.
5330   LHS = S.ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast);
5331   RHS = S.ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast);
5332   return false;
5333 }
5334 
5335 /// \brief Handle when one or both operands are void type.
5336 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
5337                                          ExprResult &RHS) {
5338     Expr *LHSExpr = LHS.get();
5339     Expr *RHSExpr = RHS.get();
5340 
5341     if (!LHSExpr->getType()->isVoidType())
5342       S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
5343         << RHSExpr->getSourceRange();
5344     if (!RHSExpr->getType()->isVoidType())
5345       S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
5346         << LHSExpr->getSourceRange();
5347     LHS = S.ImpCastExprToType(LHS.take(), S.Context.VoidTy, CK_ToVoid);
5348     RHS = S.ImpCastExprToType(RHS.take(), S.Context.VoidTy, CK_ToVoid);
5349     return S.Context.VoidTy;
5350 }
5351 
5352 /// \brief Return false if the NullExpr can be promoted to PointerTy,
5353 /// true otherwise.
5354 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
5355                                         QualType PointerTy) {
5356   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
5357       !NullExpr.get()->isNullPointerConstant(S.Context,
5358                                             Expr::NPC_ValueDependentIsNull))
5359     return true;
5360 
5361   NullExpr = S.ImpCastExprToType(NullExpr.take(), PointerTy, CK_NullToPointer);
5362   return false;
5363 }
5364 
5365 /// \brief Checks compatibility between two pointers and return the resulting
5366 /// type.
5367 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
5368                                                      ExprResult &RHS,
5369                                                      SourceLocation Loc) {
5370   QualType LHSTy = LHS.get()->getType();
5371   QualType RHSTy = RHS.get()->getType();
5372 
5373   if (S.Context.hasSameType(LHSTy, RHSTy)) {
5374     // Two identical pointers types are always compatible.
5375     return LHSTy;
5376   }
5377 
5378   QualType lhptee, rhptee;
5379 
5380   // Get the pointee types.
5381   bool IsBlockPointer = false;
5382   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
5383     lhptee = LHSBTy->getPointeeType();
5384     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
5385     IsBlockPointer = true;
5386   } else {
5387     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
5388     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
5389   }
5390 
5391   // C99 6.5.15p6: If both operands are pointers to compatible types or to
5392   // differently qualified versions of compatible types, the result type is
5393   // a pointer to an appropriately qualified version of the composite
5394   // type.
5395 
5396   // Only CVR-qualifiers exist in the standard, and the differently-qualified
5397   // clause doesn't make sense for our extensions. E.g. address space 2 should
5398   // be incompatible with address space 3: they may live on different devices or
5399   // anything.
5400   Qualifiers lhQual = lhptee.getQualifiers();
5401   Qualifiers rhQual = rhptee.getQualifiers();
5402 
5403   unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
5404   lhQual.removeCVRQualifiers();
5405   rhQual.removeCVRQualifiers();
5406 
5407   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
5408   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
5409 
5410   QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
5411 
5412   if (CompositeTy.isNull()) {
5413     S.Diag(Loc, diag::warn_typecheck_cond_incompatible_pointers)
5414       << LHSTy << RHSTy << LHS.get()->getSourceRange()
5415       << RHS.get()->getSourceRange();
5416     // In this situation, we assume void* type. No especially good
5417     // reason, but this is what gcc does, and we do have to pick
5418     // to get a consistent AST.
5419     QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy);
5420     LHS = S.ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
5421     RHS = S.ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
5422     return incompatTy;
5423   }
5424 
5425   // The pointer types are compatible.
5426   QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual);
5427   if (IsBlockPointer)
5428     ResultTy = S.Context.getBlockPointerType(ResultTy);
5429   else
5430     ResultTy = S.Context.getPointerType(ResultTy);
5431 
5432   LHS = S.ImpCastExprToType(LHS.take(), ResultTy, CK_BitCast);
5433   RHS = S.ImpCastExprToType(RHS.take(), ResultTy, CK_BitCast);
5434   return ResultTy;
5435 }
5436 
5437 /// \brief Return the resulting type when the operands are both block pointers.
5438 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
5439                                                           ExprResult &LHS,
5440                                                           ExprResult &RHS,
5441                                                           SourceLocation Loc) {
5442   QualType LHSTy = LHS.get()->getType();
5443   QualType RHSTy = RHS.get()->getType();
5444 
5445   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
5446     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
5447       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
5448       LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
5449       RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
5450       return destType;
5451     }
5452     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
5453       << LHSTy << RHSTy << LHS.get()->getSourceRange()
5454       << RHS.get()->getSourceRange();
5455     return QualType();
5456   }
5457 
5458   // We have 2 block pointer types.
5459   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
5460 }
5461 
5462 /// \brief Return the resulting type when the operands are both pointers.
5463 static QualType
5464 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
5465                                             ExprResult &RHS,
5466                                             SourceLocation Loc) {
5467   // get the pointer types
5468   QualType LHSTy = LHS.get()->getType();
5469   QualType RHSTy = RHS.get()->getType();
5470 
5471   // get the "pointed to" types
5472   QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5473   QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
5474 
5475   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
5476   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
5477     // Figure out necessary qualifiers (C99 6.5.15p6)
5478     QualType destPointee
5479       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
5480     QualType destType = S.Context.getPointerType(destPointee);
5481     // Add qualifiers if necessary.
5482     LHS = S.ImpCastExprToType(LHS.take(), destType, CK_NoOp);
5483     // Promote to void*.
5484     RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
5485     return destType;
5486   }
5487   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
5488     QualType destPointee
5489       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
5490     QualType destType = S.Context.getPointerType(destPointee);
5491     // Add qualifiers if necessary.
5492     RHS = S.ImpCastExprToType(RHS.take(), destType, CK_NoOp);
5493     // Promote to void*.
5494     LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
5495     return destType;
5496   }
5497 
5498   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
5499 }
5500 
5501 /// \brief Return false if the first expression is not an integer and the second
5502 /// expression is not a pointer, true otherwise.
5503 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
5504                                         Expr* PointerExpr, SourceLocation Loc,
5505                                         bool IsIntFirstExpr) {
5506   if (!PointerExpr->getType()->isPointerType() ||
5507       !Int.get()->getType()->isIntegerType())
5508     return false;
5509 
5510   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
5511   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
5512 
5513   S.Diag(Loc, diag::warn_typecheck_cond_pointer_integer_mismatch)
5514     << Expr1->getType() << Expr2->getType()
5515     << Expr1->getSourceRange() << Expr2->getSourceRange();
5516   Int = S.ImpCastExprToType(Int.take(), PointerExpr->getType(),
5517                             CK_IntegralToPointer);
5518   return true;
5519 }
5520 
5521 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
5522 /// In that case, LHS = cond.
5523 /// C99 6.5.15
5524 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
5525                                         ExprResult &RHS, ExprValueKind &VK,
5526                                         ExprObjectKind &OK,
5527                                         SourceLocation QuestionLoc) {
5528 
5529   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
5530   if (!LHSResult.isUsable()) return QualType();
5531   LHS = LHSResult;
5532 
5533   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
5534   if (!RHSResult.isUsable()) return QualType();
5535   RHS = RHSResult;
5536 
5537   // C++ is sufficiently different to merit its own checker.
5538   if (getLangOpts().CPlusPlus)
5539     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
5540 
5541   VK = VK_RValue;
5542   OK = OK_Ordinary;
5543 
5544   // First, check the condition.
5545   Cond = UsualUnaryConversions(Cond.take());
5546   if (Cond.isInvalid())
5547     return QualType();
5548   if (checkCondition(*this, Cond.get()))
5549     return QualType();
5550 
5551   // Now check the two expressions.
5552   if (LHS.get()->getType()->isVectorType() ||
5553       RHS.get()->getType()->isVectorType())
5554     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
5555 
5556   UsualArithmeticConversions(LHS, RHS);
5557   if (LHS.isInvalid() || RHS.isInvalid())
5558     return QualType();
5559 
5560   QualType CondTy = Cond.get()->getType();
5561   QualType LHSTy = LHS.get()->getType();
5562   QualType RHSTy = RHS.get()->getType();
5563 
5564   // If the condition is a vector, and both operands are scalar,
5565   // attempt to implicity convert them to the vector type to act like the
5566   // built in select. (OpenCL v1.1 s6.3.i)
5567   if (getLangOpts().OpenCL && CondTy->isVectorType())
5568     if (checkConditionalConvertScalarsToVectors(*this, LHS, RHS, CondTy))
5569       return QualType();
5570 
5571   // If both operands have arithmetic type, do the usual arithmetic conversions
5572   // to find a common type: C99 6.5.15p3,5.
5573   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType())
5574     return LHS.get()->getType();
5575 
5576   // If both operands are the same structure or union type, the result is that
5577   // type.
5578   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
5579     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
5580       if (LHSRT->getDecl() == RHSRT->getDecl())
5581         // "If both the operands have structure or union type, the result has
5582         // that type."  This implies that CV qualifiers are dropped.
5583         return LHSTy.getUnqualifiedType();
5584     // FIXME: Type of conditional expression must be complete in C mode.
5585   }
5586 
5587   // C99 6.5.15p5: "If both operands have void type, the result has void type."
5588   // The following || allows only one side to be void (a GCC-ism).
5589   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
5590     return checkConditionalVoidType(*this, LHS, RHS);
5591   }
5592 
5593   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
5594   // the type of the other operand."
5595   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
5596   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
5597 
5598   // All objective-c pointer type analysis is done here.
5599   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
5600                                                         QuestionLoc);
5601   if (LHS.isInvalid() || RHS.isInvalid())
5602     return QualType();
5603   if (!compositeType.isNull())
5604     return compositeType;
5605 
5606 
5607   // Handle block pointer types.
5608   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
5609     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
5610                                                      QuestionLoc);
5611 
5612   // Check constraints for C object pointers types (C99 6.5.15p3,6).
5613   if (LHSTy->isPointerType() && RHSTy->isPointerType())
5614     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
5615                                                        QuestionLoc);
5616 
5617   // GCC compatibility: soften pointer/integer mismatch.  Note that
5618   // null pointers have been filtered out by this point.
5619   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
5620       /*isIntFirstExpr=*/true))
5621     return RHSTy;
5622   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
5623       /*isIntFirstExpr=*/false))
5624     return LHSTy;
5625 
5626   // Emit a better diagnostic if one of the expressions is a null pointer
5627   // constant and the other is not a pointer type. In this case, the user most
5628   // likely forgot to take the address of the other expression.
5629   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
5630     return QualType();
5631 
5632   // Otherwise, the operands are not compatible.
5633   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
5634     << LHSTy << RHSTy << LHS.get()->getSourceRange()
5635     << RHS.get()->getSourceRange();
5636   return QualType();
5637 }
5638 
5639 /// FindCompositeObjCPointerType - Helper method to find composite type of
5640 /// two objective-c pointer types of the two input expressions.
5641 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
5642                                             SourceLocation QuestionLoc) {
5643   QualType LHSTy = LHS.get()->getType();
5644   QualType RHSTy = RHS.get()->getType();
5645 
5646   // Handle things like Class and struct objc_class*.  Here we case the result
5647   // to the pseudo-builtin, because that will be implicitly cast back to the
5648   // redefinition type if an attempt is made to access its fields.
5649   if (LHSTy->isObjCClassType() &&
5650       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
5651     RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
5652     return LHSTy;
5653   }
5654   if (RHSTy->isObjCClassType() &&
5655       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
5656     LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
5657     return RHSTy;
5658   }
5659   // And the same for struct objc_object* / id
5660   if (LHSTy->isObjCIdType() &&
5661       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
5662     RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
5663     return LHSTy;
5664   }
5665   if (RHSTy->isObjCIdType() &&
5666       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
5667     LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
5668     return RHSTy;
5669   }
5670   // And the same for struct objc_selector* / SEL
5671   if (Context.isObjCSelType(LHSTy) &&
5672       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
5673     RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
5674     return LHSTy;
5675   }
5676   if (Context.isObjCSelType(RHSTy) &&
5677       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
5678     LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
5679     return RHSTy;
5680   }
5681   // Check constraints for Objective-C object pointers types.
5682   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
5683 
5684     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5685       // Two identical object pointer types are always compatible.
5686       return LHSTy;
5687     }
5688     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
5689     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
5690     QualType compositeType = LHSTy;
5691 
5692     // If both operands are interfaces and either operand can be
5693     // assigned to the other, use that type as the composite
5694     // type. This allows
5695     //   xxx ? (A*) a : (B*) b
5696     // where B is a subclass of A.
5697     //
5698     // Additionally, as for assignment, if either type is 'id'
5699     // allow silent coercion. Finally, if the types are
5700     // incompatible then make sure to use 'id' as the composite
5701     // type so the result is acceptable for sending messages to.
5702 
5703     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
5704     // It could return the composite type.
5705     if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
5706       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
5707     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
5708       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
5709     } else if ((LHSTy->isObjCQualifiedIdType() ||
5710                 RHSTy->isObjCQualifiedIdType()) &&
5711                Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
5712       // Need to handle "id<xx>" explicitly.
5713       // GCC allows qualified id and any Objective-C type to devolve to
5714       // id. Currently localizing to here until clear this should be
5715       // part of ObjCQualifiedIdTypesAreCompatible.
5716       compositeType = Context.getObjCIdType();
5717     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
5718       compositeType = Context.getObjCIdType();
5719     } else if (!(compositeType =
5720                  Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
5721       ;
5722     else {
5723       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
5724       << LHSTy << RHSTy
5725       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5726       QualType incompatTy = Context.getObjCIdType();
5727       LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
5728       RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
5729       return incompatTy;
5730     }
5731     // The object pointer types are compatible.
5732     LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast);
5733     RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast);
5734     return compositeType;
5735   }
5736   // Check Objective-C object pointer types and 'void *'
5737   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
5738     if (getLangOpts().ObjCAutoRefCount) {
5739       // ARC forbids the implicit conversion of object pointers to 'void *',
5740       // so these types are not compatible.
5741       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
5742           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5743       LHS = RHS = true;
5744       return QualType();
5745     }
5746     QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5747     QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5748     QualType destPointee
5749     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
5750     QualType destType = Context.getPointerType(destPointee);
5751     // Add qualifiers if necessary.
5752     LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
5753     // Promote to void*.
5754     RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
5755     return destType;
5756   }
5757   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
5758     if (getLangOpts().ObjCAutoRefCount) {
5759       // ARC forbids the implicit conversion of object pointers to 'void *',
5760       // so these types are not compatible.
5761       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
5762           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5763       LHS = RHS = true;
5764       return QualType();
5765     }
5766     QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5767     QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
5768     QualType destPointee
5769     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
5770     QualType destType = Context.getPointerType(destPointee);
5771     // Add qualifiers if necessary.
5772     RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
5773     // Promote to void*.
5774     LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
5775     return destType;
5776   }
5777   return QualType();
5778 }
5779 
5780 /// SuggestParentheses - Emit a note with a fixit hint that wraps
5781 /// ParenRange in parentheses.
5782 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
5783                                const PartialDiagnostic &Note,
5784                                SourceRange ParenRange) {
5785   SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
5786   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
5787       EndLoc.isValid()) {
5788     Self.Diag(Loc, Note)
5789       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
5790       << FixItHint::CreateInsertion(EndLoc, ")");
5791   } else {
5792     // We can't display the parentheses, so just show the bare note.
5793     Self.Diag(Loc, Note) << ParenRange;
5794   }
5795 }
5796 
5797 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
5798   return Opc >= BO_Mul && Opc <= BO_Shr;
5799 }
5800 
5801 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
5802 /// expression, either using a built-in or overloaded operator,
5803 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
5804 /// expression.
5805 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
5806                                    Expr **RHSExprs) {
5807   // Don't strip parenthesis: we should not warn if E is in parenthesis.
5808   E = E->IgnoreImpCasts();
5809   E = E->IgnoreConversionOperator();
5810   E = E->IgnoreImpCasts();
5811 
5812   // Built-in binary operator.
5813   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
5814     if (IsArithmeticOp(OP->getOpcode())) {
5815       *Opcode = OP->getOpcode();
5816       *RHSExprs = OP->getRHS();
5817       return true;
5818     }
5819   }
5820 
5821   // Overloaded operator.
5822   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
5823     if (Call->getNumArgs() != 2)
5824       return false;
5825 
5826     // Make sure this is really a binary operator that is safe to pass into
5827     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
5828     OverloadedOperatorKind OO = Call->getOperator();
5829     if (OO < OO_Plus || OO > OO_Arrow ||
5830         OO == OO_PlusPlus || OO == OO_MinusMinus)
5831       return false;
5832 
5833     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
5834     if (IsArithmeticOp(OpKind)) {
5835       *Opcode = OpKind;
5836       *RHSExprs = Call->getArg(1);
5837       return true;
5838     }
5839   }
5840 
5841   return false;
5842 }
5843 
5844 static bool IsLogicOp(BinaryOperatorKind Opc) {
5845   return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
5846 }
5847 
5848 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
5849 /// or is a logical expression such as (x==y) which has int type, but is
5850 /// commonly interpreted as boolean.
5851 static bool ExprLooksBoolean(Expr *E) {
5852   E = E->IgnoreParenImpCasts();
5853 
5854   if (E->getType()->isBooleanType())
5855     return true;
5856   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
5857     return IsLogicOp(OP->getOpcode());
5858   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
5859     return OP->getOpcode() == UO_LNot;
5860 
5861   return false;
5862 }
5863 
5864 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
5865 /// and binary operator are mixed in a way that suggests the programmer assumed
5866 /// the conditional operator has higher precedence, for example:
5867 /// "int x = a + someBinaryCondition ? 1 : 2".
5868 static void DiagnoseConditionalPrecedence(Sema &Self,
5869                                           SourceLocation OpLoc,
5870                                           Expr *Condition,
5871                                           Expr *LHSExpr,
5872                                           Expr *RHSExpr) {
5873   BinaryOperatorKind CondOpcode;
5874   Expr *CondRHS;
5875 
5876   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
5877     return;
5878   if (!ExprLooksBoolean(CondRHS))
5879     return;
5880 
5881   // The condition is an arithmetic binary expression, with a right-
5882   // hand side that looks boolean, so warn.
5883 
5884   Self.Diag(OpLoc, diag::warn_precedence_conditional)
5885       << Condition->getSourceRange()
5886       << BinaryOperator::getOpcodeStr(CondOpcode);
5887 
5888   SuggestParentheses(Self, OpLoc,
5889     Self.PDiag(diag::note_precedence_silence)
5890       << BinaryOperator::getOpcodeStr(CondOpcode),
5891     SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
5892 
5893   SuggestParentheses(Self, OpLoc,
5894     Self.PDiag(diag::note_precedence_conditional_first),
5895     SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
5896 }
5897 
5898 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
5899 /// in the case of a the GNU conditional expr extension.
5900 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
5901                                     SourceLocation ColonLoc,
5902                                     Expr *CondExpr, Expr *LHSExpr,
5903                                     Expr *RHSExpr) {
5904   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
5905   // was the condition.
5906   OpaqueValueExpr *opaqueValue = 0;
5907   Expr *commonExpr = 0;
5908   if (LHSExpr == 0) {
5909     commonExpr = CondExpr;
5910     // Lower out placeholder types first.  This is important so that we don't
5911     // try to capture a placeholder. This happens in few cases in C++; such
5912     // as Objective-C++'s dictionary subscripting syntax.
5913     if (commonExpr->hasPlaceholderType()) {
5914       ExprResult result = CheckPlaceholderExpr(commonExpr);
5915       if (!result.isUsable()) return ExprError();
5916       commonExpr = result.take();
5917     }
5918     // We usually want to apply unary conversions *before* saving, except
5919     // in the special case of a C++ l-value conditional.
5920     if (!(getLangOpts().CPlusPlus
5921           && !commonExpr->isTypeDependent()
5922           && commonExpr->getValueKind() == RHSExpr->getValueKind()
5923           && commonExpr->isGLValue()
5924           && commonExpr->isOrdinaryOrBitFieldObject()
5925           && RHSExpr->isOrdinaryOrBitFieldObject()
5926           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
5927       ExprResult commonRes = UsualUnaryConversions(commonExpr);
5928       if (commonRes.isInvalid())
5929         return ExprError();
5930       commonExpr = commonRes.take();
5931     }
5932 
5933     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
5934                                                 commonExpr->getType(),
5935                                                 commonExpr->getValueKind(),
5936                                                 commonExpr->getObjectKind(),
5937                                                 commonExpr);
5938     LHSExpr = CondExpr = opaqueValue;
5939   }
5940 
5941   ExprValueKind VK = VK_RValue;
5942   ExprObjectKind OK = OK_Ordinary;
5943   ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
5944   QualType result = CheckConditionalOperands(Cond, LHS, RHS,
5945                                              VK, OK, QuestionLoc);
5946   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
5947       RHS.isInvalid())
5948     return ExprError();
5949 
5950   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
5951                                 RHS.get());
5952 
5953   if (!commonExpr)
5954     return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc,
5955                                                    LHS.take(), ColonLoc,
5956                                                    RHS.take(), result, VK, OK));
5957 
5958   return Owned(new (Context)
5959     BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(),
5960                               RHS.take(), QuestionLoc, ColonLoc, result, VK,
5961                               OK));
5962 }
5963 
5964 // checkPointerTypesForAssignment - This is a very tricky routine (despite
5965 // being closely modeled after the C99 spec:-). The odd characteristic of this
5966 // routine is it effectively iqnores the qualifiers on the top level pointee.
5967 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
5968 // FIXME: add a couple examples in this comment.
5969 static Sema::AssignConvertType
5970 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
5971   assert(LHSType.isCanonical() && "LHS not canonicalized!");
5972   assert(RHSType.isCanonical() && "RHS not canonicalized!");
5973 
5974   // get the "pointed to" type (ignoring qualifiers at the top level)
5975   const Type *lhptee, *rhptee;
5976   Qualifiers lhq, rhq;
5977   llvm::tie(lhptee, lhq) = cast<PointerType>(LHSType)->getPointeeType().split();
5978   llvm::tie(rhptee, rhq) = cast<PointerType>(RHSType)->getPointeeType().split();
5979 
5980   Sema::AssignConvertType ConvTy = Sema::Compatible;
5981 
5982   // C99 6.5.16.1p1: This following citation is common to constraints
5983   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
5984   // qualifiers of the type *pointed to* by the right;
5985 
5986   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
5987   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
5988       lhq.compatiblyIncludesObjCLifetime(rhq)) {
5989     // Ignore lifetime for further calculation.
5990     lhq.removeObjCLifetime();
5991     rhq.removeObjCLifetime();
5992   }
5993 
5994   if (!lhq.compatiblyIncludes(rhq)) {
5995     // Treat address-space mismatches as fatal.  TODO: address subspaces
5996     if (lhq.getAddressSpace() != rhq.getAddressSpace())
5997       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5998 
5999     // It's okay to add or remove GC or lifetime qualifiers when converting to
6000     // and from void*.
6001     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
6002                         .compatiblyIncludes(
6003                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
6004              && (lhptee->isVoidType() || rhptee->isVoidType()))
6005       ; // keep old
6006 
6007     // Treat lifetime mismatches as fatal.
6008     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
6009       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
6010 
6011     // For GCC compatibility, other qualifier mismatches are treated
6012     // as still compatible in C.
6013     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
6014   }
6015 
6016   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
6017   // incomplete type and the other is a pointer to a qualified or unqualified
6018   // version of void...
6019   if (lhptee->isVoidType()) {
6020     if (rhptee->isIncompleteOrObjectType())
6021       return ConvTy;
6022 
6023     // As an extension, we allow cast to/from void* to function pointer.
6024     assert(rhptee->isFunctionType());
6025     return Sema::FunctionVoidPointer;
6026   }
6027 
6028   if (rhptee->isVoidType()) {
6029     if (lhptee->isIncompleteOrObjectType())
6030       return ConvTy;
6031 
6032     // As an extension, we allow cast to/from void* to function pointer.
6033     assert(lhptee->isFunctionType());
6034     return Sema::FunctionVoidPointer;
6035   }
6036 
6037   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
6038   // unqualified versions of compatible types, ...
6039   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
6040   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
6041     // Check if the pointee types are compatible ignoring the sign.
6042     // We explicitly check for char so that we catch "char" vs
6043     // "unsigned char" on systems where "char" is unsigned.
6044     if (lhptee->isCharType())
6045       ltrans = S.Context.UnsignedCharTy;
6046     else if (lhptee->hasSignedIntegerRepresentation())
6047       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
6048 
6049     if (rhptee->isCharType())
6050       rtrans = S.Context.UnsignedCharTy;
6051     else if (rhptee->hasSignedIntegerRepresentation())
6052       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
6053 
6054     if (ltrans == rtrans) {
6055       // Types are compatible ignoring the sign. Qualifier incompatibility
6056       // takes priority over sign incompatibility because the sign
6057       // warning can be disabled.
6058       if (ConvTy != Sema::Compatible)
6059         return ConvTy;
6060 
6061       return Sema::IncompatiblePointerSign;
6062     }
6063 
6064     // If we are a multi-level pointer, it's possible that our issue is simply
6065     // one of qualification - e.g. char ** -> const char ** is not allowed. If
6066     // the eventual target type is the same and the pointers have the same
6067     // level of indirection, this must be the issue.
6068     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
6069       do {
6070         lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
6071         rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
6072       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
6073 
6074       if (lhptee == rhptee)
6075         return Sema::IncompatibleNestedPointerQualifiers;
6076     }
6077 
6078     // General pointer incompatibility takes priority over qualifiers.
6079     return Sema::IncompatiblePointer;
6080   }
6081   if (!S.getLangOpts().CPlusPlus &&
6082       S.IsNoReturnConversion(ltrans, rtrans, ltrans))
6083     return Sema::IncompatiblePointer;
6084   return ConvTy;
6085 }
6086 
6087 /// checkBlockPointerTypesForAssignment - This routine determines whether two
6088 /// block pointer types are compatible or whether a block and normal pointer
6089 /// are compatible. It is more restrict than comparing two function pointer
6090 // types.
6091 static Sema::AssignConvertType
6092 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
6093                                     QualType RHSType) {
6094   assert(LHSType.isCanonical() && "LHS not canonicalized!");
6095   assert(RHSType.isCanonical() && "RHS not canonicalized!");
6096 
6097   QualType lhptee, rhptee;
6098 
6099   // get the "pointed to" type (ignoring qualifiers at the top level)
6100   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
6101   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
6102 
6103   // In C++, the types have to match exactly.
6104   if (S.getLangOpts().CPlusPlus)
6105     return Sema::IncompatibleBlockPointer;
6106 
6107   Sema::AssignConvertType ConvTy = Sema::Compatible;
6108 
6109   // For blocks we enforce that qualifiers are identical.
6110   if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
6111     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
6112 
6113   if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
6114     return Sema::IncompatibleBlockPointer;
6115 
6116   return ConvTy;
6117 }
6118 
6119 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
6120 /// for assignment compatibility.
6121 static Sema::AssignConvertType
6122 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
6123                                    QualType RHSType) {
6124   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
6125   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
6126 
6127   if (LHSType->isObjCBuiltinType()) {
6128     // Class is not compatible with ObjC object pointers.
6129     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
6130         !RHSType->isObjCQualifiedClassType())
6131       return Sema::IncompatiblePointer;
6132     return Sema::Compatible;
6133   }
6134   if (RHSType->isObjCBuiltinType()) {
6135     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
6136         !LHSType->isObjCQualifiedClassType())
6137       return Sema::IncompatiblePointer;
6138     return Sema::Compatible;
6139   }
6140   QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
6141   QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
6142 
6143   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
6144       // make an exception for id<P>
6145       !LHSType->isObjCQualifiedIdType())
6146     return Sema::CompatiblePointerDiscardsQualifiers;
6147 
6148   if (S.Context.typesAreCompatible(LHSType, RHSType))
6149     return Sema::Compatible;
6150   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
6151     return Sema::IncompatibleObjCQualifiedId;
6152   return Sema::IncompatiblePointer;
6153 }
6154 
6155 Sema::AssignConvertType
6156 Sema::CheckAssignmentConstraints(SourceLocation Loc,
6157                                  QualType LHSType, QualType RHSType) {
6158   // Fake up an opaque expression.  We don't actually care about what
6159   // cast operations are required, so if CheckAssignmentConstraints
6160   // adds casts to this they'll be wasted, but fortunately that doesn't
6161   // usually happen on valid code.
6162   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
6163   ExprResult RHSPtr = &RHSExpr;
6164   CastKind K = CK_Invalid;
6165 
6166   return CheckAssignmentConstraints(LHSType, RHSPtr, K);
6167 }
6168 
6169 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
6170 /// has code to accommodate several GCC extensions when type checking
6171 /// pointers. Here are some objectionable examples that GCC considers warnings:
6172 ///
6173 ///  int a, *pint;
6174 ///  short *pshort;
6175 ///  struct foo *pfoo;
6176 ///
6177 ///  pint = pshort; // warning: assignment from incompatible pointer type
6178 ///  a = pint; // warning: assignment makes integer from pointer without a cast
6179 ///  pint = a; // warning: assignment makes pointer from integer without a cast
6180 ///  pint = pfoo; // warning: assignment from incompatible pointer type
6181 ///
6182 /// As a result, the code for dealing with pointers is more complex than the
6183 /// C99 spec dictates.
6184 ///
6185 /// Sets 'Kind' for any result kind except Incompatible.
6186 Sema::AssignConvertType
6187 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
6188                                  CastKind &Kind) {
6189   QualType RHSType = RHS.get()->getType();
6190   QualType OrigLHSType = LHSType;
6191 
6192   // Get canonical types.  We're not formatting these types, just comparing
6193   // them.
6194   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
6195   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
6196 
6197   // Common case: no conversion required.
6198   if (LHSType == RHSType) {
6199     Kind = CK_NoOp;
6200     return Compatible;
6201   }
6202 
6203   // If we have an atomic type, try a non-atomic assignment, then just add an
6204   // atomic qualification step.
6205   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
6206     Sema::AssignConvertType result =
6207       CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
6208     if (result != Compatible)
6209       return result;
6210     if (Kind != CK_NoOp)
6211       RHS = ImpCastExprToType(RHS.take(), AtomicTy->getValueType(), Kind);
6212     Kind = CK_NonAtomicToAtomic;
6213     return Compatible;
6214   }
6215 
6216   // If the left-hand side is a reference type, then we are in a
6217   // (rare!) case where we've allowed the use of references in C,
6218   // e.g., as a parameter type in a built-in function. In this case,
6219   // just make sure that the type referenced is compatible with the
6220   // right-hand side type. The caller is responsible for adjusting
6221   // LHSType so that the resulting expression does not have reference
6222   // type.
6223   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
6224     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
6225       Kind = CK_LValueBitCast;
6226       return Compatible;
6227     }
6228     return Incompatible;
6229   }
6230 
6231   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
6232   // to the same ExtVector type.
6233   if (LHSType->isExtVectorType()) {
6234     if (RHSType->isExtVectorType())
6235       return Incompatible;
6236     if (RHSType->isArithmeticType()) {
6237       // CK_VectorSplat does T -> vector T, so first cast to the
6238       // element type.
6239       QualType elType = cast<ExtVectorType>(LHSType)->getElementType();
6240       if (elType != RHSType) {
6241         Kind = PrepareScalarCast(RHS, elType);
6242         RHS = ImpCastExprToType(RHS.take(), elType, Kind);
6243       }
6244       Kind = CK_VectorSplat;
6245       return Compatible;
6246     }
6247   }
6248 
6249   // Conversions to or from vector type.
6250   if (LHSType->isVectorType() || RHSType->isVectorType()) {
6251     if (LHSType->isVectorType() && RHSType->isVectorType()) {
6252       // Allow assignments of an AltiVec vector type to an equivalent GCC
6253       // vector type and vice versa
6254       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
6255         Kind = CK_BitCast;
6256         return Compatible;
6257       }
6258 
6259       // If we are allowing lax vector conversions, and LHS and RHS are both
6260       // vectors, the total size only needs to be the same. This is a bitcast;
6261       // no bits are changed but the result type is different.
6262       if (getLangOpts().LaxVectorConversions &&
6263           (Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType))) {
6264         Kind = CK_BitCast;
6265         return IncompatibleVectors;
6266       }
6267     }
6268     return Incompatible;
6269   }
6270 
6271   // Arithmetic conversions.
6272   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
6273       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
6274     Kind = PrepareScalarCast(RHS, LHSType);
6275     return Compatible;
6276   }
6277 
6278   // Conversions to normal pointers.
6279   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
6280     // U* -> T*
6281     if (isa<PointerType>(RHSType)) {
6282       Kind = CK_BitCast;
6283       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
6284     }
6285 
6286     // int -> T*
6287     if (RHSType->isIntegerType()) {
6288       Kind = CK_IntegralToPointer; // FIXME: null?
6289       return IntToPointer;
6290     }
6291 
6292     // C pointers are not compatible with ObjC object pointers,
6293     // with two exceptions:
6294     if (isa<ObjCObjectPointerType>(RHSType)) {
6295       //  - conversions to void*
6296       if (LHSPointer->getPointeeType()->isVoidType()) {
6297         Kind = CK_BitCast;
6298         return Compatible;
6299       }
6300 
6301       //  - conversions from 'Class' to the redefinition type
6302       if (RHSType->isObjCClassType() &&
6303           Context.hasSameType(LHSType,
6304                               Context.getObjCClassRedefinitionType())) {
6305         Kind = CK_BitCast;
6306         return Compatible;
6307       }
6308 
6309       Kind = CK_BitCast;
6310       return IncompatiblePointer;
6311     }
6312 
6313     // U^ -> void*
6314     if (RHSType->getAs<BlockPointerType>()) {
6315       if (LHSPointer->getPointeeType()->isVoidType()) {
6316         Kind = CK_BitCast;
6317         return Compatible;
6318       }
6319     }
6320 
6321     return Incompatible;
6322   }
6323 
6324   // Conversions to block pointers.
6325   if (isa<BlockPointerType>(LHSType)) {
6326     // U^ -> T^
6327     if (RHSType->isBlockPointerType()) {
6328       Kind = CK_BitCast;
6329       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
6330     }
6331 
6332     // int or null -> T^
6333     if (RHSType->isIntegerType()) {
6334       Kind = CK_IntegralToPointer; // FIXME: null
6335       return IntToBlockPointer;
6336     }
6337 
6338     // id -> T^
6339     if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
6340       Kind = CK_AnyPointerToBlockPointerCast;
6341       return Compatible;
6342     }
6343 
6344     // void* -> T^
6345     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
6346       if (RHSPT->getPointeeType()->isVoidType()) {
6347         Kind = CK_AnyPointerToBlockPointerCast;
6348         return Compatible;
6349       }
6350 
6351     return Incompatible;
6352   }
6353 
6354   // Conversions to Objective-C pointers.
6355   if (isa<ObjCObjectPointerType>(LHSType)) {
6356     // A* -> B*
6357     if (RHSType->isObjCObjectPointerType()) {
6358       Kind = CK_BitCast;
6359       Sema::AssignConvertType result =
6360         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
6361       if (getLangOpts().ObjCAutoRefCount &&
6362           result == Compatible &&
6363           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
6364         result = IncompatibleObjCWeakRef;
6365       return result;
6366     }
6367 
6368     // int or null -> A*
6369     if (RHSType->isIntegerType()) {
6370       Kind = CK_IntegralToPointer; // FIXME: null
6371       return IntToPointer;
6372     }
6373 
6374     // In general, C pointers are not compatible with ObjC object pointers,
6375     // with two exceptions:
6376     if (isa<PointerType>(RHSType)) {
6377       Kind = CK_CPointerToObjCPointerCast;
6378 
6379       //  - conversions from 'void*'
6380       if (RHSType->isVoidPointerType()) {
6381         return Compatible;
6382       }
6383 
6384       //  - conversions to 'Class' from its redefinition type
6385       if (LHSType->isObjCClassType() &&
6386           Context.hasSameType(RHSType,
6387                               Context.getObjCClassRedefinitionType())) {
6388         return Compatible;
6389       }
6390 
6391       return IncompatiblePointer;
6392     }
6393 
6394     // T^ -> A*
6395     if (RHSType->isBlockPointerType()) {
6396       maybeExtendBlockObject(*this, RHS);
6397       Kind = CK_BlockPointerToObjCPointerCast;
6398       return Compatible;
6399     }
6400 
6401     return Incompatible;
6402   }
6403 
6404   // Conversions from pointers that are not covered by the above.
6405   if (isa<PointerType>(RHSType)) {
6406     // T* -> _Bool
6407     if (LHSType == Context.BoolTy) {
6408       Kind = CK_PointerToBoolean;
6409       return Compatible;
6410     }
6411 
6412     // T* -> int
6413     if (LHSType->isIntegerType()) {
6414       Kind = CK_PointerToIntegral;
6415       return PointerToInt;
6416     }
6417 
6418     return Incompatible;
6419   }
6420 
6421   // Conversions from Objective-C pointers that are not covered by the above.
6422   if (isa<ObjCObjectPointerType>(RHSType)) {
6423     // T* -> _Bool
6424     if (LHSType == Context.BoolTy) {
6425       Kind = CK_PointerToBoolean;
6426       return Compatible;
6427     }
6428 
6429     // T* -> int
6430     if (LHSType->isIntegerType()) {
6431       Kind = CK_PointerToIntegral;
6432       return PointerToInt;
6433     }
6434 
6435     return Incompatible;
6436   }
6437 
6438   // struct A -> struct B
6439   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
6440     if (Context.typesAreCompatible(LHSType, RHSType)) {
6441       Kind = CK_NoOp;
6442       return Compatible;
6443     }
6444   }
6445 
6446   return Incompatible;
6447 }
6448 
6449 /// \brief Constructs a transparent union from an expression that is
6450 /// used to initialize the transparent union.
6451 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
6452                                       ExprResult &EResult, QualType UnionType,
6453                                       FieldDecl *Field) {
6454   // Build an initializer list that designates the appropriate member
6455   // of the transparent union.
6456   Expr *E = EResult.take();
6457   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
6458                                                    E, SourceLocation());
6459   Initializer->setType(UnionType);
6460   Initializer->setInitializedFieldInUnion(Field);
6461 
6462   // Build a compound literal constructing a value of the transparent
6463   // union type from this initializer list.
6464   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
6465   EResult = S.Owned(
6466     new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
6467                                 VK_RValue, Initializer, false));
6468 }
6469 
6470 Sema::AssignConvertType
6471 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
6472                                                ExprResult &RHS) {
6473   QualType RHSType = RHS.get()->getType();
6474 
6475   // If the ArgType is a Union type, we want to handle a potential
6476   // transparent_union GCC extension.
6477   const RecordType *UT = ArgType->getAsUnionType();
6478   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
6479     return Incompatible;
6480 
6481   // The field to initialize within the transparent union.
6482   RecordDecl *UD = UT->getDecl();
6483   FieldDecl *InitField = 0;
6484   // It's compatible if the expression matches any of the fields.
6485   for (RecordDecl::field_iterator it = UD->field_begin(),
6486          itend = UD->field_end();
6487        it != itend; ++it) {
6488     if (it->getType()->isPointerType()) {
6489       // If the transparent union contains a pointer type, we allow:
6490       // 1) void pointer
6491       // 2) null pointer constant
6492       if (RHSType->isPointerType())
6493         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
6494           RHS = ImpCastExprToType(RHS.take(), it->getType(), CK_BitCast);
6495           InitField = *it;
6496           break;
6497         }
6498 
6499       if (RHS.get()->isNullPointerConstant(Context,
6500                                            Expr::NPC_ValueDependentIsNull)) {
6501         RHS = ImpCastExprToType(RHS.take(), it->getType(),
6502                                 CK_NullToPointer);
6503         InitField = *it;
6504         break;
6505       }
6506     }
6507 
6508     CastKind Kind = CK_Invalid;
6509     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
6510           == Compatible) {
6511       RHS = ImpCastExprToType(RHS.take(), it->getType(), Kind);
6512       InitField = *it;
6513       break;
6514     }
6515   }
6516 
6517   if (!InitField)
6518     return Incompatible;
6519 
6520   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
6521   return Compatible;
6522 }
6523 
6524 Sema::AssignConvertType
6525 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS,
6526                                        bool Diagnose,
6527                                        bool DiagnoseCFAudited) {
6528   if (getLangOpts().CPlusPlus) {
6529     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
6530       // C++ 5.17p3: If the left operand is not of class type, the
6531       // expression is implicitly converted (C++ 4) to the
6532       // cv-unqualified type of the left operand.
6533       ExprResult Res;
6534       if (Diagnose) {
6535         Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
6536                                         AA_Assigning);
6537       } else {
6538         ImplicitConversionSequence ICS =
6539             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
6540                                   /*SuppressUserConversions=*/false,
6541                                   /*AllowExplicit=*/false,
6542                                   /*InOverloadResolution=*/false,
6543                                   /*CStyle=*/false,
6544                                   /*AllowObjCWritebackConversion=*/false);
6545         if (ICS.isFailure())
6546           return Incompatible;
6547         Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
6548                                         ICS, AA_Assigning);
6549       }
6550       if (Res.isInvalid())
6551         return Incompatible;
6552       Sema::AssignConvertType result = Compatible;
6553       if (getLangOpts().ObjCAutoRefCount &&
6554           !CheckObjCARCUnavailableWeakConversion(LHSType,
6555                                                  RHS.get()->getType()))
6556         result = IncompatibleObjCWeakRef;
6557       RHS = Res;
6558       return result;
6559     }
6560 
6561     // FIXME: Currently, we fall through and treat C++ classes like C
6562     // structures.
6563     // FIXME: We also fall through for atomics; not sure what should
6564     // happen there, though.
6565   }
6566 
6567   // C99 6.5.16.1p1: the left operand is a pointer and the right is
6568   // a null pointer constant.
6569   if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
6570        LHSType->isBlockPointerType()) &&
6571       RHS.get()->isNullPointerConstant(Context,
6572                                        Expr::NPC_ValueDependentIsNull)) {
6573     CastKind Kind;
6574     CXXCastPath Path;
6575     CheckPointerConversion(RHS.get(), LHSType, Kind, Path, false);
6576     RHS = ImpCastExprToType(RHS.take(), LHSType, Kind, VK_RValue, &Path);
6577     return Compatible;
6578   }
6579 
6580   // This check seems unnatural, however it is necessary to ensure the proper
6581   // conversion of functions/arrays. If the conversion were done for all
6582   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
6583   // expressions that suppress this implicit conversion (&, sizeof).
6584   //
6585   // Suppress this for references: C++ 8.5.3p5.
6586   if (!LHSType->isReferenceType()) {
6587     RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
6588     if (RHS.isInvalid())
6589       return Incompatible;
6590   }
6591 
6592   CastKind Kind = CK_Invalid;
6593   Sema::AssignConvertType result =
6594     CheckAssignmentConstraints(LHSType, RHS, Kind);
6595 
6596   // C99 6.5.16.1p2: The value of the right operand is converted to the
6597   // type of the assignment expression.
6598   // CheckAssignmentConstraints allows the left-hand side to be a reference,
6599   // so that we can use references in built-in functions even in C.
6600   // The getNonReferenceType() call makes sure that the resulting expression
6601   // does not have reference type.
6602   if (result != Incompatible && RHS.get()->getType() != LHSType) {
6603     QualType Ty = LHSType.getNonLValueExprType(Context);
6604     Expr *E = RHS.take();
6605     if (getLangOpts().ObjCAutoRefCount)
6606       CheckObjCARCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
6607                              DiagnoseCFAudited);
6608     if (getLangOpts().ObjC1 &&
6609         (CheckObjCBridgeRelatedConversions(E->getLocStart(),
6610                                           LHSType, E->getType(), E) ||
6611          ConversionToObjCStringLiteralCheck(LHSType, E))) {
6612       RHS = Owned(E);
6613       return Compatible;
6614     }
6615 
6616     RHS = ImpCastExprToType(E, Ty, Kind);
6617   }
6618   return result;
6619 }
6620 
6621 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
6622                                ExprResult &RHS) {
6623   Diag(Loc, diag::err_typecheck_invalid_operands)
6624     << LHS.get()->getType() << RHS.get()->getType()
6625     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6626   return QualType();
6627 }
6628 
6629 static bool areVectorOperandsLaxBitCastable(ASTContext &Ctx,
6630                                             QualType LHSType, QualType RHSType){
6631   if (!Ctx.getLangOpts().LaxVectorConversions)
6632     return false;
6633 
6634   if (!(LHSType->isVectorType() || LHSType->isScalarType()) ||
6635       !(RHSType->isVectorType() || RHSType->isScalarType()))
6636     return false;
6637 
6638   unsigned LHSSize = Ctx.getTypeSize(LHSType);
6639   unsigned RHSSize = Ctx.getTypeSize(RHSType);
6640   if (LHSSize != RHSSize)
6641     return false;
6642 
6643   // For a non-power-of-2 vector ASTContext::getTypeSize returns the size
6644   // rounded to the next power-of-2, but the LLVM IR type that we create
6645   // is considered to have num-of-elements*width-of-element width.
6646   // Make sure such width is the same between the types, otherwise we may end
6647   // up with an invalid bitcast.
6648   unsigned LHSIRSize, RHSIRSize;
6649   if (LHSType->isVectorType()) {
6650     const VectorType *Vec = LHSType->getAs<VectorType>();
6651     LHSIRSize = Vec->getNumElements() *
6652         Ctx.getTypeSize(Vec->getElementType());
6653   } else {
6654     LHSIRSize = LHSSize;
6655   }
6656   if (RHSType->isVectorType()) {
6657     const VectorType *Vec = RHSType->getAs<VectorType>();
6658     RHSIRSize = Vec->getNumElements() *
6659         Ctx.getTypeSize(Vec->getElementType());
6660   } else {
6661     RHSIRSize = RHSSize;
6662   }
6663   if (LHSIRSize != RHSIRSize)
6664     return false;
6665 
6666   return true;
6667 }
6668 
6669 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
6670                                    SourceLocation Loc, bool IsCompAssign) {
6671   if (!IsCompAssign) {
6672     LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
6673     if (LHS.isInvalid())
6674       return QualType();
6675   }
6676   RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
6677   if (RHS.isInvalid())
6678     return QualType();
6679 
6680   // For conversion purposes, we ignore any qualifiers.
6681   // For example, "const float" and "float" are equivalent.
6682   QualType LHSType =
6683     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
6684   QualType RHSType =
6685     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
6686 
6687   // If the vector types are identical, return.
6688   if (LHSType == RHSType)
6689     return LHSType;
6690 
6691   // Handle the case of equivalent AltiVec and GCC vector types
6692   if (LHSType->isVectorType() && RHSType->isVectorType() &&
6693       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
6694     if (LHSType->isExtVectorType()) {
6695       RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
6696       return LHSType;
6697     }
6698 
6699     if (!IsCompAssign)
6700       LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
6701     return RHSType;
6702   }
6703 
6704   if (areVectorOperandsLaxBitCastable(Context, LHSType, RHSType)) {
6705     // If we are allowing lax vector conversions, and LHS and RHS are both
6706     // vectors, the total size only needs to be the same. This is a
6707     // bitcast; no bits are changed but the result type is different.
6708     // FIXME: Should we really be allowing this?
6709     RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
6710     return LHSType;
6711   }
6712 
6713   if (!(LHSType->isVectorType() || LHSType->isScalarType()) ||
6714       !(RHSType->isVectorType() || RHSType->isScalarType())) {
6715     Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
6716     << LHS.get()->getType() << RHS.get()->getType()
6717     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6718     return QualType();
6719   }
6720 
6721   // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
6722   // swap back (so that we don't reverse the inputs to a subtract, for instance.
6723   bool swapped = false;
6724   if (RHSType->isExtVectorType() && !IsCompAssign) {
6725     swapped = true;
6726     std::swap(RHS, LHS);
6727     std::swap(RHSType, LHSType);
6728   }
6729 
6730   // Handle the case of an ext vector and scalar.
6731   if (const ExtVectorType *LV = LHSType->getAs<ExtVectorType>()) {
6732     QualType EltTy = LV->getElementType();
6733     if (EltTy->isIntegralType(Context) && RHSType->isIntegralType(Context)) {
6734       int order = Context.getIntegerTypeOrder(EltTy, RHSType);
6735       if (order > 0)
6736         RHS = ImpCastExprToType(RHS.take(), EltTy, CK_IntegralCast);
6737       if (order >= 0) {
6738         RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
6739         if (swapped) std::swap(RHS, LHS);
6740         return LHSType;
6741       }
6742     }
6743     if (EltTy->isRealFloatingType() && RHSType->isScalarType()) {
6744       if (RHSType->isRealFloatingType()) {
6745         int order = Context.getFloatingTypeOrder(EltTy, RHSType);
6746         if (order > 0)
6747           RHS = ImpCastExprToType(RHS.take(), EltTy, CK_FloatingCast);
6748         if (order >= 0) {
6749           RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
6750           if (swapped) std::swap(RHS, LHS);
6751           return LHSType;
6752         }
6753       }
6754       if (RHSType->isIntegralType(Context)) {
6755         RHS = ImpCastExprToType(RHS.take(), EltTy, CK_IntegralToFloating);
6756         RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
6757         if (swapped) std::swap(RHS, LHS);
6758         return LHSType;
6759       }
6760     }
6761   }
6762 
6763   // Vectors of different size or scalar and non-ext-vector are errors.
6764   if (swapped) std::swap(RHS, LHS);
6765   Diag(Loc, diag::err_typecheck_vector_not_convertable)
6766     << LHS.get()->getType() << RHS.get()->getType()
6767     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6768   return QualType();
6769 }
6770 
6771 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
6772 // expression.  These are mainly cases where the null pointer is used as an
6773 // integer instead of a pointer.
6774 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
6775                                 SourceLocation Loc, bool IsCompare) {
6776   // The canonical way to check for a GNU null is with isNullPointerConstant,
6777   // but we use a bit of a hack here for speed; this is a relatively
6778   // hot path, and isNullPointerConstant is slow.
6779   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
6780   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
6781 
6782   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
6783 
6784   // Avoid analyzing cases where the result will either be invalid (and
6785   // diagnosed as such) or entirely valid and not something to warn about.
6786   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
6787       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
6788     return;
6789 
6790   // Comparison operations would not make sense with a null pointer no matter
6791   // what the other expression is.
6792   if (!IsCompare) {
6793     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
6794         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
6795         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
6796     return;
6797   }
6798 
6799   // The rest of the operations only make sense with a null pointer
6800   // if the other expression is a pointer.
6801   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
6802       NonNullType->canDecayToPointerType())
6803     return;
6804 
6805   S.Diag(Loc, diag::warn_null_in_comparison_operation)
6806       << LHSNull /* LHS is NULL */ << NonNullType
6807       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6808 }
6809 
6810 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
6811                                            SourceLocation Loc,
6812                                            bool IsCompAssign, bool IsDiv) {
6813   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6814 
6815   if (LHS.get()->getType()->isVectorType() ||
6816       RHS.get()->getType()->isVectorType())
6817     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
6818 
6819   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
6820   if (LHS.isInvalid() || RHS.isInvalid())
6821     return QualType();
6822 
6823 
6824   if (compType.isNull() || !compType->isArithmeticType())
6825     return InvalidOperands(Loc, LHS, RHS);
6826 
6827   // Check for division by zero.
6828   llvm::APSInt RHSValue;
6829   if (IsDiv && !RHS.get()->isValueDependent() &&
6830       RHS.get()->EvaluateAsInt(RHSValue, Context) && RHSValue == 0)
6831     DiagRuntimeBehavior(Loc, RHS.get(),
6832                         PDiag(diag::warn_division_by_zero)
6833                           << RHS.get()->getSourceRange());
6834 
6835   return compType;
6836 }
6837 
6838 QualType Sema::CheckRemainderOperands(
6839   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
6840   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6841 
6842   if (LHS.get()->getType()->isVectorType() ||
6843       RHS.get()->getType()->isVectorType()) {
6844     if (LHS.get()->getType()->hasIntegerRepresentation() &&
6845         RHS.get()->getType()->hasIntegerRepresentation())
6846       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
6847     return InvalidOperands(Loc, LHS, RHS);
6848   }
6849 
6850   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
6851   if (LHS.isInvalid() || RHS.isInvalid())
6852     return QualType();
6853 
6854   if (compType.isNull() || !compType->isIntegerType())
6855     return InvalidOperands(Loc, LHS, RHS);
6856 
6857   // Check for remainder by zero.
6858   llvm::APSInt RHSValue;
6859   if (!RHS.get()->isValueDependent() &&
6860       RHS.get()->EvaluateAsInt(RHSValue, Context) && RHSValue == 0)
6861     DiagRuntimeBehavior(Loc, RHS.get(),
6862                         PDiag(diag::warn_remainder_by_zero)
6863                           << RHS.get()->getSourceRange());
6864 
6865   return compType;
6866 }
6867 
6868 /// \brief Diagnose invalid arithmetic on two void pointers.
6869 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
6870                                                 Expr *LHSExpr, Expr *RHSExpr) {
6871   S.Diag(Loc, S.getLangOpts().CPlusPlus
6872                 ? diag::err_typecheck_pointer_arith_void_type
6873                 : diag::ext_gnu_void_ptr)
6874     << 1 /* two pointers */ << LHSExpr->getSourceRange()
6875                             << RHSExpr->getSourceRange();
6876 }
6877 
6878 /// \brief Diagnose invalid arithmetic on a void pointer.
6879 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
6880                                             Expr *Pointer) {
6881   S.Diag(Loc, S.getLangOpts().CPlusPlus
6882                 ? diag::err_typecheck_pointer_arith_void_type
6883                 : diag::ext_gnu_void_ptr)
6884     << 0 /* one pointer */ << Pointer->getSourceRange();
6885 }
6886 
6887 /// \brief Diagnose invalid arithmetic on two function pointers.
6888 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
6889                                                     Expr *LHS, Expr *RHS) {
6890   assert(LHS->getType()->isAnyPointerType());
6891   assert(RHS->getType()->isAnyPointerType());
6892   S.Diag(Loc, S.getLangOpts().CPlusPlus
6893                 ? diag::err_typecheck_pointer_arith_function_type
6894                 : diag::ext_gnu_ptr_func_arith)
6895     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
6896     // We only show the second type if it differs from the first.
6897     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
6898                                                    RHS->getType())
6899     << RHS->getType()->getPointeeType()
6900     << LHS->getSourceRange() << RHS->getSourceRange();
6901 }
6902 
6903 /// \brief Diagnose invalid arithmetic on a function pointer.
6904 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
6905                                                 Expr *Pointer) {
6906   assert(Pointer->getType()->isAnyPointerType());
6907   S.Diag(Loc, S.getLangOpts().CPlusPlus
6908                 ? diag::err_typecheck_pointer_arith_function_type
6909                 : diag::ext_gnu_ptr_func_arith)
6910     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
6911     << 0 /* one pointer, so only one type */
6912     << Pointer->getSourceRange();
6913 }
6914 
6915 /// \brief Emit error if Operand is incomplete pointer type
6916 ///
6917 /// \returns True if pointer has incomplete type
6918 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
6919                                                  Expr *Operand) {
6920   assert(Operand->getType()->isAnyPointerType() &&
6921          !Operand->getType()->isDependentType());
6922   QualType PointeeTy = Operand->getType()->getPointeeType();
6923   return S.RequireCompleteType(Loc, PointeeTy,
6924                                diag::err_typecheck_arithmetic_incomplete_type,
6925                                PointeeTy, Operand->getSourceRange());
6926 }
6927 
6928 /// \brief Check the validity of an arithmetic pointer operand.
6929 ///
6930 /// If the operand has pointer type, this code will check for pointer types
6931 /// which are invalid in arithmetic operations. These will be diagnosed
6932 /// appropriately, including whether or not the use is supported as an
6933 /// extension.
6934 ///
6935 /// \returns True when the operand is valid to use (even if as an extension).
6936 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
6937                                             Expr *Operand) {
6938   if (!Operand->getType()->isAnyPointerType()) return true;
6939 
6940   QualType PointeeTy = Operand->getType()->getPointeeType();
6941   if (PointeeTy->isVoidType()) {
6942     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
6943     return !S.getLangOpts().CPlusPlus;
6944   }
6945   if (PointeeTy->isFunctionType()) {
6946     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
6947     return !S.getLangOpts().CPlusPlus;
6948   }
6949 
6950   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
6951 
6952   return true;
6953 }
6954 
6955 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
6956 /// operands.
6957 ///
6958 /// This routine will diagnose any invalid arithmetic on pointer operands much
6959 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
6960 /// for emitting a single diagnostic even for operations where both LHS and RHS
6961 /// are (potentially problematic) pointers.
6962 ///
6963 /// \returns True when the operand is valid to use (even if as an extension).
6964 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
6965                                                 Expr *LHSExpr, Expr *RHSExpr) {
6966   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
6967   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
6968   if (!isLHSPointer && !isRHSPointer) return true;
6969 
6970   QualType LHSPointeeTy, RHSPointeeTy;
6971   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
6972   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
6973 
6974   // Check for arithmetic on pointers to incomplete types.
6975   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
6976   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
6977   if (isLHSVoidPtr || isRHSVoidPtr) {
6978     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
6979     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
6980     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
6981 
6982     return !S.getLangOpts().CPlusPlus;
6983   }
6984 
6985   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
6986   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
6987   if (isLHSFuncPtr || isRHSFuncPtr) {
6988     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
6989     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
6990                                                                 RHSExpr);
6991     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
6992 
6993     return !S.getLangOpts().CPlusPlus;
6994   }
6995 
6996   if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
6997     return false;
6998   if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
6999     return false;
7000 
7001   return true;
7002 }
7003 
7004 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
7005 /// literal.
7006 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
7007                                   Expr *LHSExpr, Expr *RHSExpr) {
7008   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
7009   Expr* IndexExpr = RHSExpr;
7010   if (!StrExpr) {
7011     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
7012     IndexExpr = LHSExpr;
7013   }
7014 
7015   bool IsStringPlusInt = StrExpr &&
7016       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
7017   if (!IsStringPlusInt)
7018     return;
7019 
7020   llvm::APSInt index;
7021   if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
7022     unsigned StrLenWithNull = StrExpr->getLength() + 1;
7023     if (index.isNonNegative() &&
7024         index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
7025                               index.isUnsigned()))
7026       return;
7027   }
7028 
7029   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
7030   Self.Diag(OpLoc, diag::warn_string_plus_int)
7031       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
7032 
7033   // Only print a fixit for "str" + int, not for int + "str".
7034   if (IndexExpr == RHSExpr) {
7035     SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd());
7036     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
7037         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
7038         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
7039         << FixItHint::CreateInsertion(EndLoc, "]");
7040   } else
7041     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
7042 }
7043 
7044 /// \brief Emit a warning when adding a char literal to a string.
7045 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
7046                                    Expr *LHSExpr, Expr *RHSExpr) {
7047   const DeclRefExpr *StringRefExpr =
7048       dyn_cast<DeclRefExpr>(LHSExpr->IgnoreImpCasts());
7049   const CharacterLiteral *CharExpr =
7050       dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
7051   if (!StringRefExpr) {
7052     StringRefExpr = dyn_cast<DeclRefExpr>(RHSExpr->IgnoreImpCasts());
7053     CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
7054   }
7055 
7056   if (!CharExpr || !StringRefExpr)
7057     return;
7058 
7059   const QualType StringType = StringRefExpr->getType();
7060 
7061   // Return if not a PointerType.
7062   if (!StringType->isAnyPointerType())
7063     return;
7064 
7065   // Return if not a CharacterType.
7066   if (!StringType->getPointeeType()->isAnyCharacterType())
7067     return;
7068 
7069   ASTContext &Ctx = Self.getASTContext();
7070   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
7071 
7072   const QualType CharType = CharExpr->getType();
7073   if (!CharType->isAnyCharacterType() &&
7074       CharType->isIntegerType() &&
7075       llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
7076     Self.Diag(OpLoc, diag::warn_string_plus_char)
7077         << DiagRange << Ctx.CharTy;
7078   } else {
7079     Self.Diag(OpLoc, diag::warn_string_plus_char)
7080         << DiagRange << CharExpr->getType();
7081   }
7082 
7083   // Only print a fixit for str + char, not for char + str.
7084   if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
7085     SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd());
7086     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
7087         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
7088         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
7089         << FixItHint::CreateInsertion(EndLoc, "]");
7090   } else {
7091     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
7092   }
7093 }
7094 
7095 /// \brief Emit error when two pointers are incompatible.
7096 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
7097                                            Expr *LHSExpr, Expr *RHSExpr) {
7098   assert(LHSExpr->getType()->isAnyPointerType());
7099   assert(RHSExpr->getType()->isAnyPointerType());
7100   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
7101     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
7102     << RHSExpr->getSourceRange();
7103 }
7104 
7105 QualType Sema::CheckAdditionOperands( // C99 6.5.6
7106     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc,
7107     QualType* CompLHSTy) {
7108   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7109 
7110   if (LHS.get()->getType()->isVectorType() ||
7111       RHS.get()->getType()->isVectorType()) {
7112     QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
7113     if (CompLHSTy) *CompLHSTy = compType;
7114     return compType;
7115   }
7116 
7117   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
7118   if (LHS.isInvalid() || RHS.isInvalid())
7119     return QualType();
7120 
7121   // Diagnose "string literal" '+' int and string '+' "char literal".
7122   if (Opc == BO_Add) {
7123     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
7124     diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
7125   }
7126 
7127   // handle the common case first (both operands are arithmetic).
7128   if (!compType.isNull() && compType->isArithmeticType()) {
7129     if (CompLHSTy) *CompLHSTy = compType;
7130     return compType;
7131   }
7132 
7133   // Type-checking.  Ultimately the pointer's going to be in PExp;
7134   // note that we bias towards the LHS being the pointer.
7135   Expr *PExp = LHS.get(), *IExp = RHS.get();
7136 
7137   bool isObjCPointer;
7138   if (PExp->getType()->isPointerType()) {
7139     isObjCPointer = false;
7140   } else if (PExp->getType()->isObjCObjectPointerType()) {
7141     isObjCPointer = true;
7142   } else {
7143     std::swap(PExp, IExp);
7144     if (PExp->getType()->isPointerType()) {
7145       isObjCPointer = false;
7146     } else if (PExp->getType()->isObjCObjectPointerType()) {
7147       isObjCPointer = true;
7148     } else {
7149       return InvalidOperands(Loc, LHS, RHS);
7150     }
7151   }
7152   assert(PExp->getType()->isAnyPointerType());
7153 
7154   if (!IExp->getType()->isIntegerType())
7155     return InvalidOperands(Loc, LHS, RHS);
7156 
7157   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
7158     return QualType();
7159 
7160   if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
7161     return QualType();
7162 
7163   // Check array bounds for pointer arithemtic
7164   CheckArrayAccess(PExp, IExp);
7165 
7166   if (CompLHSTy) {
7167     QualType LHSTy = Context.isPromotableBitField(LHS.get());
7168     if (LHSTy.isNull()) {
7169       LHSTy = LHS.get()->getType();
7170       if (LHSTy->isPromotableIntegerType())
7171         LHSTy = Context.getPromotedIntegerType(LHSTy);
7172     }
7173     *CompLHSTy = LHSTy;
7174   }
7175 
7176   return PExp->getType();
7177 }
7178 
7179 // C99 6.5.6
7180 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
7181                                         SourceLocation Loc,
7182                                         QualType* CompLHSTy) {
7183   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7184 
7185   if (LHS.get()->getType()->isVectorType() ||
7186       RHS.get()->getType()->isVectorType()) {
7187     QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
7188     if (CompLHSTy) *CompLHSTy = compType;
7189     return compType;
7190   }
7191 
7192   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
7193   if (LHS.isInvalid() || RHS.isInvalid())
7194     return QualType();
7195 
7196   // Enforce type constraints: C99 6.5.6p3.
7197 
7198   // Handle the common case first (both operands are arithmetic).
7199   if (!compType.isNull() && compType->isArithmeticType()) {
7200     if (CompLHSTy) *CompLHSTy = compType;
7201     return compType;
7202   }
7203 
7204   // Either ptr - int   or   ptr - ptr.
7205   if (LHS.get()->getType()->isAnyPointerType()) {
7206     QualType lpointee = LHS.get()->getType()->getPointeeType();
7207 
7208     // Diagnose bad cases where we step over interface counts.
7209     if (LHS.get()->getType()->isObjCObjectPointerType() &&
7210         checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
7211       return QualType();
7212 
7213     // The result type of a pointer-int computation is the pointer type.
7214     if (RHS.get()->getType()->isIntegerType()) {
7215       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
7216         return QualType();
7217 
7218       // Check array bounds for pointer arithemtic
7219       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/0,
7220                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
7221 
7222       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
7223       return LHS.get()->getType();
7224     }
7225 
7226     // Handle pointer-pointer subtractions.
7227     if (const PointerType *RHSPTy
7228           = RHS.get()->getType()->getAs<PointerType>()) {
7229       QualType rpointee = RHSPTy->getPointeeType();
7230 
7231       if (getLangOpts().CPlusPlus) {
7232         // Pointee types must be the same: C++ [expr.add]
7233         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
7234           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
7235         }
7236       } else {
7237         // Pointee types must be compatible C99 6.5.6p3
7238         if (!Context.typesAreCompatible(
7239                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
7240                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
7241           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
7242           return QualType();
7243         }
7244       }
7245 
7246       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
7247                                                LHS.get(), RHS.get()))
7248         return QualType();
7249 
7250       // The pointee type may have zero size.  As an extension, a structure or
7251       // union may have zero size or an array may have zero length.  In this
7252       // case subtraction does not make sense.
7253       if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
7254         CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
7255         if (ElementSize.isZero()) {
7256           Diag(Loc,diag::warn_sub_ptr_zero_size_types)
7257             << rpointee.getUnqualifiedType()
7258             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7259         }
7260       }
7261 
7262       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
7263       return Context.getPointerDiffType();
7264     }
7265   }
7266 
7267   return InvalidOperands(Loc, LHS, RHS);
7268 }
7269 
7270 static bool isScopedEnumerationType(QualType T) {
7271   if (const EnumType *ET = dyn_cast<EnumType>(T))
7272     return ET->getDecl()->isScoped();
7273   return false;
7274 }
7275 
7276 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
7277                                    SourceLocation Loc, unsigned Opc,
7278                                    QualType LHSType) {
7279   // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
7280   // so skip remaining warnings as we don't want to modify values within Sema.
7281   if (S.getLangOpts().OpenCL)
7282     return;
7283 
7284   llvm::APSInt Right;
7285   // Check right/shifter operand
7286   if (RHS.get()->isValueDependent() ||
7287       !RHS.get()->isIntegerConstantExpr(Right, S.Context))
7288     return;
7289 
7290   if (Right.isNegative()) {
7291     S.DiagRuntimeBehavior(Loc, RHS.get(),
7292                           S.PDiag(diag::warn_shift_negative)
7293                             << RHS.get()->getSourceRange());
7294     return;
7295   }
7296   llvm::APInt LeftBits(Right.getBitWidth(),
7297                        S.Context.getTypeSize(LHS.get()->getType()));
7298   if (Right.uge(LeftBits)) {
7299     S.DiagRuntimeBehavior(Loc, RHS.get(),
7300                           S.PDiag(diag::warn_shift_gt_typewidth)
7301                             << RHS.get()->getSourceRange());
7302     return;
7303   }
7304   if (Opc != BO_Shl)
7305     return;
7306 
7307   // When left shifting an ICE which is signed, we can check for overflow which
7308   // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
7309   // integers have defined behavior modulo one more than the maximum value
7310   // representable in the result type, so never warn for those.
7311   llvm::APSInt Left;
7312   if (LHS.get()->isValueDependent() ||
7313       !LHS.get()->isIntegerConstantExpr(Left, S.Context) ||
7314       LHSType->hasUnsignedIntegerRepresentation())
7315     return;
7316   llvm::APInt ResultBits =
7317       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
7318   if (LeftBits.uge(ResultBits))
7319     return;
7320   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
7321   Result = Result.shl(Right);
7322 
7323   // Print the bit representation of the signed integer as an unsigned
7324   // hexadecimal number.
7325   SmallString<40> HexResult;
7326   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
7327 
7328   // If we are only missing a sign bit, this is less likely to result in actual
7329   // bugs -- if the result is cast back to an unsigned type, it will have the
7330   // expected value. Thus we place this behind a different warning that can be
7331   // turned off separately if needed.
7332   if (LeftBits == ResultBits - 1) {
7333     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
7334         << HexResult.str() << LHSType
7335         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7336     return;
7337   }
7338 
7339   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
7340     << HexResult.str() << Result.getMinSignedBits() << LHSType
7341     << Left.getBitWidth() << LHS.get()->getSourceRange()
7342     << RHS.get()->getSourceRange();
7343 }
7344 
7345 // C99 6.5.7
7346 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
7347                                   SourceLocation Loc, unsigned Opc,
7348                                   bool IsCompAssign) {
7349   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7350 
7351   // Vector shifts promote their scalar inputs to vector type.
7352   if (LHS.get()->getType()->isVectorType() ||
7353       RHS.get()->getType()->isVectorType())
7354     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
7355 
7356   // Shifts don't perform usual arithmetic conversions, they just do integer
7357   // promotions on each operand. C99 6.5.7p3
7358 
7359   // For the LHS, do usual unary conversions, but then reset them away
7360   // if this is a compound assignment.
7361   ExprResult OldLHS = LHS;
7362   LHS = UsualUnaryConversions(LHS.take());
7363   if (LHS.isInvalid())
7364     return QualType();
7365   QualType LHSType = LHS.get()->getType();
7366   if (IsCompAssign) LHS = OldLHS;
7367 
7368   // The RHS is simpler.
7369   RHS = UsualUnaryConversions(RHS.take());
7370   if (RHS.isInvalid())
7371     return QualType();
7372   QualType RHSType = RHS.get()->getType();
7373 
7374   // C99 6.5.7p2: Each of the operands shall have integer type.
7375   if (!LHSType->hasIntegerRepresentation() ||
7376       !RHSType->hasIntegerRepresentation())
7377     return InvalidOperands(Loc, LHS, RHS);
7378 
7379   // C++0x: Don't allow scoped enums. FIXME: Use something better than
7380   // hasIntegerRepresentation() above instead of this.
7381   if (isScopedEnumerationType(LHSType) ||
7382       isScopedEnumerationType(RHSType)) {
7383     return InvalidOperands(Loc, LHS, RHS);
7384   }
7385   // Sanity-check shift operands
7386   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
7387 
7388   // "The type of the result is that of the promoted left operand."
7389   return LHSType;
7390 }
7391 
7392 static bool IsWithinTemplateSpecialization(Decl *D) {
7393   if (DeclContext *DC = D->getDeclContext()) {
7394     if (isa<ClassTemplateSpecializationDecl>(DC))
7395       return true;
7396     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
7397       return FD->isFunctionTemplateSpecialization();
7398   }
7399   return false;
7400 }
7401 
7402 /// If two different enums are compared, raise a warning.
7403 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS,
7404                                 Expr *RHS) {
7405   QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
7406   QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
7407 
7408   const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
7409   if (!LHSEnumType)
7410     return;
7411   const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
7412   if (!RHSEnumType)
7413     return;
7414 
7415   // Ignore anonymous enums.
7416   if (!LHSEnumType->getDecl()->getIdentifier())
7417     return;
7418   if (!RHSEnumType->getDecl()->getIdentifier())
7419     return;
7420 
7421   if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
7422     return;
7423 
7424   S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
7425       << LHSStrippedType << RHSStrippedType
7426       << LHS->getSourceRange() << RHS->getSourceRange();
7427 }
7428 
7429 /// \brief Diagnose bad pointer comparisons.
7430 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
7431                                               ExprResult &LHS, ExprResult &RHS,
7432                                               bool IsError) {
7433   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
7434                       : diag::ext_typecheck_comparison_of_distinct_pointers)
7435     << LHS.get()->getType() << RHS.get()->getType()
7436     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7437 }
7438 
7439 /// \brief Returns false if the pointers are converted to a composite type,
7440 /// true otherwise.
7441 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
7442                                            ExprResult &LHS, ExprResult &RHS) {
7443   // C++ [expr.rel]p2:
7444   //   [...] Pointer conversions (4.10) and qualification
7445   //   conversions (4.4) are performed on pointer operands (or on
7446   //   a pointer operand and a null pointer constant) to bring
7447   //   them to their composite pointer type. [...]
7448   //
7449   // C++ [expr.eq]p1 uses the same notion for (in)equality
7450   // comparisons of pointers.
7451 
7452   // C++ [expr.eq]p2:
7453   //   In addition, pointers to members can be compared, or a pointer to
7454   //   member and a null pointer constant. Pointer to member conversions
7455   //   (4.11) and qualification conversions (4.4) are performed to bring
7456   //   them to a common type. If one operand is a null pointer constant,
7457   //   the common type is the type of the other operand. Otherwise, the
7458   //   common type is a pointer to member type similar (4.4) to the type
7459   //   of one of the operands, with a cv-qualification signature (4.4)
7460   //   that is the union of the cv-qualification signatures of the operand
7461   //   types.
7462 
7463   QualType LHSType = LHS.get()->getType();
7464   QualType RHSType = RHS.get()->getType();
7465   assert((LHSType->isPointerType() && RHSType->isPointerType()) ||
7466          (LHSType->isMemberPointerType() && RHSType->isMemberPointerType()));
7467 
7468   bool NonStandardCompositeType = false;
7469   bool *BoolPtr = S.isSFINAEContext() ? 0 : &NonStandardCompositeType;
7470   QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr);
7471   if (T.isNull()) {
7472     diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
7473     return true;
7474   }
7475 
7476   if (NonStandardCompositeType)
7477     S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
7478       << LHSType << RHSType << T << LHS.get()->getSourceRange()
7479       << RHS.get()->getSourceRange();
7480 
7481   LHS = S.ImpCastExprToType(LHS.take(), T, CK_BitCast);
7482   RHS = S.ImpCastExprToType(RHS.take(), T, CK_BitCast);
7483   return false;
7484 }
7485 
7486 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
7487                                                     ExprResult &LHS,
7488                                                     ExprResult &RHS,
7489                                                     bool IsError) {
7490   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
7491                       : diag::ext_typecheck_comparison_of_fptr_to_void)
7492     << LHS.get()->getType() << RHS.get()->getType()
7493     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7494 }
7495 
7496 static bool isObjCObjectLiteral(ExprResult &E) {
7497   switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
7498   case Stmt::ObjCArrayLiteralClass:
7499   case Stmt::ObjCDictionaryLiteralClass:
7500   case Stmt::ObjCStringLiteralClass:
7501   case Stmt::ObjCBoxedExprClass:
7502     return true;
7503   default:
7504     // Note that ObjCBoolLiteral is NOT an object literal!
7505     return false;
7506   }
7507 }
7508 
7509 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
7510   const ObjCObjectPointerType *Type =
7511     LHS->getType()->getAs<ObjCObjectPointerType>();
7512 
7513   // If this is not actually an Objective-C object, bail out.
7514   if (!Type)
7515     return false;
7516 
7517   // Get the LHS object's interface type.
7518   QualType InterfaceType = Type->getPointeeType();
7519   if (const ObjCObjectType *iQFaceTy =
7520       InterfaceType->getAsObjCQualifiedInterfaceType())
7521     InterfaceType = iQFaceTy->getBaseType();
7522 
7523   // If the RHS isn't an Objective-C object, bail out.
7524   if (!RHS->getType()->isObjCObjectPointerType())
7525     return false;
7526 
7527   // Try to find the -isEqual: method.
7528   Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
7529   ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
7530                                                       InterfaceType,
7531                                                       /*instance=*/true);
7532   if (!Method) {
7533     if (Type->isObjCIdType()) {
7534       // For 'id', just check the global pool.
7535       Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
7536                                                   /*receiverId=*/true,
7537                                                   /*warn=*/false);
7538     } else {
7539       // Check protocols.
7540       Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
7541                                              /*instance=*/true);
7542     }
7543   }
7544 
7545   if (!Method)
7546     return false;
7547 
7548   QualType T = Method->param_begin()[0]->getType();
7549   if (!T->isObjCObjectPointerType())
7550     return false;
7551 
7552   QualType R = Method->getReturnType();
7553   if (!R->isScalarType())
7554     return false;
7555 
7556   return true;
7557 }
7558 
7559 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
7560   FromE = FromE->IgnoreParenImpCasts();
7561   switch (FromE->getStmtClass()) {
7562     default:
7563       break;
7564     case Stmt::ObjCStringLiteralClass:
7565       // "string literal"
7566       return LK_String;
7567     case Stmt::ObjCArrayLiteralClass:
7568       // "array literal"
7569       return LK_Array;
7570     case Stmt::ObjCDictionaryLiteralClass:
7571       // "dictionary literal"
7572       return LK_Dictionary;
7573     case Stmt::BlockExprClass:
7574       return LK_Block;
7575     case Stmt::ObjCBoxedExprClass: {
7576       Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
7577       switch (Inner->getStmtClass()) {
7578         case Stmt::IntegerLiteralClass:
7579         case Stmt::FloatingLiteralClass:
7580         case Stmt::CharacterLiteralClass:
7581         case Stmt::ObjCBoolLiteralExprClass:
7582         case Stmt::CXXBoolLiteralExprClass:
7583           // "numeric literal"
7584           return LK_Numeric;
7585         case Stmt::ImplicitCastExprClass: {
7586           CastKind CK = cast<CastExpr>(Inner)->getCastKind();
7587           // Boolean literals can be represented by implicit casts.
7588           if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
7589             return LK_Numeric;
7590           break;
7591         }
7592         default:
7593           break;
7594       }
7595       return LK_Boxed;
7596     }
7597   }
7598   return LK_None;
7599 }
7600 
7601 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
7602                                           ExprResult &LHS, ExprResult &RHS,
7603                                           BinaryOperator::Opcode Opc){
7604   Expr *Literal;
7605   Expr *Other;
7606   if (isObjCObjectLiteral(LHS)) {
7607     Literal = LHS.get();
7608     Other = RHS.get();
7609   } else {
7610     Literal = RHS.get();
7611     Other = LHS.get();
7612   }
7613 
7614   // Don't warn on comparisons against nil.
7615   Other = Other->IgnoreParenCasts();
7616   if (Other->isNullPointerConstant(S.getASTContext(),
7617                                    Expr::NPC_ValueDependentIsNotNull))
7618     return;
7619 
7620   // This should be kept in sync with warn_objc_literal_comparison.
7621   // LK_String should always be after the other literals, since it has its own
7622   // warning flag.
7623   Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
7624   assert(LiteralKind != Sema::LK_Block);
7625   if (LiteralKind == Sema::LK_None) {
7626     llvm_unreachable("Unknown Objective-C object literal kind");
7627   }
7628 
7629   if (LiteralKind == Sema::LK_String)
7630     S.Diag(Loc, diag::warn_objc_string_literal_comparison)
7631       << Literal->getSourceRange();
7632   else
7633     S.Diag(Loc, diag::warn_objc_literal_comparison)
7634       << LiteralKind << Literal->getSourceRange();
7635 
7636   if (BinaryOperator::isEqualityOp(Opc) &&
7637       hasIsEqualMethod(S, LHS.get(), RHS.get())) {
7638     SourceLocation Start = LHS.get()->getLocStart();
7639     SourceLocation End = S.PP.getLocForEndOfToken(RHS.get()->getLocEnd());
7640     CharSourceRange OpRange =
7641       CharSourceRange::getCharRange(Loc, S.PP.getLocForEndOfToken(Loc));
7642 
7643     S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
7644       << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
7645       << FixItHint::CreateReplacement(OpRange, " isEqual:")
7646       << FixItHint::CreateInsertion(End, "]");
7647   }
7648 }
7649 
7650 static void diagnoseLogicalNotOnLHSofComparison(Sema &S, ExprResult &LHS,
7651                                                 ExprResult &RHS,
7652                                                 SourceLocation Loc,
7653                                                 unsigned OpaqueOpc) {
7654   // This checking requires bools.
7655   if (!S.getLangOpts().Bool) return;
7656 
7657   // Check that left hand side is !something.
7658   UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
7659   if (!UO || UO->getOpcode() != UO_LNot) return;
7660 
7661   // Only check if the right hand side is non-bool arithmetic type.
7662   if (RHS.get()->getType()->isBooleanType()) return;
7663 
7664   // Make sure that the something in !something is not bool.
7665   Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
7666   if (SubExpr->getType()->isBooleanType()) return;
7667 
7668   // Emit warning.
7669   S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_comparison)
7670       << Loc;
7671 
7672   // First note suggest !(x < y)
7673   SourceLocation FirstOpen = SubExpr->getLocStart();
7674   SourceLocation FirstClose = RHS.get()->getLocEnd();
7675   FirstClose = S.getPreprocessor().getLocForEndOfToken(FirstClose);
7676   if (FirstClose.isInvalid())
7677     FirstOpen = SourceLocation();
7678   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
7679       << FixItHint::CreateInsertion(FirstOpen, "(")
7680       << FixItHint::CreateInsertion(FirstClose, ")");
7681 
7682   // Second note suggests (!x) < y
7683   SourceLocation SecondOpen = LHS.get()->getLocStart();
7684   SourceLocation SecondClose = LHS.get()->getLocEnd();
7685   SecondClose = S.getPreprocessor().getLocForEndOfToken(SecondClose);
7686   if (SecondClose.isInvalid())
7687     SecondOpen = SourceLocation();
7688   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
7689       << FixItHint::CreateInsertion(SecondOpen, "(")
7690       << FixItHint::CreateInsertion(SecondClose, ")");
7691 }
7692 
7693 // Get the decl for a simple expression: a reference to a variable,
7694 // an implicit C++ field reference, or an implicit ObjC ivar reference.
7695 static ValueDecl *getCompareDecl(Expr *E) {
7696   if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E))
7697     return DR->getDecl();
7698   if (ObjCIvarRefExpr* Ivar = dyn_cast<ObjCIvarRefExpr>(E)) {
7699     if (Ivar->isFreeIvar())
7700       return Ivar->getDecl();
7701   }
7702   if (MemberExpr* Mem = dyn_cast<MemberExpr>(E)) {
7703     if (Mem->isImplicitAccess())
7704       return Mem->getMemberDecl();
7705   }
7706   return 0;
7707 }
7708 
7709 // C99 6.5.8, C++ [expr.rel]
7710 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
7711                                     SourceLocation Loc, unsigned OpaqueOpc,
7712                                     bool IsRelational) {
7713   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
7714 
7715   BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
7716 
7717   // Handle vector comparisons separately.
7718   if (LHS.get()->getType()->isVectorType() ||
7719       RHS.get()->getType()->isVectorType())
7720     return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
7721 
7722   QualType LHSType = LHS.get()->getType();
7723   QualType RHSType = RHS.get()->getType();
7724 
7725   Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
7726   Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
7727 
7728   checkEnumComparison(*this, Loc, LHS.get(), RHS.get());
7729   diagnoseLogicalNotOnLHSofComparison(*this, LHS, RHS, Loc, OpaqueOpc);
7730 
7731   if (!LHSType->hasFloatingRepresentation() &&
7732       !(LHSType->isBlockPointerType() && IsRelational) &&
7733       !LHS.get()->getLocStart().isMacroID() &&
7734       !RHS.get()->getLocStart().isMacroID() &&
7735       ActiveTemplateInstantiations.empty()) {
7736     // For non-floating point types, check for self-comparisons of the form
7737     // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
7738     // often indicate logic errors in the program.
7739     //
7740     // NOTE: Don't warn about comparison expressions resulting from macro
7741     // expansion. Also don't warn about comparisons which are only self
7742     // comparisons within a template specialization. The warnings should catch
7743     // obvious cases in the definition of the template anyways. The idea is to
7744     // warn when the typed comparison operator will always evaluate to the same
7745     // result.
7746     ValueDecl *DL = getCompareDecl(LHSStripped);
7747     ValueDecl *DR = getCompareDecl(RHSStripped);
7748     if (DL && DR && DL == DR && !IsWithinTemplateSpecialization(DL)) {
7749       DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
7750                           << 0 // self-
7751                           << (Opc == BO_EQ
7752                               || Opc == BO_LE
7753                               || Opc == BO_GE));
7754     } else if (DL && DR && LHSType->isArrayType() && RHSType->isArrayType() &&
7755                !DL->getType()->isReferenceType() &&
7756                !DR->getType()->isReferenceType()) {
7757         // what is it always going to eval to?
7758         char always_evals_to;
7759         switch(Opc) {
7760         case BO_EQ: // e.g. array1 == array2
7761           always_evals_to = 0; // false
7762           break;
7763         case BO_NE: // e.g. array1 != array2
7764           always_evals_to = 1; // true
7765           break;
7766         default:
7767           // best we can say is 'a constant'
7768           always_evals_to = 2; // e.g. array1 <= array2
7769           break;
7770         }
7771         DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
7772                             << 1 // array
7773                             << always_evals_to);
7774     }
7775 
7776     if (isa<CastExpr>(LHSStripped))
7777       LHSStripped = LHSStripped->IgnoreParenCasts();
7778     if (isa<CastExpr>(RHSStripped))
7779       RHSStripped = RHSStripped->IgnoreParenCasts();
7780 
7781     // Warn about comparisons against a string constant (unless the other
7782     // operand is null), the user probably wants strcmp.
7783     Expr *literalString = 0;
7784     Expr *literalStringStripped = 0;
7785     if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
7786         !RHSStripped->isNullPointerConstant(Context,
7787                                             Expr::NPC_ValueDependentIsNull)) {
7788       literalString = LHS.get();
7789       literalStringStripped = LHSStripped;
7790     } else if ((isa<StringLiteral>(RHSStripped) ||
7791                 isa<ObjCEncodeExpr>(RHSStripped)) &&
7792                !LHSStripped->isNullPointerConstant(Context,
7793                                             Expr::NPC_ValueDependentIsNull)) {
7794       literalString = RHS.get();
7795       literalStringStripped = RHSStripped;
7796     }
7797 
7798     if (literalString) {
7799       DiagRuntimeBehavior(Loc, 0,
7800         PDiag(diag::warn_stringcompare)
7801           << isa<ObjCEncodeExpr>(literalStringStripped)
7802           << literalString->getSourceRange());
7803     }
7804   }
7805 
7806   // C99 6.5.8p3 / C99 6.5.9p4
7807   UsualArithmeticConversions(LHS, RHS);
7808   if (LHS.isInvalid() || RHS.isInvalid())
7809     return QualType();
7810 
7811   LHSType = LHS.get()->getType();
7812   RHSType = RHS.get()->getType();
7813 
7814   // The result of comparisons is 'bool' in C++, 'int' in C.
7815   QualType ResultTy = Context.getLogicalOperationType();
7816 
7817   if (IsRelational) {
7818     if (LHSType->isRealType() && RHSType->isRealType())
7819       return ResultTy;
7820   } else {
7821     // Check for comparisons of floating point operands using != and ==.
7822     if (LHSType->hasFloatingRepresentation())
7823       CheckFloatComparison(Loc, LHS.get(), RHS.get());
7824 
7825     if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
7826       return ResultTy;
7827   }
7828 
7829   bool LHSIsNull = LHS.get()->isNullPointerConstant(Context,
7830                                               Expr::NPC_ValueDependentIsNull);
7831   bool RHSIsNull = RHS.get()->isNullPointerConstant(Context,
7832                                               Expr::NPC_ValueDependentIsNull);
7833 
7834   // All of the following pointer-related warnings are GCC extensions, except
7835   // when handling null pointer constants.
7836   if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2
7837     QualType LCanPointeeTy =
7838       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
7839     QualType RCanPointeeTy =
7840       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
7841 
7842     if (getLangOpts().CPlusPlus) {
7843       if (LCanPointeeTy == RCanPointeeTy)
7844         return ResultTy;
7845       if (!IsRelational &&
7846           (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7847         // Valid unless comparison between non-null pointer and function pointer
7848         // This is a gcc extension compatibility comparison.
7849         // In a SFINAE context, we treat this as a hard error to maintain
7850         // conformance with the C++ standard.
7851         if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
7852             && !LHSIsNull && !RHSIsNull) {
7853           diagnoseFunctionPointerToVoidComparison(
7854               *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
7855 
7856           if (isSFINAEContext())
7857             return QualType();
7858 
7859           RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
7860           return ResultTy;
7861         }
7862       }
7863 
7864       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
7865         return QualType();
7866       else
7867         return ResultTy;
7868     }
7869     // C99 6.5.9p2 and C99 6.5.8p2
7870     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
7871                                    RCanPointeeTy.getUnqualifiedType())) {
7872       // Valid unless a relational comparison of function pointers
7873       if (IsRelational && LCanPointeeTy->isFunctionType()) {
7874         Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
7875           << LHSType << RHSType << LHS.get()->getSourceRange()
7876           << RHS.get()->getSourceRange();
7877       }
7878     } else if (!IsRelational &&
7879                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7880       // Valid unless comparison between non-null pointer and function pointer
7881       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
7882           && !LHSIsNull && !RHSIsNull)
7883         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
7884                                                 /*isError*/false);
7885     } else {
7886       // Invalid
7887       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
7888     }
7889     if (LCanPointeeTy != RCanPointeeTy) {
7890       unsigned AddrSpaceL = LCanPointeeTy.getAddressSpace();
7891       unsigned AddrSpaceR = RCanPointeeTy.getAddressSpace();
7892       CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
7893                                                : CK_BitCast;
7894       if (LHSIsNull && !RHSIsNull)
7895         LHS = ImpCastExprToType(LHS.take(), RHSType, Kind);
7896       else
7897         RHS = ImpCastExprToType(RHS.take(), LHSType, Kind);
7898     }
7899     return ResultTy;
7900   }
7901 
7902   if (getLangOpts().CPlusPlus) {
7903     // Comparison of nullptr_t with itself.
7904     if (LHSType->isNullPtrType() && RHSType->isNullPtrType())
7905       return ResultTy;
7906 
7907     // Comparison of pointers with null pointer constants and equality
7908     // comparisons of member pointers to null pointer constants.
7909     if (RHSIsNull &&
7910         ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) ||
7911          (!IsRelational &&
7912           (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) {
7913       RHS = ImpCastExprToType(RHS.take(), LHSType,
7914                         LHSType->isMemberPointerType()
7915                           ? CK_NullToMemberPointer
7916                           : CK_NullToPointer);
7917       return ResultTy;
7918     }
7919     if (LHSIsNull &&
7920         ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) ||
7921          (!IsRelational &&
7922           (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) {
7923       LHS = ImpCastExprToType(LHS.take(), RHSType,
7924                         RHSType->isMemberPointerType()
7925                           ? CK_NullToMemberPointer
7926                           : CK_NullToPointer);
7927       return ResultTy;
7928     }
7929 
7930     // Comparison of member pointers.
7931     if (!IsRelational &&
7932         LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) {
7933       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
7934         return QualType();
7935       else
7936         return ResultTy;
7937     }
7938 
7939     // Handle scoped enumeration types specifically, since they don't promote
7940     // to integers.
7941     if (LHS.get()->getType()->isEnumeralType() &&
7942         Context.hasSameUnqualifiedType(LHS.get()->getType(),
7943                                        RHS.get()->getType()))
7944       return ResultTy;
7945   }
7946 
7947   // Handle block pointer types.
7948   if (!IsRelational && LHSType->isBlockPointerType() &&
7949       RHSType->isBlockPointerType()) {
7950     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
7951     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
7952 
7953     if (!LHSIsNull && !RHSIsNull &&
7954         !Context.typesAreCompatible(lpointee, rpointee)) {
7955       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
7956         << LHSType << RHSType << LHS.get()->getSourceRange()
7957         << RHS.get()->getSourceRange();
7958     }
7959     RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
7960     return ResultTy;
7961   }
7962 
7963   // Allow block pointers to be compared with null pointer constants.
7964   if (!IsRelational
7965       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
7966           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
7967     if (!LHSIsNull && !RHSIsNull) {
7968       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
7969              ->getPointeeType()->isVoidType())
7970             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
7971                 ->getPointeeType()->isVoidType())))
7972         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
7973           << LHSType << RHSType << LHS.get()->getSourceRange()
7974           << RHS.get()->getSourceRange();
7975     }
7976     if (LHSIsNull && !RHSIsNull)
7977       LHS = ImpCastExprToType(LHS.take(), RHSType,
7978                               RHSType->isPointerType() ? CK_BitCast
7979                                 : CK_AnyPointerToBlockPointerCast);
7980     else
7981       RHS = ImpCastExprToType(RHS.take(), LHSType,
7982                               LHSType->isPointerType() ? CK_BitCast
7983                                 : CK_AnyPointerToBlockPointerCast);
7984     return ResultTy;
7985   }
7986 
7987   if (LHSType->isObjCObjectPointerType() ||
7988       RHSType->isObjCObjectPointerType()) {
7989     const PointerType *LPT = LHSType->getAs<PointerType>();
7990     const PointerType *RPT = RHSType->getAs<PointerType>();
7991     if (LPT || RPT) {
7992       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
7993       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
7994 
7995       if (!LPtrToVoid && !RPtrToVoid &&
7996           !Context.typesAreCompatible(LHSType, RHSType)) {
7997         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
7998                                           /*isError*/false);
7999       }
8000       if (LHSIsNull && !RHSIsNull) {
8001         Expr *E = LHS.take();
8002         if (getLangOpts().ObjCAutoRefCount)
8003           CheckObjCARCConversion(SourceRange(), RHSType, E, CCK_ImplicitConversion);
8004         LHS = ImpCastExprToType(E, RHSType,
8005                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
8006       }
8007       else {
8008         Expr *E = RHS.take();
8009         if (getLangOpts().ObjCAutoRefCount)
8010           CheckObjCARCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion);
8011         RHS = ImpCastExprToType(E, LHSType,
8012                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
8013       }
8014       return ResultTy;
8015     }
8016     if (LHSType->isObjCObjectPointerType() &&
8017         RHSType->isObjCObjectPointerType()) {
8018       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
8019         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
8020                                           /*isError*/false);
8021       if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
8022         diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
8023 
8024       if (LHSIsNull && !RHSIsNull)
8025         LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
8026       else
8027         RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
8028       return ResultTy;
8029     }
8030   }
8031   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
8032       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
8033     unsigned DiagID = 0;
8034     bool isError = false;
8035     if (LangOpts.DebuggerSupport) {
8036       // Under a debugger, allow the comparison of pointers to integers,
8037       // since users tend to want to compare addresses.
8038     } else if ((LHSIsNull && LHSType->isIntegerType()) ||
8039         (RHSIsNull && RHSType->isIntegerType())) {
8040       if (IsRelational && !getLangOpts().CPlusPlus)
8041         DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
8042     } else if (IsRelational && !getLangOpts().CPlusPlus)
8043       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
8044     else if (getLangOpts().CPlusPlus) {
8045       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
8046       isError = true;
8047     } else
8048       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
8049 
8050     if (DiagID) {
8051       Diag(Loc, DiagID)
8052         << LHSType << RHSType << LHS.get()->getSourceRange()
8053         << RHS.get()->getSourceRange();
8054       if (isError)
8055         return QualType();
8056     }
8057 
8058     if (LHSType->isIntegerType())
8059       LHS = ImpCastExprToType(LHS.take(), RHSType,
8060                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
8061     else
8062       RHS = ImpCastExprToType(RHS.take(), LHSType,
8063                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
8064     return ResultTy;
8065   }
8066 
8067   // Handle block pointers.
8068   if (!IsRelational && RHSIsNull
8069       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
8070     RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
8071     return ResultTy;
8072   }
8073   if (!IsRelational && LHSIsNull
8074       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
8075     LHS = ImpCastExprToType(LHS.take(), RHSType, CK_NullToPointer);
8076     return ResultTy;
8077   }
8078 
8079   return InvalidOperands(Loc, LHS, RHS);
8080 }
8081 
8082 
8083 // Return a signed type that is of identical size and number of elements.
8084 // For floating point vectors, return an integer type of identical size
8085 // and number of elements.
8086 QualType Sema::GetSignedVectorType(QualType V) {
8087   const VectorType *VTy = V->getAs<VectorType>();
8088   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
8089   if (TypeSize == Context.getTypeSize(Context.CharTy))
8090     return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
8091   else if (TypeSize == Context.getTypeSize(Context.ShortTy))
8092     return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
8093   else if (TypeSize == Context.getTypeSize(Context.IntTy))
8094     return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
8095   else if (TypeSize == Context.getTypeSize(Context.LongTy))
8096     return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
8097   assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
8098          "Unhandled vector element size in vector compare");
8099   return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
8100 }
8101 
8102 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
8103 /// operates on extended vector types.  Instead of producing an IntTy result,
8104 /// like a scalar comparison, a vector comparison produces a vector of integer
8105 /// types.
8106 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
8107                                           SourceLocation Loc,
8108                                           bool IsRelational) {
8109   // Check to make sure we're operating on vectors of the same type and width,
8110   // Allowing one side to be a scalar of element type.
8111   QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false);
8112   if (vType.isNull())
8113     return vType;
8114 
8115   QualType LHSType = LHS.get()->getType();
8116 
8117   // If AltiVec, the comparison results in a numeric type, i.e.
8118   // bool for C++, int for C
8119   if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
8120     return Context.getLogicalOperationType();
8121 
8122   // For non-floating point types, check for self-comparisons of the form
8123   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
8124   // often indicate logic errors in the program.
8125   if (!LHSType->hasFloatingRepresentation() &&
8126       ActiveTemplateInstantiations.empty()) {
8127     if (DeclRefExpr* DRL
8128           = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
8129       if (DeclRefExpr* DRR
8130             = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
8131         if (DRL->getDecl() == DRR->getDecl())
8132           DiagRuntimeBehavior(Loc, 0,
8133                               PDiag(diag::warn_comparison_always)
8134                                 << 0 // self-
8135                                 << 2 // "a constant"
8136                               );
8137   }
8138 
8139   // Check for comparisons of floating point operands using != and ==.
8140   if (!IsRelational && LHSType->hasFloatingRepresentation()) {
8141     assert (RHS.get()->getType()->hasFloatingRepresentation());
8142     CheckFloatComparison(Loc, LHS.get(), RHS.get());
8143   }
8144 
8145   // Return a signed type for the vector.
8146   return GetSignedVectorType(LHSType);
8147 }
8148 
8149 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
8150                                           SourceLocation Loc) {
8151   // Ensure that either both operands are of the same vector type, or
8152   // one operand is of a vector type and the other is of its element type.
8153   QualType vType = CheckVectorOperands(LHS, RHS, Loc, false);
8154   if (vType.isNull())
8155     return InvalidOperands(Loc, LHS, RHS);
8156   if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
8157       vType->hasFloatingRepresentation())
8158     return InvalidOperands(Loc, LHS, RHS);
8159 
8160   return GetSignedVectorType(LHS.get()->getType());
8161 }
8162 
8163 inline QualType Sema::CheckBitwiseOperands(
8164   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
8165   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8166 
8167   if (LHS.get()->getType()->isVectorType() ||
8168       RHS.get()->getType()->isVectorType()) {
8169     if (LHS.get()->getType()->hasIntegerRepresentation() &&
8170         RHS.get()->getType()->hasIntegerRepresentation())
8171       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
8172 
8173     return InvalidOperands(Loc, LHS, RHS);
8174   }
8175 
8176   ExprResult LHSResult = Owned(LHS), RHSResult = Owned(RHS);
8177   QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
8178                                                  IsCompAssign);
8179   if (LHSResult.isInvalid() || RHSResult.isInvalid())
8180     return QualType();
8181   LHS = LHSResult.take();
8182   RHS = RHSResult.take();
8183 
8184   if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
8185     return compType;
8186   return InvalidOperands(Loc, LHS, RHS);
8187 }
8188 
8189 inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
8190   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) {
8191 
8192   // Check vector operands differently.
8193   if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
8194     return CheckVectorLogicalOperands(LHS, RHS, Loc);
8195 
8196   // Diagnose cases where the user write a logical and/or but probably meant a
8197   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
8198   // is a constant.
8199   if (LHS.get()->getType()->isIntegerType() &&
8200       !LHS.get()->getType()->isBooleanType() &&
8201       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
8202       // Don't warn in macros or template instantiations.
8203       !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
8204     // If the RHS can be constant folded, and if it constant folds to something
8205     // that isn't 0 or 1 (which indicate a potential logical operation that
8206     // happened to fold to true/false) then warn.
8207     // Parens on the RHS are ignored.
8208     llvm::APSInt Result;
8209     if (RHS.get()->EvaluateAsInt(Result, Context))
8210       if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType()) ||
8211           (Result != 0 && Result != 1)) {
8212         Diag(Loc, diag::warn_logical_instead_of_bitwise)
8213           << RHS.get()->getSourceRange()
8214           << (Opc == BO_LAnd ? "&&" : "||");
8215         // Suggest replacing the logical operator with the bitwise version
8216         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
8217             << (Opc == BO_LAnd ? "&" : "|")
8218             << FixItHint::CreateReplacement(SourceRange(
8219                 Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(),
8220                                                 getLangOpts())),
8221                                             Opc == BO_LAnd ? "&" : "|");
8222         if (Opc == BO_LAnd)
8223           // Suggest replacing "Foo() && kNonZero" with "Foo()"
8224           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
8225               << FixItHint::CreateRemoval(
8226                   SourceRange(
8227                       Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(),
8228                                                  0, getSourceManager(),
8229                                                  getLangOpts()),
8230                       RHS.get()->getLocEnd()));
8231       }
8232   }
8233 
8234   if (!Context.getLangOpts().CPlusPlus) {
8235     // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
8236     // not operate on the built-in scalar and vector float types.
8237     if (Context.getLangOpts().OpenCL &&
8238         Context.getLangOpts().OpenCLVersion < 120) {
8239       if (LHS.get()->getType()->isFloatingType() ||
8240           RHS.get()->getType()->isFloatingType())
8241         return InvalidOperands(Loc, LHS, RHS);
8242     }
8243 
8244     LHS = UsualUnaryConversions(LHS.take());
8245     if (LHS.isInvalid())
8246       return QualType();
8247 
8248     RHS = UsualUnaryConversions(RHS.take());
8249     if (RHS.isInvalid())
8250       return QualType();
8251 
8252     if (!LHS.get()->getType()->isScalarType() ||
8253         !RHS.get()->getType()->isScalarType())
8254       return InvalidOperands(Loc, LHS, RHS);
8255 
8256     return Context.IntTy;
8257   }
8258 
8259   // The following is safe because we only use this method for
8260   // non-overloadable operands.
8261 
8262   // C++ [expr.log.and]p1
8263   // C++ [expr.log.or]p1
8264   // The operands are both contextually converted to type bool.
8265   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
8266   if (LHSRes.isInvalid())
8267     return InvalidOperands(Loc, LHS, RHS);
8268   LHS = LHSRes;
8269 
8270   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
8271   if (RHSRes.isInvalid())
8272     return InvalidOperands(Loc, LHS, RHS);
8273   RHS = RHSRes;
8274 
8275   // C++ [expr.log.and]p2
8276   // C++ [expr.log.or]p2
8277   // The result is a bool.
8278   return Context.BoolTy;
8279 }
8280 
8281 static bool IsReadonlyMessage(Expr *E, Sema &S) {
8282   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
8283   if (!ME) return false;
8284   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
8285   ObjCMessageExpr *Base =
8286     dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts());
8287   if (!Base) return false;
8288   return Base->getMethodDecl() != 0;
8289 }
8290 
8291 /// Is the given expression (which must be 'const') a reference to a
8292 /// variable which was originally non-const, but which has become
8293 /// 'const' due to being captured within a block?
8294 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
8295 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
8296   assert(E->isLValue() && E->getType().isConstQualified());
8297   E = E->IgnoreParens();
8298 
8299   // Must be a reference to a declaration from an enclosing scope.
8300   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
8301   if (!DRE) return NCCK_None;
8302   if (!DRE->refersToEnclosingLocal()) return NCCK_None;
8303 
8304   // The declaration must be a variable which is not declared 'const'.
8305   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
8306   if (!var) return NCCK_None;
8307   if (var->getType().isConstQualified()) return NCCK_None;
8308   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
8309 
8310   // Decide whether the first capture was for a block or a lambda.
8311   DeclContext *DC = S.CurContext, *Prev = 0;
8312   while (DC != var->getDeclContext()) {
8313     Prev = DC;
8314     DC = DC->getParent();
8315   }
8316   // Unless we have an init-capture, we've gone one step too far.
8317   if (!var->isInitCapture())
8318     DC = Prev;
8319   return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
8320 }
8321 
8322 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
8323 /// emit an error and return true.  If so, return false.
8324 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
8325   assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
8326   SourceLocation OrigLoc = Loc;
8327   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
8328                                                               &Loc);
8329   if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
8330     IsLV = Expr::MLV_InvalidMessageExpression;
8331   if (IsLV == Expr::MLV_Valid)
8332     return false;
8333 
8334   unsigned Diag = 0;
8335   bool NeedType = false;
8336   switch (IsLV) { // C99 6.5.16p2
8337   case Expr::MLV_ConstQualified:
8338     Diag = diag::err_typecheck_assign_const;
8339 
8340     // Use a specialized diagnostic when we're assigning to an object
8341     // from an enclosing function or block.
8342     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
8343       if (NCCK == NCCK_Block)
8344         Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
8345       else
8346         Diag = diag::err_lambda_decl_ref_not_modifiable_lvalue;
8347       break;
8348     }
8349 
8350     // In ARC, use some specialized diagnostics for occasions where we
8351     // infer 'const'.  These are always pseudo-strong variables.
8352     if (S.getLangOpts().ObjCAutoRefCount) {
8353       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
8354       if (declRef && isa<VarDecl>(declRef->getDecl())) {
8355         VarDecl *var = cast<VarDecl>(declRef->getDecl());
8356 
8357         // Use the normal diagnostic if it's pseudo-__strong but the
8358         // user actually wrote 'const'.
8359         if (var->isARCPseudoStrong() &&
8360             (!var->getTypeSourceInfo() ||
8361              !var->getTypeSourceInfo()->getType().isConstQualified())) {
8362           // There are two pseudo-strong cases:
8363           //  - self
8364           ObjCMethodDecl *method = S.getCurMethodDecl();
8365           if (method && var == method->getSelfDecl())
8366             Diag = method->isClassMethod()
8367               ? diag::err_typecheck_arc_assign_self_class_method
8368               : diag::err_typecheck_arc_assign_self;
8369 
8370           //  - fast enumeration variables
8371           else
8372             Diag = diag::err_typecheck_arr_assign_enumeration;
8373 
8374           SourceRange Assign;
8375           if (Loc != OrigLoc)
8376             Assign = SourceRange(OrigLoc, OrigLoc);
8377           S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
8378           // We need to preserve the AST regardless, so migration tool
8379           // can do its job.
8380           return false;
8381         }
8382       }
8383     }
8384 
8385     break;
8386   case Expr::MLV_ArrayType:
8387   case Expr::MLV_ArrayTemporary:
8388     Diag = diag::err_typecheck_array_not_modifiable_lvalue;
8389     NeedType = true;
8390     break;
8391   case Expr::MLV_NotObjectType:
8392     Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
8393     NeedType = true;
8394     break;
8395   case Expr::MLV_LValueCast:
8396     Diag = diag::err_typecheck_lvalue_casts_not_supported;
8397     break;
8398   case Expr::MLV_Valid:
8399     llvm_unreachable("did not take early return for MLV_Valid");
8400   case Expr::MLV_InvalidExpression:
8401   case Expr::MLV_MemberFunction:
8402   case Expr::MLV_ClassTemporary:
8403     Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
8404     break;
8405   case Expr::MLV_IncompleteType:
8406   case Expr::MLV_IncompleteVoidType:
8407     return S.RequireCompleteType(Loc, E->getType(),
8408              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
8409   case Expr::MLV_DuplicateVectorComponents:
8410     Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
8411     break;
8412   case Expr::MLV_NoSetterProperty:
8413     llvm_unreachable("readonly properties should be processed differently");
8414   case Expr::MLV_InvalidMessageExpression:
8415     Diag = diag::error_readonly_message_assignment;
8416     break;
8417   case Expr::MLV_SubObjCPropertySetting:
8418     Diag = diag::error_no_subobject_property_setting;
8419     break;
8420   }
8421 
8422   SourceRange Assign;
8423   if (Loc != OrigLoc)
8424     Assign = SourceRange(OrigLoc, OrigLoc);
8425   if (NeedType)
8426     S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
8427   else
8428     S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
8429   return true;
8430 }
8431 
8432 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
8433                                          SourceLocation Loc,
8434                                          Sema &Sema) {
8435   // C / C++ fields
8436   MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
8437   MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
8438   if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) {
8439     if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))
8440       Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
8441   }
8442 
8443   // Objective-C instance variables
8444   ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
8445   ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
8446   if (OL && OR && OL->getDecl() == OR->getDecl()) {
8447     DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
8448     DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
8449     if (RL && RR && RL->getDecl() == RR->getDecl())
8450       Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
8451   }
8452 }
8453 
8454 // C99 6.5.16.1
8455 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
8456                                        SourceLocation Loc,
8457                                        QualType CompoundType) {
8458   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
8459 
8460   // Verify that LHS is a modifiable lvalue, and emit error if not.
8461   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
8462     return QualType();
8463 
8464   QualType LHSType = LHSExpr->getType();
8465   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
8466                                              CompoundType;
8467   AssignConvertType ConvTy;
8468   if (CompoundType.isNull()) {
8469     Expr *RHSCheck = RHS.get();
8470 
8471     CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
8472 
8473     QualType LHSTy(LHSType);
8474     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
8475     if (RHS.isInvalid())
8476       return QualType();
8477     // Special case of NSObject attributes on c-style pointer types.
8478     if (ConvTy == IncompatiblePointer &&
8479         ((Context.isObjCNSObjectType(LHSType) &&
8480           RHSType->isObjCObjectPointerType()) ||
8481          (Context.isObjCNSObjectType(RHSType) &&
8482           LHSType->isObjCObjectPointerType())))
8483       ConvTy = Compatible;
8484 
8485     if (ConvTy == Compatible &&
8486         LHSType->isObjCObjectType())
8487         Diag(Loc, diag::err_objc_object_assignment)
8488           << LHSType;
8489 
8490     // If the RHS is a unary plus or minus, check to see if they = and + are
8491     // right next to each other.  If so, the user may have typo'd "x =+ 4"
8492     // instead of "x += 4".
8493     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
8494       RHSCheck = ICE->getSubExpr();
8495     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
8496       if ((UO->getOpcode() == UO_Plus ||
8497            UO->getOpcode() == UO_Minus) &&
8498           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
8499           // Only if the two operators are exactly adjacent.
8500           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
8501           // And there is a space or other character before the subexpr of the
8502           // unary +/-.  We don't want to warn on "x=-1".
8503           Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
8504           UO->getSubExpr()->getLocStart().isFileID()) {
8505         Diag(Loc, diag::warn_not_compound_assign)
8506           << (UO->getOpcode() == UO_Plus ? "+" : "-")
8507           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
8508       }
8509     }
8510 
8511     if (ConvTy == Compatible) {
8512       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
8513         // Warn about retain cycles where a block captures the LHS, but
8514         // not if the LHS is a simple variable into which the block is
8515         // being stored...unless that variable can be captured by reference!
8516         const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
8517         const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
8518         if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
8519           checkRetainCycles(LHSExpr, RHS.get());
8520 
8521         // It is safe to assign a weak reference into a strong variable.
8522         // Although this code can still have problems:
8523         //   id x = self.weakProp;
8524         //   id y = self.weakProp;
8525         // we do not warn to warn spuriously when 'x' and 'y' are on separate
8526         // paths through the function. This should be revisited if
8527         // -Wrepeated-use-of-weak is made flow-sensitive.
8528         DiagnosticsEngine::Level Level =
8529           Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
8530                                    RHS.get()->getLocStart());
8531         if (Level != DiagnosticsEngine::Ignored)
8532           getCurFunction()->markSafeWeakUse(RHS.get());
8533 
8534       } else if (getLangOpts().ObjCAutoRefCount) {
8535         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
8536       }
8537     }
8538   } else {
8539     // Compound assignment "x += y"
8540     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
8541   }
8542 
8543   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
8544                                RHS.get(), AA_Assigning))
8545     return QualType();
8546 
8547   CheckForNullPointerDereference(*this, LHSExpr);
8548 
8549   // C99 6.5.16p3: The type of an assignment expression is the type of the
8550   // left operand unless the left operand has qualified type, in which case
8551   // it is the unqualified version of the type of the left operand.
8552   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
8553   // is converted to the type of the assignment expression (above).
8554   // C++ 5.17p1: the type of the assignment expression is that of its left
8555   // operand.
8556   return (getLangOpts().CPlusPlus
8557           ? LHSType : LHSType.getUnqualifiedType());
8558 }
8559 
8560 // C99 6.5.17
8561 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
8562                                    SourceLocation Loc) {
8563   LHS = S.CheckPlaceholderExpr(LHS.take());
8564   RHS = S.CheckPlaceholderExpr(RHS.take());
8565   if (LHS.isInvalid() || RHS.isInvalid())
8566     return QualType();
8567 
8568   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
8569   // operands, but not unary promotions.
8570   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
8571 
8572   // So we treat the LHS as a ignored value, and in C++ we allow the
8573   // containing site to determine what should be done with the RHS.
8574   LHS = S.IgnoredValueConversions(LHS.take());
8575   if (LHS.isInvalid())
8576     return QualType();
8577 
8578   S.DiagnoseUnusedExprResult(LHS.get());
8579 
8580   if (!S.getLangOpts().CPlusPlus) {
8581     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take());
8582     if (RHS.isInvalid())
8583       return QualType();
8584     if (!RHS.get()->getType()->isVoidType())
8585       S.RequireCompleteType(Loc, RHS.get()->getType(),
8586                             diag::err_incomplete_type);
8587   }
8588 
8589   return RHS.get()->getType();
8590 }
8591 
8592 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
8593 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
8594 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
8595                                                ExprValueKind &VK,
8596                                                SourceLocation OpLoc,
8597                                                bool IsInc, bool IsPrefix) {
8598   if (Op->isTypeDependent())
8599     return S.Context.DependentTy;
8600 
8601   QualType ResType = Op->getType();
8602   // Atomic types can be used for increment / decrement where the non-atomic
8603   // versions can, so ignore the _Atomic() specifier for the purpose of
8604   // checking.
8605   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
8606     ResType = ResAtomicType->getValueType();
8607 
8608   assert(!ResType.isNull() && "no type for increment/decrement expression");
8609 
8610   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
8611     // Decrement of bool is not allowed.
8612     if (!IsInc) {
8613       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
8614       return QualType();
8615     }
8616     // Increment of bool sets it to true, but is deprecated.
8617     S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
8618   } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
8619     // Error on enum increments and decrements in C++ mode
8620     S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
8621     return QualType();
8622   } else if (ResType->isRealType()) {
8623     // OK!
8624   } else if (ResType->isPointerType()) {
8625     // C99 6.5.2.4p2, 6.5.6p2
8626     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
8627       return QualType();
8628   } else if (ResType->isObjCObjectPointerType()) {
8629     // On modern runtimes, ObjC pointer arithmetic is forbidden.
8630     // Otherwise, we just need a complete type.
8631     if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
8632         checkArithmeticOnObjCPointer(S, OpLoc, Op))
8633       return QualType();
8634   } else if (ResType->isAnyComplexType()) {
8635     // C99 does not support ++/-- on complex types, we allow as an extension.
8636     S.Diag(OpLoc, diag::ext_integer_increment_complex)
8637       << ResType << Op->getSourceRange();
8638   } else if (ResType->isPlaceholderType()) {
8639     ExprResult PR = S.CheckPlaceholderExpr(Op);
8640     if (PR.isInvalid()) return QualType();
8641     return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
8642                                           IsInc, IsPrefix);
8643   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
8644     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
8645   } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
8646             ResType->getAs<VectorType>()->getElementType()->isIntegerType()) {
8647     // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
8648   } else {
8649     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
8650       << ResType << int(IsInc) << Op->getSourceRange();
8651     return QualType();
8652   }
8653   // At this point, we know we have a real, complex or pointer type.
8654   // Now make sure the operand is a modifiable lvalue.
8655   if (CheckForModifiableLvalue(Op, OpLoc, S))
8656     return QualType();
8657   // In C++, a prefix increment is the same type as the operand. Otherwise
8658   // (in C or with postfix), the increment is the unqualified type of the
8659   // operand.
8660   if (IsPrefix && S.getLangOpts().CPlusPlus) {
8661     VK = VK_LValue;
8662     return ResType;
8663   } else {
8664     VK = VK_RValue;
8665     return ResType.getUnqualifiedType();
8666   }
8667 }
8668 
8669 
8670 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
8671 /// This routine allows us to typecheck complex/recursive expressions
8672 /// where the declaration is needed for type checking. We only need to
8673 /// handle cases when the expression references a function designator
8674 /// or is an lvalue. Here are some examples:
8675 ///  - &(x) => x
8676 ///  - &*****f => f for f a function designator.
8677 ///  - &s.xx => s
8678 ///  - &s.zz[1].yy -> s, if zz is an array
8679 ///  - *(x + 1) -> x, if x is an array
8680 ///  - &"123"[2] -> 0
8681 ///  - & __real__ x -> x
8682 static ValueDecl *getPrimaryDecl(Expr *E) {
8683   switch (E->getStmtClass()) {
8684   case Stmt::DeclRefExprClass:
8685     return cast<DeclRefExpr>(E)->getDecl();
8686   case Stmt::MemberExprClass:
8687     // If this is an arrow operator, the address is an offset from
8688     // the base's value, so the object the base refers to is
8689     // irrelevant.
8690     if (cast<MemberExpr>(E)->isArrow())
8691       return 0;
8692     // Otherwise, the expression refers to a part of the base
8693     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
8694   case Stmt::ArraySubscriptExprClass: {
8695     // FIXME: This code shouldn't be necessary!  We should catch the implicit
8696     // promotion of register arrays earlier.
8697     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
8698     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
8699       if (ICE->getSubExpr()->getType()->isArrayType())
8700         return getPrimaryDecl(ICE->getSubExpr());
8701     }
8702     return 0;
8703   }
8704   case Stmt::UnaryOperatorClass: {
8705     UnaryOperator *UO = cast<UnaryOperator>(E);
8706 
8707     switch(UO->getOpcode()) {
8708     case UO_Real:
8709     case UO_Imag:
8710     case UO_Extension:
8711       return getPrimaryDecl(UO->getSubExpr());
8712     default:
8713       return 0;
8714     }
8715   }
8716   case Stmt::ParenExprClass:
8717     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
8718   case Stmt::ImplicitCastExprClass:
8719     // If the result of an implicit cast is an l-value, we care about
8720     // the sub-expression; otherwise, the result here doesn't matter.
8721     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
8722   default:
8723     return 0;
8724   }
8725 }
8726 
8727 namespace {
8728   enum {
8729     AO_Bit_Field = 0,
8730     AO_Vector_Element = 1,
8731     AO_Property_Expansion = 2,
8732     AO_Register_Variable = 3,
8733     AO_No_Error = 4
8734   };
8735 }
8736 /// \brief Diagnose invalid operand for address of operations.
8737 ///
8738 /// \param Type The type of operand which cannot have its address taken.
8739 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
8740                                          Expr *E, unsigned Type) {
8741   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
8742 }
8743 
8744 /// CheckAddressOfOperand - The operand of & must be either a function
8745 /// designator or an lvalue designating an object. If it is an lvalue, the
8746 /// object cannot be declared with storage class register or be a bit field.
8747 /// Note: The usual conversions are *not* applied to the operand of the &
8748 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
8749 /// In C++, the operand might be an overloaded function name, in which case
8750 /// we allow the '&' but retain the overloaded-function type.
8751 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
8752   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
8753     if (PTy->getKind() == BuiltinType::Overload) {
8754       Expr *E = OrigOp.get()->IgnoreParens();
8755       if (!isa<OverloadExpr>(E)) {
8756         assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
8757         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
8758           << OrigOp.get()->getSourceRange();
8759         return QualType();
8760       }
8761 
8762       OverloadExpr *Ovl = cast<OverloadExpr>(E);
8763       if (isa<UnresolvedMemberExpr>(Ovl))
8764         if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
8765           Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
8766             << OrigOp.get()->getSourceRange();
8767           return QualType();
8768         }
8769 
8770       return Context.OverloadTy;
8771     }
8772 
8773     if (PTy->getKind() == BuiltinType::UnknownAny)
8774       return Context.UnknownAnyTy;
8775 
8776     if (PTy->getKind() == BuiltinType::BoundMember) {
8777       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
8778         << OrigOp.get()->getSourceRange();
8779       return QualType();
8780     }
8781 
8782     OrigOp = CheckPlaceholderExpr(OrigOp.take());
8783     if (OrigOp.isInvalid()) return QualType();
8784   }
8785 
8786   if (OrigOp.get()->isTypeDependent())
8787     return Context.DependentTy;
8788 
8789   assert(!OrigOp.get()->getType()->isPlaceholderType());
8790 
8791   // Make sure to ignore parentheses in subsequent checks
8792   Expr *op = OrigOp.get()->IgnoreParens();
8793 
8794   if (getLangOpts().C99) {
8795     // Implement C99-only parts of addressof rules.
8796     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
8797       if (uOp->getOpcode() == UO_Deref)
8798         // Per C99 6.5.3.2, the address of a deref always returns a valid result
8799         // (assuming the deref expression is valid).
8800         return uOp->getSubExpr()->getType();
8801     }
8802     // Technically, there should be a check for array subscript
8803     // expressions here, but the result of one is always an lvalue anyway.
8804   }
8805   ValueDecl *dcl = getPrimaryDecl(op);
8806   Expr::LValueClassification lval = op->ClassifyLValue(Context);
8807   unsigned AddressOfError = AO_No_Error;
8808 
8809   if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
8810     bool sfinae = (bool)isSFINAEContext();
8811     Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
8812                                   : diag::ext_typecheck_addrof_temporary)
8813       << op->getType() << op->getSourceRange();
8814     if (sfinae)
8815       return QualType();
8816     // Materialize the temporary as an lvalue so that we can take its address.
8817     OrigOp = op = new (Context)
8818         MaterializeTemporaryExpr(op->getType(), OrigOp.take(), true, 0);
8819   } else if (isa<ObjCSelectorExpr>(op)) {
8820     return Context.getPointerType(op->getType());
8821   } else if (lval == Expr::LV_MemberFunction) {
8822     // If it's an instance method, make a member pointer.
8823     // The expression must have exactly the form &A::foo.
8824 
8825     // If the underlying expression isn't a decl ref, give up.
8826     if (!isa<DeclRefExpr>(op)) {
8827       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
8828         << OrigOp.get()->getSourceRange();
8829       return QualType();
8830     }
8831     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
8832     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
8833 
8834     // The id-expression was parenthesized.
8835     if (OrigOp.get() != DRE) {
8836       Diag(OpLoc, diag::err_parens_pointer_member_function)
8837         << OrigOp.get()->getSourceRange();
8838 
8839     // The method was named without a qualifier.
8840     } else if (!DRE->getQualifier()) {
8841       if (MD->getParent()->getName().empty())
8842         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
8843           << op->getSourceRange();
8844       else {
8845         SmallString<32> Str;
8846         StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
8847         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
8848           << op->getSourceRange()
8849           << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
8850       }
8851     }
8852 
8853     // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
8854     if (isa<CXXDestructorDecl>(MD))
8855       Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
8856 
8857     QualType MPTy = Context.getMemberPointerType(
8858         op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
8859     if (Context.getTargetInfo().getCXXABI().isMicrosoft())
8860       RequireCompleteType(OpLoc, MPTy, 0);
8861     return MPTy;
8862   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
8863     // C99 6.5.3.2p1
8864     // The operand must be either an l-value or a function designator
8865     if (!op->getType()->isFunctionType()) {
8866       // Use a special diagnostic for loads from property references.
8867       if (isa<PseudoObjectExpr>(op)) {
8868         AddressOfError = AO_Property_Expansion;
8869       } else {
8870         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
8871           << op->getType() << op->getSourceRange();
8872         return QualType();
8873       }
8874     }
8875   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
8876     // The operand cannot be a bit-field
8877     AddressOfError = AO_Bit_Field;
8878   } else if (op->getObjectKind() == OK_VectorComponent) {
8879     // The operand cannot be an element of a vector
8880     AddressOfError = AO_Vector_Element;
8881   } else if (dcl) { // C99 6.5.3.2p1
8882     // We have an lvalue with a decl. Make sure the decl is not declared
8883     // with the register storage-class specifier.
8884     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
8885       // in C++ it is not error to take address of a register
8886       // variable (c++03 7.1.1P3)
8887       if (vd->getStorageClass() == SC_Register &&
8888           !getLangOpts().CPlusPlus) {
8889         AddressOfError = AO_Register_Variable;
8890       }
8891     } else if (isa<FunctionTemplateDecl>(dcl)) {
8892       return Context.OverloadTy;
8893     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
8894       // Okay: we can take the address of a field.
8895       // Could be a pointer to member, though, if there is an explicit
8896       // scope qualifier for the class.
8897       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
8898         DeclContext *Ctx = dcl->getDeclContext();
8899         if (Ctx && Ctx->isRecord()) {
8900           if (dcl->getType()->isReferenceType()) {
8901             Diag(OpLoc,
8902                  diag::err_cannot_form_pointer_to_member_of_reference_type)
8903               << dcl->getDeclName() << dcl->getType();
8904             return QualType();
8905           }
8906 
8907           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
8908             Ctx = Ctx->getParent();
8909 
8910           QualType MPTy = Context.getMemberPointerType(
8911               op->getType(),
8912               Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
8913           if (Context.getTargetInfo().getCXXABI().isMicrosoft())
8914             RequireCompleteType(OpLoc, MPTy, 0);
8915           return MPTy;
8916         }
8917       }
8918     } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl))
8919       llvm_unreachable("Unknown/unexpected decl type");
8920   }
8921 
8922   if (AddressOfError != AO_No_Error) {
8923     diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
8924     return QualType();
8925   }
8926 
8927   if (lval == Expr::LV_IncompleteVoidType) {
8928     // Taking the address of a void variable is technically illegal, but we
8929     // allow it in cases which are otherwise valid.
8930     // Example: "extern void x; void* y = &x;".
8931     Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
8932   }
8933 
8934   // If the operand has type "type", the result has type "pointer to type".
8935   if (op->getType()->isObjCObjectType())
8936     return Context.getObjCObjectPointerType(op->getType());
8937   return Context.getPointerType(op->getType());
8938 }
8939 
8940 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
8941 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
8942                                         SourceLocation OpLoc) {
8943   if (Op->isTypeDependent())
8944     return S.Context.DependentTy;
8945 
8946   ExprResult ConvResult = S.UsualUnaryConversions(Op);
8947   if (ConvResult.isInvalid())
8948     return QualType();
8949   Op = ConvResult.take();
8950   QualType OpTy = Op->getType();
8951   QualType Result;
8952 
8953   if (isa<CXXReinterpretCastExpr>(Op)) {
8954     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
8955     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
8956                                      Op->getSourceRange());
8957   }
8958 
8959   // Note that per both C89 and C99, indirection is always legal, even if OpTy
8960   // is an incomplete type or void.  It would be possible to warn about
8961   // dereferencing a void pointer, but it's completely well-defined, and such a
8962   // warning is unlikely to catch any mistakes.
8963   if (const PointerType *PT = OpTy->getAs<PointerType>())
8964     Result = PT->getPointeeType();
8965   else if (const ObjCObjectPointerType *OPT =
8966              OpTy->getAs<ObjCObjectPointerType>())
8967     Result = OPT->getPointeeType();
8968   else {
8969     ExprResult PR = S.CheckPlaceholderExpr(Op);
8970     if (PR.isInvalid()) return QualType();
8971     if (PR.take() != Op)
8972       return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
8973   }
8974 
8975   if (Result.isNull()) {
8976     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
8977       << OpTy << Op->getSourceRange();
8978     return QualType();
8979   }
8980 
8981   // Dereferences are usually l-values...
8982   VK = VK_LValue;
8983 
8984   // ...except that certain expressions are never l-values in C.
8985   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
8986     VK = VK_RValue;
8987 
8988   return Result;
8989 }
8990 
8991 static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
8992   tok::TokenKind Kind) {
8993   BinaryOperatorKind Opc;
8994   switch (Kind) {
8995   default: llvm_unreachable("Unknown binop!");
8996   case tok::periodstar:           Opc = BO_PtrMemD; break;
8997   case tok::arrowstar:            Opc = BO_PtrMemI; break;
8998   case tok::star:                 Opc = BO_Mul; break;
8999   case tok::slash:                Opc = BO_Div; break;
9000   case tok::percent:              Opc = BO_Rem; break;
9001   case tok::plus:                 Opc = BO_Add; break;
9002   case tok::minus:                Opc = BO_Sub; break;
9003   case tok::lessless:             Opc = BO_Shl; break;
9004   case tok::greatergreater:       Opc = BO_Shr; break;
9005   case tok::lessequal:            Opc = BO_LE; break;
9006   case tok::less:                 Opc = BO_LT; break;
9007   case tok::greaterequal:         Opc = BO_GE; break;
9008   case tok::greater:              Opc = BO_GT; break;
9009   case tok::exclaimequal:         Opc = BO_NE; break;
9010   case tok::equalequal:           Opc = BO_EQ; break;
9011   case tok::amp:                  Opc = BO_And; break;
9012   case tok::caret:                Opc = BO_Xor; break;
9013   case tok::pipe:                 Opc = BO_Or; break;
9014   case tok::ampamp:               Opc = BO_LAnd; break;
9015   case tok::pipepipe:             Opc = BO_LOr; break;
9016   case tok::equal:                Opc = BO_Assign; break;
9017   case tok::starequal:            Opc = BO_MulAssign; break;
9018   case tok::slashequal:           Opc = BO_DivAssign; break;
9019   case tok::percentequal:         Opc = BO_RemAssign; break;
9020   case tok::plusequal:            Opc = BO_AddAssign; break;
9021   case tok::minusequal:           Opc = BO_SubAssign; break;
9022   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
9023   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
9024   case tok::ampequal:             Opc = BO_AndAssign; break;
9025   case tok::caretequal:           Opc = BO_XorAssign; break;
9026   case tok::pipeequal:            Opc = BO_OrAssign; break;
9027   case tok::comma:                Opc = BO_Comma; break;
9028   }
9029   return Opc;
9030 }
9031 
9032 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
9033   tok::TokenKind Kind) {
9034   UnaryOperatorKind Opc;
9035   switch (Kind) {
9036   default: llvm_unreachable("Unknown unary op!");
9037   case tok::plusplus:     Opc = UO_PreInc; break;
9038   case tok::minusminus:   Opc = UO_PreDec; break;
9039   case tok::amp:          Opc = UO_AddrOf; break;
9040   case tok::star:         Opc = UO_Deref; break;
9041   case tok::plus:         Opc = UO_Plus; break;
9042   case tok::minus:        Opc = UO_Minus; break;
9043   case tok::tilde:        Opc = UO_Not; break;
9044   case tok::exclaim:      Opc = UO_LNot; break;
9045   case tok::kw___real:    Opc = UO_Real; break;
9046   case tok::kw___imag:    Opc = UO_Imag; break;
9047   case tok::kw___extension__: Opc = UO_Extension; break;
9048   }
9049   return Opc;
9050 }
9051 
9052 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
9053 /// This warning is only emitted for builtin assignment operations. It is also
9054 /// suppressed in the event of macro expansions.
9055 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
9056                                    SourceLocation OpLoc) {
9057   if (!S.ActiveTemplateInstantiations.empty())
9058     return;
9059   if (OpLoc.isInvalid() || OpLoc.isMacroID())
9060     return;
9061   LHSExpr = LHSExpr->IgnoreParenImpCasts();
9062   RHSExpr = RHSExpr->IgnoreParenImpCasts();
9063   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
9064   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
9065   if (!LHSDeclRef || !RHSDeclRef ||
9066       LHSDeclRef->getLocation().isMacroID() ||
9067       RHSDeclRef->getLocation().isMacroID())
9068     return;
9069   const ValueDecl *LHSDecl =
9070     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
9071   const ValueDecl *RHSDecl =
9072     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
9073   if (LHSDecl != RHSDecl)
9074     return;
9075   if (LHSDecl->getType().isVolatileQualified())
9076     return;
9077   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
9078     if (RefTy->getPointeeType().isVolatileQualified())
9079       return;
9080 
9081   S.Diag(OpLoc, diag::warn_self_assignment)
9082       << LHSDeclRef->getType()
9083       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
9084 }
9085 
9086 /// Check if a bitwise-& is performed on an Objective-C pointer.  This
9087 /// is usually indicative of introspection within the Objective-C pointer.
9088 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
9089                                           SourceLocation OpLoc) {
9090   if (!S.getLangOpts().ObjC1)
9091     return;
9092 
9093   const Expr *ObjCPointerExpr = 0, *OtherExpr = 0;
9094   const Expr *LHS = L.get();
9095   const Expr *RHS = R.get();
9096 
9097   if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
9098     ObjCPointerExpr = LHS;
9099     OtherExpr = RHS;
9100   }
9101   else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
9102     ObjCPointerExpr = RHS;
9103     OtherExpr = LHS;
9104   }
9105 
9106   // This warning is deliberately made very specific to reduce false
9107   // positives with logic that uses '&' for hashing.  This logic mainly
9108   // looks for code trying to introspect into tagged pointers, which
9109   // code should generally never do.
9110   if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
9111     unsigned Diag = diag::warn_objc_pointer_masking;
9112     // Determine if we are introspecting the result of performSelectorXXX.
9113     const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
9114     // Special case messages to -performSelector and friends, which
9115     // can return non-pointer values boxed in a pointer value.
9116     // Some clients may wish to silence warnings in this subcase.
9117     if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
9118       Selector S = ME->getSelector();
9119       StringRef SelArg0 = S.getNameForSlot(0);
9120       if (SelArg0.startswith("performSelector"))
9121         Diag = diag::warn_objc_pointer_masking_performSelector;
9122     }
9123 
9124     S.Diag(OpLoc, Diag)
9125       << ObjCPointerExpr->getSourceRange();
9126   }
9127 }
9128 
9129 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
9130 /// operator @p Opc at location @c TokLoc. This routine only supports
9131 /// built-in operations; ActOnBinOp handles overloaded operators.
9132 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
9133                                     BinaryOperatorKind Opc,
9134                                     Expr *LHSExpr, Expr *RHSExpr) {
9135   if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
9136     // The syntax only allows initializer lists on the RHS of assignment,
9137     // so we don't need to worry about accepting invalid code for
9138     // non-assignment operators.
9139     // C++11 5.17p9:
9140     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
9141     //   of x = {} is x = T().
9142     InitializationKind Kind =
9143         InitializationKind::CreateDirectList(RHSExpr->getLocStart());
9144     InitializedEntity Entity =
9145         InitializedEntity::InitializeTemporary(LHSExpr->getType());
9146     InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
9147     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
9148     if (Init.isInvalid())
9149       return Init;
9150     RHSExpr = Init.take();
9151   }
9152 
9153   ExprResult LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
9154   QualType ResultTy;     // Result type of the binary operator.
9155   // The following two variables are used for compound assignment operators
9156   QualType CompLHSTy;    // Type of LHS after promotions for computation
9157   QualType CompResultTy; // Type of computation result
9158   ExprValueKind VK = VK_RValue;
9159   ExprObjectKind OK = OK_Ordinary;
9160 
9161   switch (Opc) {
9162   case BO_Assign:
9163     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
9164     if (getLangOpts().CPlusPlus &&
9165         LHS.get()->getObjectKind() != OK_ObjCProperty) {
9166       VK = LHS.get()->getValueKind();
9167       OK = LHS.get()->getObjectKind();
9168     }
9169     if (!ResultTy.isNull())
9170       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
9171     break;
9172   case BO_PtrMemD:
9173   case BO_PtrMemI:
9174     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
9175                                             Opc == BO_PtrMemI);
9176     break;
9177   case BO_Mul:
9178   case BO_Div:
9179     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
9180                                            Opc == BO_Div);
9181     break;
9182   case BO_Rem:
9183     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
9184     break;
9185   case BO_Add:
9186     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
9187     break;
9188   case BO_Sub:
9189     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
9190     break;
9191   case BO_Shl:
9192   case BO_Shr:
9193     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
9194     break;
9195   case BO_LE:
9196   case BO_LT:
9197   case BO_GE:
9198   case BO_GT:
9199     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
9200     break;
9201   case BO_EQ:
9202   case BO_NE:
9203     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
9204     break;
9205   case BO_And:
9206     checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
9207   case BO_Xor:
9208   case BO_Or:
9209     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc);
9210     break;
9211   case BO_LAnd:
9212   case BO_LOr:
9213     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
9214     break;
9215   case BO_MulAssign:
9216   case BO_DivAssign:
9217     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
9218                                                Opc == BO_DivAssign);
9219     CompLHSTy = CompResultTy;
9220     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
9221       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
9222     break;
9223   case BO_RemAssign:
9224     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
9225     CompLHSTy = CompResultTy;
9226     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
9227       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
9228     break;
9229   case BO_AddAssign:
9230     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
9231     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
9232       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
9233     break;
9234   case BO_SubAssign:
9235     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
9236     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
9237       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
9238     break;
9239   case BO_ShlAssign:
9240   case BO_ShrAssign:
9241     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
9242     CompLHSTy = CompResultTy;
9243     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
9244       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
9245     break;
9246   case BO_AndAssign:
9247   case BO_XorAssign:
9248   case BO_OrAssign:
9249     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true);
9250     CompLHSTy = CompResultTy;
9251     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
9252       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
9253     break;
9254   case BO_Comma:
9255     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
9256     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
9257       VK = RHS.get()->getValueKind();
9258       OK = RHS.get()->getObjectKind();
9259     }
9260     break;
9261   }
9262   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
9263     return ExprError();
9264 
9265   // Check for array bounds violations for both sides of the BinaryOperator
9266   CheckArrayAccess(LHS.get());
9267   CheckArrayAccess(RHS.get());
9268 
9269   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
9270     NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
9271                                                  &Context.Idents.get("object_setClass"),
9272                                                  SourceLocation(), LookupOrdinaryName);
9273     if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
9274       SourceLocation RHSLocEnd = PP.getLocForEndOfToken(RHS.get()->getLocEnd());
9275       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) <<
9276       FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") <<
9277       FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") <<
9278       FixItHint::CreateInsertion(RHSLocEnd, ")");
9279     }
9280     else
9281       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
9282   }
9283   else if (const ObjCIvarRefExpr *OIRE =
9284            dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
9285     DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
9286 
9287   if (CompResultTy.isNull())
9288     return Owned(new (Context) BinaryOperator(LHS.take(), RHS.take(), Opc,
9289                                               ResultTy, VK, OK, OpLoc,
9290                                               FPFeatures.fp_contract));
9291   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
9292       OK_ObjCProperty) {
9293     VK = VK_LValue;
9294     OK = LHS.get()->getObjectKind();
9295   }
9296   return Owned(new (Context) CompoundAssignOperator(LHS.take(), RHS.take(), Opc,
9297                                                     ResultTy, VK, OK, CompLHSTy,
9298                                                     CompResultTy, OpLoc,
9299                                                     FPFeatures.fp_contract));
9300 }
9301 
9302 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
9303 /// operators are mixed in a way that suggests that the programmer forgot that
9304 /// comparison operators have higher precedence. The most typical example of
9305 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
9306 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
9307                                       SourceLocation OpLoc, Expr *LHSExpr,
9308                                       Expr *RHSExpr) {
9309   BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
9310   BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
9311 
9312   // Check that one of the sides is a comparison operator.
9313   bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
9314   bool isRightComp = RHSBO && RHSBO->isComparisonOp();
9315   if (!isLeftComp && !isRightComp)
9316     return;
9317 
9318   // Bitwise operations are sometimes used as eager logical ops.
9319   // Don't diagnose this.
9320   bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
9321   bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
9322   if ((isLeftComp || isLeftBitwise) && (isRightComp || isRightBitwise))
9323     return;
9324 
9325   SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
9326                                                    OpLoc)
9327                                      : SourceRange(OpLoc, RHSExpr->getLocEnd());
9328   StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
9329   SourceRange ParensRange = isLeftComp ?
9330       SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd())
9331     : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocStart());
9332 
9333   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
9334     << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
9335   SuggestParentheses(Self, OpLoc,
9336     Self.PDiag(diag::note_precedence_silence) << OpStr,
9337     (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
9338   SuggestParentheses(Self, OpLoc,
9339     Self.PDiag(diag::note_precedence_bitwise_first)
9340       << BinaryOperator::getOpcodeStr(Opc),
9341     ParensRange);
9342 }
9343 
9344 /// \brief It accepts a '&' expr that is inside a '|' one.
9345 /// Emit a diagnostic together with a fixit hint that wraps the '&' expression
9346 /// in parentheses.
9347 static void
9348 EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc,
9349                                        BinaryOperator *Bop) {
9350   assert(Bop->getOpcode() == BO_And);
9351   Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or)
9352       << Bop->getSourceRange() << OpLoc;
9353   SuggestParentheses(Self, Bop->getOperatorLoc(),
9354     Self.PDiag(diag::note_precedence_silence)
9355       << Bop->getOpcodeStr(),
9356     Bop->getSourceRange());
9357 }
9358 
9359 /// \brief It accepts a '&&' expr that is inside a '||' one.
9360 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
9361 /// in parentheses.
9362 static void
9363 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
9364                                        BinaryOperator *Bop) {
9365   assert(Bop->getOpcode() == BO_LAnd);
9366   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
9367       << Bop->getSourceRange() << OpLoc;
9368   SuggestParentheses(Self, Bop->getOperatorLoc(),
9369     Self.PDiag(diag::note_precedence_silence)
9370       << Bop->getOpcodeStr(),
9371     Bop->getSourceRange());
9372 }
9373 
9374 /// \brief Returns true if the given expression can be evaluated as a constant
9375 /// 'true'.
9376 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
9377   bool Res;
9378   return !E->isValueDependent() &&
9379          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
9380 }
9381 
9382 /// \brief Returns true if the given expression can be evaluated as a constant
9383 /// 'false'.
9384 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
9385   bool Res;
9386   return !E->isValueDependent() &&
9387          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
9388 }
9389 
9390 /// \brief Look for '&&' in the left hand of a '||' expr.
9391 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
9392                                              Expr *LHSExpr, Expr *RHSExpr) {
9393   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
9394     if (Bop->getOpcode() == BO_LAnd) {
9395       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
9396       if (EvaluatesAsFalse(S, RHSExpr))
9397         return;
9398       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
9399       if (!EvaluatesAsTrue(S, Bop->getLHS()))
9400         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
9401     } else if (Bop->getOpcode() == BO_LOr) {
9402       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
9403         // If it's "a || b && 1 || c" we didn't warn earlier for
9404         // "a || b && 1", but warn now.
9405         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
9406           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
9407       }
9408     }
9409   }
9410 }
9411 
9412 /// \brief Look for '&&' in the right hand of a '||' expr.
9413 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
9414                                              Expr *LHSExpr, Expr *RHSExpr) {
9415   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
9416     if (Bop->getOpcode() == BO_LAnd) {
9417       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
9418       if (EvaluatesAsFalse(S, LHSExpr))
9419         return;
9420       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
9421       if (!EvaluatesAsTrue(S, Bop->getRHS()))
9422         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
9423     }
9424   }
9425 }
9426 
9427 /// \brief Look for '&' in the left or right hand of a '|' expr.
9428 static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc,
9429                                              Expr *OrArg) {
9430   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) {
9431     if (Bop->getOpcode() == BO_And)
9432       return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop);
9433   }
9434 }
9435 
9436 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
9437                                     Expr *SubExpr, StringRef Shift) {
9438   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
9439     if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
9440       StringRef Op = Bop->getOpcodeStr();
9441       S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
9442           << Bop->getSourceRange() << OpLoc << Shift << Op;
9443       SuggestParentheses(S, Bop->getOperatorLoc(),
9444           S.PDiag(diag::note_precedence_silence) << Op,
9445           Bop->getSourceRange());
9446     }
9447   }
9448 }
9449 
9450 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
9451                                  Expr *LHSExpr, Expr *RHSExpr) {
9452   CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
9453   if (!OCE)
9454     return;
9455 
9456   FunctionDecl *FD = OCE->getDirectCallee();
9457   if (!FD || !FD->isOverloadedOperator())
9458     return;
9459 
9460   OverloadedOperatorKind Kind = FD->getOverloadedOperator();
9461   if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
9462     return;
9463 
9464   S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
9465       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
9466       << (Kind == OO_LessLess);
9467   SuggestParentheses(S, OCE->getOperatorLoc(),
9468                      S.PDiag(diag::note_precedence_silence)
9469                          << (Kind == OO_LessLess ? "<<" : ">>"),
9470                      OCE->getSourceRange());
9471   SuggestParentheses(S, OpLoc,
9472                      S.PDiag(diag::note_evaluate_comparison_first),
9473                      SourceRange(OCE->getArg(1)->getLocStart(),
9474                                  RHSExpr->getLocEnd()));
9475 }
9476 
9477 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
9478 /// precedence.
9479 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
9480                                     SourceLocation OpLoc, Expr *LHSExpr,
9481                                     Expr *RHSExpr){
9482   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
9483   if (BinaryOperator::isBitwiseOp(Opc))
9484     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
9485 
9486   // Diagnose "arg1 & arg2 | arg3"
9487   if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) {
9488     DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr);
9489     DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr);
9490   }
9491 
9492   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
9493   // We don't warn for 'assert(a || b && "bad")' since this is safe.
9494   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
9495     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
9496     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
9497   }
9498 
9499   if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
9500       || Opc == BO_Shr) {
9501     StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
9502     DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
9503     DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
9504   }
9505 
9506   // Warn on overloaded shift operators and comparisons, such as:
9507   // cout << 5 == 4;
9508   if (BinaryOperator::isComparisonOp(Opc))
9509     DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
9510 }
9511 
9512 // Binary Operators.  'Tok' is the token for the operator.
9513 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
9514                             tok::TokenKind Kind,
9515                             Expr *LHSExpr, Expr *RHSExpr) {
9516   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
9517   assert((LHSExpr != 0) && "ActOnBinOp(): missing left expression");
9518   assert((RHSExpr != 0) && "ActOnBinOp(): missing right expression");
9519 
9520   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
9521   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
9522 
9523   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
9524 }
9525 
9526 /// Build an overloaded binary operator expression in the given scope.
9527 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
9528                                        BinaryOperatorKind Opc,
9529                                        Expr *LHS, Expr *RHS) {
9530   // Find all of the overloaded operators visible from this
9531   // point. We perform both an operator-name lookup from the local
9532   // scope and an argument-dependent lookup based on the types of
9533   // the arguments.
9534   UnresolvedSet<16> Functions;
9535   OverloadedOperatorKind OverOp
9536     = BinaryOperator::getOverloadedOperator(Opc);
9537   if (Sc && OverOp != OO_None)
9538     S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
9539                                    RHS->getType(), Functions);
9540 
9541   // Build the (potentially-overloaded, potentially-dependent)
9542   // binary operation.
9543   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
9544 }
9545 
9546 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
9547                             BinaryOperatorKind Opc,
9548                             Expr *LHSExpr, Expr *RHSExpr) {
9549   // We want to end up calling one of checkPseudoObjectAssignment
9550   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
9551   // both expressions are overloadable or either is type-dependent),
9552   // or CreateBuiltinBinOp (in any other case).  We also want to get
9553   // any placeholder types out of the way.
9554 
9555   // Handle pseudo-objects in the LHS.
9556   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
9557     // Assignments with a pseudo-object l-value need special analysis.
9558     if (pty->getKind() == BuiltinType::PseudoObject &&
9559         BinaryOperator::isAssignmentOp(Opc))
9560       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
9561 
9562     // Don't resolve overloads if the other type is overloadable.
9563     if (pty->getKind() == BuiltinType::Overload) {
9564       // We can't actually test that if we still have a placeholder,
9565       // though.  Fortunately, none of the exceptions we see in that
9566       // code below are valid when the LHS is an overload set.  Note
9567       // that an overload set can be dependently-typed, but it never
9568       // instantiates to having an overloadable type.
9569       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
9570       if (resolvedRHS.isInvalid()) return ExprError();
9571       RHSExpr = resolvedRHS.take();
9572 
9573       if (RHSExpr->isTypeDependent() ||
9574           RHSExpr->getType()->isOverloadableType())
9575         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9576     }
9577 
9578     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
9579     if (LHS.isInvalid()) return ExprError();
9580     LHSExpr = LHS.take();
9581   }
9582 
9583   // Handle pseudo-objects in the RHS.
9584   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
9585     // An overload in the RHS can potentially be resolved by the type
9586     // being assigned to.
9587     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
9588       if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
9589         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9590 
9591       if (LHSExpr->getType()->isOverloadableType())
9592         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9593 
9594       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
9595     }
9596 
9597     // Don't resolve overloads if the other type is overloadable.
9598     if (pty->getKind() == BuiltinType::Overload &&
9599         LHSExpr->getType()->isOverloadableType())
9600       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9601 
9602     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
9603     if (!resolvedRHS.isUsable()) return ExprError();
9604     RHSExpr = resolvedRHS.take();
9605   }
9606 
9607   if (getLangOpts().CPlusPlus) {
9608     // If either expression is type-dependent, always build an
9609     // overloaded op.
9610     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
9611       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9612 
9613     // Otherwise, build an overloaded op if either expression has an
9614     // overloadable type.
9615     if (LHSExpr->getType()->isOverloadableType() ||
9616         RHSExpr->getType()->isOverloadableType())
9617       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9618   }
9619 
9620   // Build a built-in binary operation.
9621   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
9622 }
9623 
9624 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
9625                                       UnaryOperatorKind Opc,
9626                                       Expr *InputExpr) {
9627   ExprResult Input = Owned(InputExpr);
9628   ExprValueKind VK = VK_RValue;
9629   ExprObjectKind OK = OK_Ordinary;
9630   QualType resultType;
9631   switch (Opc) {
9632   case UO_PreInc:
9633   case UO_PreDec:
9634   case UO_PostInc:
9635   case UO_PostDec:
9636     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc,
9637                                                 Opc == UO_PreInc ||
9638                                                 Opc == UO_PostInc,
9639                                                 Opc == UO_PreInc ||
9640                                                 Opc == UO_PreDec);
9641     break;
9642   case UO_AddrOf:
9643     resultType = CheckAddressOfOperand(Input, OpLoc);
9644     break;
9645   case UO_Deref: {
9646     Input = DefaultFunctionArrayLvalueConversion(Input.take());
9647     if (Input.isInvalid()) return ExprError();
9648     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
9649     break;
9650   }
9651   case UO_Plus:
9652   case UO_Minus:
9653     Input = UsualUnaryConversions(Input.take());
9654     if (Input.isInvalid()) return ExprError();
9655     resultType = Input.get()->getType();
9656     if (resultType->isDependentType())
9657       break;
9658     if (resultType->isArithmeticType() || // C99 6.5.3.3p1
9659         resultType->isVectorType())
9660       break;
9661     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
9662              Opc == UO_Plus &&
9663              resultType->isPointerType())
9664       break;
9665 
9666     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9667       << resultType << Input.get()->getSourceRange());
9668 
9669   case UO_Not: // bitwise complement
9670     Input = UsualUnaryConversions(Input.take());
9671     if (Input.isInvalid())
9672       return ExprError();
9673     resultType = Input.get()->getType();
9674     if (resultType->isDependentType())
9675       break;
9676     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
9677     if (resultType->isComplexType() || resultType->isComplexIntegerType())
9678       // C99 does not support '~' for complex conjugation.
9679       Diag(OpLoc, diag::ext_integer_complement_complex)
9680           << resultType << Input.get()->getSourceRange();
9681     else if (resultType->hasIntegerRepresentation())
9682       break;
9683     else if (resultType->isExtVectorType()) {
9684       if (Context.getLangOpts().OpenCL) {
9685         // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
9686         // on vector float types.
9687         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
9688         if (!T->isIntegerType())
9689           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9690                            << resultType << Input.get()->getSourceRange());
9691       }
9692       break;
9693     } else {
9694       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9695                        << resultType << Input.get()->getSourceRange());
9696     }
9697     break;
9698 
9699   case UO_LNot: // logical negation
9700     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
9701     Input = DefaultFunctionArrayLvalueConversion(Input.take());
9702     if (Input.isInvalid()) return ExprError();
9703     resultType = Input.get()->getType();
9704 
9705     // Though we still have to promote half FP to float...
9706     if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
9707       Input = ImpCastExprToType(Input.take(), Context.FloatTy, CK_FloatingCast).take();
9708       resultType = Context.FloatTy;
9709     }
9710 
9711     if (resultType->isDependentType())
9712       break;
9713     if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
9714       // C99 6.5.3.3p1: ok, fallthrough;
9715       if (Context.getLangOpts().CPlusPlus) {
9716         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
9717         // operand contextually converted to bool.
9718         Input = ImpCastExprToType(Input.take(), Context.BoolTy,
9719                                   ScalarTypeToBooleanCastKind(resultType));
9720       } else if (Context.getLangOpts().OpenCL &&
9721                  Context.getLangOpts().OpenCLVersion < 120) {
9722         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
9723         // operate on scalar float types.
9724         if (!resultType->isIntegerType())
9725           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9726                            << resultType << Input.get()->getSourceRange());
9727       }
9728     } else if (resultType->isExtVectorType()) {
9729       if (Context.getLangOpts().OpenCL &&
9730           Context.getLangOpts().OpenCLVersion < 120) {
9731         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
9732         // operate on vector float types.
9733         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
9734         if (!T->isIntegerType())
9735           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9736                            << resultType << Input.get()->getSourceRange());
9737       }
9738       // Vector logical not returns the signed variant of the operand type.
9739       resultType = GetSignedVectorType(resultType);
9740       break;
9741     } else {
9742       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9743         << resultType << Input.get()->getSourceRange());
9744     }
9745 
9746     // LNot always has type int. C99 6.5.3.3p5.
9747     // In C++, it's bool. C++ 5.3.1p8
9748     resultType = Context.getLogicalOperationType();
9749     break;
9750   case UO_Real:
9751   case UO_Imag:
9752     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
9753     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
9754     // complex l-values to ordinary l-values and all other values to r-values.
9755     if (Input.isInvalid()) return ExprError();
9756     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
9757       if (Input.get()->getValueKind() != VK_RValue &&
9758           Input.get()->getObjectKind() == OK_Ordinary)
9759         VK = Input.get()->getValueKind();
9760     } else if (!getLangOpts().CPlusPlus) {
9761       // In C, a volatile scalar is read by __imag. In C++, it is not.
9762       Input = DefaultLvalueConversion(Input.take());
9763     }
9764     break;
9765   case UO_Extension:
9766     resultType = Input.get()->getType();
9767     VK = Input.get()->getValueKind();
9768     OK = Input.get()->getObjectKind();
9769     break;
9770   }
9771   if (resultType.isNull() || Input.isInvalid())
9772     return ExprError();
9773 
9774   // Check for array bounds violations in the operand of the UnaryOperator,
9775   // except for the '*' and '&' operators that have to be handled specially
9776   // by CheckArrayAccess (as there are special cases like &array[arraysize]
9777   // that are explicitly defined as valid by the standard).
9778   if (Opc != UO_AddrOf && Opc != UO_Deref)
9779     CheckArrayAccess(Input.get());
9780 
9781   return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType,
9782                                            VK, OK, OpLoc));
9783 }
9784 
9785 /// \brief Determine whether the given expression is a qualified member
9786 /// access expression, of a form that could be turned into a pointer to member
9787 /// with the address-of operator.
9788 static bool isQualifiedMemberAccess(Expr *E) {
9789   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
9790     if (!DRE->getQualifier())
9791       return false;
9792 
9793     ValueDecl *VD = DRE->getDecl();
9794     if (!VD->isCXXClassMember())
9795       return false;
9796 
9797     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
9798       return true;
9799     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
9800       return Method->isInstance();
9801 
9802     return false;
9803   }
9804 
9805   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
9806     if (!ULE->getQualifier())
9807       return false;
9808 
9809     for (UnresolvedLookupExpr::decls_iterator D = ULE->decls_begin(),
9810                                            DEnd = ULE->decls_end();
9811          D != DEnd; ++D) {
9812       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*D)) {
9813         if (Method->isInstance())
9814           return true;
9815       } else {
9816         // Overload set does not contain methods.
9817         break;
9818       }
9819     }
9820 
9821     return false;
9822   }
9823 
9824   return false;
9825 }
9826 
9827 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
9828                               UnaryOperatorKind Opc, Expr *Input) {
9829   // First things first: handle placeholders so that the
9830   // overloaded-operator check considers the right type.
9831   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
9832     // Increment and decrement of pseudo-object references.
9833     if (pty->getKind() == BuiltinType::PseudoObject &&
9834         UnaryOperator::isIncrementDecrementOp(Opc))
9835       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
9836 
9837     // extension is always a builtin operator.
9838     if (Opc == UO_Extension)
9839       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
9840 
9841     // & gets special logic for several kinds of placeholder.
9842     // The builtin code knows what to do.
9843     if (Opc == UO_AddrOf &&
9844         (pty->getKind() == BuiltinType::Overload ||
9845          pty->getKind() == BuiltinType::UnknownAny ||
9846          pty->getKind() == BuiltinType::BoundMember))
9847       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
9848 
9849     // Anything else needs to be handled now.
9850     ExprResult Result = CheckPlaceholderExpr(Input);
9851     if (Result.isInvalid()) return ExprError();
9852     Input = Result.take();
9853   }
9854 
9855   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
9856       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
9857       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
9858     // Find all of the overloaded operators visible from this
9859     // point. We perform both an operator-name lookup from the local
9860     // scope and an argument-dependent lookup based on the types of
9861     // the arguments.
9862     UnresolvedSet<16> Functions;
9863     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
9864     if (S && OverOp != OO_None)
9865       LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
9866                                    Functions);
9867 
9868     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
9869   }
9870 
9871   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
9872 }
9873 
9874 // Unary Operators.  'Tok' is the token for the operator.
9875 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
9876                               tok::TokenKind Op, Expr *Input) {
9877   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
9878 }
9879 
9880 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
9881 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
9882                                 LabelDecl *TheDecl) {
9883   TheDecl->markUsed(Context);
9884   // Create the AST node.  The address of a label always has type 'void*'.
9885   return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
9886                                        Context.getPointerType(Context.VoidTy)));
9887 }
9888 
9889 /// Given the last statement in a statement-expression, check whether
9890 /// the result is a producing expression (like a call to an
9891 /// ns_returns_retained function) and, if so, rebuild it to hoist the
9892 /// release out of the full-expression.  Otherwise, return null.
9893 /// Cannot fail.
9894 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
9895   // Should always be wrapped with one of these.
9896   ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
9897   if (!cleanups) return 0;
9898 
9899   ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
9900   if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
9901     return 0;
9902 
9903   // Splice out the cast.  This shouldn't modify any interesting
9904   // features of the statement.
9905   Expr *producer = cast->getSubExpr();
9906   assert(producer->getType() == cast->getType());
9907   assert(producer->getValueKind() == cast->getValueKind());
9908   cleanups->setSubExpr(producer);
9909   return cleanups;
9910 }
9911 
9912 void Sema::ActOnStartStmtExpr() {
9913   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
9914 }
9915 
9916 void Sema::ActOnStmtExprError() {
9917   // Note that function is also called by TreeTransform when leaving a
9918   // StmtExpr scope without rebuilding anything.
9919 
9920   DiscardCleanupsInEvaluationContext();
9921   PopExpressionEvaluationContext();
9922 }
9923 
9924 ExprResult
9925 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
9926                     SourceLocation RPLoc) { // "({..})"
9927   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
9928   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
9929 
9930   if (hasAnyUnrecoverableErrorsInThisFunction())
9931     DiscardCleanupsInEvaluationContext();
9932   assert(!ExprNeedsCleanups && "cleanups within StmtExpr not correctly bound!");
9933   PopExpressionEvaluationContext();
9934 
9935   bool isFileScope
9936     = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
9937   if (isFileScope)
9938     return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
9939 
9940   // FIXME: there are a variety of strange constraints to enforce here, for
9941   // example, it is not possible to goto into a stmt expression apparently.
9942   // More semantic analysis is needed.
9943 
9944   // If there are sub-stmts in the compound stmt, take the type of the last one
9945   // as the type of the stmtexpr.
9946   QualType Ty = Context.VoidTy;
9947   bool StmtExprMayBindToTemp = false;
9948   if (!Compound->body_empty()) {
9949     Stmt *LastStmt = Compound->body_back();
9950     LabelStmt *LastLabelStmt = 0;
9951     // If LastStmt is a label, skip down through into the body.
9952     while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
9953       LastLabelStmt = Label;
9954       LastStmt = Label->getSubStmt();
9955     }
9956 
9957     if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
9958       // Do function/array conversion on the last expression, but not
9959       // lvalue-to-rvalue.  However, initialize an unqualified type.
9960       ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
9961       if (LastExpr.isInvalid())
9962         return ExprError();
9963       Ty = LastExpr.get()->getType().getUnqualifiedType();
9964 
9965       if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
9966         // In ARC, if the final expression ends in a consume, splice
9967         // the consume out and bind it later.  In the alternate case
9968         // (when dealing with a retainable type), the result
9969         // initialization will create a produce.  In both cases the
9970         // result will be +1, and we'll need to balance that out with
9971         // a bind.
9972         if (Expr *rebuiltLastStmt
9973               = maybeRebuildARCConsumingStmt(LastExpr.get())) {
9974           LastExpr = rebuiltLastStmt;
9975         } else {
9976           LastExpr = PerformCopyInitialization(
9977                             InitializedEntity::InitializeResult(LPLoc,
9978                                                                 Ty,
9979                                                                 false),
9980                                                    SourceLocation(),
9981                                                LastExpr);
9982         }
9983 
9984         if (LastExpr.isInvalid())
9985           return ExprError();
9986         if (LastExpr.get() != 0) {
9987           if (!LastLabelStmt)
9988             Compound->setLastStmt(LastExpr.take());
9989           else
9990             LastLabelStmt->setSubStmt(LastExpr.take());
9991           StmtExprMayBindToTemp = true;
9992         }
9993       }
9994     }
9995   }
9996 
9997   // FIXME: Check that expression type is complete/non-abstract; statement
9998   // expressions are not lvalues.
9999   Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
10000   if (StmtExprMayBindToTemp)
10001     return MaybeBindToTemporary(ResStmtExpr);
10002   return Owned(ResStmtExpr);
10003 }
10004 
10005 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
10006                                       TypeSourceInfo *TInfo,
10007                                       OffsetOfComponent *CompPtr,
10008                                       unsigned NumComponents,
10009                                       SourceLocation RParenLoc) {
10010   QualType ArgTy = TInfo->getType();
10011   bool Dependent = ArgTy->isDependentType();
10012   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
10013 
10014   // We must have at least one component that refers to the type, and the first
10015   // one is known to be a field designator.  Verify that the ArgTy represents
10016   // a struct/union/class.
10017   if (!Dependent && !ArgTy->isRecordType())
10018     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
10019                        << ArgTy << TypeRange);
10020 
10021   // Type must be complete per C99 7.17p3 because a declaring a variable
10022   // with an incomplete type would be ill-formed.
10023   if (!Dependent
10024       && RequireCompleteType(BuiltinLoc, ArgTy,
10025                              diag::err_offsetof_incomplete_type, TypeRange))
10026     return ExprError();
10027 
10028   // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
10029   // GCC extension, diagnose them.
10030   // FIXME: This diagnostic isn't actually visible because the location is in
10031   // a system header!
10032   if (NumComponents != 1)
10033     Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
10034       << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
10035 
10036   bool DidWarnAboutNonPOD = false;
10037   QualType CurrentType = ArgTy;
10038   typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
10039   SmallVector<OffsetOfNode, 4> Comps;
10040   SmallVector<Expr*, 4> Exprs;
10041   for (unsigned i = 0; i != NumComponents; ++i) {
10042     const OffsetOfComponent &OC = CompPtr[i];
10043     if (OC.isBrackets) {
10044       // Offset of an array sub-field.  TODO: Should we allow vector elements?
10045       if (!CurrentType->isDependentType()) {
10046         const ArrayType *AT = Context.getAsArrayType(CurrentType);
10047         if(!AT)
10048           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
10049                            << CurrentType);
10050         CurrentType = AT->getElementType();
10051       } else
10052         CurrentType = Context.DependentTy;
10053 
10054       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
10055       if (IdxRval.isInvalid())
10056         return ExprError();
10057       Expr *Idx = IdxRval.take();
10058 
10059       // The expression must be an integral expression.
10060       // FIXME: An integral constant expression?
10061       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
10062           !Idx->getType()->isIntegerType())
10063         return ExprError(Diag(Idx->getLocStart(),
10064                               diag::err_typecheck_subscript_not_integer)
10065                          << Idx->getSourceRange());
10066 
10067       // Record this array index.
10068       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
10069       Exprs.push_back(Idx);
10070       continue;
10071     }
10072 
10073     // Offset of a field.
10074     if (CurrentType->isDependentType()) {
10075       // We have the offset of a field, but we can't look into the dependent
10076       // type. Just record the identifier of the field.
10077       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
10078       CurrentType = Context.DependentTy;
10079       continue;
10080     }
10081 
10082     // We need to have a complete type to look into.
10083     if (RequireCompleteType(OC.LocStart, CurrentType,
10084                             diag::err_offsetof_incomplete_type))
10085       return ExprError();
10086 
10087     // Look for the designated field.
10088     const RecordType *RC = CurrentType->getAs<RecordType>();
10089     if (!RC)
10090       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
10091                        << CurrentType);
10092     RecordDecl *RD = RC->getDecl();
10093 
10094     // C++ [lib.support.types]p5:
10095     //   The macro offsetof accepts a restricted set of type arguments in this
10096     //   International Standard. type shall be a POD structure or a POD union
10097     //   (clause 9).
10098     // C++11 [support.types]p4:
10099     //   If type is not a standard-layout class (Clause 9), the results are
10100     //   undefined.
10101     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
10102       bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
10103       unsigned DiagID =
10104         LangOpts.CPlusPlus11? diag::warn_offsetof_non_standardlayout_type
10105                             : diag::warn_offsetof_non_pod_type;
10106 
10107       if (!IsSafe && !DidWarnAboutNonPOD &&
10108           DiagRuntimeBehavior(BuiltinLoc, 0,
10109                               PDiag(DiagID)
10110                               << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
10111                               << CurrentType))
10112         DidWarnAboutNonPOD = true;
10113     }
10114 
10115     // Look for the field.
10116     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
10117     LookupQualifiedName(R, RD);
10118     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
10119     IndirectFieldDecl *IndirectMemberDecl = 0;
10120     if (!MemberDecl) {
10121       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
10122         MemberDecl = IndirectMemberDecl->getAnonField();
10123     }
10124 
10125     if (!MemberDecl)
10126       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
10127                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
10128                                                               OC.LocEnd));
10129 
10130     // C99 7.17p3:
10131     //   (If the specified member is a bit-field, the behavior is undefined.)
10132     //
10133     // We diagnose this as an error.
10134     if (MemberDecl->isBitField()) {
10135       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
10136         << MemberDecl->getDeclName()
10137         << SourceRange(BuiltinLoc, RParenLoc);
10138       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
10139       return ExprError();
10140     }
10141 
10142     RecordDecl *Parent = MemberDecl->getParent();
10143     if (IndirectMemberDecl)
10144       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
10145 
10146     // If the member was found in a base class, introduce OffsetOfNodes for
10147     // the base class indirections.
10148     CXXBasePaths Paths;
10149     if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
10150       if (Paths.getDetectedVirtual()) {
10151         Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
10152           << MemberDecl->getDeclName()
10153           << SourceRange(BuiltinLoc, RParenLoc);
10154         return ExprError();
10155       }
10156 
10157       CXXBasePath &Path = Paths.front();
10158       for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
10159            B != BEnd; ++B)
10160         Comps.push_back(OffsetOfNode(B->Base));
10161     }
10162 
10163     if (IndirectMemberDecl) {
10164       for (IndirectFieldDecl::chain_iterator FI =
10165            IndirectMemberDecl->chain_begin(),
10166            FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
10167         assert(isa<FieldDecl>(*FI));
10168         Comps.push_back(OffsetOfNode(OC.LocStart,
10169                                      cast<FieldDecl>(*FI), OC.LocEnd));
10170       }
10171     } else
10172       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
10173 
10174     CurrentType = MemberDecl->getType().getNonReferenceType();
10175   }
10176 
10177   return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
10178                                     TInfo, Comps, Exprs, RParenLoc));
10179 }
10180 
10181 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
10182                                       SourceLocation BuiltinLoc,
10183                                       SourceLocation TypeLoc,
10184                                       ParsedType ParsedArgTy,
10185                                       OffsetOfComponent *CompPtr,
10186                                       unsigned NumComponents,
10187                                       SourceLocation RParenLoc) {
10188 
10189   TypeSourceInfo *ArgTInfo;
10190   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
10191   if (ArgTy.isNull())
10192     return ExprError();
10193 
10194   if (!ArgTInfo)
10195     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
10196 
10197   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
10198                               RParenLoc);
10199 }
10200 
10201 
10202 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
10203                                  Expr *CondExpr,
10204                                  Expr *LHSExpr, Expr *RHSExpr,
10205                                  SourceLocation RPLoc) {
10206   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
10207 
10208   ExprValueKind VK = VK_RValue;
10209   ExprObjectKind OK = OK_Ordinary;
10210   QualType resType;
10211   bool ValueDependent = false;
10212   bool CondIsTrue = false;
10213   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
10214     resType = Context.DependentTy;
10215     ValueDependent = true;
10216   } else {
10217     // The conditional expression is required to be a constant expression.
10218     llvm::APSInt condEval(32);
10219     ExprResult CondICE
10220       = VerifyIntegerConstantExpression(CondExpr, &condEval,
10221           diag::err_typecheck_choose_expr_requires_constant, false);
10222     if (CondICE.isInvalid())
10223       return ExprError();
10224     CondExpr = CondICE.take();
10225     CondIsTrue = condEval.getZExtValue();
10226 
10227     // If the condition is > zero, then the AST type is the same as the LSHExpr.
10228     Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
10229 
10230     resType = ActiveExpr->getType();
10231     ValueDependent = ActiveExpr->isValueDependent();
10232     VK = ActiveExpr->getValueKind();
10233     OK = ActiveExpr->getObjectKind();
10234   }
10235 
10236   return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
10237                                         resType, VK, OK, RPLoc, CondIsTrue,
10238                                         resType->isDependentType(),
10239                                         ValueDependent));
10240 }
10241 
10242 //===----------------------------------------------------------------------===//
10243 // Clang Extensions.
10244 //===----------------------------------------------------------------------===//
10245 
10246 /// ActOnBlockStart - This callback is invoked when a block literal is started.
10247 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
10248   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
10249 
10250   if (LangOpts.CPlusPlus) {
10251     Decl *ManglingContextDecl;
10252     if (MangleNumberingContext *MCtx =
10253             getCurrentMangleNumberContext(Block->getDeclContext(),
10254                                           ManglingContextDecl)) {
10255       unsigned ManglingNumber = MCtx->getManglingNumber(Block);
10256       Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
10257     }
10258   }
10259 
10260   PushBlockScope(CurScope, Block);
10261   CurContext->addDecl(Block);
10262   if (CurScope)
10263     PushDeclContext(CurScope, Block);
10264   else
10265     CurContext = Block;
10266 
10267   getCurBlock()->HasImplicitReturnType = true;
10268 
10269   // Enter a new evaluation context to insulate the block from any
10270   // cleanups from the enclosing full-expression.
10271   PushExpressionEvaluationContext(PotentiallyEvaluated);
10272 }
10273 
10274 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
10275                                Scope *CurScope) {
10276   assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
10277   assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
10278   BlockScopeInfo *CurBlock = getCurBlock();
10279 
10280   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
10281   QualType T = Sig->getType();
10282 
10283   // FIXME: We should allow unexpanded parameter packs here, but that would,
10284   // in turn, make the block expression contain unexpanded parameter packs.
10285   if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
10286     // Drop the parameters.
10287     FunctionProtoType::ExtProtoInfo EPI;
10288     EPI.HasTrailingReturn = false;
10289     EPI.TypeQuals |= DeclSpec::TQ_const;
10290     T = Context.getFunctionType(Context.DependentTy, None, EPI);
10291     Sig = Context.getTrivialTypeSourceInfo(T);
10292   }
10293 
10294   // GetTypeForDeclarator always produces a function type for a block
10295   // literal signature.  Furthermore, it is always a FunctionProtoType
10296   // unless the function was written with a typedef.
10297   assert(T->isFunctionType() &&
10298          "GetTypeForDeclarator made a non-function block signature");
10299 
10300   // Look for an explicit signature in that function type.
10301   FunctionProtoTypeLoc ExplicitSignature;
10302 
10303   TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
10304   if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) {
10305 
10306     // Check whether that explicit signature was synthesized by
10307     // GetTypeForDeclarator.  If so, don't save that as part of the
10308     // written signature.
10309     if (ExplicitSignature.getLocalRangeBegin() ==
10310         ExplicitSignature.getLocalRangeEnd()) {
10311       // This would be much cheaper if we stored TypeLocs instead of
10312       // TypeSourceInfos.
10313       TypeLoc Result = ExplicitSignature.getReturnLoc();
10314       unsigned Size = Result.getFullDataSize();
10315       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
10316       Sig->getTypeLoc().initializeFullCopy(Result, Size);
10317 
10318       ExplicitSignature = FunctionProtoTypeLoc();
10319     }
10320   }
10321 
10322   CurBlock->TheDecl->setSignatureAsWritten(Sig);
10323   CurBlock->FunctionType = T;
10324 
10325   const FunctionType *Fn = T->getAs<FunctionType>();
10326   QualType RetTy = Fn->getReturnType();
10327   bool isVariadic =
10328     (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
10329 
10330   CurBlock->TheDecl->setIsVariadic(isVariadic);
10331 
10332   // Context.DependentTy is used as a placeholder for a missing block
10333   // return type.  TODO:  what should we do with declarators like:
10334   //   ^ * { ... }
10335   // If the answer is "apply template argument deduction"....
10336   if (RetTy != Context.DependentTy) {
10337     CurBlock->ReturnType = RetTy;
10338     CurBlock->TheDecl->setBlockMissingReturnType(false);
10339     CurBlock->HasImplicitReturnType = false;
10340   }
10341 
10342   // Push block parameters from the declarator if we had them.
10343   SmallVector<ParmVarDecl*, 8> Params;
10344   if (ExplicitSignature) {
10345     for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
10346       ParmVarDecl *Param = ExplicitSignature.getParam(I);
10347       if (Param->getIdentifier() == 0 &&
10348           !Param->isImplicit() &&
10349           !Param->isInvalidDecl() &&
10350           !getLangOpts().CPlusPlus)
10351         Diag(Param->getLocation(), diag::err_parameter_name_omitted);
10352       Params.push_back(Param);
10353     }
10354 
10355   // Fake up parameter variables if we have a typedef, like
10356   //   ^ fntype { ... }
10357   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
10358     for (FunctionProtoType::param_type_iterator I = Fn->param_type_begin(),
10359                                                 E = Fn->param_type_end();
10360          I != E; ++I) {
10361       ParmVarDecl *Param =
10362         BuildParmVarDeclForTypedef(CurBlock->TheDecl,
10363                                    ParamInfo.getLocStart(),
10364                                    *I);
10365       Params.push_back(Param);
10366     }
10367   }
10368 
10369   // Set the parameters on the block decl.
10370   if (!Params.empty()) {
10371     CurBlock->TheDecl->setParams(Params);
10372     CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
10373                              CurBlock->TheDecl->param_end(),
10374                              /*CheckParameterNames=*/false);
10375   }
10376 
10377   // Finally we can process decl attributes.
10378   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
10379 
10380   // Put the parameter variables in scope.
10381   for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
10382          E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
10383     (*AI)->setOwningFunction(CurBlock->TheDecl);
10384 
10385     // If this has an identifier, add it to the scope stack.
10386     if ((*AI)->getIdentifier()) {
10387       CheckShadow(CurBlock->TheScope, *AI);
10388 
10389       PushOnScopeChains(*AI, CurBlock->TheScope);
10390     }
10391   }
10392 }
10393 
10394 /// ActOnBlockError - If there is an error parsing a block, this callback
10395 /// is invoked to pop the information about the block from the action impl.
10396 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
10397   // Leave the expression-evaluation context.
10398   DiscardCleanupsInEvaluationContext();
10399   PopExpressionEvaluationContext();
10400 
10401   // Pop off CurBlock, handle nested blocks.
10402   PopDeclContext();
10403   PopFunctionScopeInfo();
10404 }
10405 
10406 /// ActOnBlockStmtExpr - This is called when the body of a block statement
10407 /// literal was successfully completed.  ^(int x){...}
10408 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
10409                                     Stmt *Body, Scope *CurScope) {
10410   // If blocks are disabled, emit an error.
10411   if (!LangOpts.Blocks)
10412     Diag(CaretLoc, diag::err_blocks_disable);
10413 
10414   // Leave the expression-evaluation context.
10415   if (hasAnyUnrecoverableErrorsInThisFunction())
10416     DiscardCleanupsInEvaluationContext();
10417   assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!");
10418   PopExpressionEvaluationContext();
10419 
10420   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
10421 
10422   if (BSI->HasImplicitReturnType)
10423     deduceClosureReturnType(*BSI);
10424 
10425   PopDeclContext();
10426 
10427   QualType RetTy = Context.VoidTy;
10428   if (!BSI->ReturnType.isNull())
10429     RetTy = BSI->ReturnType;
10430 
10431   bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>();
10432   QualType BlockTy;
10433 
10434   // Set the captured variables on the block.
10435   // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
10436   SmallVector<BlockDecl::Capture, 4> Captures;
10437   for (unsigned i = 0, e = BSI->Captures.size(); i != e; i++) {
10438     CapturingScopeInfo::Capture &Cap = BSI->Captures[i];
10439     if (Cap.isThisCapture())
10440       continue;
10441     BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
10442                               Cap.isNested(), Cap.getInitExpr());
10443     Captures.push_back(NewCap);
10444   }
10445   BSI->TheDecl->setCaptures(Context, Captures.begin(), Captures.end(),
10446                             BSI->CXXThisCaptureIndex != 0);
10447 
10448   // If the user wrote a function type in some form, try to use that.
10449   if (!BSI->FunctionType.isNull()) {
10450     const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
10451 
10452     FunctionType::ExtInfo Ext = FTy->getExtInfo();
10453     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
10454 
10455     // Turn protoless block types into nullary block types.
10456     if (isa<FunctionNoProtoType>(FTy)) {
10457       FunctionProtoType::ExtProtoInfo EPI;
10458       EPI.ExtInfo = Ext;
10459       BlockTy = Context.getFunctionType(RetTy, None, EPI);
10460 
10461     // Otherwise, if we don't need to change anything about the function type,
10462     // preserve its sugar structure.
10463     } else if (FTy->getReturnType() == RetTy &&
10464                (!NoReturn || FTy->getNoReturnAttr())) {
10465       BlockTy = BSI->FunctionType;
10466 
10467     // Otherwise, make the minimal modifications to the function type.
10468     } else {
10469       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
10470       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10471       EPI.TypeQuals = 0; // FIXME: silently?
10472       EPI.ExtInfo = Ext;
10473       BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
10474     }
10475 
10476   // If we don't have a function type, just build one from nothing.
10477   } else {
10478     FunctionProtoType::ExtProtoInfo EPI;
10479     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
10480     BlockTy = Context.getFunctionType(RetTy, None, EPI);
10481   }
10482 
10483   DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
10484                            BSI->TheDecl->param_end());
10485   BlockTy = Context.getBlockPointerType(BlockTy);
10486 
10487   // If needed, diagnose invalid gotos and switches in the block.
10488   if (getCurFunction()->NeedsScopeChecking() &&
10489       !hasAnyUnrecoverableErrorsInThisFunction() &&
10490       !PP.isCodeCompletionEnabled())
10491     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
10492 
10493   BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
10494 
10495   // Try to apply the named return value optimization. We have to check again
10496   // if we can do this, though, because blocks keep return statements around
10497   // to deduce an implicit return type.
10498   if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
10499       !BSI->TheDecl->isDependentContext())
10500     computeNRVO(Body, getCurBlock());
10501 
10502   BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
10503   AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
10504   PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
10505 
10506   // If the block isn't obviously global, i.e. it captures anything at
10507   // all, then we need to do a few things in the surrounding context:
10508   if (Result->getBlockDecl()->hasCaptures()) {
10509     // First, this expression has a new cleanup object.
10510     ExprCleanupObjects.push_back(Result->getBlockDecl());
10511     ExprNeedsCleanups = true;
10512 
10513     // It also gets a branch-protected scope if any of the captured
10514     // variables needs destruction.
10515     for (BlockDecl::capture_const_iterator
10516            ci = Result->getBlockDecl()->capture_begin(),
10517            ce = Result->getBlockDecl()->capture_end(); ci != ce; ++ci) {
10518       const VarDecl *var = ci->getVariable();
10519       if (var->getType().isDestructedType() != QualType::DK_none) {
10520         getCurFunction()->setHasBranchProtectedScope();
10521         break;
10522       }
10523     }
10524   }
10525 
10526   return Owned(Result);
10527 }
10528 
10529 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
10530                                         Expr *E, ParsedType Ty,
10531                                         SourceLocation RPLoc) {
10532   TypeSourceInfo *TInfo;
10533   GetTypeFromParser(Ty, &TInfo);
10534   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
10535 }
10536 
10537 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
10538                                 Expr *E, TypeSourceInfo *TInfo,
10539                                 SourceLocation RPLoc) {
10540   Expr *OrigExpr = E;
10541 
10542   // Get the va_list type
10543   QualType VaListType = Context.getBuiltinVaListType();
10544   if (VaListType->isArrayType()) {
10545     // Deal with implicit array decay; for example, on x86-64,
10546     // va_list is an array, but it's supposed to decay to
10547     // a pointer for va_arg.
10548     VaListType = Context.getArrayDecayedType(VaListType);
10549     // Make sure the input expression also decays appropriately.
10550     ExprResult Result = UsualUnaryConversions(E);
10551     if (Result.isInvalid())
10552       return ExprError();
10553     E = Result.take();
10554   } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
10555     // If va_list is a record type and we are compiling in C++ mode,
10556     // check the argument using reference binding.
10557     InitializedEntity Entity
10558       = InitializedEntity::InitializeParameter(Context,
10559           Context.getLValueReferenceType(VaListType), false);
10560     ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
10561     if (Init.isInvalid())
10562       return ExprError();
10563     E = Init.takeAs<Expr>();
10564   } else {
10565     // Otherwise, the va_list argument must be an l-value because
10566     // it is modified by va_arg.
10567     if (!E->isTypeDependent() &&
10568         CheckForModifiableLvalue(E, BuiltinLoc, *this))
10569       return ExprError();
10570   }
10571 
10572   if (!E->isTypeDependent() &&
10573       !Context.hasSameType(VaListType, E->getType())) {
10574     return ExprError(Diag(E->getLocStart(),
10575                          diag::err_first_argument_to_va_arg_not_of_type_va_list)
10576       << OrigExpr->getType() << E->getSourceRange());
10577   }
10578 
10579   if (!TInfo->getType()->isDependentType()) {
10580     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
10581                             diag::err_second_parameter_to_va_arg_incomplete,
10582                             TInfo->getTypeLoc()))
10583       return ExprError();
10584 
10585     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
10586                                TInfo->getType(),
10587                                diag::err_second_parameter_to_va_arg_abstract,
10588                                TInfo->getTypeLoc()))
10589       return ExprError();
10590 
10591     if (!TInfo->getType().isPODType(Context)) {
10592       Diag(TInfo->getTypeLoc().getBeginLoc(),
10593            TInfo->getType()->isObjCLifetimeType()
10594              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
10595              : diag::warn_second_parameter_to_va_arg_not_pod)
10596         << TInfo->getType()
10597         << TInfo->getTypeLoc().getSourceRange();
10598     }
10599 
10600     // Check for va_arg where arguments of the given type will be promoted
10601     // (i.e. this va_arg is guaranteed to have undefined behavior).
10602     QualType PromoteType;
10603     if (TInfo->getType()->isPromotableIntegerType()) {
10604       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
10605       if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
10606         PromoteType = QualType();
10607     }
10608     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
10609       PromoteType = Context.DoubleTy;
10610     if (!PromoteType.isNull())
10611       DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
10612                   PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
10613                           << TInfo->getType()
10614                           << PromoteType
10615                           << TInfo->getTypeLoc().getSourceRange());
10616   }
10617 
10618   QualType T = TInfo->getType().getNonLValueExprType(Context);
10619   return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
10620 }
10621 
10622 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
10623   // The type of __null will be int or long, depending on the size of
10624   // pointers on the target.
10625   QualType Ty;
10626   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
10627   if (pw == Context.getTargetInfo().getIntWidth())
10628     Ty = Context.IntTy;
10629   else if (pw == Context.getTargetInfo().getLongWidth())
10630     Ty = Context.LongTy;
10631   else if (pw == Context.getTargetInfo().getLongLongWidth())
10632     Ty = Context.LongLongTy;
10633   else {
10634     llvm_unreachable("I don't know size of pointer!");
10635   }
10636 
10637   return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
10638 }
10639 
10640 bool
10641 Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp) {
10642   if (!getLangOpts().ObjC1)
10643     return false;
10644 
10645   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
10646   if (!PT)
10647     return false;
10648 
10649   if (!PT->isObjCIdType()) {
10650     // Check if the destination is the 'NSString' interface.
10651     const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
10652     if (!ID || !ID->getIdentifier()->isStr("NSString"))
10653       return false;
10654   }
10655 
10656   // Ignore any parens, implicit casts (should only be
10657   // array-to-pointer decays), and not-so-opaque values.  The last is
10658   // important for making this trigger for property assignments.
10659   Expr *SrcExpr = Exp->IgnoreParenImpCasts();
10660   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
10661     if (OV->getSourceExpr())
10662       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
10663 
10664   StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
10665   if (!SL || !SL->isAscii())
10666     return false;
10667   Diag(SL->getLocStart(), diag::err_missing_atsign_prefix)
10668     << FixItHint::CreateInsertion(SL->getLocStart(), "@");
10669   Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).take();
10670   return true;
10671 }
10672 
10673 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
10674                                     SourceLocation Loc,
10675                                     QualType DstType, QualType SrcType,
10676                                     Expr *SrcExpr, AssignmentAction Action,
10677                                     bool *Complained) {
10678   if (Complained)
10679     *Complained = false;
10680 
10681   // Decode the result (notice that AST's are still created for extensions).
10682   bool CheckInferredResultType = false;
10683   bool isInvalid = false;
10684   unsigned DiagKind = 0;
10685   FixItHint Hint;
10686   ConversionFixItGenerator ConvHints;
10687   bool MayHaveConvFixit = false;
10688   bool MayHaveFunctionDiff = false;
10689 
10690   switch (ConvTy) {
10691   case Compatible:
10692       DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
10693       return false;
10694 
10695   case PointerToInt:
10696     DiagKind = diag::ext_typecheck_convert_pointer_int;
10697     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
10698     MayHaveConvFixit = true;
10699     break;
10700   case IntToPointer:
10701     DiagKind = diag::ext_typecheck_convert_int_pointer;
10702     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
10703     MayHaveConvFixit = true;
10704     break;
10705   case IncompatiblePointer:
10706       DiagKind =
10707         (Action == AA_Passing_CFAudited ?
10708           diag::err_arc_typecheck_convert_incompatible_pointer :
10709           diag::ext_typecheck_convert_incompatible_pointer);
10710     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
10711       SrcType->isObjCObjectPointerType();
10712     if (Hint.isNull() && !CheckInferredResultType) {
10713       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
10714     }
10715     else if (CheckInferredResultType) {
10716       SrcType = SrcType.getUnqualifiedType();
10717       DstType = DstType.getUnqualifiedType();
10718     }
10719     MayHaveConvFixit = true;
10720     break;
10721   case IncompatiblePointerSign:
10722     DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
10723     break;
10724   case FunctionVoidPointer:
10725     DiagKind = diag::ext_typecheck_convert_pointer_void_func;
10726     break;
10727   case IncompatiblePointerDiscardsQualifiers: {
10728     // Perform array-to-pointer decay if necessary.
10729     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
10730 
10731     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
10732     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
10733     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
10734       DiagKind = diag::err_typecheck_incompatible_address_space;
10735       break;
10736 
10737 
10738     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
10739       DiagKind = diag::err_typecheck_incompatible_ownership;
10740       break;
10741     }
10742 
10743     llvm_unreachable("unknown error case for discarding qualifiers!");
10744     // fallthrough
10745   }
10746   case CompatiblePointerDiscardsQualifiers:
10747     // If the qualifiers lost were because we were applying the
10748     // (deprecated) C++ conversion from a string literal to a char*
10749     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
10750     // Ideally, this check would be performed in
10751     // checkPointerTypesForAssignment. However, that would require a
10752     // bit of refactoring (so that the second argument is an
10753     // expression, rather than a type), which should be done as part
10754     // of a larger effort to fix checkPointerTypesForAssignment for
10755     // C++ semantics.
10756     if (getLangOpts().CPlusPlus &&
10757         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
10758       return false;
10759     DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
10760     break;
10761   case IncompatibleNestedPointerQualifiers:
10762     DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
10763     break;
10764   case IntToBlockPointer:
10765     DiagKind = diag::err_int_to_block_pointer;
10766     break;
10767   case IncompatibleBlockPointer:
10768     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
10769     break;
10770   case IncompatibleObjCQualifiedId:
10771     // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
10772     // it can give a more specific diagnostic.
10773     DiagKind = diag::warn_incompatible_qualified_id;
10774     break;
10775   case IncompatibleVectors:
10776     DiagKind = diag::warn_incompatible_vectors;
10777     break;
10778   case IncompatibleObjCWeakRef:
10779     DiagKind = diag::err_arc_weak_unavailable_assign;
10780     break;
10781   case Incompatible:
10782     DiagKind = diag::err_typecheck_convert_incompatible;
10783     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
10784     MayHaveConvFixit = true;
10785     isInvalid = true;
10786     MayHaveFunctionDiff = true;
10787     break;
10788   }
10789 
10790   QualType FirstType, SecondType;
10791   switch (Action) {
10792   case AA_Assigning:
10793   case AA_Initializing:
10794     // The destination type comes first.
10795     FirstType = DstType;
10796     SecondType = SrcType;
10797     break;
10798 
10799   case AA_Returning:
10800   case AA_Passing:
10801   case AA_Passing_CFAudited:
10802   case AA_Converting:
10803   case AA_Sending:
10804   case AA_Casting:
10805     // The source type comes first.
10806     FirstType = SrcType;
10807     SecondType = DstType;
10808     break;
10809   }
10810 
10811   PartialDiagnostic FDiag = PDiag(DiagKind);
10812   if (Action == AA_Passing_CFAudited)
10813     FDiag << FirstType << SecondType << SrcExpr->getSourceRange();
10814   else
10815     FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
10816 
10817   // If we can fix the conversion, suggest the FixIts.
10818   assert(ConvHints.isNull() || Hint.isNull());
10819   if (!ConvHints.isNull()) {
10820     for (std::vector<FixItHint>::iterator HI = ConvHints.Hints.begin(),
10821          HE = ConvHints.Hints.end(); HI != HE; ++HI)
10822       FDiag << *HI;
10823   } else {
10824     FDiag << Hint;
10825   }
10826   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
10827 
10828   if (MayHaveFunctionDiff)
10829     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
10830 
10831   Diag(Loc, FDiag);
10832 
10833   if (SecondType == Context.OverloadTy)
10834     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
10835                               FirstType);
10836 
10837   if (CheckInferredResultType)
10838     EmitRelatedResultTypeNote(SrcExpr);
10839 
10840   if (Action == AA_Returning && ConvTy == IncompatiblePointer)
10841     EmitRelatedResultTypeNoteForReturn(DstType);
10842 
10843   if (Complained)
10844     *Complained = true;
10845   return isInvalid;
10846 }
10847 
10848 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
10849                                                  llvm::APSInt *Result) {
10850   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
10851   public:
10852     virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
10853       S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
10854     }
10855   } Diagnoser;
10856 
10857   return VerifyIntegerConstantExpression(E, Result, Diagnoser);
10858 }
10859 
10860 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
10861                                                  llvm::APSInt *Result,
10862                                                  unsigned DiagID,
10863                                                  bool AllowFold) {
10864   class IDDiagnoser : public VerifyICEDiagnoser {
10865     unsigned DiagID;
10866 
10867   public:
10868     IDDiagnoser(unsigned DiagID)
10869       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
10870 
10871     virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
10872       S.Diag(Loc, DiagID) << SR;
10873     }
10874   } Diagnoser(DiagID);
10875 
10876   return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
10877 }
10878 
10879 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
10880                                             SourceRange SR) {
10881   S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
10882 }
10883 
10884 ExprResult
10885 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
10886                                       VerifyICEDiagnoser &Diagnoser,
10887                                       bool AllowFold) {
10888   SourceLocation DiagLoc = E->getLocStart();
10889 
10890   if (getLangOpts().CPlusPlus11) {
10891     // C++11 [expr.const]p5:
10892     //   If an expression of literal class type is used in a context where an
10893     //   integral constant expression is required, then that class type shall
10894     //   have a single non-explicit conversion function to an integral or
10895     //   unscoped enumeration type
10896     ExprResult Converted;
10897     class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
10898     public:
10899       CXX11ConvertDiagnoser(bool Silent)
10900           : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
10901                                 Silent, true) {}
10902 
10903       virtual SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
10904                                                    QualType T) {
10905         return S.Diag(Loc, diag::err_ice_not_integral) << T;
10906       }
10907 
10908       virtual SemaDiagnosticBuilder diagnoseIncomplete(
10909           Sema &S, SourceLocation Loc, QualType T) {
10910         return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
10911       }
10912 
10913       virtual SemaDiagnosticBuilder diagnoseExplicitConv(
10914           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) {
10915         return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
10916       }
10917 
10918       virtual SemaDiagnosticBuilder noteExplicitConv(
10919           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) {
10920         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
10921                  << ConvTy->isEnumeralType() << ConvTy;
10922       }
10923 
10924       virtual SemaDiagnosticBuilder diagnoseAmbiguous(
10925           Sema &S, SourceLocation Loc, QualType T) {
10926         return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
10927       }
10928 
10929       virtual SemaDiagnosticBuilder noteAmbiguous(
10930           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) {
10931         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
10932                  << ConvTy->isEnumeralType() << ConvTy;
10933       }
10934 
10935       virtual SemaDiagnosticBuilder diagnoseConversion(
10936           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) {
10937         llvm_unreachable("conversion functions are permitted");
10938       }
10939     } ConvertDiagnoser(Diagnoser.Suppress);
10940 
10941     Converted = PerformContextualImplicitConversion(DiagLoc, E,
10942                                                     ConvertDiagnoser);
10943     if (Converted.isInvalid())
10944       return Converted;
10945     E = Converted.take();
10946     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
10947       return ExprError();
10948   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
10949     // An ICE must be of integral or unscoped enumeration type.
10950     if (!Diagnoser.Suppress)
10951       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
10952     return ExprError();
10953   }
10954 
10955   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
10956   // in the non-ICE case.
10957   if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
10958     if (Result)
10959       *Result = E->EvaluateKnownConstInt(Context);
10960     return Owned(E);
10961   }
10962 
10963   Expr::EvalResult EvalResult;
10964   SmallVector<PartialDiagnosticAt, 8> Notes;
10965   EvalResult.Diag = &Notes;
10966 
10967   // Try to evaluate the expression, and produce diagnostics explaining why it's
10968   // not a constant expression as a side-effect.
10969   bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
10970                 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
10971 
10972   // In C++11, we can rely on diagnostics being produced for any expression
10973   // which is not a constant expression. If no diagnostics were produced, then
10974   // this is a constant expression.
10975   if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
10976     if (Result)
10977       *Result = EvalResult.Val.getInt();
10978     return Owned(E);
10979   }
10980 
10981   // If our only note is the usual "invalid subexpression" note, just point
10982   // the caret at its location rather than producing an essentially
10983   // redundant note.
10984   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
10985         diag::note_invalid_subexpr_in_const_expr) {
10986     DiagLoc = Notes[0].first;
10987     Notes.clear();
10988   }
10989 
10990   if (!Folded || !AllowFold) {
10991     if (!Diagnoser.Suppress) {
10992       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
10993       for (unsigned I = 0, N = Notes.size(); I != N; ++I)
10994         Diag(Notes[I].first, Notes[I].second);
10995     }
10996 
10997     return ExprError();
10998   }
10999 
11000   Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
11001   for (unsigned I = 0, N = Notes.size(); I != N; ++I)
11002     Diag(Notes[I].first, Notes[I].second);
11003 
11004   if (Result)
11005     *Result = EvalResult.Val.getInt();
11006   return Owned(E);
11007 }
11008 
11009 namespace {
11010   // Handle the case where we conclude a expression which we speculatively
11011   // considered to be unevaluated is actually evaluated.
11012   class TransformToPE : public TreeTransform<TransformToPE> {
11013     typedef TreeTransform<TransformToPE> BaseTransform;
11014 
11015   public:
11016     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
11017 
11018     // Make sure we redo semantic analysis
11019     bool AlwaysRebuild() { return true; }
11020 
11021     // Make sure we handle LabelStmts correctly.
11022     // FIXME: This does the right thing, but maybe we need a more general
11023     // fix to TreeTransform?
11024     StmtResult TransformLabelStmt(LabelStmt *S) {
11025       S->getDecl()->setStmt(0);
11026       return BaseTransform::TransformLabelStmt(S);
11027     }
11028 
11029     // We need to special-case DeclRefExprs referring to FieldDecls which
11030     // are not part of a member pointer formation; normal TreeTransforming
11031     // doesn't catch this case because of the way we represent them in the AST.
11032     // FIXME: This is a bit ugly; is it really the best way to handle this
11033     // case?
11034     //
11035     // Error on DeclRefExprs referring to FieldDecls.
11036     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
11037       if (isa<FieldDecl>(E->getDecl()) &&
11038           !SemaRef.isUnevaluatedContext())
11039         return SemaRef.Diag(E->getLocation(),
11040                             diag::err_invalid_non_static_member_use)
11041             << E->getDecl() << E->getSourceRange();
11042 
11043       return BaseTransform::TransformDeclRefExpr(E);
11044     }
11045 
11046     // Exception: filter out member pointer formation
11047     ExprResult TransformUnaryOperator(UnaryOperator *E) {
11048       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
11049         return E;
11050 
11051       return BaseTransform::TransformUnaryOperator(E);
11052     }
11053 
11054     ExprResult TransformLambdaExpr(LambdaExpr *E) {
11055       // Lambdas never need to be transformed.
11056       return E;
11057     }
11058   };
11059 }
11060 
11061 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
11062   assert(isUnevaluatedContext() &&
11063          "Should only transform unevaluated expressions");
11064   ExprEvalContexts.back().Context =
11065       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
11066   if (isUnevaluatedContext())
11067     return E;
11068   return TransformToPE(*this).TransformExpr(E);
11069 }
11070 
11071 void
11072 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
11073                                       Decl *LambdaContextDecl,
11074                                       bool IsDecltype) {
11075   ExprEvalContexts.push_back(
11076              ExpressionEvaluationContextRecord(NewContext,
11077                                                ExprCleanupObjects.size(),
11078                                                ExprNeedsCleanups,
11079                                                LambdaContextDecl,
11080                                                IsDecltype));
11081   ExprNeedsCleanups = false;
11082   if (!MaybeODRUseExprs.empty())
11083     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
11084 }
11085 
11086 void
11087 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
11088                                       ReuseLambdaContextDecl_t,
11089                                       bool IsDecltype) {
11090   Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
11091   PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype);
11092 }
11093 
11094 void Sema::PopExpressionEvaluationContext() {
11095   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
11096 
11097   if (!Rec.Lambdas.empty()) {
11098     if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) {
11099       unsigned D;
11100       if (Rec.isUnevaluated()) {
11101         // C++11 [expr.prim.lambda]p2:
11102         //   A lambda-expression shall not appear in an unevaluated operand
11103         //   (Clause 5).
11104         D = diag::err_lambda_unevaluated_operand;
11105       } else {
11106         // C++1y [expr.const]p2:
11107         //   A conditional-expression e is a core constant expression unless the
11108         //   evaluation of e, following the rules of the abstract machine, would
11109         //   evaluate [...] a lambda-expression.
11110         D = diag::err_lambda_in_constant_expression;
11111       }
11112       for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I)
11113         Diag(Rec.Lambdas[I]->getLocStart(), D);
11114     } else {
11115       // Mark the capture expressions odr-used. This was deferred
11116       // during lambda expression creation.
11117       for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I) {
11118         LambdaExpr *Lambda = Rec.Lambdas[I];
11119         for (LambdaExpr::capture_init_iterator
11120                   C = Lambda->capture_init_begin(),
11121                CEnd = Lambda->capture_init_end();
11122              C != CEnd; ++C) {
11123           MarkDeclarationsReferencedInExpr(*C);
11124         }
11125       }
11126     }
11127   }
11128 
11129   // When are coming out of an unevaluated context, clear out any
11130   // temporaries that we may have created as part of the evaluation of
11131   // the expression in that context: they aren't relevant because they
11132   // will never be constructed.
11133   if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) {
11134     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
11135                              ExprCleanupObjects.end());
11136     ExprNeedsCleanups = Rec.ParentNeedsCleanups;
11137     CleanupVarDeclMarking();
11138     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
11139   // Otherwise, merge the contexts together.
11140   } else {
11141     ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
11142     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
11143                             Rec.SavedMaybeODRUseExprs.end());
11144   }
11145 
11146   // Pop the current expression evaluation context off the stack.
11147   ExprEvalContexts.pop_back();
11148 }
11149 
11150 void Sema::DiscardCleanupsInEvaluationContext() {
11151   ExprCleanupObjects.erase(
11152          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
11153          ExprCleanupObjects.end());
11154   ExprNeedsCleanups = false;
11155   MaybeODRUseExprs.clear();
11156 }
11157 
11158 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
11159   if (!E->getType()->isVariablyModifiedType())
11160     return E;
11161   return TransformToPotentiallyEvaluated(E);
11162 }
11163 
11164 static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) {
11165   // Do not mark anything as "used" within a dependent context; wait for
11166   // an instantiation.
11167   if (SemaRef.CurContext->isDependentContext())
11168     return false;
11169 
11170   switch (SemaRef.ExprEvalContexts.back().Context) {
11171     case Sema::Unevaluated:
11172     case Sema::UnevaluatedAbstract:
11173       // We are in an expression that is not potentially evaluated; do nothing.
11174       // (Depending on how you read the standard, we actually do need to do
11175       // something here for null pointer constants, but the standard's
11176       // definition of a null pointer constant is completely crazy.)
11177       return false;
11178 
11179     case Sema::ConstantEvaluated:
11180     case Sema::PotentiallyEvaluated:
11181       // We are in a potentially evaluated expression (or a constant-expression
11182       // in C++03); we need to do implicit template instantiation, implicitly
11183       // define class members, and mark most declarations as used.
11184       return true;
11185 
11186     case Sema::PotentiallyEvaluatedIfUsed:
11187       // Referenced declarations will only be used if the construct in the
11188       // containing expression is used.
11189       return false;
11190   }
11191   llvm_unreachable("Invalid context");
11192 }
11193 
11194 /// \brief Mark a function referenced, and check whether it is odr-used
11195 /// (C++ [basic.def.odr]p2, C99 6.9p3)
11196 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func) {
11197   assert(Func && "No function?");
11198 
11199   Func->setReferenced();
11200 
11201   // C++11 [basic.def.odr]p3:
11202   //   A function whose name appears as a potentially-evaluated expression is
11203   //   odr-used if it is the unique lookup result or the selected member of a
11204   //   set of overloaded functions [...].
11205   //
11206   // We (incorrectly) mark overload resolution as an unevaluated context, so we
11207   // can just check that here. Skip the rest of this function if we've already
11208   // marked the function as used.
11209   if (Func->isUsed(false) || !IsPotentiallyEvaluatedContext(*this)) {
11210     // C++11 [temp.inst]p3:
11211     //   Unless a function template specialization has been explicitly
11212     //   instantiated or explicitly specialized, the function template
11213     //   specialization is implicitly instantiated when the specialization is
11214     //   referenced in a context that requires a function definition to exist.
11215     //
11216     // We consider constexpr function templates to be referenced in a context
11217     // that requires a definition to exist whenever they are referenced.
11218     //
11219     // FIXME: This instantiates constexpr functions too frequently. If this is
11220     // really an unevaluated context (and we're not just in the definition of a
11221     // function template or overload resolution or other cases which we
11222     // incorrectly consider to be unevaluated contexts), and we're not in a
11223     // subexpression which we actually need to evaluate (for instance, a
11224     // template argument, array bound or an expression in a braced-init-list),
11225     // we are not permitted to instantiate this constexpr function definition.
11226     //
11227     // FIXME: This also implicitly defines special members too frequently. They
11228     // are only supposed to be implicitly defined if they are odr-used, but they
11229     // are not odr-used from constant expressions in unevaluated contexts.
11230     // However, they cannot be referenced if they are deleted, and they are
11231     // deleted whenever the implicit definition of the special member would
11232     // fail.
11233     if (!Func->isConstexpr() || Func->getBody())
11234       return;
11235     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
11236     if (!Func->isImplicitlyInstantiable() && (!MD || MD->isUserProvided()))
11237       return;
11238   }
11239 
11240   // Note that this declaration has been used.
11241   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
11242     Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
11243     if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
11244       if (Constructor->isDefaultConstructor()) {
11245         if (Constructor->isTrivial())
11246           return;
11247         DefineImplicitDefaultConstructor(Loc, Constructor);
11248       } else if (Constructor->isCopyConstructor()) {
11249         DefineImplicitCopyConstructor(Loc, Constructor);
11250       } else if (Constructor->isMoveConstructor()) {
11251         DefineImplicitMoveConstructor(Loc, Constructor);
11252       }
11253     } else if (Constructor->getInheritedConstructor()) {
11254       DefineInheritingConstructor(Loc, Constructor);
11255     }
11256 
11257     MarkVTableUsed(Loc, Constructor->getParent());
11258   } else if (CXXDestructorDecl *Destructor =
11259                  dyn_cast<CXXDestructorDecl>(Func)) {
11260     Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
11261     if (Destructor->isDefaulted() && !Destructor->isDeleted())
11262       DefineImplicitDestructor(Loc, Destructor);
11263     if (Destructor->isVirtual())
11264       MarkVTableUsed(Loc, Destructor->getParent());
11265   } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
11266     if (MethodDecl->isOverloadedOperator() &&
11267         MethodDecl->getOverloadedOperator() == OO_Equal) {
11268       MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
11269       if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
11270         if (MethodDecl->isCopyAssignmentOperator())
11271           DefineImplicitCopyAssignment(Loc, MethodDecl);
11272         else
11273           DefineImplicitMoveAssignment(Loc, MethodDecl);
11274       }
11275     } else if (isa<CXXConversionDecl>(MethodDecl) &&
11276                MethodDecl->getParent()->isLambda()) {
11277       CXXConversionDecl *Conversion =
11278           cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
11279       if (Conversion->isLambdaToBlockPointerConversion())
11280         DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
11281       else
11282         DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
11283     } else if (MethodDecl->isVirtual())
11284       MarkVTableUsed(Loc, MethodDecl->getParent());
11285   }
11286 
11287   // Recursive functions should be marked when used from another function.
11288   // FIXME: Is this really right?
11289   if (CurContext == Func) return;
11290 
11291   // Resolve the exception specification for any function which is
11292   // used: CodeGen will need it.
11293   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
11294   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
11295     ResolveExceptionSpec(Loc, FPT);
11296 
11297   // Implicit instantiation of function templates and member functions of
11298   // class templates.
11299   if (Func->isImplicitlyInstantiable()) {
11300     bool AlreadyInstantiated = false;
11301     SourceLocation PointOfInstantiation = Loc;
11302     if (FunctionTemplateSpecializationInfo *SpecInfo
11303                               = Func->getTemplateSpecializationInfo()) {
11304       if (SpecInfo->getPointOfInstantiation().isInvalid())
11305         SpecInfo->setPointOfInstantiation(Loc);
11306       else if (SpecInfo->getTemplateSpecializationKind()
11307                  == TSK_ImplicitInstantiation) {
11308         AlreadyInstantiated = true;
11309         PointOfInstantiation = SpecInfo->getPointOfInstantiation();
11310       }
11311     } else if (MemberSpecializationInfo *MSInfo
11312                                 = Func->getMemberSpecializationInfo()) {
11313       if (MSInfo->getPointOfInstantiation().isInvalid())
11314         MSInfo->setPointOfInstantiation(Loc);
11315       else if (MSInfo->getTemplateSpecializationKind()
11316                  == TSK_ImplicitInstantiation) {
11317         AlreadyInstantiated = true;
11318         PointOfInstantiation = MSInfo->getPointOfInstantiation();
11319       }
11320     }
11321 
11322     if (!AlreadyInstantiated || Func->isConstexpr()) {
11323       if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
11324           cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
11325           ActiveTemplateInstantiations.size())
11326         PendingLocalImplicitInstantiations.push_back(
11327             std::make_pair(Func, PointOfInstantiation));
11328       else if (Func->isConstexpr())
11329         // Do not defer instantiations of constexpr functions, to avoid the
11330         // expression evaluator needing to call back into Sema if it sees a
11331         // call to such a function.
11332         InstantiateFunctionDefinition(PointOfInstantiation, Func);
11333       else {
11334         PendingInstantiations.push_back(std::make_pair(Func,
11335                                                        PointOfInstantiation));
11336         // Notify the consumer that a function was implicitly instantiated.
11337         Consumer.HandleCXXImplicitFunctionInstantiation(Func);
11338       }
11339     }
11340   } else {
11341     // Walk redefinitions, as some of them may be instantiable.
11342     for (FunctionDecl::redecl_iterator i(Func->redecls_begin()),
11343          e(Func->redecls_end()); i != e; ++i) {
11344       if (!i->isUsed(false) && i->isImplicitlyInstantiable())
11345         MarkFunctionReferenced(Loc, *i);
11346     }
11347   }
11348 
11349   // Keep track of used but undefined functions.
11350   if (!Func->isDefined()) {
11351     if (mightHaveNonExternalLinkage(Func))
11352       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
11353     else if (Func->getMostRecentDecl()->isInlined() &&
11354              (LangOpts.CPlusPlus || !LangOpts.GNUInline) &&
11355              !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
11356       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
11357   }
11358 
11359   // Normally the most current decl is marked used while processing the use and
11360   // any subsequent decls are marked used by decl merging. This fails with
11361   // template instantiation since marking can happen at the end of the file
11362   // and, because of the two phase lookup, this function is called with at
11363   // decl in the middle of a decl chain. We loop to maintain the invariant
11364   // that once a decl is used, all decls after it are also used.
11365   for (FunctionDecl *F = Func->getMostRecentDecl();; F = F->getPreviousDecl()) {
11366     F->markUsed(Context);
11367     if (F == Func)
11368       break;
11369   }
11370 }
11371 
11372 static void
11373 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
11374                                    VarDecl *var, DeclContext *DC) {
11375   DeclContext *VarDC = var->getDeclContext();
11376 
11377   //  If the parameter still belongs to the translation unit, then
11378   //  we're actually just using one parameter in the declaration of
11379   //  the next.
11380   if (isa<ParmVarDecl>(var) &&
11381       isa<TranslationUnitDecl>(VarDC))
11382     return;
11383 
11384   // For C code, don't diagnose about capture if we're not actually in code
11385   // right now; it's impossible to write a non-constant expression outside of
11386   // function context, so we'll get other (more useful) diagnostics later.
11387   //
11388   // For C++, things get a bit more nasty... it would be nice to suppress this
11389   // diagnostic for certain cases like using a local variable in an array bound
11390   // for a member of a local class, but the correct predicate is not obvious.
11391   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
11392     return;
11393 
11394   if (isa<CXXMethodDecl>(VarDC) &&
11395       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
11396     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda)
11397       << var->getIdentifier();
11398   } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) {
11399     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
11400       << var->getIdentifier() << fn->getDeclName();
11401   } else if (isa<BlockDecl>(VarDC)) {
11402     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block)
11403       << var->getIdentifier();
11404   } else {
11405     // FIXME: Is there any other context where a local variable can be
11406     // declared?
11407     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context)
11408       << var->getIdentifier();
11409   }
11410 
11411   S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
11412     << var->getIdentifier();
11413 
11414   // FIXME: Add additional diagnostic info about class etc. which prevents
11415   // capture.
11416 }
11417 
11418 
11419 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
11420                                       bool &SubCapturesAreNested,
11421                                       QualType &CaptureType,
11422                                       QualType &DeclRefType) {
11423    // Check whether we've already captured it.
11424   if (CSI->CaptureMap.count(Var)) {
11425     // If we found a capture, any subcaptures are nested.
11426     SubCapturesAreNested = true;
11427 
11428     // Retrieve the capture type for this variable.
11429     CaptureType = CSI->getCapture(Var).getCaptureType();
11430 
11431     // Compute the type of an expression that refers to this variable.
11432     DeclRefType = CaptureType.getNonReferenceType();
11433 
11434     const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var);
11435     if (Cap.isCopyCapture() &&
11436         !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable))
11437       DeclRefType.addConst();
11438     return true;
11439   }
11440   return false;
11441 }
11442 
11443 // Only block literals, captured statements, and lambda expressions can
11444 // capture; other scopes don't work.
11445 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
11446                                  SourceLocation Loc,
11447                                  const bool Diagnose, Sema &S) {
11448   if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
11449     return getLambdaAwareParentOfDeclContext(DC);
11450   else {
11451     if (Diagnose)
11452        diagnoseUncapturableValueReference(S, Loc, Var, DC);
11453   }
11454   return 0;
11455 }
11456 
11457 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
11458 // certain types of variables (unnamed, variably modified types etc.)
11459 // so check for eligibility.
11460 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
11461                                  SourceLocation Loc,
11462                                  const bool Diagnose, Sema &S) {
11463 
11464   bool IsBlock = isa<BlockScopeInfo>(CSI);
11465   bool IsLambda = isa<LambdaScopeInfo>(CSI);
11466 
11467   // Lambdas are not allowed to capture unnamed variables
11468   // (e.g. anonymous unions).
11469   // FIXME: The C++11 rule don't actually state this explicitly, but I'm
11470   // assuming that's the intent.
11471   if (IsLambda && !Var->getDeclName()) {
11472     if (Diagnose) {
11473       S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
11474       S.Diag(Var->getLocation(), diag::note_declared_at);
11475     }
11476     return false;
11477   }
11478 
11479   // Prohibit variably-modified types; they're difficult to deal with.
11480   if (Var->getType()->isVariablyModifiedType()) {
11481     if (Diagnose) {
11482       if (IsBlock)
11483         S.Diag(Loc, diag::err_ref_vm_type);
11484       else
11485         S.Diag(Loc, diag::err_lambda_capture_vm_type) << Var->getDeclName();
11486       S.Diag(Var->getLocation(), diag::note_previous_decl)
11487         << Var->getDeclName();
11488     }
11489     return false;
11490   }
11491   // Prohibit structs with flexible array members too.
11492   // We cannot capture what is in the tail end of the struct.
11493   if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
11494     if (VTTy->getDecl()->hasFlexibleArrayMember()) {
11495       if (Diagnose) {
11496         if (IsBlock)
11497           S.Diag(Loc, diag::err_ref_flexarray_type);
11498         else
11499           S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
11500             << Var->getDeclName();
11501         S.Diag(Var->getLocation(), diag::note_previous_decl)
11502           << Var->getDeclName();
11503       }
11504       return false;
11505     }
11506   }
11507   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
11508   // Lambdas and captured statements are not allowed to capture __block
11509   // variables; they don't support the expected semantics.
11510   if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
11511     if (Diagnose) {
11512       S.Diag(Loc, diag::err_capture_block_variable)
11513         << Var->getDeclName() << !IsLambda;
11514       S.Diag(Var->getLocation(), diag::note_previous_decl)
11515         << Var->getDeclName();
11516     }
11517     return false;
11518   }
11519 
11520   return true;
11521 }
11522 
11523 // Returns true if the capture by block was successful.
11524 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
11525                                  SourceLocation Loc,
11526                                  const bool BuildAndDiagnose,
11527                                  QualType &CaptureType,
11528                                  QualType &DeclRefType,
11529                                  const bool Nested,
11530                                  Sema &S) {
11531   Expr *CopyExpr = 0;
11532   bool ByRef = false;
11533 
11534   // Blocks are not allowed to capture arrays.
11535   if (CaptureType->isArrayType()) {
11536     if (BuildAndDiagnose) {
11537       S.Diag(Loc, diag::err_ref_array_type);
11538       S.Diag(Var->getLocation(), diag::note_previous_decl)
11539       << Var->getDeclName();
11540     }
11541     return false;
11542   }
11543 
11544   // Forbid the block-capture of autoreleasing variables.
11545   if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
11546     if (BuildAndDiagnose) {
11547       S.Diag(Loc, diag::err_arc_autoreleasing_capture)
11548         << /*block*/ 0;
11549       S.Diag(Var->getLocation(), diag::note_previous_decl)
11550         << Var->getDeclName();
11551     }
11552     return false;
11553   }
11554   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
11555   if (HasBlocksAttr || CaptureType->isReferenceType()) {
11556     // Block capture by reference does not change the capture or
11557     // declaration reference types.
11558     ByRef = true;
11559   } else {
11560     // Block capture by copy introduces 'const'.
11561     CaptureType = CaptureType.getNonReferenceType().withConst();
11562     DeclRefType = CaptureType;
11563 
11564     if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) {
11565       if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
11566         // The capture logic needs the destructor, so make sure we mark it.
11567         // Usually this is unnecessary because most local variables have
11568         // their destructors marked at declaration time, but parameters are
11569         // an exception because it's technically only the call site that
11570         // actually requires the destructor.
11571         if (isa<ParmVarDecl>(Var))
11572           S.FinalizeVarWithDestructor(Var, Record);
11573 
11574         // Enter a new evaluation context to insulate the copy
11575         // full-expression.
11576         EnterExpressionEvaluationContext scope(S, S.PotentiallyEvaluated);
11577 
11578         // According to the blocks spec, the capture of a variable from
11579         // the stack requires a const copy constructor.  This is not true
11580         // of the copy/move done to move a __block variable to the heap.
11581         Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested,
11582                                                   DeclRefType.withConst(),
11583                                                   VK_LValue, Loc);
11584 
11585         ExprResult Result
11586           = S.PerformCopyInitialization(
11587               InitializedEntity::InitializeBlock(Var->getLocation(),
11588                                                   CaptureType, false),
11589               Loc, S.Owned(DeclRef));
11590 
11591         // Build a full-expression copy expression if initialization
11592         // succeeded and used a non-trivial constructor.  Recover from
11593         // errors by pretending that the copy isn't necessary.
11594         if (!Result.isInvalid() &&
11595             !cast<CXXConstructExpr>(Result.get())->getConstructor()
11596                 ->isTrivial()) {
11597           Result = S.MaybeCreateExprWithCleanups(Result);
11598           CopyExpr = Result.take();
11599         }
11600       }
11601     }
11602   }
11603 
11604   // Actually capture the variable.
11605   if (BuildAndDiagnose)
11606     BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
11607                     SourceLocation(), CaptureType, CopyExpr);
11608 
11609   return true;
11610 
11611 }
11612 
11613 
11614 /// \brief Capture the given variable in the captured region.
11615 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
11616                                     VarDecl *Var,
11617                                     SourceLocation Loc,
11618                                     const bool BuildAndDiagnose,
11619                                     QualType &CaptureType,
11620                                     QualType &DeclRefType,
11621                                     const bool RefersToEnclosingLocal,
11622                                     Sema &S) {
11623 
11624   // By default, capture variables by reference.
11625   bool ByRef = true;
11626   // Using an LValue reference type is consistent with Lambdas (see below).
11627   CaptureType = S.Context.getLValueReferenceType(DeclRefType);
11628   Expr *CopyExpr = 0;
11629   if (BuildAndDiagnose) {
11630     // The current implementation assumes that all variables are captured
11631     // by references. Since there is no capture by copy, no expression evaluation
11632     // will be needed.
11633     //
11634     RecordDecl *RD = RSI->TheRecordDecl;
11635 
11636     FieldDecl *Field
11637       = FieldDecl::Create(S.Context, RD, Loc, Loc, 0, CaptureType,
11638                           S.Context.getTrivialTypeSourceInfo(CaptureType, Loc),
11639                           0, false, ICIS_NoInit);
11640     Field->setImplicit(true);
11641     Field->setAccess(AS_private);
11642     RD->addDecl(Field);
11643 
11644     CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToEnclosingLocal,
11645                                             DeclRefType, VK_LValue, Loc);
11646     Var->setReferenced(true);
11647     Var->markUsed(S.Context);
11648   }
11649 
11650   // Actually capture the variable.
11651   if (BuildAndDiagnose)
11652     RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToEnclosingLocal, Loc,
11653                     SourceLocation(), CaptureType, CopyExpr);
11654 
11655 
11656   return true;
11657 }
11658 
11659 /// \brief Create a field within the lambda class for the variable
11660 ///  being captured.  Handle Array captures.
11661 static ExprResult addAsFieldToClosureType(Sema &S,
11662                                  LambdaScopeInfo *LSI,
11663                                   VarDecl *Var, QualType FieldType,
11664                                   QualType DeclRefType,
11665                                   SourceLocation Loc,
11666                                   bool RefersToEnclosingLocal) {
11667   CXXRecordDecl *Lambda = LSI->Lambda;
11668 
11669   // Build the non-static data member.
11670   FieldDecl *Field
11671     = FieldDecl::Create(S.Context, Lambda, Loc, Loc, 0, FieldType,
11672                         S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
11673                         0, false, ICIS_NoInit);
11674   Field->setImplicit(true);
11675   Field->setAccess(AS_private);
11676   Lambda->addDecl(Field);
11677 
11678   // C++11 [expr.prim.lambda]p21:
11679   //   When the lambda-expression is evaluated, the entities that
11680   //   are captured by copy are used to direct-initialize each
11681   //   corresponding non-static data member of the resulting closure
11682   //   object. (For array members, the array elements are
11683   //   direct-initialized in increasing subscript order.) These
11684   //   initializations are performed in the (unspecified) order in
11685   //   which the non-static data members are declared.
11686 
11687   // Introduce a new evaluation context for the initialization, so
11688   // that temporaries introduced as part of the capture are retained
11689   // to be re-"exported" from the lambda expression itself.
11690   EnterExpressionEvaluationContext scope(S, Sema::PotentiallyEvaluated);
11691 
11692   // C++ [expr.prim.labda]p12:
11693   //   An entity captured by a lambda-expression is odr-used (3.2) in
11694   //   the scope containing the lambda-expression.
11695   Expr *Ref = new (S.Context) DeclRefExpr(Var, RefersToEnclosingLocal,
11696                                           DeclRefType, VK_LValue, Loc);
11697   Var->setReferenced(true);
11698   Var->markUsed(S.Context);
11699 
11700   // When the field has array type, create index variables for each
11701   // dimension of the array. We use these index variables to subscript
11702   // the source array, and other clients (e.g., CodeGen) will perform
11703   // the necessary iteration with these index variables.
11704   SmallVector<VarDecl *, 4> IndexVariables;
11705   QualType BaseType = FieldType;
11706   QualType SizeType = S.Context.getSizeType();
11707   LSI->ArrayIndexStarts.push_back(LSI->ArrayIndexVars.size());
11708   while (const ConstantArrayType *Array
11709                         = S.Context.getAsConstantArrayType(BaseType)) {
11710     // Create the iteration variable for this array index.
11711     IdentifierInfo *IterationVarName = 0;
11712     {
11713       SmallString<8> Str;
11714       llvm::raw_svector_ostream OS(Str);
11715       OS << "__i" << IndexVariables.size();
11716       IterationVarName = &S.Context.Idents.get(OS.str());
11717     }
11718     VarDecl *IterationVar
11719       = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
11720                         IterationVarName, SizeType,
11721                         S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
11722                         SC_None);
11723     IndexVariables.push_back(IterationVar);
11724     LSI->ArrayIndexVars.push_back(IterationVar);
11725 
11726     // Create a reference to the iteration variable.
11727     ExprResult IterationVarRef
11728       = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
11729     assert(!IterationVarRef.isInvalid() &&
11730            "Reference to invented variable cannot fail!");
11731     IterationVarRef = S.DefaultLvalueConversion(IterationVarRef.take());
11732     assert(!IterationVarRef.isInvalid() &&
11733            "Conversion of invented variable cannot fail!");
11734 
11735     // Subscript the array with this iteration variable.
11736     ExprResult Subscript = S.CreateBuiltinArraySubscriptExpr(
11737                              Ref, Loc, IterationVarRef.take(), Loc);
11738     if (Subscript.isInvalid()) {
11739       S.CleanupVarDeclMarking();
11740       S.DiscardCleanupsInEvaluationContext();
11741       return ExprError();
11742     }
11743 
11744     Ref = Subscript.take();
11745     BaseType = Array->getElementType();
11746   }
11747 
11748   // Construct the entity that we will be initializing. For an array, this
11749   // will be first element in the array, which may require several levels
11750   // of array-subscript entities.
11751   SmallVector<InitializedEntity, 4> Entities;
11752   Entities.reserve(1 + IndexVariables.size());
11753   Entities.push_back(
11754     InitializedEntity::InitializeLambdaCapture(Var->getIdentifier(),
11755         Field->getType(), Loc));
11756   for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
11757     Entities.push_back(InitializedEntity::InitializeElement(S.Context,
11758                                                             0,
11759                                                             Entities.back()));
11760 
11761   InitializationKind InitKind
11762     = InitializationKind::CreateDirect(Loc, Loc, Loc);
11763   InitializationSequence Init(S, Entities.back(), InitKind, Ref);
11764   ExprResult Result(true);
11765   if (!Init.Diagnose(S, Entities.back(), InitKind, Ref))
11766     Result = Init.Perform(S, Entities.back(), InitKind, Ref);
11767 
11768   // If this initialization requires any cleanups (e.g., due to a
11769   // default argument to a copy constructor), note that for the
11770   // lambda.
11771   if (S.ExprNeedsCleanups)
11772     LSI->ExprNeedsCleanups = true;
11773 
11774   // Exit the expression evaluation context used for the capture.
11775   S.CleanupVarDeclMarking();
11776   S.DiscardCleanupsInEvaluationContext();
11777   return Result;
11778 }
11779 
11780 
11781 
11782 /// \brief Capture the given variable in the lambda.
11783 static bool captureInLambda(LambdaScopeInfo *LSI,
11784                             VarDecl *Var,
11785                             SourceLocation Loc,
11786                             const bool BuildAndDiagnose,
11787                             QualType &CaptureType,
11788                             QualType &DeclRefType,
11789                             const bool RefersToEnclosingLocal,
11790                             const Sema::TryCaptureKind Kind,
11791                             SourceLocation EllipsisLoc,
11792                             const bool IsTopScope,
11793                             Sema &S) {
11794 
11795   // Determine whether we are capturing by reference or by value.
11796   bool ByRef = false;
11797   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
11798     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
11799   } else {
11800     ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
11801   }
11802 
11803   // Compute the type of the field that will capture this variable.
11804   if (ByRef) {
11805     // C++11 [expr.prim.lambda]p15:
11806     //   An entity is captured by reference if it is implicitly or
11807     //   explicitly captured but not captured by copy. It is
11808     //   unspecified whether additional unnamed non-static data
11809     //   members are declared in the closure type for entities
11810     //   captured by reference.
11811     //
11812     // FIXME: It is not clear whether we want to build an lvalue reference
11813     // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
11814     // to do the former, while EDG does the latter. Core issue 1249 will
11815     // clarify, but for now we follow GCC because it's a more permissive and
11816     // easily defensible position.
11817     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
11818   } else {
11819     // C++11 [expr.prim.lambda]p14:
11820     //   For each entity captured by copy, an unnamed non-static
11821     //   data member is declared in the closure type. The
11822     //   declaration order of these members is unspecified. The type
11823     //   of such a data member is the type of the corresponding
11824     //   captured entity if the entity is not a reference to an
11825     //   object, or the referenced type otherwise. [Note: If the
11826     //   captured entity is a reference to a function, the
11827     //   corresponding data member is also a reference to a
11828     //   function. - end note ]
11829     if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
11830       if (!RefType->getPointeeType()->isFunctionType())
11831         CaptureType = RefType->getPointeeType();
11832     }
11833 
11834     // Forbid the lambda copy-capture of autoreleasing variables.
11835     if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
11836       if (BuildAndDiagnose) {
11837         S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
11838         S.Diag(Var->getLocation(), diag::note_previous_decl)
11839           << Var->getDeclName();
11840       }
11841       return false;
11842     }
11843 
11844     // Make sure that by-copy captures are of a complete and non-abstract type.
11845     if (BuildAndDiagnose) {
11846       if (!CaptureType->isDependentType() &&
11847           S.RequireCompleteType(Loc, CaptureType,
11848                                 diag::err_capture_of_incomplete_type,
11849                                 Var->getDeclName()))
11850         return false;
11851 
11852       if (S.RequireNonAbstractType(Loc, CaptureType,
11853                                    diag::err_capture_of_abstract_type))
11854         return false;
11855     }
11856   }
11857 
11858   // Capture this variable in the lambda.
11859   Expr *CopyExpr = 0;
11860   if (BuildAndDiagnose) {
11861     ExprResult Result = addAsFieldToClosureType(S, LSI, Var,
11862                                         CaptureType, DeclRefType, Loc,
11863                                         RefersToEnclosingLocal);
11864     if (!Result.isInvalid())
11865       CopyExpr = Result.take();
11866   }
11867 
11868   // Compute the type of a reference to this captured variable.
11869   if (ByRef)
11870     DeclRefType = CaptureType.getNonReferenceType();
11871   else {
11872     // C++ [expr.prim.lambda]p5:
11873     //   The closure type for a lambda-expression has a public inline
11874     //   function call operator [...]. This function call operator is
11875     //   declared const (9.3.1) if and only if the lambda-expression’s
11876     //   parameter-declaration-clause is not followed by mutable.
11877     DeclRefType = CaptureType.getNonReferenceType();
11878     if (!LSI->Mutable && !CaptureType->isReferenceType())
11879       DeclRefType.addConst();
11880   }
11881 
11882   // Add the capture.
11883   if (BuildAndDiagnose)
11884     LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToEnclosingLocal,
11885                     Loc, EllipsisLoc, CaptureType, CopyExpr);
11886 
11887   return true;
11888 }
11889 
11890 
11891 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation ExprLoc,
11892                               TryCaptureKind Kind, SourceLocation EllipsisLoc,
11893                               bool BuildAndDiagnose,
11894                               QualType &CaptureType,
11895                               QualType &DeclRefType,
11896 						                const unsigned *const FunctionScopeIndexToStopAt) {
11897   bool Nested = false;
11898 
11899   DeclContext *DC = CurContext;
11900   const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
11901       ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
11902   // We need to sync up the Declaration Context with the
11903   // FunctionScopeIndexToStopAt
11904   if (FunctionScopeIndexToStopAt) {
11905     unsigned FSIndex = FunctionScopes.size() - 1;
11906     while (FSIndex != MaxFunctionScopesIndex) {
11907       DC = getLambdaAwareParentOfDeclContext(DC);
11908       --FSIndex;
11909     }
11910   }
11911 
11912 
11913   // If the variable is declared in the current context (and is not an
11914   // init-capture), there is no need to capture it.
11915   if (!Var->isInitCapture() && Var->getDeclContext() == DC) return true;
11916   if (!Var->hasLocalStorage()) return true;
11917 
11918   // Walk up the stack to determine whether we can capture the variable,
11919   // performing the "simple" checks that don't depend on type. We stop when
11920   // we've either hit the declared scope of the variable or find an existing
11921   // capture of that variable.  We start from the innermost capturing-entity
11922   // (the DC) and ensure that all intervening capturing-entities
11923   // (blocks/lambdas etc.) between the innermost capturer and the variable`s
11924   // declcontext can either capture the variable or have already captured
11925   // the variable.
11926   CaptureType = Var->getType();
11927   DeclRefType = CaptureType.getNonReferenceType();
11928   bool Explicit = (Kind != TryCapture_Implicit);
11929   unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
11930   do {
11931     // Only block literals, captured statements, and lambda expressions can
11932     // capture; other scopes don't work.
11933     DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
11934                                                               ExprLoc,
11935                                                               BuildAndDiagnose,
11936                                                               *this);
11937     if (!ParentDC) return true;
11938 
11939     FunctionScopeInfo  *FSI = FunctionScopes[FunctionScopesIndex];
11940     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
11941 
11942 
11943     // Check whether we've already captured it.
11944     if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
11945                                              DeclRefType))
11946       break;
11947     // If we are instantiating a generic lambda call operator body,
11948     // we do not want to capture new variables.  What was captured
11949     // during either a lambdas transformation or initial parsing
11950     // should be used.
11951     if (isGenericLambdaCallOperatorSpecialization(DC)) {
11952       if (BuildAndDiagnose) {
11953         LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
11954         if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
11955           Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
11956           Diag(Var->getLocation(), diag::note_previous_decl)
11957              << Var->getDeclName();
11958           Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl);
11959         } else
11960           diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
11961       }
11962       return true;
11963     }
11964     // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
11965     // certain types of variables (unnamed, variably modified types etc.)
11966     // so check for eligibility.
11967     if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this))
11968        return true;
11969 
11970     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
11971       // No capture-default, and this is not an explicit capture
11972       // so cannot capture this variable.
11973       if (BuildAndDiagnose) {
11974         Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
11975         Diag(Var->getLocation(), diag::note_previous_decl)
11976           << Var->getDeclName();
11977         Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
11978              diag::note_lambda_decl);
11979         // FIXME: If we error out because an outer lambda can not implicitly
11980         // capture a variable that an inner lambda explicitly captures, we
11981         // should have the inner lambda do the explicit capture - because
11982         // it makes for cleaner diagnostics later.  This would purely be done
11983         // so that the diagnostic does not misleadingly claim that a variable
11984         // can not be captured by a lambda implicitly even though it is captured
11985         // explicitly.  Suggestion:
11986         //  - create const bool VariableCaptureWasInitiallyExplicit = Explicit
11987         //    at the function head
11988         //  - cache the StartingDeclContext - this must be a lambda
11989         //  - captureInLambda in the innermost lambda the variable.
11990       }
11991       return true;
11992     }
11993 
11994     FunctionScopesIndex--;
11995     DC = ParentDC;
11996     Explicit = false;
11997   } while (!Var->getDeclContext()->Equals(DC));
11998 
11999   // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
12000   // computing the type of the capture at each step, checking type-specific
12001   // requirements, and adding captures if requested.
12002   // If the variable had already been captured previously, we start capturing
12003   // at the lambda nested within that one.
12004   for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
12005        ++I) {
12006     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
12007 
12008     if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
12009       if (!captureInBlock(BSI, Var, ExprLoc,
12010                           BuildAndDiagnose, CaptureType,
12011                           DeclRefType, Nested, *this))
12012         return true;
12013       Nested = true;
12014     } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
12015       if (!captureInCapturedRegion(RSI, Var, ExprLoc,
12016                                    BuildAndDiagnose, CaptureType,
12017                                    DeclRefType, Nested, *this))
12018         return true;
12019       Nested = true;
12020     } else {
12021       LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
12022       if (!captureInLambda(LSI, Var, ExprLoc,
12023                            BuildAndDiagnose, CaptureType,
12024                            DeclRefType, Nested, Kind, EllipsisLoc,
12025                             /*IsTopScope*/I == N - 1, *this))
12026         return true;
12027       Nested = true;
12028     }
12029   }
12030   return false;
12031 }
12032 
12033 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
12034                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {
12035   QualType CaptureType;
12036   QualType DeclRefType;
12037   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
12038                             /*BuildAndDiagnose=*/true, CaptureType,
12039                             DeclRefType, 0);
12040 }
12041 
12042 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
12043   QualType CaptureType;
12044   QualType DeclRefType;
12045 
12046   // Determine whether we can capture this variable.
12047   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
12048                          /*BuildAndDiagnose=*/false, CaptureType,
12049                          DeclRefType, 0))
12050     return QualType();
12051 
12052   return DeclRefType;
12053 }
12054 
12055 
12056 
12057 // If either the type of the variable or the initializer is dependent,
12058 // return false. Otherwise, determine whether the variable is a constant
12059 // expression. Use this if you need to know if a variable that might or
12060 // might not be dependent is truly a constant expression.
12061 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var,
12062     ASTContext &Context) {
12063 
12064   if (Var->getType()->isDependentType())
12065     return false;
12066   const VarDecl *DefVD = 0;
12067   Var->getAnyInitializer(DefVD);
12068   if (!DefVD)
12069     return false;
12070   EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
12071   Expr *Init = cast<Expr>(Eval->Value);
12072   if (Init->isValueDependent())
12073     return false;
12074   return IsVariableAConstantExpression(Var, Context);
12075 }
12076 
12077 
12078 void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
12079   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
12080   // an object that satisfies the requirements for appearing in a
12081   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
12082   // is immediately applied."  This function handles the lvalue-to-rvalue
12083   // conversion part.
12084   MaybeODRUseExprs.erase(E->IgnoreParens());
12085 
12086   // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers
12087   // to a variable that is a constant expression, and if so, identify it as
12088   // a reference to a variable that does not involve an odr-use of that
12089   // variable.
12090   if (LambdaScopeInfo *LSI = getCurLambda()) {
12091     Expr *SansParensExpr = E->IgnoreParens();
12092     VarDecl *Var = 0;
12093     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr))
12094       Var = dyn_cast<VarDecl>(DRE->getFoundDecl());
12095     else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr))
12096       Var = dyn_cast<VarDecl>(ME->getMemberDecl());
12097 
12098     if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context))
12099       LSI->markVariableExprAsNonODRUsed(SansParensExpr);
12100   }
12101 }
12102 
12103 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
12104   if (!Res.isUsable())
12105     return Res;
12106 
12107   // If a constant-expression is a reference to a variable where we delay
12108   // deciding whether it is an odr-use, just assume we will apply the
12109   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
12110   // (a non-type template argument), we have special handling anyway.
12111   UpdateMarkingForLValueToRValue(Res.get());
12112   return Res;
12113 }
12114 
12115 void Sema::CleanupVarDeclMarking() {
12116   for (llvm::SmallPtrSetIterator<Expr*> i = MaybeODRUseExprs.begin(),
12117                                         e = MaybeODRUseExprs.end();
12118        i != e; ++i) {
12119     VarDecl *Var;
12120     SourceLocation Loc;
12121     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(*i)) {
12122       Var = cast<VarDecl>(DRE->getDecl());
12123       Loc = DRE->getLocation();
12124     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(*i)) {
12125       Var = cast<VarDecl>(ME->getMemberDecl());
12126       Loc = ME->getMemberLoc();
12127     } else {
12128       llvm_unreachable("Unexpcted expression");
12129     }
12130 
12131     MarkVarDeclODRUsed(Var, Loc, *this, /*MaxFunctionScopeIndex Pointer*/ 0);
12132   }
12133 
12134   MaybeODRUseExprs.clear();
12135 }
12136 
12137 
12138 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
12139                                     VarDecl *Var, Expr *E) {
12140   assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) &&
12141          "Invalid Expr argument to DoMarkVarDeclReferenced");
12142   Var->setReferenced();
12143 
12144   // If the context is not PotentiallyEvaluated and not Unevaluated
12145   // (i.e PotentiallyEvaluatedIfUsed) do not bother to consider variables
12146   // in this context for odr-use unless we are within a lambda.
12147   // If we don't know whether the context is potentially evaluated or not
12148   // (for e.g., if we're in a generic lambda), we want to add a potential
12149   // capture and eventually analyze for odr-use.
12150   // We should also be able to analyze certain constructs in a non-generic
12151   // lambda setting for potential odr-use and capture violation:
12152   // template<class T> void foo(T t) {
12153   //    auto L = [](int i) { return t; };
12154   // }
12155   //
12156   if (!IsPotentiallyEvaluatedContext(SemaRef)) {
12157 
12158     if (SemaRef.isUnevaluatedContext()) return;
12159 
12160     const bool refersToEnclosingScope =
12161       (SemaRef.CurContext != Var->getDeclContext() &&
12162            Var->getDeclContext()->isFunctionOrMethod());
12163     if (!refersToEnclosingScope) return;
12164 
12165     if (LambdaScopeInfo *const LSI = SemaRef.getCurLambda()) {
12166       // If a variable could potentially be odr-used, defer marking it so
12167       // until we finish analyzing the full expression for any lvalue-to-rvalue
12168       // or discarded value conversions that would obviate odr-use.
12169       // Add it to the list of potential captures that will be analyzed
12170       // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
12171       // unless the variable is a reference that was initialized by a constant
12172       // expression (this will never need to be captured or odr-used).
12173       const bool IsConstantExpr = IsVariableNonDependentAndAConstantExpression(
12174           Var, SemaRef.Context);
12175       assert(E && "Capture variable should be used in an expression.");
12176       if (!IsConstantExpr || !Var->getType()->isReferenceType())
12177         LSI->addPotentialCapture(E->IgnoreParens());
12178     }
12179     return;
12180   }
12181 
12182   VarTemplateSpecializationDecl *VarSpec =
12183       dyn_cast<VarTemplateSpecializationDecl>(Var);
12184   assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
12185          "Can't instantiate a partial template specialization.");
12186 
12187   // Implicit instantiation of static data members, static data member
12188   // templates of class templates, and variable template specializations.
12189   // Delay instantiations of variable templates, except for those
12190   // that could be used in a constant expression.
12191   TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
12192   if (isTemplateInstantiation(TSK)) {
12193     bool TryInstantiating = TSK == TSK_ImplicitInstantiation;
12194 
12195     if (TryInstantiating && !isa<VarTemplateSpecializationDecl>(Var)) {
12196       if (Var->getPointOfInstantiation().isInvalid()) {
12197         // This is a modification of an existing AST node. Notify listeners.
12198         if (ASTMutationListener *L = SemaRef.getASTMutationListener())
12199           L->StaticDataMemberInstantiated(Var);
12200       } else if (!Var->isUsableInConstantExpressions(SemaRef.Context))
12201         // Don't bother trying to instantiate it again, unless we might need
12202         // its initializer before we get to the end of the TU.
12203         TryInstantiating = false;
12204     }
12205 
12206     if (Var->getPointOfInstantiation().isInvalid())
12207       Var->setTemplateSpecializationKind(TSK, Loc);
12208 
12209     if (TryInstantiating) {
12210       SourceLocation PointOfInstantiation = Var->getPointOfInstantiation();
12211       bool InstantiationDependent = false;
12212       bool IsNonDependent =
12213           VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
12214                         VarSpec->getTemplateArgsInfo(), InstantiationDependent)
12215                   : true;
12216 
12217       // Do not instantiate specializations that are still type-dependent.
12218       if (IsNonDependent) {
12219         if (Var->isUsableInConstantExpressions(SemaRef.Context)) {
12220           // Do not defer instantiations of variables which could be used in a
12221           // constant expression.
12222           SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
12223         } else {
12224           SemaRef.PendingInstantiations
12225               .push_back(std::make_pair(Var, PointOfInstantiation));
12226         }
12227       }
12228     }
12229   }
12230   // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies
12231   // the requirements for appearing in a constant expression (5.19) and, if
12232   // it is an object, the lvalue-to-rvalue conversion (4.1)
12233   // is immediately applied."  We check the first part here, and
12234   // Sema::UpdateMarkingForLValueToRValue deals with the second part.
12235   // Note that we use the C++11 definition everywhere because nothing in
12236   // C++03 depends on whether we get the C++03 version correct. The second
12237   // part does not apply to references, since they are not objects.
12238   if (E && IsVariableAConstantExpression(Var, SemaRef.Context)) {
12239     // A reference initialized by a constant expression can never be
12240     // odr-used, so simply ignore it.
12241     // But a non-reference might get odr-used if it doesn't undergo
12242     // an lvalue-to-rvalue or is discarded, so track it.
12243     if (!Var->getType()->isReferenceType())
12244       SemaRef.MaybeODRUseExprs.insert(E);
12245   }
12246   else
12247     MarkVarDeclODRUsed(Var, Loc, SemaRef, /*MaxFunctionScopeIndex ptr*/0);
12248 }
12249 
12250 /// \brief Mark a variable referenced, and check whether it is odr-used
12251 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
12252 /// used directly for normal expressions referring to VarDecl.
12253 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
12254   DoMarkVarDeclReferenced(*this, Loc, Var, 0);
12255 }
12256 
12257 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
12258                                Decl *D, Expr *E, bool OdrUse) {
12259   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
12260     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
12261     return;
12262   }
12263 
12264   SemaRef.MarkAnyDeclReferenced(Loc, D, OdrUse);
12265 
12266   // If this is a call to a method via a cast, also mark the method in the
12267   // derived class used in case codegen can devirtualize the call.
12268   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
12269   if (!ME)
12270     return;
12271   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
12272   if (!MD)
12273     return;
12274   const Expr *Base = ME->getBase();
12275   const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
12276   if (!MostDerivedClassDecl)
12277     return;
12278   CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl);
12279   if (!DM || DM->isPure())
12280     return;
12281   SemaRef.MarkAnyDeclReferenced(Loc, DM, OdrUse);
12282 }
12283 
12284 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
12285 void Sema::MarkDeclRefReferenced(DeclRefExpr *E) {
12286   // TODO: update this with DR# once a defect report is filed.
12287   // C++11 defect. The address of a pure member should not be an ODR use, even
12288   // if it's a qualified reference.
12289   bool OdrUse = true;
12290   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
12291     if (Method->isVirtual())
12292       OdrUse = false;
12293   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
12294 }
12295 
12296 /// \brief Perform reference-marking and odr-use handling for a MemberExpr.
12297 void Sema::MarkMemberReferenced(MemberExpr *E) {
12298   // C++11 [basic.def.odr]p2:
12299   //   A non-overloaded function whose name appears as a potentially-evaluated
12300   //   expression or a member of a set of candidate functions, if selected by
12301   //   overload resolution when referred to from a potentially-evaluated
12302   //   expression, is odr-used, unless it is a pure virtual function and its
12303   //   name is not explicitly qualified.
12304   bool OdrUse = true;
12305   if (!E->hasQualifier()) {
12306     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
12307       if (Method->isPure())
12308         OdrUse = false;
12309   }
12310   SourceLocation Loc = E->getMemberLoc().isValid() ?
12311                             E->getMemberLoc() : E->getLocStart();
12312   MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, OdrUse);
12313 }
12314 
12315 /// \brief Perform marking for a reference to an arbitrary declaration.  It
12316 /// marks the declaration referenced, and performs odr-use checking for functions
12317 /// and variables. This method should not be used when building an normal
12318 /// expression which refers to a variable.
12319 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool OdrUse) {
12320   if (OdrUse) {
12321     if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
12322       MarkVariableReferenced(Loc, VD);
12323       return;
12324     }
12325     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
12326       MarkFunctionReferenced(Loc, FD);
12327       return;
12328     }
12329   }
12330   D->setReferenced();
12331 }
12332 
12333 namespace {
12334   // Mark all of the declarations referenced
12335   // FIXME: Not fully implemented yet! We need to have a better understanding
12336   // of when we're entering
12337   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
12338     Sema &S;
12339     SourceLocation Loc;
12340 
12341   public:
12342     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
12343 
12344     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
12345 
12346     bool TraverseTemplateArgument(const TemplateArgument &Arg);
12347     bool TraverseRecordType(RecordType *T);
12348   };
12349 }
12350 
12351 bool MarkReferencedDecls::TraverseTemplateArgument(
12352   const TemplateArgument &Arg) {
12353   if (Arg.getKind() == TemplateArgument::Declaration) {
12354     if (Decl *D = Arg.getAsDecl())
12355       S.MarkAnyDeclReferenced(Loc, D, true);
12356   }
12357 
12358   return Inherited::TraverseTemplateArgument(Arg);
12359 }
12360 
12361 bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
12362   if (ClassTemplateSpecializationDecl *Spec
12363                   = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
12364     const TemplateArgumentList &Args = Spec->getTemplateArgs();
12365     return TraverseTemplateArguments(Args.data(), Args.size());
12366   }
12367 
12368   return true;
12369 }
12370 
12371 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
12372   MarkReferencedDecls Marker(*this, Loc);
12373   Marker.TraverseType(Context.getCanonicalType(T));
12374 }
12375 
12376 namespace {
12377   /// \brief Helper class that marks all of the declarations referenced by
12378   /// potentially-evaluated subexpressions as "referenced".
12379   class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
12380     Sema &S;
12381     bool SkipLocalVariables;
12382 
12383   public:
12384     typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
12385 
12386     EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
12387       : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
12388 
12389     void VisitDeclRefExpr(DeclRefExpr *E) {
12390       // If we were asked not to visit local variables, don't.
12391       if (SkipLocalVariables) {
12392         if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
12393           if (VD->hasLocalStorage())
12394             return;
12395       }
12396 
12397       S.MarkDeclRefReferenced(E);
12398     }
12399 
12400     void VisitMemberExpr(MemberExpr *E) {
12401       S.MarkMemberReferenced(E);
12402       Inherited::VisitMemberExpr(E);
12403     }
12404 
12405     void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
12406       S.MarkFunctionReferenced(E->getLocStart(),
12407             const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
12408       Visit(E->getSubExpr());
12409     }
12410 
12411     void VisitCXXNewExpr(CXXNewExpr *E) {
12412       if (E->getOperatorNew())
12413         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
12414       if (E->getOperatorDelete())
12415         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
12416       Inherited::VisitCXXNewExpr(E);
12417     }
12418 
12419     void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
12420       if (E->getOperatorDelete())
12421         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
12422       QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
12423       if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
12424         CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
12425         S.MarkFunctionReferenced(E->getLocStart(),
12426                                     S.LookupDestructor(Record));
12427       }
12428 
12429       Inherited::VisitCXXDeleteExpr(E);
12430     }
12431 
12432     void VisitCXXConstructExpr(CXXConstructExpr *E) {
12433       S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
12434       Inherited::VisitCXXConstructExpr(E);
12435     }
12436 
12437     void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
12438       Visit(E->getExpr());
12439     }
12440 
12441     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
12442       Inherited::VisitImplicitCastExpr(E);
12443 
12444       if (E->getCastKind() == CK_LValueToRValue)
12445         S.UpdateMarkingForLValueToRValue(E->getSubExpr());
12446     }
12447   };
12448 }
12449 
12450 /// \brief Mark any declarations that appear within this expression or any
12451 /// potentially-evaluated subexpressions as "referenced".
12452 ///
12453 /// \param SkipLocalVariables If true, don't mark local variables as
12454 /// 'referenced'.
12455 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
12456                                             bool SkipLocalVariables) {
12457   EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
12458 }
12459 
12460 /// \brief Emit a diagnostic that describes an effect on the run-time behavior
12461 /// of the program being compiled.
12462 ///
12463 /// This routine emits the given diagnostic when the code currently being
12464 /// type-checked is "potentially evaluated", meaning that there is a
12465 /// possibility that the code will actually be executable. Code in sizeof()
12466 /// expressions, code used only during overload resolution, etc., are not
12467 /// potentially evaluated. This routine will suppress such diagnostics or,
12468 /// in the absolutely nutty case of potentially potentially evaluated
12469 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
12470 /// later.
12471 ///
12472 /// This routine should be used for all diagnostics that describe the run-time
12473 /// behavior of a program, such as passing a non-POD value through an ellipsis.
12474 /// Failure to do so will likely result in spurious diagnostics or failures
12475 /// during overload resolution or within sizeof/alignof/typeof/typeid.
12476 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
12477                                const PartialDiagnostic &PD) {
12478   switch (ExprEvalContexts.back().Context) {
12479   case Unevaluated:
12480   case UnevaluatedAbstract:
12481     // The argument will never be evaluated, so don't complain.
12482     break;
12483 
12484   case ConstantEvaluated:
12485     // Relevant diagnostics should be produced by constant evaluation.
12486     break;
12487 
12488   case PotentiallyEvaluated:
12489   case PotentiallyEvaluatedIfUsed:
12490     if (Statement && getCurFunctionOrMethodDecl()) {
12491       FunctionScopes.back()->PossiblyUnreachableDiags.
12492         push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
12493     }
12494     else
12495       Diag(Loc, PD);
12496 
12497     return true;
12498   }
12499 
12500   return false;
12501 }
12502 
12503 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
12504                                CallExpr *CE, FunctionDecl *FD) {
12505   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
12506     return false;
12507 
12508   // If we're inside a decltype's expression, don't check for a valid return
12509   // type or construct temporaries until we know whether this is the last call.
12510   if (ExprEvalContexts.back().IsDecltype) {
12511     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
12512     return false;
12513   }
12514 
12515   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
12516     FunctionDecl *FD;
12517     CallExpr *CE;
12518 
12519   public:
12520     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
12521       : FD(FD), CE(CE) { }
12522 
12523     virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
12524       if (!FD) {
12525         S.Diag(Loc, diag::err_call_incomplete_return)
12526           << T << CE->getSourceRange();
12527         return;
12528       }
12529 
12530       S.Diag(Loc, diag::err_call_function_incomplete_return)
12531         << CE->getSourceRange() << FD->getDeclName() << T;
12532       S.Diag(FD->getLocation(),
12533              diag::note_function_with_incomplete_return_type_declared_here)
12534         << FD->getDeclName();
12535     }
12536   } Diagnoser(FD, CE);
12537 
12538   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
12539     return true;
12540 
12541   return false;
12542 }
12543 
12544 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
12545 // will prevent this condition from triggering, which is what we want.
12546 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
12547   SourceLocation Loc;
12548 
12549   unsigned diagnostic = diag::warn_condition_is_assignment;
12550   bool IsOrAssign = false;
12551 
12552   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
12553     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
12554       return;
12555 
12556     IsOrAssign = Op->getOpcode() == BO_OrAssign;
12557 
12558     // Greylist some idioms by putting them into a warning subcategory.
12559     if (ObjCMessageExpr *ME
12560           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
12561       Selector Sel = ME->getSelector();
12562 
12563       // self = [<foo> init...]
12564       if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
12565         diagnostic = diag::warn_condition_is_idiomatic_assignment;
12566 
12567       // <foo> = [<bar> nextObject]
12568       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
12569         diagnostic = diag::warn_condition_is_idiomatic_assignment;
12570     }
12571 
12572     Loc = Op->getOperatorLoc();
12573   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
12574     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
12575       return;
12576 
12577     IsOrAssign = Op->getOperator() == OO_PipeEqual;
12578     Loc = Op->getOperatorLoc();
12579   } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
12580     return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
12581   else {
12582     // Not an assignment.
12583     return;
12584   }
12585 
12586   Diag(Loc, diagnostic) << E->getSourceRange();
12587 
12588   SourceLocation Open = E->getLocStart();
12589   SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
12590   Diag(Loc, diag::note_condition_assign_silence)
12591         << FixItHint::CreateInsertion(Open, "(")
12592         << FixItHint::CreateInsertion(Close, ")");
12593 
12594   if (IsOrAssign)
12595     Diag(Loc, diag::note_condition_or_assign_to_comparison)
12596       << FixItHint::CreateReplacement(Loc, "!=");
12597   else
12598     Diag(Loc, diag::note_condition_assign_to_comparison)
12599       << FixItHint::CreateReplacement(Loc, "==");
12600 }
12601 
12602 /// \brief Redundant parentheses over an equality comparison can indicate
12603 /// that the user intended an assignment used as condition.
12604 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
12605   // Don't warn if the parens came from a macro.
12606   SourceLocation parenLoc = ParenE->getLocStart();
12607   if (parenLoc.isInvalid() || parenLoc.isMacroID())
12608     return;
12609   // Don't warn for dependent expressions.
12610   if (ParenE->isTypeDependent())
12611     return;
12612 
12613   Expr *E = ParenE->IgnoreParens();
12614 
12615   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
12616     if (opE->getOpcode() == BO_EQ &&
12617         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
12618                                                            == Expr::MLV_Valid) {
12619       SourceLocation Loc = opE->getOperatorLoc();
12620 
12621       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
12622       SourceRange ParenERange = ParenE->getSourceRange();
12623       Diag(Loc, diag::note_equality_comparison_silence)
12624         << FixItHint::CreateRemoval(ParenERange.getBegin())
12625         << FixItHint::CreateRemoval(ParenERange.getEnd());
12626       Diag(Loc, diag::note_equality_comparison_to_assign)
12627         << FixItHint::CreateReplacement(Loc, "=");
12628     }
12629 }
12630 
12631 ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
12632   DiagnoseAssignmentAsCondition(E);
12633   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
12634     DiagnoseEqualityWithExtraParens(parenE);
12635 
12636   ExprResult result = CheckPlaceholderExpr(E);
12637   if (result.isInvalid()) return ExprError();
12638   E = result.take();
12639 
12640   if (!E->isTypeDependent()) {
12641     if (getLangOpts().CPlusPlus)
12642       return CheckCXXBooleanCondition(E); // C++ 6.4p4
12643 
12644     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
12645     if (ERes.isInvalid())
12646       return ExprError();
12647     E = ERes.take();
12648 
12649     QualType T = E->getType();
12650     if (!T->isScalarType()) { // C99 6.8.4.1p1
12651       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
12652         << T << E->getSourceRange();
12653       return ExprError();
12654     }
12655   }
12656 
12657   return Owned(E);
12658 }
12659 
12660 ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
12661                                        Expr *SubExpr) {
12662   if (!SubExpr)
12663     return ExprError();
12664 
12665   return CheckBooleanCondition(SubExpr, Loc);
12666 }
12667 
12668 namespace {
12669   /// A visitor for rebuilding a call to an __unknown_any expression
12670   /// to have an appropriate type.
12671   struct RebuildUnknownAnyFunction
12672     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
12673 
12674     Sema &S;
12675 
12676     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
12677 
12678     ExprResult VisitStmt(Stmt *S) {
12679       llvm_unreachable("unexpected statement!");
12680     }
12681 
12682     ExprResult VisitExpr(Expr *E) {
12683       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
12684         << E->getSourceRange();
12685       return ExprError();
12686     }
12687 
12688     /// Rebuild an expression which simply semantically wraps another
12689     /// expression which it shares the type and value kind of.
12690     template <class T> ExprResult rebuildSugarExpr(T *E) {
12691       ExprResult SubResult = Visit(E->getSubExpr());
12692       if (SubResult.isInvalid()) return ExprError();
12693 
12694       Expr *SubExpr = SubResult.take();
12695       E->setSubExpr(SubExpr);
12696       E->setType(SubExpr->getType());
12697       E->setValueKind(SubExpr->getValueKind());
12698       assert(E->getObjectKind() == OK_Ordinary);
12699       return E;
12700     }
12701 
12702     ExprResult VisitParenExpr(ParenExpr *E) {
12703       return rebuildSugarExpr(E);
12704     }
12705 
12706     ExprResult VisitUnaryExtension(UnaryOperator *E) {
12707       return rebuildSugarExpr(E);
12708     }
12709 
12710     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
12711       ExprResult SubResult = Visit(E->getSubExpr());
12712       if (SubResult.isInvalid()) return ExprError();
12713 
12714       Expr *SubExpr = SubResult.take();
12715       E->setSubExpr(SubExpr);
12716       E->setType(S.Context.getPointerType(SubExpr->getType()));
12717       assert(E->getValueKind() == VK_RValue);
12718       assert(E->getObjectKind() == OK_Ordinary);
12719       return E;
12720     }
12721 
12722     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
12723       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
12724 
12725       E->setType(VD->getType());
12726 
12727       assert(E->getValueKind() == VK_RValue);
12728       if (S.getLangOpts().CPlusPlus &&
12729           !(isa<CXXMethodDecl>(VD) &&
12730             cast<CXXMethodDecl>(VD)->isInstance()))
12731         E->setValueKind(VK_LValue);
12732 
12733       return E;
12734     }
12735 
12736     ExprResult VisitMemberExpr(MemberExpr *E) {
12737       return resolveDecl(E, E->getMemberDecl());
12738     }
12739 
12740     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
12741       return resolveDecl(E, E->getDecl());
12742     }
12743   };
12744 }
12745 
12746 /// Given a function expression of unknown-any type, try to rebuild it
12747 /// to have a function type.
12748 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
12749   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
12750   if (Result.isInvalid()) return ExprError();
12751   return S.DefaultFunctionArrayConversion(Result.take());
12752 }
12753 
12754 namespace {
12755   /// A visitor for rebuilding an expression of type __unknown_anytype
12756   /// into one which resolves the type directly on the referring
12757   /// expression.  Strict preservation of the original source
12758   /// structure is not a goal.
12759   struct RebuildUnknownAnyExpr
12760     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
12761 
12762     Sema &S;
12763 
12764     /// The current destination type.
12765     QualType DestType;
12766 
12767     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
12768       : S(S), DestType(CastType) {}
12769 
12770     ExprResult VisitStmt(Stmt *S) {
12771       llvm_unreachable("unexpected statement!");
12772     }
12773 
12774     ExprResult VisitExpr(Expr *E) {
12775       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
12776         << E->getSourceRange();
12777       return ExprError();
12778     }
12779 
12780     ExprResult VisitCallExpr(CallExpr *E);
12781     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
12782 
12783     /// Rebuild an expression which simply semantically wraps another
12784     /// expression which it shares the type and value kind of.
12785     template <class T> ExprResult rebuildSugarExpr(T *E) {
12786       ExprResult SubResult = Visit(E->getSubExpr());
12787       if (SubResult.isInvalid()) return ExprError();
12788       Expr *SubExpr = SubResult.take();
12789       E->setSubExpr(SubExpr);
12790       E->setType(SubExpr->getType());
12791       E->setValueKind(SubExpr->getValueKind());
12792       assert(E->getObjectKind() == OK_Ordinary);
12793       return E;
12794     }
12795 
12796     ExprResult VisitParenExpr(ParenExpr *E) {
12797       return rebuildSugarExpr(E);
12798     }
12799 
12800     ExprResult VisitUnaryExtension(UnaryOperator *E) {
12801       return rebuildSugarExpr(E);
12802     }
12803 
12804     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
12805       const PointerType *Ptr = DestType->getAs<PointerType>();
12806       if (!Ptr) {
12807         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
12808           << E->getSourceRange();
12809         return ExprError();
12810       }
12811       assert(E->getValueKind() == VK_RValue);
12812       assert(E->getObjectKind() == OK_Ordinary);
12813       E->setType(DestType);
12814 
12815       // Build the sub-expression as if it were an object of the pointee type.
12816       DestType = Ptr->getPointeeType();
12817       ExprResult SubResult = Visit(E->getSubExpr());
12818       if (SubResult.isInvalid()) return ExprError();
12819       E->setSubExpr(SubResult.take());
12820       return E;
12821     }
12822 
12823     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
12824 
12825     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
12826 
12827     ExprResult VisitMemberExpr(MemberExpr *E) {
12828       return resolveDecl(E, E->getMemberDecl());
12829     }
12830 
12831     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
12832       return resolveDecl(E, E->getDecl());
12833     }
12834   };
12835 }
12836 
12837 /// Rebuilds a call expression which yielded __unknown_anytype.
12838 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
12839   Expr *CalleeExpr = E->getCallee();
12840 
12841   enum FnKind {
12842     FK_MemberFunction,
12843     FK_FunctionPointer,
12844     FK_BlockPointer
12845   };
12846 
12847   FnKind Kind;
12848   QualType CalleeType = CalleeExpr->getType();
12849   if (CalleeType == S.Context.BoundMemberTy) {
12850     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
12851     Kind = FK_MemberFunction;
12852     CalleeType = Expr::findBoundMemberType(CalleeExpr);
12853   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
12854     CalleeType = Ptr->getPointeeType();
12855     Kind = FK_FunctionPointer;
12856   } else {
12857     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
12858     Kind = FK_BlockPointer;
12859   }
12860   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
12861 
12862   // Verify that this is a legal result type of a function.
12863   if (DestType->isArrayType() || DestType->isFunctionType()) {
12864     unsigned diagID = diag::err_func_returning_array_function;
12865     if (Kind == FK_BlockPointer)
12866       diagID = diag::err_block_returning_array_function;
12867 
12868     S.Diag(E->getExprLoc(), diagID)
12869       << DestType->isFunctionType() << DestType;
12870     return ExprError();
12871   }
12872 
12873   // Otherwise, go ahead and set DestType as the call's result.
12874   E->setType(DestType.getNonLValueExprType(S.Context));
12875   E->setValueKind(Expr::getValueKindForType(DestType));
12876   assert(E->getObjectKind() == OK_Ordinary);
12877 
12878   // Rebuild the function type, replacing the result type with DestType.
12879   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
12880   if (Proto) {
12881     // __unknown_anytype(...) is a special case used by the debugger when
12882     // it has no idea what a function's signature is.
12883     //
12884     // We want to build this call essentially under the K&R
12885     // unprototyped rules, but making a FunctionNoProtoType in C++
12886     // would foul up all sorts of assumptions.  However, we cannot
12887     // simply pass all arguments as variadic arguments, nor can we
12888     // portably just call the function under a non-variadic type; see
12889     // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
12890     // However, it turns out that in practice it is generally safe to
12891     // call a function declared as "A foo(B,C,D);" under the prototype
12892     // "A foo(B,C,D,...);".  The only known exception is with the
12893     // Windows ABI, where any variadic function is implicitly cdecl
12894     // regardless of its normal CC.  Therefore we change the parameter
12895     // types to match the types of the arguments.
12896     //
12897     // This is a hack, but it is far superior to moving the
12898     // corresponding target-specific code from IR-gen to Sema/AST.
12899 
12900     ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
12901     SmallVector<QualType, 8> ArgTypes;
12902     if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
12903       ArgTypes.reserve(E->getNumArgs());
12904       for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
12905         Expr *Arg = E->getArg(i);
12906         QualType ArgType = Arg->getType();
12907         if (E->isLValue()) {
12908           ArgType = S.Context.getLValueReferenceType(ArgType);
12909         } else if (E->isXValue()) {
12910           ArgType = S.Context.getRValueReferenceType(ArgType);
12911         }
12912         ArgTypes.push_back(ArgType);
12913       }
12914       ParamTypes = ArgTypes;
12915     }
12916     DestType = S.Context.getFunctionType(DestType, ParamTypes,
12917                                          Proto->getExtProtoInfo());
12918   } else {
12919     DestType = S.Context.getFunctionNoProtoType(DestType,
12920                                                 FnType->getExtInfo());
12921   }
12922 
12923   // Rebuild the appropriate pointer-to-function type.
12924   switch (Kind) {
12925   case FK_MemberFunction:
12926     // Nothing to do.
12927     break;
12928 
12929   case FK_FunctionPointer:
12930     DestType = S.Context.getPointerType(DestType);
12931     break;
12932 
12933   case FK_BlockPointer:
12934     DestType = S.Context.getBlockPointerType(DestType);
12935     break;
12936   }
12937 
12938   // Finally, we can recurse.
12939   ExprResult CalleeResult = Visit(CalleeExpr);
12940   if (!CalleeResult.isUsable()) return ExprError();
12941   E->setCallee(CalleeResult.take());
12942 
12943   // Bind a temporary if necessary.
12944   return S.MaybeBindToTemporary(E);
12945 }
12946 
12947 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
12948   // Verify that this is a legal result type of a call.
12949   if (DestType->isArrayType() || DestType->isFunctionType()) {
12950     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
12951       << DestType->isFunctionType() << DestType;
12952     return ExprError();
12953   }
12954 
12955   // Rewrite the method result type if available.
12956   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
12957     assert(Method->getReturnType() == S.Context.UnknownAnyTy);
12958     Method->setReturnType(DestType);
12959   }
12960 
12961   // Change the type of the message.
12962   E->setType(DestType.getNonReferenceType());
12963   E->setValueKind(Expr::getValueKindForType(DestType));
12964 
12965   return S.MaybeBindToTemporary(E);
12966 }
12967 
12968 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
12969   // The only case we should ever see here is a function-to-pointer decay.
12970   if (E->getCastKind() == CK_FunctionToPointerDecay) {
12971     assert(E->getValueKind() == VK_RValue);
12972     assert(E->getObjectKind() == OK_Ordinary);
12973 
12974     E->setType(DestType);
12975 
12976     // Rebuild the sub-expression as the pointee (function) type.
12977     DestType = DestType->castAs<PointerType>()->getPointeeType();
12978 
12979     ExprResult Result = Visit(E->getSubExpr());
12980     if (!Result.isUsable()) return ExprError();
12981 
12982     E->setSubExpr(Result.take());
12983     return S.Owned(E);
12984   } else if (E->getCastKind() == CK_LValueToRValue) {
12985     assert(E->getValueKind() == VK_RValue);
12986     assert(E->getObjectKind() == OK_Ordinary);
12987 
12988     assert(isa<BlockPointerType>(E->getType()));
12989 
12990     E->setType(DestType);
12991 
12992     // The sub-expression has to be a lvalue reference, so rebuild it as such.
12993     DestType = S.Context.getLValueReferenceType(DestType);
12994 
12995     ExprResult Result = Visit(E->getSubExpr());
12996     if (!Result.isUsable()) return ExprError();
12997 
12998     E->setSubExpr(Result.take());
12999     return S.Owned(E);
13000   } else {
13001     llvm_unreachable("Unhandled cast type!");
13002   }
13003 }
13004 
13005 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
13006   ExprValueKind ValueKind = VK_LValue;
13007   QualType Type = DestType;
13008 
13009   // We know how to make this work for certain kinds of decls:
13010 
13011   //  - functions
13012   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
13013     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
13014       DestType = Ptr->getPointeeType();
13015       ExprResult Result = resolveDecl(E, VD);
13016       if (Result.isInvalid()) return ExprError();
13017       return S.ImpCastExprToType(Result.take(), Type,
13018                                  CK_FunctionToPointerDecay, VK_RValue);
13019     }
13020 
13021     if (!Type->isFunctionType()) {
13022       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
13023         << VD << E->getSourceRange();
13024       return ExprError();
13025     }
13026 
13027     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
13028       if (MD->isInstance()) {
13029         ValueKind = VK_RValue;
13030         Type = S.Context.BoundMemberTy;
13031       }
13032 
13033     // Function references aren't l-values in C.
13034     if (!S.getLangOpts().CPlusPlus)
13035       ValueKind = VK_RValue;
13036 
13037   //  - variables
13038   } else if (isa<VarDecl>(VD)) {
13039     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
13040       Type = RefTy->getPointeeType();
13041     } else if (Type->isFunctionType()) {
13042       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
13043         << VD << E->getSourceRange();
13044       return ExprError();
13045     }
13046 
13047   //  - nothing else
13048   } else {
13049     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
13050       << VD << E->getSourceRange();
13051     return ExprError();
13052   }
13053 
13054   // Modifying the declaration like this is friendly to IR-gen but
13055   // also really dangerous.
13056   VD->setType(DestType);
13057   E->setType(Type);
13058   E->setValueKind(ValueKind);
13059   return S.Owned(E);
13060 }
13061 
13062 /// Check a cast of an unknown-any type.  We intentionally only
13063 /// trigger this for C-style casts.
13064 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
13065                                      Expr *CastExpr, CastKind &CastKind,
13066                                      ExprValueKind &VK, CXXCastPath &Path) {
13067   // Rewrite the casted expression from scratch.
13068   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
13069   if (!result.isUsable()) return ExprError();
13070 
13071   CastExpr = result.take();
13072   VK = CastExpr->getValueKind();
13073   CastKind = CK_NoOp;
13074 
13075   return CastExpr;
13076 }
13077 
13078 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
13079   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
13080 }
13081 
13082 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
13083                                     Expr *arg, QualType &paramType) {
13084   // If the syntactic form of the argument is not an explicit cast of
13085   // any sort, just do default argument promotion.
13086   ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
13087   if (!castArg) {
13088     ExprResult result = DefaultArgumentPromotion(arg);
13089     if (result.isInvalid()) return ExprError();
13090     paramType = result.get()->getType();
13091     return result;
13092   }
13093 
13094   // Otherwise, use the type that was written in the explicit cast.
13095   assert(!arg->hasPlaceholderType());
13096   paramType = castArg->getTypeAsWritten();
13097 
13098   // Copy-initialize a parameter of that type.
13099   InitializedEntity entity =
13100     InitializedEntity::InitializeParameter(Context, paramType,
13101                                            /*consumed*/ false);
13102   return PerformCopyInitialization(entity, callLoc, Owned(arg));
13103 }
13104 
13105 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
13106   Expr *orig = E;
13107   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
13108   while (true) {
13109     E = E->IgnoreParenImpCasts();
13110     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
13111       E = call->getCallee();
13112       diagID = diag::err_uncasted_call_of_unknown_any;
13113     } else {
13114       break;
13115     }
13116   }
13117 
13118   SourceLocation loc;
13119   NamedDecl *d;
13120   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
13121     loc = ref->getLocation();
13122     d = ref->getDecl();
13123   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
13124     loc = mem->getMemberLoc();
13125     d = mem->getMemberDecl();
13126   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
13127     diagID = diag::err_uncasted_call_of_unknown_any;
13128     loc = msg->getSelectorStartLoc();
13129     d = msg->getMethodDecl();
13130     if (!d) {
13131       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
13132         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
13133         << orig->getSourceRange();
13134       return ExprError();
13135     }
13136   } else {
13137     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
13138       << E->getSourceRange();
13139     return ExprError();
13140   }
13141 
13142   S.Diag(loc, diagID) << d << orig->getSourceRange();
13143 
13144   // Never recoverable.
13145   return ExprError();
13146 }
13147 
13148 /// Check for operands with placeholder types and complain if found.
13149 /// Returns true if there was an error and no recovery was possible.
13150 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
13151   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
13152   if (!placeholderType) return Owned(E);
13153 
13154   switch (placeholderType->getKind()) {
13155 
13156   // Overloaded expressions.
13157   case BuiltinType::Overload: {
13158     // Try to resolve a single function template specialization.
13159     // This is obligatory.
13160     ExprResult result = Owned(E);
13161     if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) {
13162       return result;
13163 
13164     // If that failed, try to recover with a call.
13165     } else {
13166       tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable),
13167                            /*complain*/ true);
13168       return result;
13169     }
13170   }
13171 
13172   // Bound member functions.
13173   case BuiltinType::BoundMember: {
13174     ExprResult result = Owned(E);
13175     tryToRecoverWithCall(result, PDiag(diag::err_bound_member_function),
13176                          /*complain*/ true);
13177     return result;
13178   }
13179 
13180   // ARC unbridged casts.
13181   case BuiltinType::ARCUnbridgedCast: {
13182     Expr *realCast = stripARCUnbridgedCast(E);
13183     diagnoseARCUnbridgedCast(realCast);
13184     return Owned(realCast);
13185   }
13186 
13187   // Expressions of unknown type.
13188   case BuiltinType::UnknownAny:
13189     return diagnoseUnknownAnyExpr(*this, E);
13190 
13191   // Pseudo-objects.
13192   case BuiltinType::PseudoObject:
13193     return checkPseudoObjectRValue(E);
13194 
13195   case BuiltinType::BuiltinFn:
13196     Diag(E->getLocStart(), diag::err_builtin_fn_use);
13197     return ExprError();
13198 
13199   // Everything else should be impossible.
13200 #define BUILTIN_TYPE(Id, SingletonId) \
13201   case BuiltinType::Id:
13202 #define PLACEHOLDER_TYPE(Id, SingletonId)
13203 #include "clang/AST/BuiltinTypes.def"
13204     break;
13205   }
13206 
13207   llvm_unreachable("invalid placeholder type!");
13208 }
13209 
13210 bool Sema::CheckCaseExpression(Expr *E) {
13211   if (E->isTypeDependent())
13212     return true;
13213   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
13214     return E->getType()->isIntegralOrEnumerationType();
13215   return false;
13216 }
13217 
13218 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
13219 ExprResult
13220 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
13221   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
13222          "Unknown Objective-C Boolean value!");
13223   QualType BoolT = Context.ObjCBuiltinBoolTy;
13224   if (!Context.getBOOLDecl()) {
13225     LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
13226                         Sema::LookupOrdinaryName);
13227     if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
13228       NamedDecl *ND = Result.getFoundDecl();
13229       if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
13230         Context.setBOOLDecl(TD);
13231     }
13232   }
13233   if (Context.getBOOLDecl())
13234     BoolT = Context.getBOOLType();
13235   return Owned(new (Context) ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes,
13236                                         BoolT, OpLoc));
13237 }
13238