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->getResultType()->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       S.EmitDeprecationWarning(D, Message, Loc, UnknownObjCClass, ObjCPDecl);
115       break;
116 
117     case AR_Unavailable:
118       if (S.getCurContextAvailability() != AR_Unavailable) {
119         if (Message.empty()) {
120           if (!UnknownObjCClass) {
121             S.Diag(Loc, diag::err_unavailable) << D->getDeclName();
122             if (ObjCPDecl)
123               S.Diag(ObjCPDecl->getLocation(), diag::note_property_attribute)
124                 << ObjCPDecl->getDeclName() << 1;
125           }
126           else
127             S.Diag(Loc, diag::warn_unavailable_fwdclass_message)
128               << D->getDeclName();
129         }
130         else
131           S.Diag(Loc, diag::err_unavailable_message)
132             << D->getDeclName() << Message;
133         S.Diag(D->getLocation(), diag::note_unavailable_here)
134                   << isa<FunctionDecl>(D) << false;
135         if (ObjCPDecl)
136           S.Diag(ObjCPDecl->getLocation(), diag::note_property_attribute)
137           << ObjCPDecl->getDeclName() << 1;
138       }
139       break;
140     }
141     return Result;
142 }
143 
144 /// \brief Emit a note explaining that this function is deleted.
145 void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
146   assert(Decl->isDeleted());
147 
148   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
149 
150   if (Method && Method->isDeleted() && Method->isDefaulted()) {
151     // If the method was explicitly defaulted, point at that declaration.
152     if (!Method->isImplicit())
153       Diag(Decl->getLocation(), diag::note_implicitly_deleted);
154 
155     // Try to diagnose why this special member function was implicitly
156     // deleted. This might fail, if that reason no longer applies.
157     CXXSpecialMember CSM = getSpecialMember(Method);
158     if (CSM != CXXInvalid)
159       ShouldDeleteSpecialMember(Method, CSM, /*Diagnose=*/true);
160 
161     return;
162   }
163 
164   if (CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Decl)) {
165     if (CXXConstructorDecl *BaseCD =
166             const_cast<CXXConstructorDecl*>(CD->getInheritedConstructor())) {
167       Diag(Decl->getLocation(), diag::note_inherited_deleted_here);
168       if (BaseCD->isDeleted()) {
169         NoteDeletedFunction(BaseCD);
170       } else {
171         // FIXME: An explanation of why exactly it can't be inherited
172         // would be nice.
173         Diag(BaseCD->getLocation(), diag::note_cannot_inherit);
174       }
175       return;
176     }
177   }
178 
179   Diag(Decl->getLocation(), diag::note_unavailable_here)
180     << 1 << true;
181 }
182 
183 /// \brief Determine whether a FunctionDecl was ever declared with an
184 /// explicit storage class.
185 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
186   for (FunctionDecl::redecl_iterator I = D->redecls_begin(),
187                                      E = D->redecls_end();
188        I != E; ++I) {
189     if (I->getStorageClass() != SC_None)
190       return true;
191   }
192   return false;
193 }
194 
195 /// \brief Check whether we're in an extern inline function and referring to a
196 /// variable or function with internal linkage (C11 6.7.4p3).
197 ///
198 /// This is only a warning because we used to silently accept this code, but
199 /// in many cases it will not behave correctly. This is not enabled in C++ mode
200 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
201 /// and so while there may still be user mistakes, most of the time we can't
202 /// prove that there are errors.
203 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
204                                                       const NamedDecl *D,
205                                                       SourceLocation Loc) {
206   // This is disabled under C++; there are too many ways for this to fire in
207   // contexts where the warning is a false positive, or where it is technically
208   // correct but benign.
209   if (S.getLangOpts().CPlusPlus)
210     return;
211 
212   // Check if this is an inlined function or method.
213   FunctionDecl *Current = S.getCurFunctionDecl();
214   if (!Current)
215     return;
216   if (!Current->isInlined())
217     return;
218   if (!Current->isExternallyVisible())
219     return;
220 
221   // Check if the decl has internal linkage.
222   if (D->getFormalLinkage() != InternalLinkage)
223     return;
224 
225   // Downgrade from ExtWarn to Extension if
226   //  (1) the supposedly external inline function is in the main file,
227   //      and probably won't be included anywhere else.
228   //  (2) the thing we're referencing is a pure function.
229   //  (3) the thing we're referencing is another inline function.
230   // This last can give us false negatives, but it's better than warning on
231   // wrappers for simple C library functions.
232   const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
233   bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
234   if (!DowngradeWarning && UsedFn)
235     DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
236 
237   S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline
238                                : diag::warn_internal_in_extern_inline)
239     << /*IsVar=*/!UsedFn << D;
240 
241   S.MaybeSuggestAddingStaticToDecl(Current);
242 
243   S.Diag(D->getCanonicalDecl()->getLocation(),
244          diag::note_internal_decl_declared_here)
245     << D;
246 }
247 
248 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
249   const FunctionDecl *First = Cur->getFirstDecl();
250 
251   // Suggest "static" on the function, if possible.
252   if (!hasAnyExplicitStorageClass(First)) {
253     SourceLocation DeclBegin = First->getSourceRange().getBegin();
254     Diag(DeclBegin, diag::note_convert_inline_to_static)
255       << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
256   }
257 }
258 
259 /// \brief Determine whether the use of this declaration is valid, and
260 /// emit any corresponding diagnostics.
261 ///
262 /// This routine diagnoses various problems with referencing
263 /// declarations that can occur when using a declaration. For example,
264 /// it might warn if a deprecated or unavailable declaration is being
265 /// used, or produce an error (and return true) if a C++0x deleted
266 /// function is being used.
267 ///
268 /// \returns true if there was an error (this declaration cannot be
269 /// referenced), false otherwise.
270 ///
271 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
272                              const ObjCInterfaceDecl *UnknownObjCClass) {
273   if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
274     // If there were any diagnostics suppressed by template argument deduction,
275     // emit them now.
276     SuppressedDiagnosticsMap::iterator
277       Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
278     if (Pos != SuppressedDiagnostics.end()) {
279       SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second;
280       for (unsigned I = 0, N = Suppressed.size(); I != N; ++I)
281         Diag(Suppressed[I].first, Suppressed[I].second);
282 
283       // Clear out the list of suppressed diagnostics, so that we don't emit
284       // them again for this specialization. However, we don't obsolete this
285       // entry from the table, because we want to avoid ever emitting these
286       // diagnostics again.
287       Suppressed.clear();
288     }
289   }
290 
291   // See if this is an auto-typed variable whose initializer we are parsing.
292   if (ParsingInitForAutoVars.count(D)) {
293     Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
294       << D->getDeclName();
295     return true;
296   }
297 
298   // See if this is a deleted function.
299   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
300     if (FD->isDeleted()) {
301       Diag(Loc, diag::err_deleted_function_use);
302       NoteDeletedFunction(FD);
303       return true;
304     }
305 
306     // If the function has a deduced return type, and we can't deduce it,
307     // then we can't use it either.
308     if (getLangOpts().CPlusPlus1y && FD->getResultType()->isUndeducedType() &&
309         DeduceReturnType(FD, Loc))
310       return true;
311   }
312   DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass);
313 
314   DiagnoseUnusedOfDecl(*this, D, Loc);
315 
316   diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
317 
318   return false;
319 }
320 
321 /// \brief Retrieve the message suffix that should be added to a
322 /// diagnostic complaining about the given function being deleted or
323 /// unavailable.
324 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
325   std::string Message;
326   if (FD->getAvailability(&Message))
327     return ": " + Message;
328 
329   return std::string();
330 }
331 
332 /// DiagnoseSentinelCalls - This routine checks whether a call or
333 /// message-send is to a declaration with the sentinel attribute, and
334 /// if so, it checks that the requirements of the sentinel are
335 /// satisfied.
336 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
337                                  ArrayRef<Expr *> Args) {
338   const SentinelAttr *attr = D->getAttr<SentinelAttr>();
339   if (!attr)
340     return;
341 
342   // The number of formal parameters of the declaration.
343   unsigned numFormalParams;
344 
345   // The kind of declaration.  This is also an index into a %select in
346   // the diagnostic.
347   enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
348 
349   if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
350     numFormalParams = MD->param_size();
351     calleeType = CT_Method;
352   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
353     numFormalParams = FD->param_size();
354     calleeType = CT_Function;
355   } else if (isa<VarDecl>(D)) {
356     QualType type = cast<ValueDecl>(D)->getType();
357     const FunctionType *fn = 0;
358     if (const PointerType *ptr = type->getAs<PointerType>()) {
359       fn = ptr->getPointeeType()->getAs<FunctionType>();
360       if (!fn) return;
361       calleeType = CT_Function;
362     } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
363       fn = ptr->getPointeeType()->castAs<FunctionType>();
364       calleeType = CT_Block;
365     } else {
366       return;
367     }
368 
369     if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
370       numFormalParams = proto->getNumArgs();
371     } else {
372       numFormalParams = 0;
373     }
374   } else {
375     return;
376   }
377 
378   // "nullPos" is the number of formal parameters at the end which
379   // effectively count as part of the variadic arguments.  This is
380   // useful if you would prefer to not have *any* formal parameters,
381   // but the language forces you to have at least one.
382   unsigned nullPos = attr->getNullPos();
383   assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
384   numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
385 
386   // The number of arguments which should follow the sentinel.
387   unsigned numArgsAfterSentinel = attr->getSentinel();
388 
389   // If there aren't enough arguments for all the formal parameters,
390   // the sentinel, and the args after the sentinel, complain.
391   if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
392     Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
393     Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
394     return;
395   }
396 
397   // Otherwise, find the sentinel expression.
398   Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
399   if (!sentinelExpr) return;
400   if (sentinelExpr->isValueDependent()) return;
401   if (Context.isSentinelNullExpr(sentinelExpr)) return;
402 
403   // Pick a reasonable string to insert.  Optimistically use 'nil' or
404   // 'NULL' if those are actually defined in the context.  Only use
405   // 'nil' for ObjC methods, where it's much more likely that the
406   // variadic arguments form a list of object pointers.
407   SourceLocation MissingNilLoc
408     = PP.getLocForEndOfToken(sentinelExpr->getLocEnd());
409   std::string NullValue;
410   if (calleeType == CT_Method &&
411       PP.getIdentifierInfo("nil")->hasMacroDefinition())
412     NullValue = "nil";
413   else if (PP.getIdentifierInfo("NULL")->hasMacroDefinition())
414     NullValue = "NULL";
415   else
416     NullValue = "(void*) 0";
417 
418   if (MissingNilLoc.isInvalid())
419     Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
420   else
421     Diag(MissingNilLoc, diag::warn_missing_sentinel)
422       << int(calleeType)
423       << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
424   Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
425 }
426 
427 SourceRange Sema::getExprRange(Expr *E) const {
428   return E ? E->getSourceRange() : SourceRange();
429 }
430 
431 //===----------------------------------------------------------------------===//
432 //  Standard Promotions and Conversions
433 //===----------------------------------------------------------------------===//
434 
435 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
436 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) {
437   // Handle any placeholder expressions which made it here.
438   if (E->getType()->isPlaceholderType()) {
439     ExprResult result = CheckPlaceholderExpr(E);
440     if (result.isInvalid()) return ExprError();
441     E = result.take();
442   }
443 
444   QualType Ty = E->getType();
445   assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
446 
447   if (Ty->isFunctionType())
448     E = ImpCastExprToType(E, Context.getPointerType(Ty),
449                           CK_FunctionToPointerDecay).take();
450   else if (Ty->isArrayType()) {
451     // In C90 mode, arrays only promote to pointers if the array expression is
452     // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
453     // type 'array of type' is converted to an expression that has type 'pointer
454     // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
455     // that has type 'array of type' ...".  The relevant change is "an lvalue"
456     // (C90) to "an expression" (C99).
457     //
458     // C++ 4.2p1:
459     // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
460     // T" can be converted to an rvalue of type "pointer to T".
461     //
462     if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
463       E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
464                             CK_ArrayToPointerDecay).take();
465   }
466   return Owned(E);
467 }
468 
469 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
470   // Check to see if we are dereferencing a null pointer.  If so,
471   // and if not volatile-qualified, this is undefined behavior that the
472   // optimizer will delete, so warn about it.  People sometimes try to use this
473   // to get a deterministic trap and are surprised by clang's behavior.  This
474   // only handles the pattern "*null", which is a very syntactic check.
475   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
476     if (UO->getOpcode() == UO_Deref &&
477         UO->getSubExpr()->IgnoreParenCasts()->
478           isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
479         !UO->getType().isVolatileQualified()) {
480     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
481                           S.PDiag(diag::warn_indirection_through_null)
482                             << UO->getSubExpr()->getSourceRange());
483     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
484                         S.PDiag(diag::note_indirection_through_null));
485   }
486 }
487 
488 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
489                                     SourceLocation AssignLoc,
490                                     const Expr* RHS) {
491   const ObjCIvarDecl *IV = OIRE->getDecl();
492   if (!IV)
493     return;
494 
495   DeclarationName MemberName = IV->getDeclName();
496   IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
497   if (!Member || !Member->isStr("isa"))
498     return;
499 
500   const Expr *Base = OIRE->getBase();
501   QualType BaseType = Base->getType();
502   if (OIRE->isArrow())
503     BaseType = BaseType->getPointeeType();
504   if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
505     if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
506       ObjCInterfaceDecl *ClassDeclared = 0;
507       ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
508       if (!ClassDeclared->getSuperClass()
509           && (*ClassDeclared->ivar_begin()) == IV) {
510         if (RHS) {
511           NamedDecl *ObjectSetClass =
512             S.LookupSingleName(S.TUScope,
513                                &S.Context.Idents.get("object_setClass"),
514                                SourceLocation(), S.LookupOrdinaryName);
515           if (ObjectSetClass) {
516             SourceLocation RHSLocEnd = S.PP.getLocForEndOfToken(RHS->getLocEnd());
517             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) <<
518             FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") <<
519             FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(),
520                                                      AssignLoc), ",") <<
521             FixItHint::CreateInsertion(RHSLocEnd, ")");
522           }
523           else
524             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
525         } else {
526           NamedDecl *ObjectGetClass =
527             S.LookupSingleName(S.TUScope,
528                                &S.Context.Idents.get("object_getClass"),
529                                SourceLocation(), S.LookupOrdinaryName);
530           if (ObjectGetClass)
531             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) <<
532             FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") <<
533             FixItHint::CreateReplacement(
534                                          SourceRange(OIRE->getOpLoc(),
535                                                      OIRE->getLocEnd()), ")");
536           else
537             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
538         }
539         S.Diag(IV->getLocation(), diag::note_ivar_decl);
540       }
541     }
542 }
543 
544 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
545   // Handle any placeholder expressions which made it here.
546   if (E->getType()->isPlaceholderType()) {
547     ExprResult result = CheckPlaceholderExpr(E);
548     if (result.isInvalid()) return ExprError();
549     E = result.take();
550   }
551 
552   // C++ [conv.lval]p1:
553   //   A glvalue of a non-function, non-array type T can be
554   //   converted to a prvalue.
555   if (!E->isGLValue()) return Owned(E);
556 
557   QualType T = E->getType();
558   assert(!T.isNull() && "r-value conversion on typeless expression?");
559 
560   // We don't want to throw lvalue-to-rvalue casts on top of
561   // expressions of certain types in C++.
562   if (getLangOpts().CPlusPlus &&
563       (E->getType() == Context.OverloadTy ||
564        T->isDependentType() ||
565        T->isRecordType()))
566     return Owned(E);
567 
568   // The C standard is actually really unclear on this point, and
569   // DR106 tells us what the result should be but not why.  It's
570   // generally best to say that void types just doesn't undergo
571   // lvalue-to-rvalue at all.  Note that expressions of unqualified
572   // 'void' type are never l-values, but qualified void can be.
573   if (T->isVoidType())
574     return Owned(E);
575 
576   // OpenCL usually rejects direct accesses to values of 'half' type.
577   if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16 &&
578       T->isHalfType()) {
579     Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
580       << 0 << T;
581     return ExprError();
582   }
583 
584   CheckForNullPointerDereference(*this, E);
585   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
586     NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
587                                      &Context.Idents.get("object_getClass"),
588                                      SourceLocation(), LookupOrdinaryName);
589     if (ObjectGetClass)
590       Diag(E->getExprLoc(), diag::warn_objc_isa_use) <<
591         FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") <<
592         FixItHint::CreateReplacement(
593                     SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
594     else
595       Diag(E->getExprLoc(), diag::warn_objc_isa_use);
596   }
597   else if (const ObjCIvarRefExpr *OIRE =
598             dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
599     DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/0);
600 
601   // C++ [conv.lval]p1:
602   //   [...] If T is a non-class type, the type of the prvalue is the
603   //   cv-unqualified version of T. Otherwise, the type of the
604   //   rvalue is T.
605   //
606   // C99 6.3.2.1p2:
607   //   If the lvalue has qualified type, the value has the unqualified
608   //   version of the type of the lvalue; otherwise, the value has the
609   //   type of the lvalue.
610   if (T.hasQualifiers())
611     T = T.getUnqualifiedType();
612 
613   UpdateMarkingForLValueToRValue(E);
614 
615   // Loading a __weak object implicitly retains the value, so we need a cleanup to
616   // balance that.
617   if (getLangOpts().ObjCAutoRefCount &&
618       E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
619     ExprNeedsCleanups = true;
620 
621   ExprResult Res = Owned(ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
622                                                   E, 0, VK_RValue));
623 
624   // C11 6.3.2.1p2:
625   //   ... if the lvalue has atomic type, the value has the non-atomic version
626   //   of the type of the lvalue ...
627   if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
628     T = Atomic->getValueType().getUnqualifiedType();
629     Res = Owned(ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic,
630                                          Res.get(), 0, VK_RValue));
631   }
632 
633   return Res;
634 }
635 
636 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) {
637   ExprResult Res = DefaultFunctionArrayConversion(E);
638   if (Res.isInvalid())
639     return ExprError();
640   Res = DefaultLvalueConversion(Res.take());
641   if (Res.isInvalid())
642     return ExprError();
643   return Res;
644 }
645 
646 
647 /// UsualUnaryConversions - Performs various conversions that are common to most
648 /// operators (C99 6.3). The conversions of array and function types are
649 /// sometimes suppressed. For example, the array->pointer conversion doesn't
650 /// apply if the array is an argument to the sizeof or address (&) operators.
651 /// In these instances, this routine should *not* be called.
652 ExprResult Sema::UsualUnaryConversions(Expr *E) {
653   // First, convert to an r-value.
654   ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
655   if (Res.isInvalid())
656     return ExprError();
657   E = Res.take();
658 
659   QualType Ty = E->getType();
660   assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
661 
662   // Half FP have to be promoted to float unless it is natively supported
663   if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
664     return ImpCastExprToType(Res.take(), Context.FloatTy, CK_FloatingCast);
665 
666   // Try to perform integral promotions if the object has a theoretically
667   // promotable type.
668   if (Ty->isIntegralOrUnscopedEnumerationType()) {
669     // C99 6.3.1.1p2:
670     //
671     //   The following may be used in an expression wherever an int or
672     //   unsigned int may be used:
673     //     - an object or expression with an integer type whose integer
674     //       conversion rank is less than or equal to the rank of int
675     //       and unsigned int.
676     //     - A bit-field of type _Bool, int, signed int, or unsigned int.
677     //
678     //   If an int can represent all values of the original type, the
679     //   value is converted to an int; otherwise, it is converted to an
680     //   unsigned int. These are called the integer promotions. All
681     //   other types are unchanged by the integer promotions.
682 
683     QualType PTy = Context.isPromotableBitField(E);
684     if (!PTy.isNull()) {
685       E = ImpCastExprToType(E, PTy, CK_IntegralCast).take();
686       return Owned(E);
687     }
688     if (Ty->isPromotableIntegerType()) {
689       QualType PT = Context.getPromotedIntegerType(Ty);
690       E = ImpCastExprToType(E, PT, CK_IntegralCast).take();
691       return Owned(E);
692     }
693   }
694   return Owned(E);
695 }
696 
697 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
698 /// do not have a prototype. Arguments that have type float or __fp16
699 /// are promoted to double. All other argument types are converted by
700 /// UsualUnaryConversions().
701 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
702   QualType Ty = E->getType();
703   assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
704 
705   ExprResult Res = UsualUnaryConversions(E);
706   if (Res.isInvalid())
707     return ExprError();
708   E = Res.take();
709 
710   // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to
711   // double.
712   const BuiltinType *BTy = Ty->getAs<BuiltinType>();
713   if (BTy && (BTy->getKind() == BuiltinType::Half ||
714               BTy->getKind() == BuiltinType::Float))
715     E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).take();
716 
717   // C++ performs lvalue-to-rvalue conversion as a default argument
718   // promotion, even on class types, but note:
719   //   C++11 [conv.lval]p2:
720   //     When an lvalue-to-rvalue conversion occurs in an unevaluated
721   //     operand or a subexpression thereof the value contained in the
722   //     referenced object is not accessed. Otherwise, if the glvalue
723   //     has a class type, the conversion copy-initializes a temporary
724   //     of type T from the glvalue and the result of the conversion
725   //     is a prvalue for the temporary.
726   // FIXME: add some way to gate this entire thing for correctness in
727   // potentially potentially evaluated contexts.
728   if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
729     ExprResult Temp = PerformCopyInitialization(
730                        InitializedEntity::InitializeTemporary(E->getType()),
731                                                 E->getExprLoc(),
732                                                 Owned(E));
733     if (Temp.isInvalid())
734       return ExprError();
735     E = Temp.get();
736   }
737 
738   return Owned(E);
739 }
740 
741 /// Determine the degree of POD-ness for an expression.
742 /// Incomplete types are considered POD, since this check can be performed
743 /// when we're in an unevaluated context.
744 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
745   if (Ty->isIncompleteType()) {
746     // C++11 [expr.call]p7:
747     //   After these conversions, if the argument does not have arithmetic,
748     //   enumeration, pointer, pointer to member, or class type, the program
749     //   is ill-formed.
750     //
751     // Since we've already performed array-to-pointer and function-to-pointer
752     // decay, the only such type in C++ is cv void. This also handles
753     // initializer lists as variadic arguments.
754     if (Ty->isVoidType())
755       return VAK_Invalid;
756 
757     if (Ty->isObjCObjectType())
758       return VAK_Invalid;
759     return VAK_Valid;
760   }
761 
762   if (Ty.isCXX98PODType(Context))
763     return VAK_Valid;
764 
765   // C++11 [expr.call]p7:
766   //   Passing a potentially-evaluated argument of class type (Clause 9)
767   //   having a non-trivial copy constructor, a non-trivial move constructor,
768   //   or a non-trivial destructor, with no corresponding parameter,
769   //   is conditionally-supported with implementation-defined semantics.
770   if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
771     if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
772       if (!Record->hasNonTrivialCopyConstructor() &&
773           !Record->hasNonTrivialMoveConstructor() &&
774           !Record->hasNonTrivialDestructor())
775         return VAK_ValidInCXX11;
776 
777   if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
778     return VAK_Valid;
779 
780   if (Ty->isObjCObjectType())
781     return VAK_Invalid;
782 
783   // FIXME: In C++11, these cases are conditionally-supported, meaning we're
784   // permitted to reject them. We should consider doing so.
785   return VAK_Undefined;
786 }
787 
788 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
789   // Don't allow one to pass an Objective-C interface to a vararg.
790   const QualType &Ty = E->getType();
791   VarArgKind VAK = isValidVarArgType(Ty);
792 
793   // Complain about passing non-POD types through varargs.
794   switch (VAK) {
795   case VAK_Valid:
796     break;
797 
798   case VAK_ValidInCXX11:
799     DiagRuntimeBehavior(
800         E->getLocStart(), 0,
801         PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
802           << E->getType() << CT);
803     break;
804 
805   case VAK_Undefined:
806     DiagRuntimeBehavior(
807         E->getLocStart(), 0,
808         PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
809           << getLangOpts().CPlusPlus11 << Ty << CT);
810     break;
811 
812   case VAK_Invalid:
813     if (Ty->isObjCObjectType())
814       DiagRuntimeBehavior(
815           E->getLocStart(), 0,
816           PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
817             << Ty << CT);
818     else
819       Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg)
820         << isa<InitListExpr>(E) << Ty << CT;
821     break;
822   }
823 }
824 
825 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
826 /// will create a trap if the resulting type is not a POD type.
827 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
828                                                   FunctionDecl *FDecl) {
829   if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
830     // Strip the unbridged-cast placeholder expression off, if applicable.
831     if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
832         (CT == VariadicMethod ||
833          (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
834       E = stripARCUnbridgedCast(E);
835 
836     // Otherwise, do normal placeholder checking.
837     } else {
838       ExprResult ExprRes = CheckPlaceholderExpr(E);
839       if (ExprRes.isInvalid())
840         return ExprError();
841       E = ExprRes.take();
842     }
843   }
844 
845   ExprResult ExprRes = DefaultArgumentPromotion(E);
846   if (ExprRes.isInvalid())
847     return ExprError();
848   E = ExprRes.take();
849 
850   // Diagnostics regarding non-POD argument types are
851   // emitted along with format string checking in Sema::CheckFunctionCall().
852   if (isValidVarArgType(E->getType()) == VAK_Undefined) {
853     // Turn this into a trap.
854     CXXScopeSpec SS;
855     SourceLocation TemplateKWLoc;
856     UnqualifiedId Name;
857     Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
858                        E->getLocStart());
859     ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
860                                           Name, true, false);
861     if (TrapFn.isInvalid())
862       return ExprError();
863 
864     ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(),
865                                     E->getLocStart(), None,
866                                     E->getLocEnd());
867     if (Call.isInvalid())
868       return ExprError();
869 
870     ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
871                                   Call.get(), E);
872     if (Comma.isInvalid())
873       return ExprError();
874     return Comma.get();
875   }
876 
877   if (!getLangOpts().CPlusPlus &&
878       RequireCompleteType(E->getExprLoc(), E->getType(),
879                           diag::err_call_incomplete_argument))
880     return ExprError();
881 
882   return Owned(E);
883 }
884 
885 /// \brief Converts an integer to complex float type.  Helper function of
886 /// UsualArithmeticConversions()
887 ///
888 /// \return false if the integer expression is an integer type and is
889 /// successfully converted to the complex type.
890 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
891                                                   ExprResult &ComplexExpr,
892                                                   QualType IntTy,
893                                                   QualType ComplexTy,
894                                                   bool SkipCast) {
895   if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
896   if (SkipCast) return false;
897   if (IntTy->isIntegerType()) {
898     QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
899     IntExpr = S.ImpCastExprToType(IntExpr.take(), fpTy, CK_IntegralToFloating);
900     IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
901                                   CK_FloatingRealToComplex);
902   } else {
903     assert(IntTy->isComplexIntegerType());
904     IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
905                                   CK_IntegralComplexToFloatingComplex);
906   }
907   return false;
908 }
909 
910 /// \brief Takes two complex float types and converts them to the same type.
911 /// Helper function of UsualArithmeticConversions()
912 static QualType
913 handleComplexFloatToComplexFloatConverstion(Sema &S, ExprResult &LHS,
914                                             ExprResult &RHS, QualType LHSType,
915                                             QualType RHSType,
916                                             bool IsCompAssign) {
917   int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
918 
919   if (order < 0) {
920     // _Complex float -> _Complex double
921     if (!IsCompAssign)
922       LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingComplexCast);
923     return RHSType;
924   }
925   if (order > 0)
926     // _Complex float -> _Complex double
927     RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingComplexCast);
928   return LHSType;
929 }
930 
931 /// \brief Converts otherExpr to complex float and promotes complexExpr if
932 /// necessary.  Helper function of UsualArithmeticConversions()
933 static QualType handleOtherComplexFloatConversion(Sema &S,
934                                                   ExprResult &ComplexExpr,
935                                                   ExprResult &OtherExpr,
936                                                   QualType ComplexTy,
937                                                   QualType OtherTy,
938                                                   bool ConvertComplexExpr,
939                                                   bool ConvertOtherExpr) {
940   int order = S.Context.getFloatingTypeOrder(ComplexTy, OtherTy);
941 
942   // If just the complexExpr is complex, the otherExpr needs to be converted,
943   // and the complexExpr might need to be promoted.
944   if (order > 0) { // complexExpr is wider
945     // float -> _Complex double
946     if (ConvertOtherExpr) {
947       QualType fp = cast<ComplexType>(ComplexTy)->getElementType();
948       OtherExpr = S.ImpCastExprToType(OtherExpr.take(), fp, CK_FloatingCast);
949       OtherExpr = S.ImpCastExprToType(OtherExpr.take(), ComplexTy,
950                                       CK_FloatingRealToComplex);
951     }
952     return ComplexTy;
953   }
954 
955   // otherTy is at least as wide.  Find its corresponding complex type.
956   QualType result = (order == 0 ? ComplexTy :
957                                   S.Context.getComplexType(OtherTy));
958 
959   // double -> _Complex double
960   if (ConvertOtherExpr)
961     OtherExpr = S.ImpCastExprToType(OtherExpr.take(), result,
962                                     CK_FloatingRealToComplex);
963 
964   // _Complex float -> _Complex double
965   if (ConvertComplexExpr && order < 0)
966     ComplexExpr = S.ImpCastExprToType(ComplexExpr.take(), result,
967                                       CK_FloatingComplexCast);
968 
969   return result;
970 }
971 
972 /// \brief Handle arithmetic conversion with complex types.  Helper function of
973 /// UsualArithmeticConversions()
974 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
975                                              ExprResult &RHS, QualType LHSType,
976                                              QualType RHSType,
977                                              bool IsCompAssign) {
978   // if we have an integer operand, the result is the complex type.
979   if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
980                                              /*skipCast*/false))
981     return LHSType;
982   if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
983                                              /*skipCast*/IsCompAssign))
984     return RHSType;
985 
986   // This handles complex/complex, complex/float, or float/complex.
987   // When both operands are complex, the shorter operand is converted to the
988   // type of the longer, and that is the type of the result. This corresponds
989   // to what is done when combining two real floating-point operands.
990   // The fun begins when size promotion occur across type domains.
991   // From H&S 6.3.4: When one operand is complex and the other is a real
992   // floating-point type, the less precise type is converted, within it's
993   // real or complex domain, to the precision of the other type. For example,
994   // when combining a "long double" with a "double _Complex", the
995   // "double _Complex" is promoted to "long double _Complex".
996 
997   bool LHSComplexFloat = LHSType->isComplexType();
998   bool RHSComplexFloat = RHSType->isComplexType();
999 
1000   // If both are complex, just cast to the more precise type.
1001   if (LHSComplexFloat && RHSComplexFloat)
1002     return handleComplexFloatToComplexFloatConverstion(S, LHS, RHS,
1003                                                        LHSType, RHSType,
1004                                                        IsCompAssign);
1005 
1006   // If only one operand is complex, promote it if necessary and convert the
1007   // other operand to complex.
1008   if (LHSComplexFloat)
1009     return handleOtherComplexFloatConversion(
1010         S, LHS, RHS, LHSType, RHSType, /*convertComplexExpr*/!IsCompAssign,
1011         /*convertOtherExpr*/ true);
1012 
1013   assert(RHSComplexFloat);
1014   return handleOtherComplexFloatConversion(
1015       S, RHS, LHS, RHSType, LHSType, /*convertComplexExpr*/true,
1016       /*convertOtherExpr*/ !IsCompAssign);
1017 }
1018 
1019 /// \brief Hande arithmetic conversion from integer to float.  Helper function
1020 /// of UsualArithmeticConversions()
1021 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1022                                            ExprResult &IntExpr,
1023                                            QualType FloatTy, QualType IntTy,
1024                                            bool ConvertFloat, bool ConvertInt) {
1025   if (IntTy->isIntegerType()) {
1026     if (ConvertInt)
1027       // Convert intExpr to the lhs floating point type.
1028       IntExpr = S.ImpCastExprToType(IntExpr.take(), FloatTy,
1029                                     CK_IntegralToFloating);
1030     return FloatTy;
1031   }
1032 
1033   // Convert both sides to the appropriate complex float.
1034   assert(IntTy->isComplexIntegerType());
1035   QualType result = S.Context.getComplexType(FloatTy);
1036 
1037   // _Complex int -> _Complex float
1038   if (ConvertInt)
1039     IntExpr = S.ImpCastExprToType(IntExpr.take(), result,
1040                                   CK_IntegralComplexToFloatingComplex);
1041 
1042   // float -> _Complex float
1043   if (ConvertFloat)
1044     FloatExpr = S.ImpCastExprToType(FloatExpr.take(), result,
1045                                     CK_FloatingRealToComplex);
1046 
1047   return result;
1048 }
1049 
1050 /// \brief Handle arithmethic conversion with floating point types.  Helper
1051 /// function of UsualArithmeticConversions()
1052 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1053                                       ExprResult &RHS, QualType LHSType,
1054                                       QualType RHSType, bool IsCompAssign) {
1055   bool LHSFloat = LHSType->isRealFloatingType();
1056   bool RHSFloat = RHSType->isRealFloatingType();
1057 
1058   // If we have two real floating types, convert the smaller operand
1059   // to the bigger result.
1060   if (LHSFloat && RHSFloat) {
1061     int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1062     if (order > 0) {
1063       RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingCast);
1064       return LHSType;
1065     }
1066 
1067     assert(order < 0 && "illegal float comparison");
1068     if (!IsCompAssign)
1069       LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingCast);
1070     return RHSType;
1071   }
1072 
1073   if (LHSFloat)
1074     return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1075                                       /*convertFloat=*/!IsCompAssign,
1076                                       /*convertInt=*/ true);
1077   assert(RHSFloat);
1078   return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1079                                     /*convertInt=*/ true,
1080                                     /*convertFloat=*/!IsCompAssign);
1081 }
1082 
1083 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1084 
1085 namespace {
1086 /// These helper callbacks are placed in an anonymous namespace to
1087 /// permit their use as function template parameters.
1088 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1089   return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1090 }
1091 
1092 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1093   return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1094                              CK_IntegralComplexCast);
1095 }
1096 }
1097 
1098 /// \brief Handle integer arithmetic conversions.  Helper function of
1099 /// UsualArithmeticConversions()
1100 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1101 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1102                                         ExprResult &RHS, QualType LHSType,
1103                                         QualType RHSType, bool IsCompAssign) {
1104   // The rules for this case are in C99 6.3.1.8
1105   int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1106   bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1107   bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1108   if (LHSSigned == RHSSigned) {
1109     // Same signedness; use the higher-ranked type
1110     if (order >= 0) {
1111       RHS = (*doRHSCast)(S, RHS.take(), LHSType);
1112       return LHSType;
1113     } else if (!IsCompAssign)
1114       LHS = (*doLHSCast)(S, LHS.take(), RHSType);
1115     return RHSType;
1116   } else if (order != (LHSSigned ? 1 : -1)) {
1117     // The unsigned type has greater than or equal rank to the
1118     // signed type, so use the unsigned type
1119     if (RHSSigned) {
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 if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1126     // The two types are different widths; if we are here, that
1127     // means the signed type is larger than the unsigned type, so
1128     // use the signed type.
1129     if (LHSSigned) {
1130       RHS = (*doRHSCast)(S, RHS.take(), LHSType);
1131       return LHSType;
1132     } else if (!IsCompAssign)
1133       LHS = (*doLHSCast)(S, LHS.take(), RHSType);
1134     return RHSType;
1135   } else {
1136     // The signed type is higher-ranked than the unsigned type,
1137     // but isn't actually any bigger (like unsigned int and long
1138     // on most 32-bit systems).  Use the unsigned type corresponding
1139     // to the signed type.
1140     QualType result =
1141       S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1142     RHS = (*doRHSCast)(S, RHS.take(), result);
1143     if (!IsCompAssign)
1144       LHS = (*doLHSCast)(S, LHS.take(), result);
1145     return result;
1146   }
1147 }
1148 
1149 /// \brief Handle conversions with GCC complex int extension.  Helper function
1150 /// of UsualArithmeticConversions()
1151 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1152                                            ExprResult &RHS, QualType LHSType,
1153                                            QualType RHSType,
1154                                            bool IsCompAssign) {
1155   const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1156   const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1157 
1158   if (LHSComplexInt && RHSComplexInt) {
1159     QualType LHSEltType = LHSComplexInt->getElementType();
1160     QualType RHSEltType = RHSComplexInt->getElementType();
1161     QualType ScalarType =
1162       handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1163         (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1164 
1165     return S.Context.getComplexType(ScalarType);
1166   }
1167 
1168   if (LHSComplexInt) {
1169     QualType LHSEltType = LHSComplexInt->getElementType();
1170     QualType ScalarType =
1171       handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1172         (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1173     QualType ComplexType = S.Context.getComplexType(ScalarType);
1174     RHS = S.ImpCastExprToType(RHS.take(), ComplexType,
1175                               CK_IntegralRealToComplex);
1176 
1177     return ComplexType;
1178   }
1179 
1180   assert(RHSComplexInt);
1181 
1182   QualType RHSEltType = RHSComplexInt->getElementType();
1183   QualType ScalarType =
1184     handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1185       (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1186   QualType ComplexType = S.Context.getComplexType(ScalarType);
1187 
1188   if (!IsCompAssign)
1189     LHS = S.ImpCastExprToType(LHS.take(), ComplexType,
1190                               CK_IntegralRealToComplex);
1191   return ComplexType;
1192 }
1193 
1194 /// UsualArithmeticConversions - Performs various conversions that are common to
1195 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1196 /// routine returns the first non-arithmetic type found. The client is
1197 /// responsible for emitting appropriate error diagnostics.
1198 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1199                                           bool IsCompAssign) {
1200   if (!IsCompAssign) {
1201     LHS = UsualUnaryConversions(LHS.take());
1202     if (LHS.isInvalid())
1203       return QualType();
1204   }
1205 
1206   RHS = UsualUnaryConversions(RHS.take());
1207   if (RHS.isInvalid())
1208     return QualType();
1209 
1210   // For conversion purposes, we ignore any qualifiers.
1211   // For example, "const float" and "float" are equivalent.
1212   QualType LHSType =
1213     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1214   QualType RHSType =
1215     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1216 
1217   // For conversion purposes, we ignore any atomic qualifier on the LHS.
1218   if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1219     LHSType = AtomicLHS->getValueType();
1220 
1221   // If both types are identical, no conversion is needed.
1222   if (LHSType == RHSType)
1223     return LHSType;
1224 
1225   // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1226   // The caller can deal with this (e.g. pointer + int).
1227   if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1228     return QualType();
1229 
1230   // Apply unary and bitfield promotions to the LHS's type.
1231   QualType LHSUnpromotedType = LHSType;
1232   if (LHSType->isPromotableIntegerType())
1233     LHSType = Context.getPromotedIntegerType(LHSType);
1234   QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1235   if (!LHSBitfieldPromoteTy.isNull())
1236     LHSType = LHSBitfieldPromoteTy;
1237   if (LHSType != LHSUnpromotedType && !IsCompAssign)
1238     LHS = ImpCastExprToType(LHS.take(), LHSType, CK_IntegralCast);
1239 
1240   // If both types are identical, no conversion is needed.
1241   if (LHSType == RHSType)
1242     return LHSType;
1243 
1244   // At this point, we have two different arithmetic types.
1245 
1246   // Handle complex types first (C99 6.3.1.8p1).
1247   if (LHSType->isComplexType() || RHSType->isComplexType())
1248     return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1249                                         IsCompAssign);
1250 
1251   // Now handle "real" floating types (i.e. float, double, long double).
1252   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1253     return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1254                                  IsCompAssign);
1255 
1256   // Handle GCC complex int extension.
1257   if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1258     return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1259                                       IsCompAssign);
1260 
1261   // Finally, we have two differing integer types.
1262   return handleIntegerConversion<doIntegralCast, doIntegralCast>
1263            (*this, LHS, RHS, LHSType, RHSType, IsCompAssign);
1264 }
1265 
1266 
1267 //===----------------------------------------------------------------------===//
1268 //  Semantic Analysis for various Expression Types
1269 //===----------------------------------------------------------------------===//
1270 
1271 
1272 ExprResult
1273 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1274                                 SourceLocation DefaultLoc,
1275                                 SourceLocation RParenLoc,
1276                                 Expr *ControllingExpr,
1277                                 ArrayRef<ParsedType> ArgTypes,
1278                                 ArrayRef<Expr *> ArgExprs) {
1279   unsigned NumAssocs = ArgTypes.size();
1280   assert(NumAssocs == ArgExprs.size());
1281 
1282   TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1283   for (unsigned i = 0; i < NumAssocs; ++i) {
1284     if (ArgTypes[i])
1285       (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1286     else
1287       Types[i] = 0;
1288   }
1289 
1290   ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1291                                              ControllingExpr,
1292                                              llvm::makeArrayRef(Types, NumAssocs),
1293                                              ArgExprs);
1294   delete [] Types;
1295   return ER;
1296 }
1297 
1298 ExprResult
1299 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1300                                  SourceLocation DefaultLoc,
1301                                  SourceLocation RParenLoc,
1302                                  Expr *ControllingExpr,
1303                                  ArrayRef<TypeSourceInfo *> Types,
1304                                  ArrayRef<Expr *> Exprs) {
1305   unsigned NumAssocs = Types.size();
1306   assert(NumAssocs == Exprs.size());
1307   if (ControllingExpr->getType()->isPlaceholderType()) {
1308     ExprResult result = CheckPlaceholderExpr(ControllingExpr);
1309     if (result.isInvalid()) return ExprError();
1310     ControllingExpr = result.take();
1311   }
1312 
1313   bool TypeErrorFound = false,
1314        IsResultDependent = ControllingExpr->isTypeDependent(),
1315        ContainsUnexpandedParameterPack
1316          = ControllingExpr->containsUnexpandedParameterPack();
1317 
1318   for (unsigned i = 0; i < NumAssocs; ++i) {
1319     if (Exprs[i]->containsUnexpandedParameterPack())
1320       ContainsUnexpandedParameterPack = true;
1321 
1322     if (Types[i]) {
1323       if (Types[i]->getType()->containsUnexpandedParameterPack())
1324         ContainsUnexpandedParameterPack = true;
1325 
1326       if (Types[i]->getType()->isDependentType()) {
1327         IsResultDependent = true;
1328       } else {
1329         // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1330         // complete object type other than a variably modified type."
1331         unsigned D = 0;
1332         if (Types[i]->getType()->isIncompleteType())
1333           D = diag::err_assoc_type_incomplete;
1334         else if (!Types[i]->getType()->isObjectType())
1335           D = diag::err_assoc_type_nonobject;
1336         else if (Types[i]->getType()->isVariablyModifiedType())
1337           D = diag::err_assoc_type_variably_modified;
1338 
1339         if (D != 0) {
1340           Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1341             << Types[i]->getTypeLoc().getSourceRange()
1342             << Types[i]->getType();
1343           TypeErrorFound = true;
1344         }
1345 
1346         // C11 6.5.1.1p2 "No two generic associations in the same generic
1347         // selection shall specify compatible types."
1348         for (unsigned j = i+1; j < NumAssocs; ++j)
1349           if (Types[j] && !Types[j]->getType()->isDependentType() &&
1350               Context.typesAreCompatible(Types[i]->getType(),
1351                                          Types[j]->getType())) {
1352             Diag(Types[j]->getTypeLoc().getBeginLoc(),
1353                  diag::err_assoc_compatible_types)
1354               << Types[j]->getTypeLoc().getSourceRange()
1355               << Types[j]->getType()
1356               << Types[i]->getType();
1357             Diag(Types[i]->getTypeLoc().getBeginLoc(),
1358                  diag::note_compat_assoc)
1359               << Types[i]->getTypeLoc().getSourceRange()
1360               << Types[i]->getType();
1361             TypeErrorFound = true;
1362           }
1363       }
1364     }
1365   }
1366   if (TypeErrorFound)
1367     return ExprError();
1368 
1369   // If we determined that the generic selection is result-dependent, don't
1370   // try to compute the result expression.
1371   if (IsResultDependent)
1372     return Owned(new (Context) GenericSelectionExpr(
1373                    Context, KeyLoc, ControllingExpr,
1374                    Types, Exprs,
1375                    DefaultLoc, RParenLoc, ContainsUnexpandedParameterPack));
1376 
1377   SmallVector<unsigned, 1> CompatIndices;
1378   unsigned DefaultIndex = -1U;
1379   for (unsigned i = 0; i < NumAssocs; ++i) {
1380     if (!Types[i])
1381       DefaultIndex = i;
1382     else if (Context.typesAreCompatible(ControllingExpr->getType(),
1383                                         Types[i]->getType()))
1384       CompatIndices.push_back(i);
1385   }
1386 
1387   // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1388   // type compatible with at most one of the types named in its generic
1389   // association list."
1390   if (CompatIndices.size() > 1) {
1391     // We strip parens here because the controlling expression is typically
1392     // parenthesized in macro definitions.
1393     ControllingExpr = ControllingExpr->IgnoreParens();
1394     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1395       << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1396       << (unsigned) CompatIndices.size();
1397     for (SmallVectorImpl<unsigned>::iterator I = CompatIndices.begin(),
1398          E = CompatIndices.end(); I != E; ++I) {
1399       Diag(Types[*I]->getTypeLoc().getBeginLoc(),
1400            diag::note_compat_assoc)
1401         << Types[*I]->getTypeLoc().getSourceRange()
1402         << Types[*I]->getType();
1403     }
1404     return ExprError();
1405   }
1406 
1407   // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1408   // its controlling expression shall have type compatible with exactly one of
1409   // the types named in its generic association list."
1410   if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1411     // We strip parens here because the controlling expression is typically
1412     // parenthesized in macro definitions.
1413     ControllingExpr = ControllingExpr->IgnoreParens();
1414     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1415       << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1416     return ExprError();
1417   }
1418 
1419   // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1420   // type name that is compatible with the type of the controlling expression,
1421   // then the result expression of the generic selection is the expression
1422   // in that generic association. Otherwise, the result expression of the
1423   // generic selection is the expression in the default generic association."
1424   unsigned ResultIndex =
1425     CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1426 
1427   return Owned(new (Context) GenericSelectionExpr(
1428                  Context, KeyLoc, ControllingExpr,
1429                  Types, Exprs,
1430                  DefaultLoc, RParenLoc, ContainsUnexpandedParameterPack,
1431                  ResultIndex));
1432 }
1433 
1434 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1435 /// location of the token and the offset of the ud-suffix within it.
1436 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1437                                      unsigned Offset) {
1438   return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1439                                         S.getLangOpts());
1440 }
1441 
1442 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1443 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1444 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1445                                                  IdentifierInfo *UDSuffix,
1446                                                  SourceLocation UDSuffixLoc,
1447                                                  ArrayRef<Expr*> Args,
1448                                                  SourceLocation LitEndLoc) {
1449   assert(Args.size() <= 2 && "too many arguments for literal operator");
1450 
1451   QualType ArgTy[2];
1452   for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1453     ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1454     if (ArgTy[ArgIdx]->isArrayType())
1455       ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1456   }
1457 
1458   DeclarationName OpName =
1459     S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1460   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1461   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1462 
1463   LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1464   if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1465                               /*AllowRaw*/false, /*AllowTemplate*/false,
1466                               /*AllowStringTemplate*/false) == Sema::LOLR_Error)
1467     return ExprError();
1468 
1469   return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1470 }
1471 
1472 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1473 /// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
1474 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1475 /// multiple tokens.  However, the common case is that StringToks points to one
1476 /// string.
1477 ///
1478 ExprResult
1479 Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks,
1480                          Scope *UDLScope) {
1481   assert(NumStringToks && "Must have at least one string!");
1482 
1483   StringLiteralParser Literal(StringToks, NumStringToks, PP);
1484   if (Literal.hadError)
1485     return ExprError();
1486 
1487   SmallVector<SourceLocation, 4> StringTokLocs;
1488   for (unsigned i = 0; i != NumStringToks; ++i)
1489     StringTokLocs.push_back(StringToks[i].getLocation());
1490 
1491   QualType CharTy = Context.CharTy;
1492   StringLiteral::StringKind Kind = StringLiteral::Ascii;
1493   if (Literal.isWide()) {
1494     CharTy = Context.getWideCharType();
1495     Kind = StringLiteral::Wide;
1496   } else if (Literal.isUTF8()) {
1497     Kind = StringLiteral::UTF8;
1498   } else if (Literal.isUTF16()) {
1499     CharTy = Context.Char16Ty;
1500     Kind = StringLiteral::UTF16;
1501   } else if (Literal.isUTF32()) {
1502     CharTy = Context.Char32Ty;
1503     Kind = StringLiteral::UTF32;
1504   } else if (Literal.isPascal()) {
1505     CharTy = Context.UnsignedCharTy;
1506   }
1507 
1508   QualType CharTyConst = CharTy;
1509   // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
1510   if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
1511     CharTyConst.addConst();
1512 
1513   // Get an array type for the string, according to C99 6.4.5.  This includes
1514   // the nul terminator character as well as the string length for pascal
1515   // strings.
1516   QualType StrTy = Context.getConstantArrayType(CharTyConst,
1517                                  llvm::APInt(32, Literal.GetNumStringChars()+1),
1518                                  ArrayType::Normal, 0);
1519 
1520   // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
1521   if (getLangOpts().OpenCL) {
1522     StrTy = Context.getAddrSpaceQualType(StrTy, LangAS::opencl_constant);
1523   }
1524 
1525   // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1526   StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1527                                              Kind, Literal.Pascal, StrTy,
1528                                              &StringTokLocs[0],
1529                                              StringTokLocs.size());
1530   if (Literal.getUDSuffix().empty())
1531     return Owned(Lit);
1532 
1533   // We're building a user-defined literal.
1534   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1535   SourceLocation UDSuffixLoc =
1536     getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1537                    Literal.getUDSuffixOffset());
1538 
1539   // Make sure we're allowed user-defined literals here.
1540   if (!UDLScope)
1541     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1542 
1543   // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1544   //   operator "" X (str, len)
1545   QualType SizeType = Context.getSizeType();
1546 
1547   DeclarationName OpName =
1548     Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1549   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1550   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1551 
1552   QualType ArgTy[] = {
1553     Context.getArrayDecayedType(StrTy), SizeType
1554   };
1555 
1556   LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1557   switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1558                                 /*AllowRaw*/false, /*AllowTemplate*/false,
1559                                 /*AllowStringTemplate*/true)) {
1560 
1561   case LOLR_Cooked: {
1562     llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1563     IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1564                                                     StringTokLocs[0]);
1565     Expr *Args[] = { Lit, LenArg };
1566 
1567     return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1568   }
1569 
1570   case LOLR_StringTemplate: {
1571     TemplateArgumentListInfo ExplicitArgs;
1572 
1573     unsigned CharBits = Context.getIntWidth(CharTy);
1574     bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1575     llvm::APSInt Value(CharBits, CharIsUnsigned);
1576 
1577     TemplateArgument TypeArg(CharTy);
1578     TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1579     ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1580 
1581     for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1582       Value = Lit->getCodeUnit(I);
1583       TemplateArgument Arg(Context, Value, CharTy);
1584       TemplateArgumentLocInfo ArgInfo;
1585       ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1586     }
1587     return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1588                                     &ExplicitArgs);
1589   }
1590   case LOLR_Raw:
1591   case LOLR_Template:
1592     llvm_unreachable("unexpected literal operator lookup result");
1593   case LOLR_Error:
1594     return ExprError();
1595   }
1596   llvm_unreachable("unexpected literal operator lookup result");
1597 }
1598 
1599 ExprResult
1600 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1601                        SourceLocation Loc,
1602                        const CXXScopeSpec *SS) {
1603   DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1604   return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1605 }
1606 
1607 /// BuildDeclRefExpr - Build an expression that references a
1608 /// declaration that does not require a closure capture.
1609 ExprResult
1610 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1611                        const DeclarationNameInfo &NameInfo,
1612                        const CXXScopeSpec *SS, NamedDecl *FoundD,
1613                        const TemplateArgumentListInfo *TemplateArgs) {
1614   if (getLangOpts().CUDA)
1615     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
1616       if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) {
1617         CUDAFunctionTarget CallerTarget = IdentifyCUDATarget(Caller),
1618                            CalleeTarget = IdentifyCUDATarget(Callee);
1619         if (CheckCUDATarget(CallerTarget, CalleeTarget)) {
1620           Diag(NameInfo.getLoc(), diag::err_ref_bad_target)
1621             << CalleeTarget << D->getIdentifier() << CallerTarget;
1622           Diag(D->getLocation(), diag::note_previous_decl)
1623             << D->getIdentifier();
1624           return ExprError();
1625         }
1626       }
1627 
1628   bool refersToEnclosingScope =
1629     (CurContext != D->getDeclContext() &&
1630      D->getDeclContext()->isFunctionOrMethod()) ||
1631     (isa<VarDecl>(D) &&
1632      cast<VarDecl>(D)->isInitCapture());
1633 
1634   DeclRefExpr *E;
1635   if (isa<VarTemplateSpecializationDecl>(D)) {
1636     VarTemplateSpecializationDecl *VarSpec =
1637         cast<VarTemplateSpecializationDecl>(D);
1638 
1639     E = DeclRefExpr::Create(
1640         Context,
1641         SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(),
1642         VarSpec->getTemplateKeywordLoc(), D, refersToEnclosingScope,
1643         NameInfo.getLoc(), Ty, VK, FoundD, TemplateArgs);
1644   } else {
1645     assert(!TemplateArgs && "No template arguments for non-variable"
1646                             " template specialization referrences");
1647     E = DeclRefExpr::Create(
1648         Context,
1649         SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(),
1650         SourceLocation(), D, refersToEnclosingScope, NameInfo, Ty, VK, FoundD);
1651   }
1652 
1653   MarkDeclRefReferenced(E);
1654 
1655   if (getLangOpts().ObjCARCWeak && isa<VarDecl>(D) &&
1656       Ty.getObjCLifetime() == Qualifiers::OCL_Weak) {
1657     DiagnosticsEngine::Level Level =
1658       Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
1659                                E->getLocStart());
1660     if (Level != DiagnosticsEngine::Ignored)
1661       recordUseOfEvaluatedWeak(E);
1662   }
1663 
1664   // Just in case we're building an illegal pointer-to-member.
1665   FieldDecl *FD = dyn_cast<FieldDecl>(D);
1666   if (FD && FD->isBitField())
1667     E->setObjectKind(OK_BitField);
1668 
1669   return Owned(E);
1670 }
1671 
1672 /// Decomposes the given name into a DeclarationNameInfo, its location, and
1673 /// possibly a list of template arguments.
1674 ///
1675 /// If this produces template arguments, it is permitted to call
1676 /// DecomposeTemplateName.
1677 ///
1678 /// This actually loses a lot of source location information for
1679 /// non-standard name kinds; we should consider preserving that in
1680 /// some way.
1681 void
1682 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1683                              TemplateArgumentListInfo &Buffer,
1684                              DeclarationNameInfo &NameInfo,
1685                              const TemplateArgumentListInfo *&TemplateArgs) {
1686   if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1687     Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1688     Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1689 
1690     ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
1691                                        Id.TemplateId->NumArgs);
1692     translateTemplateArguments(TemplateArgsPtr, Buffer);
1693 
1694     TemplateName TName = Id.TemplateId->Template.get();
1695     SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1696     NameInfo = Context.getNameForTemplate(TName, TNameLoc);
1697     TemplateArgs = &Buffer;
1698   } else {
1699     NameInfo = GetNameFromUnqualifiedId(Id);
1700     TemplateArgs = 0;
1701   }
1702 }
1703 
1704 /// Diagnose an empty lookup.
1705 ///
1706 /// \return false if new lookup candidates were found
1707 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1708                                CorrectionCandidateCallback &CCC,
1709                                TemplateArgumentListInfo *ExplicitTemplateArgs,
1710                                ArrayRef<Expr *> Args) {
1711   DeclarationName Name = R.getLookupName();
1712 
1713   unsigned diagnostic = diag::err_undeclared_var_use;
1714   unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
1715   if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1716       Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
1717       Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
1718     diagnostic = diag::err_undeclared_use;
1719     diagnostic_suggest = diag::err_undeclared_use_suggest;
1720   }
1721 
1722   // If the original lookup was an unqualified lookup, fake an
1723   // unqualified lookup.  This is useful when (for example) the
1724   // original lookup would not have found something because it was a
1725   // dependent name.
1726   DeclContext *DC = (SS.isEmpty() && !CallsUndergoingInstantiation.empty())
1727     ? CurContext : 0;
1728   while (DC) {
1729     if (isa<CXXRecordDecl>(DC)) {
1730       LookupQualifiedName(R, DC);
1731 
1732       if (!R.empty()) {
1733         // Don't give errors about ambiguities in this lookup.
1734         R.suppressDiagnostics();
1735 
1736         // During a default argument instantiation the CurContext points
1737         // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1738         // function parameter list, hence add an explicit check.
1739         bool isDefaultArgument = !ActiveTemplateInstantiations.empty() &&
1740                               ActiveTemplateInstantiations.back().Kind ==
1741             ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
1742         CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1743         bool isInstance = CurMethod &&
1744                           CurMethod->isInstance() &&
1745                           DC == CurMethod->getParent() && !isDefaultArgument;
1746 
1747 
1748         // Give a code modification hint to insert 'this->'.
1749         // TODO: fixit for inserting 'Base<T>::' in the other cases.
1750         // Actually quite difficult!
1751         if (getLangOpts().MicrosoftMode)
1752           diagnostic = diag::warn_found_via_dependent_bases_lookup;
1753         if (isInstance) {
1754           Diag(R.getNameLoc(), diagnostic) << Name
1755             << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1756           UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1757               CallsUndergoingInstantiation.back()->getCallee());
1758 
1759           CXXMethodDecl *DepMethod;
1760           if (CurMethod->isDependentContext())
1761             DepMethod = CurMethod;
1762           else if (CurMethod->getTemplatedKind() ==
1763               FunctionDecl::TK_FunctionTemplateSpecialization)
1764             DepMethod = cast<CXXMethodDecl>(CurMethod->getPrimaryTemplate()->
1765                 getInstantiatedFromMemberTemplate()->getTemplatedDecl());
1766           else
1767             DepMethod = cast<CXXMethodDecl>(
1768                 CurMethod->getInstantiatedFromMemberFunction());
1769           assert(DepMethod && "No template pattern found");
1770 
1771           QualType DepThisType = DepMethod->getThisType(Context);
1772           CheckCXXThisCapture(R.getNameLoc());
1773           CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1774                                      R.getNameLoc(), DepThisType, false);
1775           TemplateArgumentListInfo TList;
1776           if (ULE->hasExplicitTemplateArgs())
1777             ULE->copyTemplateArgumentsInto(TList);
1778 
1779           CXXScopeSpec SS;
1780           SS.Adopt(ULE->getQualifierLoc());
1781           CXXDependentScopeMemberExpr *DepExpr =
1782               CXXDependentScopeMemberExpr::Create(
1783                   Context, DepThis, DepThisType, true, SourceLocation(),
1784                   SS.getWithLocInContext(Context),
1785                   ULE->getTemplateKeywordLoc(), 0,
1786                   R.getLookupNameInfo(),
1787                   ULE->hasExplicitTemplateArgs() ? &TList : 0);
1788           CallsUndergoingInstantiation.back()->setCallee(DepExpr);
1789         } else {
1790           Diag(R.getNameLoc(), diagnostic) << Name;
1791         }
1792 
1793         // Do we really want to note all of these?
1794         for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1795           Diag((*I)->getLocation(), diag::note_dependent_var_use);
1796 
1797         // Return true if we are inside a default argument instantiation
1798         // and the found name refers to an instance member function, otherwise
1799         // the function calling DiagnoseEmptyLookup will try to create an
1800         // implicit member call and this is wrong for default argument.
1801         if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1802           Diag(R.getNameLoc(), diag::err_member_call_without_object);
1803           return true;
1804         }
1805 
1806         // Tell the callee to try to recover.
1807         return false;
1808       }
1809 
1810       R.clear();
1811     }
1812 
1813     // In Microsoft mode, if we are performing lookup from within a friend
1814     // function definition declared at class scope then we must set
1815     // DC to the lexical parent to be able to search into the parent
1816     // class.
1817     if (getLangOpts().MicrosoftMode && isa<FunctionDecl>(DC) &&
1818         cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1819         DC->getLexicalParent()->isRecord())
1820       DC = DC->getLexicalParent();
1821     else
1822       DC = DC->getParent();
1823   }
1824 
1825   // We didn't find anything, so try to correct for a typo.
1826   TypoCorrection Corrected;
1827   if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
1828                                     S, &SS, CCC))) {
1829     std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1830     bool DroppedSpecifier =
1831         Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
1832     R.setLookupName(Corrected.getCorrection());
1833 
1834     bool AcceptableWithRecovery = false;
1835     bool AcceptableWithoutRecovery = false;
1836     NamedDecl *ND = Corrected.getCorrectionDecl();
1837     if (ND) {
1838       if (Corrected.isOverloaded()) {
1839         OverloadCandidateSet OCS(R.getNameLoc());
1840         OverloadCandidateSet::iterator Best;
1841         for (TypoCorrection::decl_iterator CD = Corrected.begin(),
1842                                         CDEnd = Corrected.end();
1843              CD != CDEnd; ++CD) {
1844           if (FunctionTemplateDecl *FTD =
1845                    dyn_cast<FunctionTemplateDecl>(*CD))
1846             AddTemplateOverloadCandidate(
1847                 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
1848                 Args, OCS);
1849           else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
1850             if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1851               AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
1852                                    Args, OCS);
1853         }
1854         switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1855         case OR_Success:
1856           ND = Best->Function;
1857           Corrected.setCorrectionDecl(ND);
1858           break;
1859         default:
1860           // FIXME: Arbitrarily pick the first declaration for the note.
1861           Corrected.setCorrectionDecl(ND);
1862           break;
1863         }
1864       }
1865       R.addDecl(ND);
1866 
1867       AcceptableWithRecovery =
1868           isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND);
1869       // FIXME: If we ended up with a typo for a type name or
1870       // Objective-C class name, we're in trouble because the parser
1871       // is in the wrong place to recover. Suggest the typo
1872       // correction, but don't make it a fix-it since we're not going
1873       // to recover well anyway.
1874       AcceptableWithoutRecovery =
1875           isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
1876     } else {
1877       // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
1878       // because we aren't able to recover.
1879       AcceptableWithoutRecovery = true;
1880     }
1881 
1882     if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
1883       unsigned NoteID = (Corrected.getCorrectionDecl() &&
1884                          isa<ImplicitParamDecl>(Corrected.getCorrectionDecl()))
1885                             ? diag::note_implicit_param_decl
1886                             : diag::note_previous_decl;
1887       if (SS.isEmpty())
1888         diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
1889                      PDiag(NoteID), AcceptableWithRecovery);
1890       else
1891         diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
1892                                   << Name << computeDeclContext(SS, false)
1893                                   << DroppedSpecifier << SS.getRange(),
1894                      PDiag(NoteID), AcceptableWithRecovery);
1895 
1896       // Tell the callee whether to try to recover.
1897       return !AcceptableWithRecovery;
1898     }
1899   }
1900   R.clear();
1901 
1902   // Emit a special diagnostic for failed member lookups.
1903   // FIXME: computing the declaration context might fail here (?)
1904   if (!SS.isEmpty()) {
1905     Diag(R.getNameLoc(), diag::err_no_member)
1906       << Name << computeDeclContext(SS, false)
1907       << SS.getRange();
1908     return true;
1909   }
1910 
1911   // Give up, we can't recover.
1912   Diag(R.getNameLoc(), diagnostic) << Name;
1913   return true;
1914 }
1915 
1916 ExprResult Sema::ActOnIdExpression(Scope *S,
1917                                    CXXScopeSpec &SS,
1918                                    SourceLocation TemplateKWLoc,
1919                                    UnqualifiedId &Id,
1920                                    bool HasTrailingLParen,
1921                                    bool IsAddressOfOperand,
1922                                    CorrectionCandidateCallback *CCC,
1923                                    bool IsInlineAsmIdentifier) {
1924   assert(!(IsAddressOfOperand && HasTrailingLParen) &&
1925          "cannot be direct & operand and have a trailing lparen");
1926   if (SS.isInvalid())
1927     return ExprError();
1928 
1929   TemplateArgumentListInfo TemplateArgsBuffer;
1930 
1931   // Decompose the UnqualifiedId into the following data.
1932   DeclarationNameInfo NameInfo;
1933   const TemplateArgumentListInfo *TemplateArgs;
1934   DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
1935 
1936   DeclarationName Name = NameInfo.getName();
1937   IdentifierInfo *II = Name.getAsIdentifierInfo();
1938   SourceLocation NameLoc = NameInfo.getLoc();
1939 
1940   // C++ [temp.dep.expr]p3:
1941   //   An id-expression is type-dependent if it contains:
1942   //     -- an identifier that was declared with a dependent type,
1943   //        (note: handled after lookup)
1944   //     -- a template-id that is dependent,
1945   //        (note: handled in BuildTemplateIdExpr)
1946   //     -- a conversion-function-id that specifies a dependent type,
1947   //     -- a nested-name-specifier that contains a class-name that
1948   //        names a dependent type.
1949   // Determine whether this is a member of an unknown specialization;
1950   // we need to handle these differently.
1951   bool DependentID = false;
1952   if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1953       Name.getCXXNameType()->isDependentType()) {
1954     DependentID = true;
1955   } else if (SS.isSet()) {
1956     if (DeclContext *DC = computeDeclContext(SS, false)) {
1957       if (RequireCompleteDeclContext(SS, DC))
1958         return ExprError();
1959     } else {
1960       DependentID = true;
1961     }
1962   }
1963 
1964   if (DependentID)
1965     return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1966                                       IsAddressOfOperand, TemplateArgs);
1967 
1968   // Perform the required lookup.
1969   LookupResult R(*this, NameInfo,
1970                  (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
1971                   ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
1972   if (TemplateArgs) {
1973     // Lookup the template name again to correctly establish the context in
1974     // which it was found. This is really unfortunate as we already did the
1975     // lookup to determine that it was a template name in the first place. If
1976     // this becomes a performance hit, we can work harder to preserve those
1977     // results until we get here but it's likely not worth it.
1978     bool MemberOfUnknownSpecialization;
1979     LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1980                        MemberOfUnknownSpecialization);
1981 
1982     if (MemberOfUnknownSpecialization ||
1983         (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
1984       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1985                                         IsAddressOfOperand, TemplateArgs);
1986   } else {
1987     bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
1988     LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
1989 
1990     // If the result might be in a dependent base class, this is a dependent
1991     // id-expression.
1992     if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
1993       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1994                                         IsAddressOfOperand, TemplateArgs);
1995 
1996     // If this reference is in an Objective-C method, then we need to do
1997     // some special Objective-C lookup, too.
1998     if (IvarLookupFollowUp) {
1999       ExprResult E(LookupInObjCMethod(R, S, II, true));
2000       if (E.isInvalid())
2001         return ExprError();
2002 
2003       if (Expr *Ex = E.takeAs<Expr>())
2004         return Owned(Ex);
2005     }
2006   }
2007 
2008   if (R.isAmbiguous())
2009     return ExprError();
2010 
2011   // Determine whether this name might be a candidate for
2012   // argument-dependent lookup.
2013   bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2014 
2015   if (R.empty() && !ADL) {
2016 
2017     // Otherwise, this could be an implicitly declared function reference (legal
2018     // in C90, extension in C99, forbidden in C++).
2019     if (HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2020       NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2021       if (D) R.addDecl(D);
2022     }
2023 
2024     // If this name wasn't predeclared and if this is not a function
2025     // call, diagnose the problem.
2026     if (R.empty()) {
2027       // In Microsoft mode, if we are inside a template class member function
2028       // whose parent class has dependent base classes, and we can't resolve
2029       // an identifier, then assume the identifier is a member of a dependent
2030       // base class.  The goal is to postpone name lookup to instantiation time
2031       // to be able to search into the type dependent base classes.
2032       // FIXME: If we want 100% compatibility with MSVC, we will have delay all
2033       // unqualified name lookup.  Any name lookup during template parsing means
2034       // clang might find something that MSVC doesn't.  For now, we only handle
2035       // the common case of members of a dependent base class.
2036       if (getLangOpts().MicrosoftMode) {
2037         CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext);
2038         if (MD && MD->isInstance() && MD->getParent()->hasAnyDependentBases()) {
2039           assert(SS.isEmpty() && "qualifiers should be already handled");
2040           QualType ThisType = MD->getThisType(Context);
2041           // Since the 'this' expression is synthesized, we don't need to
2042           // perform the double-lookup check.
2043           NamedDecl *FirstQualifierInScope = 0;
2044           return Owned(CXXDependentScopeMemberExpr::Create(
2045               Context, /*This=*/0, ThisType, /*IsArrow=*/true,
2046               /*Op=*/SourceLocation(), SS.getWithLocInContext(Context),
2047               TemplateKWLoc, FirstQualifierInScope, NameInfo, TemplateArgs));
2048         }
2049       }
2050 
2051       // Don't diagnose an empty lookup for inline assmebly.
2052       if (IsInlineAsmIdentifier)
2053         return ExprError();
2054 
2055       CorrectionCandidateCallback DefaultValidator;
2056       if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator))
2057         return ExprError();
2058 
2059       assert(!R.empty() &&
2060              "DiagnoseEmptyLookup returned false but added no results");
2061 
2062       // If we found an Objective-C instance variable, let
2063       // LookupInObjCMethod build the appropriate expression to
2064       // reference the ivar.
2065       if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2066         R.clear();
2067         ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2068         // In a hopelessly buggy code, Objective-C instance variable
2069         // lookup fails and no expression will be built to reference it.
2070         if (!E.isInvalid() && !E.get())
2071           return ExprError();
2072         return E;
2073       }
2074     }
2075   }
2076 
2077   // This is guaranteed from this point on.
2078   assert(!R.empty() || ADL);
2079 
2080   // Check whether this might be a C++ implicit instance member access.
2081   // C++ [class.mfct.non-static]p3:
2082   //   When an id-expression that is not part of a class member access
2083   //   syntax and not used to form a pointer to member is used in the
2084   //   body of a non-static member function of class X, if name lookup
2085   //   resolves the name in the id-expression to a non-static non-type
2086   //   member of some class C, the id-expression is transformed into a
2087   //   class member access expression using (*this) as the
2088   //   postfix-expression to the left of the . operator.
2089   //
2090   // But we don't actually need to do this for '&' operands if R
2091   // resolved to a function or overloaded function set, because the
2092   // expression is ill-formed if it actually works out to be a
2093   // non-static member function:
2094   //
2095   // C++ [expr.ref]p4:
2096   //   Otherwise, if E1.E2 refers to a non-static member function. . .
2097   //   [t]he expression can be used only as the left-hand operand of a
2098   //   member function call.
2099   //
2100   // There are other safeguards against such uses, but it's important
2101   // to get this right here so that we don't end up making a
2102   // spuriously dependent expression if we're inside a dependent
2103   // instance method.
2104   if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2105     bool MightBeImplicitMember;
2106     if (!IsAddressOfOperand)
2107       MightBeImplicitMember = true;
2108     else if (!SS.isEmpty())
2109       MightBeImplicitMember = false;
2110     else if (R.isOverloadedResult())
2111       MightBeImplicitMember = false;
2112     else if (R.isUnresolvableResult())
2113       MightBeImplicitMember = true;
2114     else
2115       MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2116                               isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2117                               isa<MSPropertyDecl>(R.getFoundDecl());
2118 
2119     if (MightBeImplicitMember)
2120       return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2121                                              R, TemplateArgs);
2122   }
2123 
2124   if (TemplateArgs || TemplateKWLoc.isValid()) {
2125 
2126     // In C++1y, if this is a variable template id, then check it
2127     // in BuildTemplateIdExpr().
2128     // The single lookup result must be a variable template declaration.
2129     if (Id.getKind() == UnqualifiedId::IK_TemplateId && Id.TemplateId &&
2130         Id.TemplateId->Kind == TNK_Var_template) {
2131       assert(R.getAsSingle<VarTemplateDecl>() &&
2132              "There should only be one declaration found.");
2133     }
2134 
2135     return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2136   }
2137 
2138   return BuildDeclarationNameExpr(SS, R, ADL);
2139 }
2140 
2141 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2142 /// declaration name, generally during template instantiation.
2143 /// There's a large number of things which don't need to be done along
2144 /// this path.
2145 ExprResult
2146 Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
2147                                         const DeclarationNameInfo &NameInfo,
2148                                         bool IsAddressOfOperand) {
2149   DeclContext *DC = computeDeclContext(SS, false);
2150   if (!DC)
2151     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2152                                      NameInfo, /*TemplateArgs=*/0);
2153 
2154   if (RequireCompleteDeclContext(SS, DC))
2155     return ExprError();
2156 
2157   LookupResult R(*this, NameInfo, LookupOrdinaryName);
2158   LookupQualifiedName(R, DC);
2159 
2160   if (R.isAmbiguous())
2161     return ExprError();
2162 
2163   if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2164     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2165                                      NameInfo, /*TemplateArgs=*/0);
2166 
2167   if (R.empty()) {
2168     Diag(NameInfo.getLoc(), diag::err_no_member)
2169       << NameInfo.getName() << DC << SS.getRange();
2170     return ExprError();
2171   }
2172 
2173   // Defend against this resolving to an implicit member access. We usually
2174   // won't get here if this might be a legitimate a class member (we end up in
2175   // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2176   // a pointer-to-member or in an unevaluated context in C++11.
2177   if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2178     return BuildPossibleImplicitMemberExpr(SS,
2179                                            /*TemplateKWLoc=*/SourceLocation(),
2180                                            R, /*TemplateArgs=*/0);
2181 
2182   return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2183 }
2184 
2185 /// LookupInObjCMethod - The parser has read a name in, and Sema has
2186 /// detected that we're currently inside an ObjC method.  Perform some
2187 /// additional lookup.
2188 ///
2189 /// Ideally, most of this would be done by lookup, but there's
2190 /// actually quite a lot of extra work involved.
2191 ///
2192 /// Returns a null sentinel to indicate trivial success.
2193 ExprResult
2194 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2195                          IdentifierInfo *II, bool AllowBuiltinCreation) {
2196   SourceLocation Loc = Lookup.getNameLoc();
2197   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2198 
2199   // Check for error condition which is already reported.
2200   if (!CurMethod)
2201     return ExprError();
2202 
2203   // There are two cases to handle here.  1) scoped lookup could have failed,
2204   // in which case we should look for an ivar.  2) scoped lookup could have
2205   // found a decl, but that decl is outside the current instance method (i.e.
2206   // a global variable).  In these two cases, we do a lookup for an ivar with
2207   // this name, if the lookup sucedes, we replace it our current decl.
2208 
2209   // If we're in a class method, we don't normally want to look for
2210   // ivars.  But if we don't find anything else, and there's an
2211   // ivar, that's an error.
2212   bool IsClassMethod = CurMethod->isClassMethod();
2213 
2214   bool LookForIvars;
2215   if (Lookup.empty())
2216     LookForIvars = true;
2217   else if (IsClassMethod)
2218     LookForIvars = false;
2219   else
2220     LookForIvars = (Lookup.isSingleResult() &&
2221                     Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2222   ObjCInterfaceDecl *IFace = 0;
2223   if (LookForIvars) {
2224     IFace = CurMethod->getClassInterface();
2225     ObjCInterfaceDecl *ClassDeclared;
2226     ObjCIvarDecl *IV = 0;
2227     if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2228       // Diagnose using an ivar in a class method.
2229       if (IsClassMethod)
2230         return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
2231                          << IV->getDeclName());
2232 
2233       // If we're referencing an invalid decl, just return this as a silent
2234       // error node.  The error diagnostic was already emitted on the decl.
2235       if (IV->isInvalidDecl())
2236         return ExprError();
2237 
2238       // Check if referencing a field with __attribute__((deprecated)).
2239       if (DiagnoseUseOfDecl(IV, Loc))
2240         return ExprError();
2241 
2242       // Diagnose the use of an ivar outside of the declaring class.
2243       if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2244           !declaresSameEntity(ClassDeclared, IFace) &&
2245           !getLangOpts().DebuggerSupport)
2246         Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
2247 
2248       // FIXME: This should use a new expr for a direct reference, don't
2249       // turn this into Self->ivar, just return a BareIVarExpr or something.
2250       IdentifierInfo &II = Context.Idents.get("self");
2251       UnqualifiedId SelfName;
2252       SelfName.setIdentifier(&II, SourceLocation());
2253       SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
2254       CXXScopeSpec SelfScopeSpec;
2255       SourceLocation TemplateKWLoc;
2256       ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
2257                                               SelfName, false, false);
2258       if (SelfExpr.isInvalid())
2259         return ExprError();
2260 
2261       SelfExpr = DefaultLvalueConversion(SelfExpr.take());
2262       if (SelfExpr.isInvalid())
2263         return ExprError();
2264 
2265       MarkAnyDeclReferenced(Loc, IV, true);
2266       if (!IV->getBackingIvarReferencedInAccessor()) {
2267         // Mark this ivar 'referenced' in this method, if it is a backing ivar
2268         // of a property and current method is one of its property accessor.
2269         const ObjCPropertyDecl *PDecl;
2270         const ObjCIvarDecl *BIV = GetIvarBackingPropertyAccessor(CurMethod, PDecl);
2271         if (BIV && BIV == IV)
2272           IV->setBackingIvarReferencedInAccessor(true);
2273       }
2274 
2275       ObjCMethodFamily MF = CurMethod->getMethodFamily();
2276       if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2277           !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2278         Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2279 
2280       ObjCIvarRefExpr *Result = new (Context) ObjCIvarRefExpr(IV, IV->getType(),
2281                                                               Loc, IV->getLocation(),
2282                                                               SelfExpr.take(),
2283                                                               true, true);
2284 
2285       if (getLangOpts().ObjCAutoRefCount) {
2286         if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2287           DiagnosticsEngine::Level Level =
2288             Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, Loc);
2289           if (Level != DiagnosticsEngine::Ignored)
2290             recordUseOfEvaluatedWeak(Result);
2291         }
2292         if (CurContext->isClosure())
2293           Diag(Loc, diag::warn_implicitly_retains_self)
2294             << FixItHint::CreateInsertion(Loc, "self->");
2295       }
2296 
2297       return Owned(Result);
2298     }
2299   } else if (CurMethod->isInstanceMethod()) {
2300     // We should warn if a local variable hides an ivar.
2301     if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2302       ObjCInterfaceDecl *ClassDeclared;
2303       if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2304         if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2305             declaresSameEntity(IFace, ClassDeclared))
2306           Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2307       }
2308     }
2309   } else if (Lookup.isSingleResult() &&
2310              Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2311     // If accessing a stand-alone ivar in a class method, this is an error.
2312     if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
2313       return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
2314                        << IV->getDeclName());
2315   }
2316 
2317   if (Lookup.empty() && II && AllowBuiltinCreation) {
2318     // FIXME. Consolidate this with similar code in LookupName.
2319     if (unsigned BuiltinID = II->getBuiltinID()) {
2320       if (!(getLangOpts().CPlusPlus &&
2321             Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2322         NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2323                                            S, Lookup.isForRedeclaration(),
2324                                            Lookup.getNameLoc());
2325         if (D) Lookup.addDecl(D);
2326       }
2327     }
2328   }
2329   // Sentinel value saying that we didn't do anything special.
2330   return Owned((Expr*) 0);
2331 }
2332 
2333 /// \brief Cast a base object to a member's actual type.
2334 ///
2335 /// Logically this happens in three phases:
2336 ///
2337 /// * First we cast from the base type to the naming class.
2338 ///   The naming class is the class into which we were looking
2339 ///   when we found the member;  it's the qualifier type if a
2340 ///   qualifier was provided, and otherwise it's the base type.
2341 ///
2342 /// * Next we cast from the naming class to the declaring class.
2343 ///   If the member we found was brought into a class's scope by
2344 ///   a using declaration, this is that class;  otherwise it's
2345 ///   the class declaring the member.
2346 ///
2347 /// * Finally we cast from the declaring class to the "true"
2348 ///   declaring class of the member.  This conversion does not
2349 ///   obey access control.
2350 ExprResult
2351 Sema::PerformObjectMemberConversion(Expr *From,
2352                                     NestedNameSpecifier *Qualifier,
2353                                     NamedDecl *FoundDecl,
2354                                     NamedDecl *Member) {
2355   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2356   if (!RD)
2357     return Owned(From);
2358 
2359   QualType DestRecordType;
2360   QualType DestType;
2361   QualType FromRecordType;
2362   QualType FromType = From->getType();
2363   bool PointerConversions = false;
2364   if (isa<FieldDecl>(Member)) {
2365     DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2366 
2367     if (FromType->getAs<PointerType>()) {
2368       DestType = Context.getPointerType(DestRecordType);
2369       FromRecordType = FromType->getPointeeType();
2370       PointerConversions = true;
2371     } else {
2372       DestType = DestRecordType;
2373       FromRecordType = FromType;
2374     }
2375   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2376     if (Method->isStatic())
2377       return Owned(From);
2378 
2379     DestType = Method->getThisType(Context);
2380     DestRecordType = DestType->getPointeeType();
2381 
2382     if (FromType->getAs<PointerType>()) {
2383       FromRecordType = FromType->getPointeeType();
2384       PointerConversions = true;
2385     } else {
2386       FromRecordType = FromType;
2387       DestType = DestRecordType;
2388     }
2389   } else {
2390     // No conversion necessary.
2391     return Owned(From);
2392   }
2393 
2394   if (DestType->isDependentType() || FromType->isDependentType())
2395     return Owned(From);
2396 
2397   // If the unqualified types are the same, no conversion is necessary.
2398   if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2399     return Owned(From);
2400 
2401   SourceRange FromRange = From->getSourceRange();
2402   SourceLocation FromLoc = FromRange.getBegin();
2403 
2404   ExprValueKind VK = From->getValueKind();
2405 
2406   // C++ [class.member.lookup]p8:
2407   //   [...] Ambiguities can often be resolved by qualifying a name with its
2408   //   class name.
2409   //
2410   // If the member was a qualified name and the qualified referred to a
2411   // specific base subobject type, we'll cast to that intermediate type
2412   // first and then to the object in which the member is declared. That allows
2413   // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2414   //
2415   //   class Base { public: int x; };
2416   //   class Derived1 : public Base { };
2417   //   class Derived2 : public Base { };
2418   //   class VeryDerived : public Derived1, public Derived2 { void f(); };
2419   //
2420   //   void VeryDerived::f() {
2421   //     x = 17; // error: ambiguous base subobjects
2422   //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
2423   //   }
2424   if (Qualifier && Qualifier->getAsType()) {
2425     QualType QType = QualType(Qualifier->getAsType(), 0);
2426     assert(QType->isRecordType() && "lookup done with non-record type");
2427 
2428     QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2429 
2430     // In C++98, the qualifier type doesn't actually have to be a base
2431     // type of the object type, in which case we just ignore it.
2432     // Otherwise build the appropriate casts.
2433     if (IsDerivedFrom(FromRecordType, QRecordType)) {
2434       CXXCastPath BasePath;
2435       if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2436                                        FromLoc, FromRange, &BasePath))
2437         return ExprError();
2438 
2439       if (PointerConversions)
2440         QType = Context.getPointerType(QType);
2441       From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2442                                VK, &BasePath).take();
2443 
2444       FromType = QType;
2445       FromRecordType = QRecordType;
2446 
2447       // If the qualifier type was the same as the destination type,
2448       // we're done.
2449       if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2450         return Owned(From);
2451     }
2452   }
2453 
2454   bool IgnoreAccess = false;
2455 
2456   // If we actually found the member through a using declaration, cast
2457   // down to the using declaration's type.
2458   //
2459   // Pointer equality is fine here because only one declaration of a
2460   // class ever has member declarations.
2461   if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2462     assert(isa<UsingShadowDecl>(FoundDecl));
2463     QualType URecordType = Context.getTypeDeclType(
2464                            cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2465 
2466     // We only need to do this if the naming-class to declaring-class
2467     // conversion is non-trivial.
2468     if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2469       assert(IsDerivedFrom(FromRecordType, URecordType));
2470       CXXCastPath BasePath;
2471       if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2472                                        FromLoc, FromRange, &BasePath))
2473         return ExprError();
2474 
2475       QualType UType = URecordType;
2476       if (PointerConversions)
2477         UType = Context.getPointerType(UType);
2478       From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2479                                VK, &BasePath).take();
2480       FromType = UType;
2481       FromRecordType = URecordType;
2482     }
2483 
2484     // We don't do access control for the conversion from the
2485     // declaring class to the true declaring class.
2486     IgnoreAccess = true;
2487   }
2488 
2489   CXXCastPath BasePath;
2490   if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2491                                    FromLoc, FromRange, &BasePath,
2492                                    IgnoreAccess))
2493     return ExprError();
2494 
2495   return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2496                            VK, &BasePath);
2497 }
2498 
2499 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2500                                       const LookupResult &R,
2501                                       bool HasTrailingLParen) {
2502   // Only when used directly as the postfix-expression of a call.
2503   if (!HasTrailingLParen)
2504     return false;
2505 
2506   // Never if a scope specifier was provided.
2507   if (SS.isSet())
2508     return false;
2509 
2510   // Only in C++ or ObjC++.
2511   if (!getLangOpts().CPlusPlus)
2512     return false;
2513 
2514   // Turn off ADL when we find certain kinds of declarations during
2515   // normal lookup:
2516   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2517     NamedDecl *D = *I;
2518 
2519     // C++0x [basic.lookup.argdep]p3:
2520     //     -- a declaration of a class member
2521     // Since using decls preserve this property, we check this on the
2522     // original decl.
2523     if (D->isCXXClassMember())
2524       return false;
2525 
2526     // C++0x [basic.lookup.argdep]p3:
2527     //     -- a block-scope function declaration that is not a
2528     //        using-declaration
2529     // NOTE: we also trigger this for function templates (in fact, we
2530     // don't check the decl type at all, since all other decl types
2531     // turn off ADL anyway).
2532     if (isa<UsingShadowDecl>(D))
2533       D = cast<UsingShadowDecl>(D)->getTargetDecl();
2534     else if (D->getLexicalDeclContext()->isFunctionOrMethod())
2535       return false;
2536 
2537     // C++0x [basic.lookup.argdep]p3:
2538     //     -- a declaration that is neither a function or a function
2539     //        template
2540     // And also for builtin functions.
2541     if (isa<FunctionDecl>(D)) {
2542       FunctionDecl *FDecl = cast<FunctionDecl>(D);
2543 
2544       // But also builtin functions.
2545       if (FDecl->getBuiltinID() && FDecl->isImplicit())
2546         return false;
2547     } else if (!isa<FunctionTemplateDecl>(D))
2548       return false;
2549   }
2550 
2551   return true;
2552 }
2553 
2554 
2555 /// Diagnoses obvious problems with the use of the given declaration
2556 /// as an expression.  This is only actually called for lookups that
2557 /// were not overloaded, and it doesn't promise that the declaration
2558 /// will in fact be used.
2559 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2560   if (isa<TypedefNameDecl>(D)) {
2561     S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2562     return true;
2563   }
2564 
2565   if (isa<ObjCInterfaceDecl>(D)) {
2566     S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2567     return true;
2568   }
2569 
2570   if (isa<NamespaceDecl>(D)) {
2571     S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2572     return true;
2573   }
2574 
2575   return false;
2576 }
2577 
2578 ExprResult
2579 Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2580                                LookupResult &R,
2581                                bool NeedsADL) {
2582   // If this is a single, fully-resolved result and we don't need ADL,
2583   // just build an ordinary singleton decl ref.
2584   if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
2585     return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
2586                                     R.getRepresentativeDecl());
2587 
2588   // We only need to check the declaration if there's exactly one
2589   // result, because in the overloaded case the results can only be
2590   // functions and function templates.
2591   if (R.isSingleResult() &&
2592       CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
2593     return ExprError();
2594 
2595   // Otherwise, just build an unresolved lookup expression.  Suppress
2596   // any lookup-related diagnostics; we'll hash these out later, when
2597   // we've picked a target.
2598   R.suppressDiagnostics();
2599 
2600   UnresolvedLookupExpr *ULE
2601     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2602                                    SS.getWithLocInContext(Context),
2603                                    R.getLookupNameInfo(),
2604                                    NeedsADL, R.isOverloadedResult(),
2605                                    R.begin(), R.end());
2606 
2607   return Owned(ULE);
2608 }
2609 
2610 /// \brief Complete semantic analysis for a reference to the given declaration.
2611 ExprResult Sema::BuildDeclarationNameExpr(
2612     const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
2613     NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs) {
2614   assert(D && "Cannot refer to a NULL declaration");
2615   assert(!isa<FunctionTemplateDecl>(D) &&
2616          "Cannot refer unambiguously to a function template");
2617 
2618   SourceLocation Loc = NameInfo.getLoc();
2619   if (CheckDeclInExpr(*this, Loc, D))
2620     return ExprError();
2621 
2622   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2623     // Specifically diagnose references to class templates that are missing
2624     // a template argument list.
2625     Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0)
2626                                            << Template << SS.getRange();
2627     Diag(Template->getLocation(), diag::note_template_decl_here);
2628     return ExprError();
2629   }
2630 
2631   // Make sure that we're referring to a value.
2632   ValueDecl *VD = dyn_cast<ValueDecl>(D);
2633   if (!VD) {
2634     Diag(Loc, diag::err_ref_non_value)
2635       << D << SS.getRange();
2636     Diag(D->getLocation(), diag::note_declared_at);
2637     return ExprError();
2638   }
2639 
2640   // Check whether this declaration can be used. Note that we suppress
2641   // this check when we're going to perform argument-dependent lookup
2642   // on this function name, because this might not be the function
2643   // that overload resolution actually selects.
2644   if (DiagnoseUseOfDecl(VD, Loc))
2645     return ExprError();
2646 
2647   // Only create DeclRefExpr's for valid Decl's.
2648   if (VD->isInvalidDecl())
2649     return ExprError();
2650 
2651   // Handle members of anonymous structs and unions.  If we got here,
2652   // and the reference is to a class member indirect field, then this
2653   // must be the subject of a pointer-to-member expression.
2654   if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2655     if (!indirectField->isCXXClassMember())
2656       return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2657                                                       indirectField);
2658 
2659   {
2660     QualType type = VD->getType();
2661     ExprValueKind valueKind = VK_RValue;
2662 
2663     switch (D->getKind()) {
2664     // Ignore all the non-ValueDecl kinds.
2665 #define ABSTRACT_DECL(kind)
2666 #define VALUE(type, base)
2667 #define DECL(type, base) \
2668     case Decl::type:
2669 #include "clang/AST/DeclNodes.inc"
2670       llvm_unreachable("invalid value decl kind");
2671 
2672     // These shouldn't make it here.
2673     case Decl::ObjCAtDefsField:
2674     case Decl::ObjCIvar:
2675       llvm_unreachable("forming non-member reference to ivar?");
2676 
2677     // Enum constants are always r-values and never references.
2678     // Unresolved using declarations are dependent.
2679     case Decl::EnumConstant:
2680     case Decl::UnresolvedUsingValue:
2681       valueKind = VK_RValue;
2682       break;
2683 
2684     // Fields and indirect fields that got here must be for
2685     // pointer-to-member expressions; we just call them l-values for
2686     // internal consistency, because this subexpression doesn't really
2687     // exist in the high-level semantics.
2688     case Decl::Field:
2689     case Decl::IndirectField:
2690       assert(getLangOpts().CPlusPlus &&
2691              "building reference to field in C?");
2692 
2693       // These can't have reference type in well-formed programs, but
2694       // for internal consistency we do this anyway.
2695       type = type.getNonReferenceType();
2696       valueKind = VK_LValue;
2697       break;
2698 
2699     // Non-type template parameters are either l-values or r-values
2700     // depending on the type.
2701     case Decl::NonTypeTemplateParm: {
2702       if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2703         type = reftype->getPointeeType();
2704         valueKind = VK_LValue; // even if the parameter is an r-value reference
2705         break;
2706       }
2707 
2708       // For non-references, we need to strip qualifiers just in case
2709       // the template parameter was declared as 'const int' or whatever.
2710       valueKind = VK_RValue;
2711       type = type.getUnqualifiedType();
2712       break;
2713     }
2714 
2715     case Decl::Var:
2716     case Decl::VarTemplateSpecialization:
2717     case Decl::VarTemplatePartialSpecialization:
2718       // In C, "extern void blah;" is valid and is an r-value.
2719       if (!getLangOpts().CPlusPlus &&
2720           !type.hasQualifiers() &&
2721           type->isVoidType()) {
2722         valueKind = VK_RValue;
2723         break;
2724       }
2725       // fallthrough
2726 
2727     case Decl::ImplicitParam:
2728     case Decl::ParmVar: {
2729       // These are always l-values.
2730       valueKind = VK_LValue;
2731       type = type.getNonReferenceType();
2732 
2733       // FIXME: Does the addition of const really only apply in
2734       // potentially-evaluated contexts? Since the variable isn't actually
2735       // captured in an unevaluated context, it seems that the answer is no.
2736       if (!isUnevaluatedContext()) {
2737         QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
2738         if (!CapturedType.isNull())
2739           type = CapturedType;
2740       }
2741 
2742       break;
2743     }
2744 
2745     case Decl::Function: {
2746       if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
2747         if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
2748           type = Context.BuiltinFnTy;
2749           valueKind = VK_RValue;
2750           break;
2751         }
2752       }
2753 
2754       const FunctionType *fty = type->castAs<FunctionType>();
2755 
2756       // If we're referring to a function with an __unknown_anytype
2757       // result type, make the entire expression __unknown_anytype.
2758       if (fty->getResultType() == Context.UnknownAnyTy) {
2759         type = Context.UnknownAnyTy;
2760         valueKind = VK_RValue;
2761         break;
2762       }
2763 
2764       // Functions are l-values in C++.
2765       if (getLangOpts().CPlusPlus) {
2766         valueKind = VK_LValue;
2767         break;
2768       }
2769 
2770       // C99 DR 316 says that, if a function type comes from a
2771       // function definition (without a prototype), that type is only
2772       // used for checking compatibility. Therefore, when referencing
2773       // the function, we pretend that we don't have the full function
2774       // type.
2775       if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2776           isa<FunctionProtoType>(fty))
2777         type = Context.getFunctionNoProtoType(fty->getResultType(),
2778                                               fty->getExtInfo());
2779 
2780       // Functions are r-values in C.
2781       valueKind = VK_RValue;
2782       break;
2783     }
2784 
2785     case Decl::MSProperty:
2786       valueKind = VK_LValue;
2787       break;
2788 
2789     case Decl::CXXMethod:
2790       // If we're referring to a method with an __unknown_anytype
2791       // result type, make the entire expression __unknown_anytype.
2792       // This should only be possible with a type written directly.
2793       if (const FunctionProtoType *proto
2794             = dyn_cast<FunctionProtoType>(VD->getType()))
2795         if (proto->getResultType() == Context.UnknownAnyTy) {
2796           type = Context.UnknownAnyTy;
2797           valueKind = VK_RValue;
2798           break;
2799         }
2800 
2801       // C++ methods are l-values if static, r-values if non-static.
2802       if (cast<CXXMethodDecl>(VD)->isStatic()) {
2803         valueKind = VK_LValue;
2804         break;
2805       }
2806       // fallthrough
2807 
2808     case Decl::CXXConversion:
2809     case Decl::CXXDestructor:
2810     case Decl::CXXConstructor:
2811       valueKind = VK_RValue;
2812       break;
2813     }
2814 
2815     return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
2816                             TemplateArgs);
2817   }
2818 }
2819 
2820 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
2821                                      PredefinedExpr::IdentType IT) {
2822   // Pick the current block, lambda, captured statement or function.
2823   Decl *currentDecl = 0;
2824   if (const BlockScopeInfo *BSI = getCurBlock())
2825     currentDecl = BSI->TheDecl;
2826   else if (const LambdaScopeInfo *LSI = getCurLambda())
2827     currentDecl = LSI->CallOperator;
2828   else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
2829     currentDecl = CSI->TheCapturedDecl;
2830   else
2831     currentDecl = getCurFunctionOrMethodDecl();
2832 
2833   if (!currentDecl) {
2834     Diag(Loc, diag::ext_predef_outside_function);
2835     currentDecl = Context.getTranslationUnitDecl();
2836   }
2837 
2838   QualType ResTy;
2839   if (cast<DeclContext>(currentDecl)->isDependentContext())
2840     ResTy = Context.DependentTy;
2841   else {
2842     // Pre-defined identifiers are of type char[x], where x is the length of
2843     // the string.
2844     unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
2845 
2846     llvm::APInt LengthI(32, Length + 1);
2847     if (IT == PredefinedExpr::LFunction)
2848       ResTy = Context.WideCharTy.withConst();
2849     else
2850       ResTy = Context.CharTy.withConst();
2851     ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2852   }
2853 
2854   return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
2855 }
2856 
2857 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
2858   PredefinedExpr::IdentType IT;
2859 
2860   switch (Kind) {
2861   default: llvm_unreachable("Unknown simple primary expr!");
2862   case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2863   case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
2864   case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS]
2865   case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break;
2866   case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
2867   }
2868 
2869   return BuildPredefinedExpr(Loc, IT);
2870 }
2871 
2872 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
2873   SmallString<16> CharBuffer;
2874   bool Invalid = false;
2875   StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
2876   if (Invalid)
2877     return ExprError();
2878 
2879   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
2880                             PP, Tok.getKind());
2881   if (Literal.hadError())
2882     return ExprError();
2883 
2884   QualType Ty;
2885   if (Literal.isWide())
2886     Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
2887   else if (Literal.isUTF16())
2888     Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
2889   else if (Literal.isUTF32())
2890     Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
2891   else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
2892     Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
2893   else
2894     Ty = Context.CharTy;  // 'x' -> char in C++
2895 
2896   CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
2897   if (Literal.isWide())
2898     Kind = CharacterLiteral::Wide;
2899   else if (Literal.isUTF16())
2900     Kind = CharacterLiteral::UTF16;
2901   else if (Literal.isUTF32())
2902     Kind = CharacterLiteral::UTF32;
2903 
2904   Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
2905                                              Tok.getLocation());
2906 
2907   if (Literal.getUDSuffix().empty())
2908     return Owned(Lit);
2909 
2910   // We're building a user-defined literal.
2911   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2912   SourceLocation UDSuffixLoc =
2913     getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
2914 
2915   // Make sure we're allowed user-defined literals here.
2916   if (!UDLScope)
2917     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
2918 
2919   // C++11 [lex.ext]p6: The literal L is treated as a call of the form
2920   //   operator "" X (ch)
2921   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
2922                                         Lit, Tok.getLocation());
2923 }
2924 
2925 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
2926   unsigned IntSize = Context.getTargetInfo().getIntWidth();
2927   return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
2928                                       Context.IntTy, Loc));
2929 }
2930 
2931 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
2932                                   QualType Ty, SourceLocation Loc) {
2933   const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
2934 
2935   using llvm::APFloat;
2936   APFloat Val(Format);
2937 
2938   APFloat::opStatus result = Literal.GetFloatValue(Val);
2939 
2940   // Overflow is always an error, but underflow is only an error if
2941   // we underflowed to zero (APFloat reports denormals as underflow).
2942   if ((result & APFloat::opOverflow) ||
2943       ((result & APFloat::opUnderflow) && Val.isZero())) {
2944     unsigned diagnostic;
2945     SmallString<20> buffer;
2946     if (result & APFloat::opOverflow) {
2947       diagnostic = diag::warn_float_overflow;
2948       APFloat::getLargest(Format).toString(buffer);
2949     } else {
2950       diagnostic = diag::warn_float_underflow;
2951       APFloat::getSmallest(Format).toString(buffer);
2952     }
2953 
2954     S.Diag(Loc, diagnostic)
2955       << Ty
2956       << StringRef(buffer.data(), buffer.size());
2957   }
2958 
2959   bool isExact = (result == APFloat::opOK);
2960   return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
2961 }
2962 
2963 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
2964   // Fast path for a single digit (which is quite common).  A single digit
2965   // cannot have a trigraph, escaped newline, radix prefix, or suffix.
2966   if (Tok.getLength() == 1) {
2967     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
2968     return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
2969   }
2970 
2971   SmallString<128> SpellingBuffer;
2972   // NumericLiteralParser wants to overread by one character.  Add padding to
2973   // the buffer in case the token is copied to the buffer.  If getSpelling()
2974   // returns a StringRef to the memory buffer, it should have a null char at
2975   // the EOF, so it is also safe.
2976   SpellingBuffer.resize(Tok.getLength() + 1);
2977 
2978   // Get the spelling of the token, which eliminates trigraphs, etc.
2979   bool Invalid = false;
2980   StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
2981   if (Invalid)
2982     return ExprError();
2983 
2984   NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
2985   if (Literal.hadError)
2986     return ExprError();
2987 
2988   if (Literal.hasUDSuffix()) {
2989     // We're building a user-defined literal.
2990     IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2991     SourceLocation UDSuffixLoc =
2992       getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
2993 
2994     // Make sure we're allowed user-defined literals here.
2995     if (!UDLScope)
2996       return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
2997 
2998     QualType CookedTy;
2999     if (Literal.isFloatingLiteral()) {
3000       // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3001       // long double, the literal is treated as a call of the form
3002       //   operator "" X (f L)
3003       CookedTy = Context.LongDoubleTy;
3004     } else {
3005       // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3006       // unsigned long long, the literal is treated as a call of the form
3007       //   operator "" X (n ULL)
3008       CookedTy = Context.UnsignedLongLongTy;
3009     }
3010 
3011     DeclarationName OpName =
3012       Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3013     DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3014     OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3015 
3016     SourceLocation TokLoc = Tok.getLocation();
3017 
3018     // Perform literal operator lookup to determine if we're building a raw
3019     // literal or a cooked one.
3020     LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3021     switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3022                                   /*AllowRaw*/true, /*AllowTemplate*/true,
3023                                   /*AllowStringTemplate*/false)) {
3024     case LOLR_Error:
3025       return ExprError();
3026 
3027     case LOLR_Cooked: {
3028       Expr *Lit;
3029       if (Literal.isFloatingLiteral()) {
3030         Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3031       } else {
3032         llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3033         if (Literal.GetIntegerValue(ResultVal))
3034           Diag(Tok.getLocation(), diag::err_integer_too_large);
3035         Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3036                                      Tok.getLocation());
3037       }
3038       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3039     }
3040 
3041     case LOLR_Raw: {
3042       // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3043       // literal is treated as a call of the form
3044       //   operator "" X ("n")
3045       unsigned Length = Literal.getUDSuffixOffset();
3046       QualType StrTy = Context.getConstantArrayType(
3047           Context.CharTy.withConst(), llvm::APInt(32, Length + 1),
3048           ArrayType::Normal, 0);
3049       Expr *Lit = StringLiteral::Create(
3050           Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3051           /*Pascal*/false, StrTy, &TokLoc, 1);
3052       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3053     }
3054 
3055     case LOLR_Template: {
3056       // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3057       // template), L is treated as a call fo the form
3058       //   operator "" X <'c1', 'c2', ... 'ck'>()
3059       // where n is the source character sequence c1 c2 ... ck.
3060       TemplateArgumentListInfo ExplicitArgs;
3061       unsigned CharBits = Context.getIntWidth(Context.CharTy);
3062       bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3063       llvm::APSInt Value(CharBits, CharIsUnsigned);
3064       for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3065         Value = TokSpelling[I];
3066         TemplateArgument Arg(Context, Value, Context.CharTy);
3067         TemplateArgumentLocInfo ArgInfo;
3068         ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3069       }
3070       return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3071                                       &ExplicitArgs);
3072     }
3073     case LOLR_StringTemplate:
3074       llvm_unreachable("unexpected literal operator lookup result");
3075     }
3076   }
3077 
3078   Expr *Res;
3079 
3080   if (Literal.isFloatingLiteral()) {
3081     QualType Ty;
3082     if (Literal.isFloat)
3083       Ty = Context.FloatTy;
3084     else if (!Literal.isLong)
3085       Ty = Context.DoubleTy;
3086     else
3087       Ty = Context.LongDoubleTy;
3088 
3089     Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3090 
3091     if (Ty == Context.DoubleTy) {
3092       if (getLangOpts().SinglePrecisionConstants) {
3093         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
3094       } else if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
3095         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3096         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
3097       }
3098     }
3099   } else if (!Literal.isIntegerLiteral()) {
3100     return ExprError();
3101   } else {
3102     QualType Ty;
3103 
3104     // 'long long' is a C99 or C++11 feature.
3105     if (!getLangOpts().C99 && Literal.isLongLong) {
3106       if (getLangOpts().CPlusPlus)
3107         Diag(Tok.getLocation(),
3108              getLangOpts().CPlusPlus11 ?
3109              diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3110       else
3111         Diag(Tok.getLocation(), diag::ext_c99_longlong);
3112     }
3113 
3114     // Get the value in the widest-possible width.
3115     unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3116     // The microsoft literal suffix extensions support 128-bit literals, which
3117     // may be wider than [u]intmax_t.
3118     // FIXME: Actually, they don't. We seem to have accidentally invented the
3119     //        i128 suffix.
3120     if (Literal.isMicrosoftInteger && MaxWidth < 128 &&
3121         PP.getTargetInfo().hasInt128Type())
3122       MaxWidth = 128;
3123     llvm::APInt ResultVal(MaxWidth, 0);
3124 
3125     if (Literal.GetIntegerValue(ResultVal)) {
3126       // If this value didn't fit into uintmax_t, error and force to ull.
3127       Diag(Tok.getLocation(), diag::err_integer_too_large);
3128       Ty = Context.UnsignedLongLongTy;
3129       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3130              "long long is not intmax_t?");
3131     } else {
3132       // If this value fits into a ULL, try to figure out what else it fits into
3133       // according to the rules of C99 6.4.4.1p5.
3134 
3135       // Octal, Hexadecimal, and integers with a U suffix are allowed to
3136       // be an unsigned int.
3137       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3138 
3139       // Check from smallest to largest, picking the smallest type we can.
3140       unsigned Width = 0;
3141       if (!Literal.isLong && !Literal.isLongLong) {
3142         // Are int/unsigned possibilities?
3143         unsigned IntSize = Context.getTargetInfo().getIntWidth();
3144 
3145         // Does it fit in a unsigned int?
3146         if (ResultVal.isIntN(IntSize)) {
3147           // Does it fit in a signed int?
3148           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3149             Ty = Context.IntTy;
3150           else if (AllowUnsigned)
3151             Ty = Context.UnsignedIntTy;
3152           Width = IntSize;
3153         }
3154       }
3155 
3156       // Are long/unsigned long possibilities?
3157       if (Ty.isNull() && !Literal.isLongLong) {
3158         unsigned LongSize = Context.getTargetInfo().getLongWidth();
3159 
3160         // Does it fit in a unsigned long?
3161         if (ResultVal.isIntN(LongSize)) {
3162           // Does it fit in a signed long?
3163           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3164             Ty = Context.LongTy;
3165           else if (AllowUnsigned)
3166             Ty = Context.UnsignedLongTy;
3167           Width = LongSize;
3168         }
3169       }
3170 
3171       // Check long long if needed.
3172       if (Ty.isNull()) {
3173         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3174 
3175         // Does it fit in a unsigned long long?
3176         if (ResultVal.isIntN(LongLongSize)) {
3177           // Does it fit in a signed long long?
3178           // To be compatible with MSVC, hex integer literals ending with the
3179           // LL or i64 suffix are always signed in Microsoft mode.
3180           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3181               (getLangOpts().MicrosoftExt && Literal.isLongLong)))
3182             Ty = Context.LongLongTy;
3183           else if (AllowUnsigned)
3184             Ty = Context.UnsignedLongLongTy;
3185           Width = LongLongSize;
3186         }
3187       }
3188 
3189       // If it doesn't fit in unsigned long long, and we're using Microsoft
3190       // extensions, then its a 128-bit integer literal.
3191       if (Ty.isNull() && Literal.isMicrosoftInteger &&
3192           PP.getTargetInfo().hasInt128Type()) {
3193         if (Literal.isUnsigned)
3194           Ty = Context.UnsignedInt128Ty;
3195         else
3196           Ty = Context.Int128Ty;
3197         Width = 128;
3198       }
3199 
3200       // If we still couldn't decide a type, we probably have something that
3201       // does not fit in a signed long long, but has no U suffix.
3202       if (Ty.isNull()) {
3203         Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
3204         Ty = Context.UnsignedLongLongTy;
3205         Width = Context.getTargetInfo().getLongLongWidth();
3206       }
3207 
3208       if (ResultVal.getBitWidth() != Width)
3209         ResultVal = ResultVal.trunc(Width);
3210     }
3211     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3212   }
3213 
3214   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3215   if (Literal.isImaginary)
3216     Res = new (Context) ImaginaryLiteral(Res,
3217                                         Context.getComplexType(Res->getType()));
3218 
3219   return Owned(Res);
3220 }
3221 
3222 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
3223   assert((E != 0) && "ActOnParenExpr() missing expr");
3224   return Owned(new (Context) ParenExpr(L, R, E));
3225 }
3226 
3227 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3228                                          SourceLocation Loc,
3229                                          SourceRange ArgRange) {
3230   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3231   // scalar or vector data type argument..."
3232   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3233   // type (C99 6.2.5p18) or void.
3234   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3235     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3236       << T << ArgRange;
3237     return true;
3238   }
3239 
3240   assert((T->isVoidType() || !T->isIncompleteType()) &&
3241          "Scalar types should always be complete");
3242   return false;
3243 }
3244 
3245 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3246                                            SourceLocation Loc,
3247                                            SourceRange ArgRange,
3248                                            UnaryExprOrTypeTrait TraitKind) {
3249   // Invalid types must be hard errors for SFINAE in C++.
3250   if (S.LangOpts.CPlusPlus)
3251     return true;
3252 
3253   // C99 6.5.3.4p1:
3254   if (T->isFunctionType() &&
3255       (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) {
3256     // sizeof(function)/alignof(function) is allowed as an extension.
3257     S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3258       << TraitKind << ArgRange;
3259     return false;
3260   }
3261 
3262   // Allow sizeof(void)/alignof(void) as an extension.
3263   if (T->isVoidType()) {
3264     S.Diag(Loc, diag::ext_sizeof_alignof_void_type) << TraitKind << ArgRange;
3265     return false;
3266   }
3267 
3268   return true;
3269 }
3270 
3271 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
3272                                              SourceLocation Loc,
3273                                              SourceRange ArgRange,
3274                                              UnaryExprOrTypeTrait TraitKind) {
3275   // Reject sizeof(interface) and sizeof(interface<proto>) if the
3276   // runtime doesn't allow it.
3277   if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
3278     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3279       << T << (TraitKind == UETT_SizeOf)
3280       << ArgRange;
3281     return true;
3282   }
3283 
3284   return false;
3285 }
3286 
3287 /// \brief Check whether E is a pointer from a decayed array type (the decayed
3288 /// pointer type is equal to T) and emit a warning if it is.
3289 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
3290                                      Expr *E) {
3291   // Don't warn if the operation changed the type.
3292   if (T != E->getType())
3293     return;
3294 
3295   // Now look for array decays.
3296   ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
3297   if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
3298     return;
3299 
3300   S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
3301                                              << ICE->getType()
3302                                              << ICE->getSubExpr()->getType();
3303 }
3304 
3305 /// \brief Check the constrains on expression operands to unary type expression
3306 /// and type traits.
3307 ///
3308 /// Completes any types necessary and validates the constraints on the operand
3309 /// expression. The logic mostly mirrors the type-based overload, but may modify
3310 /// the expression as it completes the type for that expression through template
3311 /// instantiation, etc.
3312 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
3313                                             UnaryExprOrTypeTrait ExprKind) {
3314   QualType ExprTy = E->getType();
3315   assert(!ExprTy->isReferenceType());
3316 
3317   if (ExprKind == UETT_VecStep)
3318     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
3319                                         E->getSourceRange());
3320 
3321   // Whitelist some types as extensions
3322   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
3323                                       E->getSourceRange(), ExprKind))
3324     return false;
3325 
3326   if (RequireCompleteExprType(E,
3327                               diag::err_sizeof_alignof_incomplete_type,
3328                               ExprKind, E->getSourceRange()))
3329     return true;
3330 
3331   // Completing the expression's type may have changed it.
3332   ExprTy = E->getType();
3333   assert(!ExprTy->isReferenceType());
3334 
3335   if (ExprTy->isFunctionType()) {
3336     Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
3337       << ExprKind << E->getSourceRange();
3338     return true;
3339   }
3340 
3341   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
3342                                        E->getSourceRange(), ExprKind))
3343     return true;
3344 
3345   if (ExprKind == UETT_SizeOf) {
3346     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
3347       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
3348         QualType OType = PVD->getOriginalType();
3349         QualType Type = PVD->getType();
3350         if (Type->isPointerType() && OType->isArrayType()) {
3351           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
3352             << Type << OType;
3353           Diag(PVD->getLocation(), diag::note_declared_at);
3354         }
3355       }
3356     }
3357 
3358     // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
3359     // decays into a pointer and returns an unintended result. This is most
3360     // likely a typo for "sizeof(array) op x".
3361     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
3362       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3363                                BO->getLHS());
3364       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3365                                BO->getRHS());
3366     }
3367   }
3368 
3369   return false;
3370 }
3371 
3372 /// \brief Check the constraints on operands to unary expression and type
3373 /// traits.
3374 ///
3375 /// This will complete any types necessary, and validate the various constraints
3376 /// on those operands.
3377 ///
3378 /// The UsualUnaryConversions() function is *not* called by this routine.
3379 /// C99 6.3.2.1p[2-4] all state:
3380 ///   Except when it is the operand of the sizeof operator ...
3381 ///
3382 /// C++ [expr.sizeof]p4
3383 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3384 ///   standard conversions are not applied to the operand of sizeof.
3385 ///
3386 /// This policy is followed for all of the unary trait expressions.
3387 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
3388                                             SourceLocation OpLoc,
3389                                             SourceRange ExprRange,
3390                                             UnaryExprOrTypeTrait ExprKind) {
3391   if (ExprType->isDependentType())
3392     return false;
3393 
3394   // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
3395   //   the result is the size of the referenced type."
3396   // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
3397   //   result shall be the alignment of the referenced type."
3398   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3399     ExprType = Ref->getPointeeType();
3400 
3401   if (ExprKind == UETT_VecStep)
3402     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
3403 
3404   // Whitelist some types as extensions
3405   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
3406                                       ExprKind))
3407     return false;
3408 
3409   if (RequireCompleteType(OpLoc, ExprType,
3410                           diag::err_sizeof_alignof_incomplete_type,
3411                           ExprKind, ExprRange))
3412     return true;
3413 
3414   if (ExprType->isFunctionType()) {
3415     Diag(OpLoc, diag::err_sizeof_alignof_function_type)
3416       << ExprKind << ExprRange;
3417     return true;
3418   }
3419 
3420   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
3421                                        ExprKind))
3422     return true;
3423 
3424   return false;
3425 }
3426 
3427 static bool CheckAlignOfExpr(Sema &S, Expr *E) {
3428   E = E->IgnoreParens();
3429 
3430   // Cannot know anything else if the expression is dependent.
3431   if (E->isTypeDependent())
3432     return false;
3433 
3434   if (E->getObjectKind() == OK_BitField) {
3435     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield)
3436        << 1 << E->getSourceRange();
3437     return true;
3438   }
3439 
3440   ValueDecl *D = 0;
3441   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3442     D = DRE->getDecl();
3443   } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3444     D = ME->getMemberDecl();
3445   }
3446 
3447   // If it's a field, require the containing struct to have a
3448   // complete definition so that we can compute the layout.
3449   //
3450   // This requires a very particular set of circumstances.  For a
3451   // field to be contained within an incomplete type, we must in the
3452   // process of parsing that type.  To have an expression refer to a
3453   // field, it must be an id-expression or a member-expression, but
3454   // the latter are always ill-formed when the base type is
3455   // incomplete, including only being partially complete.  An
3456   // id-expression can never refer to a field in C because fields
3457   // are not in the ordinary namespace.  In C++, an id-expression
3458   // can implicitly be a member access, but only if there's an
3459   // implicit 'this' value, and all such contexts are subject to
3460   // delayed parsing --- except for trailing return types in C++11.
3461   // And if an id-expression referring to a field occurs in a
3462   // context that lacks a 'this' value, it's ill-formed --- except,
3463   // agian, in C++11, where such references are allowed in an
3464   // unevaluated context.  So C++11 introduces some new complexity.
3465   //
3466   // For the record, since __alignof__ on expressions is a GCC
3467   // extension, GCC seems to permit this but always gives the
3468   // nonsensical answer 0.
3469   //
3470   // We don't really need the layout here --- we could instead just
3471   // directly check for all the appropriate alignment-lowing
3472   // attributes --- but that would require duplicating a lot of
3473   // logic that just isn't worth duplicating for such a marginal
3474   // use-case.
3475   if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
3476     // Fast path this check, since we at least know the record has a
3477     // definition if we can find a member of it.
3478     if (!FD->getParent()->isCompleteDefinition()) {
3479       S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
3480         << E->getSourceRange();
3481       return true;
3482     }
3483 
3484     // Otherwise, if it's a field, and the field doesn't have
3485     // reference type, then it must have a complete type (or be a
3486     // flexible array member, which we explicitly want to
3487     // white-list anyway), which makes the following checks trivial.
3488     if (!FD->getType()->isReferenceType())
3489       return false;
3490   }
3491 
3492   return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
3493 }
3494 
3495 bool Sema::CheckVecStepExpr(Expr *E) {
3496   E = E->IgnoreParens();
3497 
3498   // Cannot know anything else if the expression is dependent.
3499   if (E->isTypeDependent())
3500     return false;
3501 
3502   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
3503 }
3504 
3505 /// \brief Build a sizeof or alignof expression given a type operand.
3506 ExprResult
3507 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3508                                      SourceLocation OpLoc,
3509                                      UnaryExprOrTypeTrait ExprKind,
3510                                      SourceRange R) {
3511   if (!TInfo)
3512     return ExprError();
3513 
3514   QualType T = TInfo->getType();
3515 
3516   if (!T->isDependentType() &&
3517       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
3518     return ExprError();
3519 
3520   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
3521   return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo,
3522                                                       Context.getSizeType(),
3523                                                       OpLoc, R.getEnd()));
3524 }
3525 
3526 /// \brief Build a sizeof or alignof expression given an expression
3527 /// operand.
3528 ExprResult
3529 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
3530                                      UnaryExprOrTypeTrait ExprKind) {
3531   ExprResult PE = CheckPlaceholderExpr(E);
3532   if (PE.isInvalid())
3533     return ExprError();
3534 
3535   E = PE.get();
3536 
3537   // Verify that the operand is valid.
3538   bool isInvalid = false;
3539   if (E->isTypeDependent()) {
3540     // Delay type-checking for type-dependent expressions.
3541   } else if (ExprKind == UETT_AlignOf) {
3542     isInvalid = CheckAlignOfExpr(*this, E);
3543   } else if (ExprKind == UETT_VecStep) {
3544     isInvalid = CheckVecStepExpr(E);
3545   } else if (E->refersToBitField()) {  // C99 6.5.3.4p1.
3546     Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0;
3547     isInvalid = true;
3548   } else {
3549     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
3550   }
3551 
3552   if (isInvalid)
3553     return ExprError();
3554 
3555   if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
3556     PE = TransformToPotentiallyEvaluated(E);
3557     if (PE.isInvalid()) return ExprError();
3558     E = PE.take();
3559   }
3560 
3561   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
3562   return Owned(new (Context) UnaryExprOrTypeTraitExpr(
3563       ExprKind, E, Context.getSizeType(), OpLoc,
3564       E->getSourceRange().getEnd()));
3565 }
3566 
3567 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
3568 /// expr and the same for @c alignof and @c __alignof
3569 /// Note that the ArgRange is invalid if isType is false.
3570 ExprResult
3571 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
3572                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
3573                                     void *TyOrEx, const SourceRange &ArgRange) {
3574   // If error parsing type, ignore.
3575   if (TyOrEx == 0) return ExprError();
3576 
3577   if (IsType) {
3578     TypeSourceInfo *TInfo;
3579     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
3580     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
3581   }
3582 
3583   Expr *ArgEx = (Expr *)TyOrEx;
3584   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
3585   return Result;
3586 }
3587 
3588 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
3589                                      bool IsReal) {
3590   if (V.get()->isTypeDependent())
3591     return S.Context.DependentTy;
3592 
3593   // _Real and _Imag are only l-values for normal l-values.
3594   if (V.get()->getObjectKind() != OK_Ordinary) {
3595     V = S.DefaultLvalueConversion(V.take());
3596     if (V.isInvalid())
3597       return QualType();
3598   }
3599 
3600   // These operators return the element type of a complex type.
3601   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
3602     return CT->getElementType();
3603 
3604   // Otherwise they pass through real integer and floating point types here.
3605   if (V.get()->getType()->isArithmeticType())
3606     return V.get()->getType();
3607 
3608   // Test for placeholders.
3609   ExprResult PR = S.CheckPlaceholderExpr(V.get());
3610   if (PR.isInvalid()) return QualType();
3611   if (PR.get() != V.get()) {
3612     V = PR;
3613     return CheckRealImagOperand(S, V, Loc, IsReal);
3614   }
3615 
3616   // Reject anything else.
3617   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
3618     << (IsReal ? "__real" : "__imag");
3619   return QualType();
3620 }
3621 
3622 
3623 
3624 ExprResult
3625 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
3626                           tok::TokenKind Kind, Expr *Input) {
3627   UnaryOperatorKind Opc;
3628   switch (Kind) {
3629   default: llvm_unreachable("Unknown unary op!");
3630   case tok::plusplus:   Opc = UO_PostInc; break;
3631   case tok::minusminus: Opc = UO_PostDec; break;
3632   }
3633 
3634   // Since this might is a postfix expression, get rid of ParenListExprs.
3635   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
3636   if (Result.isInvalid()) return ExprError();
3637   Input = Result.take();
3638 
3639   return BuildUnaryOp(S, OpLoc, Opc, Input);
3640 }
3641 
3642 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal.
3643 ///
3644 /// \return true on error
3645 static bool checkArithmeticOnObjCPointer(Sema &S,
3646                                          SourceLocation opLoc,
3647                                          Expr *op) {
3648   assert(op->getType()->isObjCObjectPointerType());
3649   if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
3650       !S.LangOpts.ObjCSubscriptingLegacyRuntime)
3651     return false;
3652 
3653   S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
3654     << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
3655     << op->getSourceRange();
3656   return true;
3657 }
3658 
3659 ExprResult
3660 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
3661                               Expr *idx, SourceLocation rbLoc) {
3662   // Since this might be a postfix expression, get rid of ParenListExprs.
3663   if (isa<ParenListExpr>(base)) {
3664     ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
3665     if (result.isInvalid()) return ExprError();
3666     base = result.take();
3667   }
3668 
3669   // Handle any non-overload placeholder types in the base and index
3670   // expressions.  We can't handle overloads here because the other
3671   // operand might be an overloadable type, in which case the overload
3672   // resolution for the operator overload should get the first crack
3673   // at the overload.
3674   if (base->getType()->isNonOverloadPlaceholderType()) {
3675     ExprResult result = CheckPlaceholderExpr(base);
3676     if (result.isInvalid()) return ExprError();
3677     base = result.take();
3678   }
3679   if (idx->getType()->isNonOverloadPlaceholderType()) {
3680     ExprResult result = CheckPlaceholderExpr(idx);
3681     if (result.isInvalid()) return ExprError();
3682     idx = result.take();
3683   }
3684 
3685   // Build an unanalyzed expression if either operand is type-dependent.
3686   if (getLangOpts().CPlusPlus &&
3687       (base->isTypeDependent() || idx->isTypeDependent())) {
3688     return Owned(new (Context) ArraySubscriptExpr(base, idx,
3689                                                   Context.DependentTy,
3690                                                   VK_LValue, OK_Ordinary,
3691                                                   rbLoc));
3692   }
3693 
3694   // Use C++ overloaded-operator rules if either operand has record
3695   // type.  The spec says to do this if either type is *overloadable*,
3696   // but enum types can't declare subscript operators or conversion
3697   // operators, so there's nothing interesting for overload resolution
3698   // to do if there aren't any record types involved.
3699   //
3700   // ObjC pointers have their own subscripting logic that is not tied
3701   // to overload resolution and so should not take this path.
3702   if (getLangOpts().CPlusPlus &&
3703       (base->getType()->isRecordType() ||
3704        (!base->getType()->isObjCObjectPointerType() &&
3705         idx->getType()->isRecordType()))) {
3706     return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
3707   }
3708 
3709   return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
3710 }
3711 
3712 ExprResult
3713 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
3714                                       Expr *Idx, SourceLocation RLoc) {
3715   Expr *LHSExp = Base;
3716   Expr *RHSExp = Idx;
3717 
3718   // Perform default conversions.
3719   if (!LHSExp->getType()->getAs<VectorType>()) {
3720     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
3721     if (Result.isInvalid())
3722       return ExprError();
3723     LHSExp = Result.take();
3724   }
3725   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
3726   if (Result.isInvalid())
3727     return ExprError();
3728   RHSExp = Result.take();
3729 
3730   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
3731   ExprValueKind VK = VK_LValue;
3732   ExprObjectKind OK = OK_Ordinary;
3733 
3734   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
3735   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
3736   // in the subscript position. As a result, we need to derive the array base
3737   // and index from the expression types.
3738   Expr *BaseExpr, *IndexExpr;
3739   QualType ResultType;
3740   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3741     BaseExpr = LHSExp;
3742     IndexExpr = RHSExp;
3743     ResultType = Context.DependentTy;
3744   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
3745     BaseExpr = LHSExp;
3746     IndexExpr = RHSExp;
3747     ResultType = PTy->getPointeeType();
3748   } else if (const ObjCObjectPointerType *PTy =
3749                LHSTy->getAs<ObjCObjectPointerType>()) {
3750     BaseExpr = LHSExp;
3751     IndexExpr = RHSExp;
3752 
3753     // Use custom logic if this should be the pseudo-object subscript
3754     // expression.
3755     if (!LangOpts.isSubscriptPointerArithmetic())
3756       return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, 0, 0);
3757 
3758     ResultType = PTy->getPointeeType();
3759   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
3760      // Handle the uncommon case of "123[Ptr]".
3761     BaseExpr = RHSExp;
3762     IndexExpr = LHSExp;
3763     ResultType = PTy->getPointeeType();
3764   } else if (const ObjCObjectPointerType *PTy =
3765                RHSTy->getAs<ObjCObjectPointerType>()) {
3766      // Handle the uncommon case of "123[Ptr]".
3767     BaseExpr = RHSExp;
3768     IndexExpr = LHSExp;
3769     ResultType = PTy->getPointeeType();
3770     if (!LangOpts.isSubscriptPointerArithmetic()) {
3771       Diag(LLoc, diag::err_subscript_nonfragile_interface)
3772         << ResultType << BaseExpr->getSourceRange();
3773       return ExprError();
3774     }
3775   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
3776     BaseExpr = LHSExp;    // vectors: V[123]
3777     IndexExpr = RHSExp;
3778     VK = LHSExp->getValueKind();
3779     if (VK != VK_RValue)
3780       OK = OK_VectorComponent;
3781 
3782     // FIXME: need to deal with const...
3783     ResultType = VTy->getElementType();
3784   } else if (LHSTy->isArrayType()) {
3785     // If we see an array that wasn't promoted by
3786     // DefaultFunctionArrayLvalueConversion, it must be an array that
3787     // wasn't promoted because of the C90 rule that doesn't
3788     // allow promoting non-lvalue arrays.  Warn, then
3789     // force the promotion here.
3790     Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3791         LHSExp->getSourceRange();
3792     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
3793                                CK_ArrayToPointerDecay).take();
3794     LHSTy = LHSExp->getType();
3795 
3796     BaseExpr = LHSExp;
3797     IndexExpr = RHSExp;
3798     ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
3799   } else if (RHSTy->isArrayType()) {
3800     // Same as previous, except for 123[f().a] case
3801     Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3802         RHSExp->getSourceRange();
3803     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
3804                                CK_ArrayToPointerDecay).take();
3805     RHSTy = RHSExp->getType();
3806 
3807     BaseExpr = RHSExp;
3808     IndexExpr = LHSExp;
3809     ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
3810   } else {
3811     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3812        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
3813   }
3814   // C99 6.5.2.1p1
3815   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
3816     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3817                      << IndexExpr->getSourceRange());
3818 
3819   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
3820        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3821          && !IndexExpr->isTypeDependent())
3822     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3823 
3824   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
3825   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3826   // type. Note that Functions are not objects, and that (in C99 parlance)
3827   // incomplete types are not object types.
3828   if (ResultType->isFunctionType()) {
3829     Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3830       << ResultType << BaseExpr->getSourceRange();
3831     return ExprError();
3832   }
3833 
3834   if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
3835     // GNU extension: subscripting on pointer to void
3836     Diag(LLoc, diag::ext_gnu_subscript_void_type)
3837       << BaseExpr->getSourceRange();
3838 
3839     // C forbids expressions of unqualified void type from being l-values.
3840     // See IsCForbiddenLValueType.
3841     if (!ResultType.hasQualifiers()) VK = VK_RValue;
3842   } else if (!ResultType->isDependentType() &&
3843       RequireCompleteType(LLoc, ResultType,
3844                           diag::err_subscript_incomplete_type, BaseExpr))
3845     return ExprError();
3846 
3847   assert(VK == VK_RValue || LangOpts.CPlusPlus ||
3848          !ResultType.isCForbiddenLValueType());
3849 
3850   return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
3851                                                 ResultType, VK, OK, RLoc));
3852 }
3853 
3854 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
3855                                         FunctionDecl *FD,
3856                                         ParmVarDecl *Param) {
3857   if (Param->hasUnparsedDefaultArg()) {
3858     Diag(CallLoc,
3859          diag::err_use_of_default_argument_to_function_declared_later) <<
3860       FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
3861     Diag(UnparsedDefaultArgLocs[Param],
3862          diag::note_default_argument_declared_here);
3863     return ExprError();
3864   }
3865 
3866   if (Param->hasUninstantiatedDefaultArg()) {
3867     Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
3868 
3869     EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated,
3870                                                  Param);
3871 
3872     // Instantiate the expression.
3873     MultiLevelTemplateArgumentList MutiLevelArgList
3874       = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
3875 
3876     InstantiatingTemplate Inst(*this, CallLoc, Param,
3877                                MutiLevelArgList.getInnermost());
3878     if (Inst.isInvalid())
3879       return ExprError();
3880 
3881     ExprResult Result;
3882     {
3883       // C++ [dcl.fct.default]p5:
3884       //   The names in the [default argument] expression are bound, and
3885       //   the semantic constraints are checked, at the point where the
3886       //   default argument expression appears.
3887       ContextRAII SavedContext(*this, FD);
3888       LocalInstantiationScope Local(*this);
3889       Result = SubstExpr(UninstExpr, MutiLevelArgList);
3890     }
3891     if (Result.isInvalid())
3892       return ExprError();
3893 
3894     // Check the expression as an initializer for the parameter.
3895     InitializedEntity Entity
3896       = InitializedEntity::InitializeParameter(Context, Param);
3897     InitializationKind Kind
3898       = InitializationKind::CreateCopy(Param->getLocation(),
3899              /*FIXME:EqualLoc*/UninstExpr->getLocStart());
3900     Expr *ResultE = Result.takeAs<Expr>();
3901 
3902     InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
3903     Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
3904     if (Result.isInvalid())
3905       return ExprError();
3906 
3907     Expr *Arg = Result.takeAs<Expr>();
3908     CheckCompletedExpr(Arg, Param->getOuterLocStart());
3909     // Build the default argument expression.
3910     return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param, Arg));
3911   }
3912 
3913   // If the default expression creates temporaries, we need to
3914   // push them to the current stack of expression temporaries so they'll
3915   // be properly destroyed.
3916   // FIXME: We should really be rebuilding the default argument with new
3917   // bound temporaries; see the comment in PR5810.
3918   // We don't need to do that with block decls, though, because
3919   // blocks in default argument expression can never capture anything.
3920   if (isa<ExprWithCleanups>(Param->getInit())) {
3921     // Set the "needs cleanups" bit regardless of whether there are
3922     // any explicit objects.
3923     ExprNeedsCleanups = true;
3924 
3925     // Append all the objects to the cleanup list.  Right now, this
3926     // should always be a no-op, because blocks in default argument
3927     // expressions should never be able to capture anything.
3928     assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() &&
3929            "default argument expression has capturing blocks?");
3930   }
3931 
3932   // We already type-checked the argument, so we know it works.
3933   // Just mark all of the declarations in this potentially-evaluated expression
3934   // as being "referenced".
3935   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
3936                                    /*SkipLocalVariables=*/true);
3937   return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
3938 }
3939 
3940 
3941 Sema::VariadicCallType
3942 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
3943                           Expr *Fn) {
3944   if (Proto && Proto->isVariadic()) {
3945     if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
3946       return VariadicConstructor;
3947     else if (Fn && Fn->getType()->isBlockPointerType())
3948       return VariadicBlock;
3949     else if (FDecl) {
3950       if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3951         if (Method->isInstance())
3952           return VariadicMethod;
3953     } else if (Fn && Fn->getType() == Context.BoundMemberTy)
3954       return VariadicMethod;
3955     return VariadicFunction;
3956   }
3957   return VariadicDoesNotApply;
3958 }
3959 
3960 namespace {
3961 class FunctionCallCCC : public FunctionCallFilterCCC {
3962 public:
3963   FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
3964                   unsigned NumArgs, bool HasExplicitTemplateArgs)
3965       : FunctionCallFilterCCC(SemaRef, NumArgs, HasExplicitTemplateArgs),
3966         FunctionName(FuncName) {}
3967 
3968   virtual bool ValidateCandidate(const TypoCorrection &candidate) {
3969     if (!candidate.getCorrectionSpecifier() ||
3970         candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
3971       return false;
3972     }
3973 
3974     return FunctionCallFilterCCC::ValidateCandidate(candidate);
3975   }
3976 
3977 private:
3978   const IdentifierInfo *const FunctionName;
3979 };
3980 }
3981 
3982 static TypoCorrection TryTypoCorrectionForCall(Sema &S,
3983                                                DeclarationNameInfo FuncName,
3984                                                ArrayRef<Expr *> Args) {
3985   FunctionCallCCC CCC(S, FuncName.getName().getAsIdentifierInfo(),
3986                       Args.size(), false);
3987   if (TypoCorrection Corrected =
3988           S.CorrectTypo(FuncName, Sema::LookupOrdinaryName,
3989                         S.getScopeForContext(S.CurContext), NULL, CCC)) {
3990     if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
3991       if (Corrected.isOverloaded()) {
3992         OverloadCandidateSet OCS(FuncName.getLoc());
3993         OverloadCandidateSet::iterator Best;
3994         for (TypoCorrection::decl_iterator CD = Corrected.begin(),
3995                                            CDEnd = Corrected.end();
3996              CD != CDEnd; ++CD) {
3997           if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
3998             S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
3999                                    OCS);
4000         }
4001         switch (OCS.BestViableFunction(S, FuncName.getLoc(), Best)) {
4002         case OR_Success:
4003           ND = Best->Function;
4004           Corrected.setCorrectionDecl(ND);
4005           break;
4006         default:
4007           break;
4008         }
4009       }
4010       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
4011         return Corrected;
4012       }
4013     }
4014   }
4015   return TypoCorrection();
4016 }
4017 
4018 /// ConvertArgumentsForCall - Converts the arguments specified in
4019 /// Args/NumArgs to the parameter types of the function FDecl with
4020 /// function prototype Proto. Call is the call expression itself, and
4021 /// Fn is the function expression. For a C++ member function, this
4022 /// routine does not attempt to convert the object argument. Returns
4023 /// true if the call is ill-formed.
4024 bool
4025 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
4026                               FunctionDecl *FDecl,
4027                               const FunctionProtoType *Proto,
4028                               ArrayRef<Expr *> Args,
4029                               SourceLocation RParenLoc,
4030                               bool IsExecConfig) {
4031   // Bail out early if calling a builtin with custom typechecking.
4032   // We don't need to do this in the
4033   if (FDecl)
4034     if (unsigned ID = FDecl->getBuiltinID())
4035       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
4036         return false;
4037 
4038   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
4039   // assignment, to the types of the corresponding parameter, ...
4040   unsigned NumArgsInProto = Proto->getNumArgs();
4041   bool Invalid = false;
4042   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumArgsInProto;
4043   unsigned FnKind = Fn->getType()->isBlockPointerType()
4044                        ? 1 /* block */
4045                        : (IsExecConfig ? 3 /* kernel function (exec config) */
4046                                        : 0 /* function */);
4047 
4048   // If too few arguments are available (and we don't have default
4049   // arguments for the remaining parameters), don't make the call.
4050   if (Args.size() < NumArgsInProto) {
4051     if (Args.size() < MinArgs) {
4052       MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
4053       TypoCorrection TC;
4054       if (FDecl && (TC = TryTypoCorrectionForCall(
4055                         *this, DeclarationNameInfo(FDecl->getDeclName(),
4056                                                    (ME ? ME->getMemberLoc()
4057                                                        : Fn->getLocStart())),
4058                         Args))) {
4059         unsigned diag_id =
4060             MinArgs == NumArgsInProto && !Proto->isVariadic()
4061                 ? diag::err_typecheck_call_too_few_args_suggest
4062                 : diag::err_typecheck_call_too_few_args_at_least_suggest;
4063         diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
4064                                         << static_cast<unsigned>(Args.size())
4065                                         << Fn->getSourceRange());
4066       } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
4067         Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic()
4068                           ? diag::err_typecheck_call_too_few_args_one
4069                           : diag::err_typecheck_call_too_few_args_at_least_one)
4070           << FnKind
4071           << FDecl->getParamDecl(0) << Fn->getSourceRange();
4072       else
4073         Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic()
4074                           ? diag::err_typecheck_call_too_few_args
4075                           : diag::err_typecheck_call_too_few_args_at_least)
4076           << FnKind
4077           << MinArgs << static_cast<unsigned>(Args.size())
4078           << Fn->getSourceRange();
4079 
4080       // Emit the location of the prototype.
4081       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4082         Diag(FDecl->getLocStart(), diag::note_callee_decl)
4083           << FDecl;
4084 
4085       return true;
4086     }
4087     Call->setNumArgs(Context, NumArgsInProto);
4088   }
4089 
4090   // If too many are passed and not variadic, error on the extras and drop
4091   // them.
4092   if (Args.size() > NumArgsInProto) {
4093     if (!Proto->isVariadic()) {
4094       TypoCorrection TC;
4095       if (FDecl && (TC = TryTypoCorrectionForCall(
4096                         *this, DeclarationNameInfo(FDecl->getDeclName(),
4097                                                    Fn->getLocStart()),
4098                         Args))) {
4099         unsigned diag_id =
4100             MinArgs == NumArgsInProto && !Proto->isVariadic()
4101                 ? diag::err_typecheck_call_too_many_args_suggest
4102                 : diag::err_typecheck_call_too_many_args_at_most_suggest;
4103         diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumArgsInProto
4104                                         << static_cast<unsigned>(Args.size())
4105                                         << Fn->getSourceRange());
4106       } else if (NumArgsInProto == 1 && FDecl &&
4107                  FDecl->getParamDecl(0)->getDeclName())
4108         Diag(Args[NumArgsInProto]->getLocStart(),
4109              MinArgs == NumArgsInProto
4110                ? diag::err_typecheck_call_too_many_args_one
4111                : diag::err_typecheck_call_too_many_args_at_most_one)
4112           << FnKind
4113           << FDecl->getParamDecl(0) << static_cast<unsigned>(Args.size())
4114           << Fn->getSourceRange()
4115           << SourceRange(Args[NumArgsInProto]->getLocStart(),
4116                          Args.back()->getLocEnd());
4117       else
4118         Diag(Args[NumArgsInProto]->getLocStart(),
4119              MinArgs == NumArgsInProto
4120                ? diag::err_typecheck_call_too_many_args
4121                : diag::err_typecheck_call_too_many_args_at_most)
4122           << FnKind
4123           << NumArgsInProto << static_cast<unsigned>(Args.size())
4124           << Fn->getSourceRange()
4125           << SourceRange(Args[NumArgsInProto]->getLocStart(),
4126                          Args.back()->getLocEnd());
4127 
4128       // Emit the location of the prototype.
4129       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4130         Diag(FDecl->getLocStart(), diag::note_callee_decl)
4131           << FDecl;
4132 
4133       // This deletes the extra arguments.
4134       Call->setNumArgs(Context, NumArgsInProto);
4135       return true;
4136     }
4137   }
4138   SmallVector<Expr *, 8> AllArgs;
4139   VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
4140 
4141   Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
4142                                    Proto, 0, Args, AllArgs, CallType);
4143   if (Invalid)
4144     return true;
4145   unsigned TotalNumArgs = AllArgs.size();
4146   for (unsigned i = 0; i < TotalNumArgs; ++i)
4147     Call->setArg(i, AllArgs[i]);
4148 
4149   return false;
4150 }
4151 
4152 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
4153                                   FunctionDecl *FDecl,
4154                                   const FunctionProtoType *Proto,
4155                                   unsigned FirstProtoArg,
4156                                   ArrayRef<Expr *> Args,
4157                                   SmallVectorImpl<Expr *> &AllArgs,
4158                                   VariadicCallType CallType,
4159                                   bool AllowExplicit,
4160                                   bool IsListInitialization) {
4161   unsigned NumArgsInProto = Proto->getNumArgs();
4162   unsigned NumArgsToCheck = Args.size();
4163   bool Invalid = false;
4164   if (Args.size() != NumArgsInProto)
4165     // Use default arguments for missing arguments
4166     NumArgsToCheck = NumArgsInProto;
4167   unsigned ArgIx = 0;
4168   // Continue to check argument types (even if we have too few/many args).
4169   for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
4170     QualType ProtoArgType = Proto->getArgType(i);
4171 
4172     Expr *Arg;
4173     ParmVarDecl *Param;
4174     if (ArgIx < Args.size()) {
4175       Arg = Args[ArgIx++];
4176 
4177       if (RequireCompleteType(Arg->getLocStart(),
4178                               ProtoArgType,
4179                               diag::err_call_incomplete_argument, Arg))
4180         return true;
4181 
4182       // Pass the argument
4183       Param = 0;
4184       if (FDecl && i < FDecl->getNumParams())
4185         Param = FDecl->getParamDecl(i);
4186 
4187       // Strip the unbridged-cast placeholder expression off, if applicable.
4188       bool CFAudited = false;
4189       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
4190           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4191           (!Param || !Param->hasAttr<CFConsumedAttr>()))
4192         Arg = stripARCUnbridgedCast(Arg);
4193       else if (getLangOpts().ObjCAutoRefCount &&
4194                FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4195                (!Param || !Param->hasAttr<CFConsumedAttr>()))
4196         CFAudited = true;
4197 
4198       InitializedEntity Entity = Param ?
4199           InitializedEntity::InitializeParameter(Context, Param, ProtoArgType)
4200         : InitializedEntity::InitializeParameter(Context, ProtoArgType,
4201                                                  Proto->isArgConsumed(i));
4202 
4203       // Remember that parameter belongs to a CF audited API.
4204       if (CFAudited)
4205         Entity.setParameterCFAudited();
4206 
4207       ExprResult ArgE = PerformCopyInitialization(Entity,
4208                                                   SourceLocation(),
4209                                                   Owned(Arg),
4210                                                   IsListInitialization,
4211                                                   AllowExplicit);
4212       if (ArgE.isInvalid())
4213         return true;
4214 
4215       Arg = ArgE.takeAs<Expr>();
4216     } else {
4217       assert(FDecl && "can't use default arguments without a known callee");
4218       Param = FDecl->getParamDecl(i);
4219 
4220       ExprResult ArgExpr =
4221         BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
4222       if (ArgExpr.isInvalid())
4223         return true;
4224 
4225       Arg = ArgExpr.takeAs<Expr>();
4226     }
4227 
4228     // Check for array bounds violations for each argument to the call. This
4229     // check only triggers warnings when the argument isn't a more complex Expr
4230     // with its own checking, such as a BinaryOperator.
4231     CheckArrayAccess(Arg);
4232 
4233     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
4234     CheckStaticArrayArgument(CallLoc, Param, Arg);
4235 
4236     AllArgs.push_back(Arg);
4237   }
4238 
4239   // If this is a variadic call, handle args passed through "...".
4240   if (CallType != VariadicDoesNotApply) {
4241     // Assume that extern "C" functions with variadic arguments that
4242     // return __unknown_anytype aren't *really* variadic.
4243     if (Proto->getResultType() == Context.UnknownAnyTy &&
4244         FDecl && FDecl->isExternC()) {
4245       for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) {
4246         QualType paramType; // ignored
4247         ExprResult arg = checkUnknownAnyArg(CallLoc, Args[i], paramType);
4248         Invalid |= arg.isInvalid();
4249         AllArgs.push_back(arg.take());
4250       }
4251 
4252     // Otherwise do argument promotion, (C99 6.5.2.2p7).
4253     } else {
4254       for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) {
4255         ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType,
4256                                                           FDecl);
4257         Invalid |= Arg.isInvalid();
4258         AllArgs.push_back(Arg.take());
4259       }
4260     }
4261 
4262     // Check for array bounds violations.
4263     for (unsigned i = ArgIx, e = Args.size(); i != e; ++i)
4264       CheckArrayAccess(Args[i]);
4265   }
4266   return Invalid;
4267 }
4268 
4269 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
4270   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
4271   if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
4272     TL = DTL.getOriginalLoc();
4273   if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
4274     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
4275       << ATL.getLocalSourceRange();
4276 }
4277 
4278 /// CheckStaticArrayArgument - If the given argument corresponds to a static
4279 /// array parameter, check that it is non-null, and that if it is formed by
4280 /// array-to-pointer decay, the underlying array is sufficiently large.
4281 ///
4282 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
4283 /// array type derivation, then for each call to the function, the value of the
4284 /// corresponding actual argument shall provide access to the first element of
4285 /// an array with at least as many elements as specified by the size expression.
4286 void
4287 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
4288                                ParmVarDecl *Param,
4289                                const Expr *ArgExpr) {
4290   // Static array parameters are not supported in C++.
4291   if (!Param || getLangOpts().CPlusPlus)
4292     return;
4293 
4294   QualType OrigTy = Param->getOriginalType();
4295 
4296   const ArrayType *AT = Context.getAsArrayType(OrigTy);
4297   if (!AT || AT->getSizeModifier() != ArrayType::Static)
4298     return;
4299 
4300   if (ArgExpr->isNullPointerConstant(Context,
4301                                      Expr::NPC_NeverValueDependent)) {
4302     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
4303     DiagnoseCalleeStaticArrayParam(*this, Param);
4304     return;
4305   }
4306 
4307   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
4308   if (!CAT)
4309     return;
4310 
4311   const ConstantArrayType *ArgCAT =
4312     Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
4313   if (!ArgCAT)
4314     return;
4315 
4316   if (ArgCAT->getSize().ult(CAT->getSize())) {
4317     Diag(CallLoc, diag::warn_static_array_too_small)
4318       << ArgExpr->getSourceRange()
4319       << (unsigned) ArgCAT->getSize().getZExtValue()
4320       << (unsigned) CAT->getSize().getZExtValue();
4321     DiagnoseCalleeStaticArrayParam(*this, Param);
4322   }
4323 }
4324 
4325 /// Given a function expression of unknown-any type, try to rebuild it
4326 /// to have a function type.
4327 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
4328 
4329 /// Is the given type a placeholder that we need to lower out
4330 /// immediately during argument processing?
4331 static bool isPlaceholderToRemoveAsArg(QualType type) {
4332   // Placeholders are never sugared.
4333   const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
4334   if (!placeholder) return false;
4335 
4336   switch (placeholder->getKind()) {
4337   // Ignore all the non-placeholder types.
4338 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
4339 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
4340 #include "clang/AST/BuiltinTypes.def"
4341     return false;
4342 
4343   // We cannot lower out overload sets; they might validly be resolved
4344   // by the call machinery.
4345   case BuiltinType::Overload:
4346     return false;
4347 
4348   // Unbridged casts in ARC can be handled in some call positions and
4349   // should be left in place.
4350   case BuiltinType::ARCUnbridgedCast:
4351     return false;
4352 
4353   // Pseudo-objects should be converted as soon as possible.
4354   case BuiltinType::PseudoObject:
4355     return true;
4356 
4357   // The debugger mode could theoretically but currently does not try
4358   // to resolve unknown-typed arguments based on known parameter types.
4359   case BuiltinType::UnknownAny:
4360     return true;
4361 
4362   // These are always invalid as call arguments and should be reported.
4363   case BuiltinType::BoundMember:
4364   case BuiltinType::BuiltinFn:
4365     return true;
4366   }
4367   llvm_unreachable("bad builtin type kind");
4368 }
4369 
4370 /// Check an argument list for placeholders that we won't try to
4371 /// handle later.
4372 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
4373   // Apply this processing to all the arguments at once instead of
4374   // dying at the first failure.
4375   bool hasInvalid = false;
4376   for (size_t i = 0, e = args.size(); i != e; i++) {
4377     if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
4378       ExprResult result = S.CheckPlaceholderExpr(args[i]);
4379       if (result.isInvalid()) hasInvalid = true;
4380       else args[i] = result.take();
4381     }
4382   }
4383   return hasInvalid;
4384 }
4385 
4386 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
4387 /// This provides the location of the left/right parens and a list of comma
4388 /// locations.
4389 ExprResult
4390 Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
4391                     MultiExprArg ArgExprs, SourceLocation RParenLoc,
4392                     Expr *ExecConfig, bool IsExecConfig) {
4393   // Since this might be a postfix expression, get rid of ParenListExprs.
4394   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
4395   if (Result.isInvalid()) return ExprError();
4396   Fn = Result.take();
4397 
4398   if (checkArgsForPlaceholders(*this, ArgExprs))
4399     return ExprError();
4400 
4401   if (getLangOpts().CPlusPlus) {
4402     // If this is a pseudo-destructor expression, build the call immediately.
4403     if (isa<CXXPseudoDestructorExpr>(Fn)) {
4404       if (!ArgExprs.empty()) {
4405         // Pseudo-destructor calls should not have any arguments.
4406         Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
4407           << FixItHint::CreateRemoval(
4408                                     SourceRange(ArgExprs[0]->getLocStart(),
4409                                                 ArgExprs.back()->getLocEnd()));
4410       }
4411 
4412       return Owned(new (Context) CallExpr(Context, Fn, None,
4413                                           Context.VoidTy, VK_RValue,
4414                                           RParenLoc));
4415     }
4416     if (Fn->getType() == Context.PseudoObjectTy) {
4417       ExprResult result = CheckPlaceholderExpr(Fn);
4418       if (result.isInvalid()) return ExprError();
4419       Fn = result.take();
4420     }
4421 
4422     // Determine whether this is a dependent call inside a C++ template,
4423     // in which case we won't do any semantic analysis now.
4424     // FIXME: Will need to cache the results of name lookup (including ADL) in
4425     // Fn.
4426     bool Dependent = false;
4427     if (Fn->isTypeDependent())
4428       Dependent = true;
4429     else if (Expr::hasAnyTypeDependentArguments(ArgExprs))
4430       Dependent = true;
4431 
4432     if (Dependent) {
4433       if (ExecConfig) {
4434         return Owned(new (Context) CUDAKernelCallExpr(
4435             Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
4436             Context.DependentTy, VK_RValue, RParenLoc));
4437       } else {
4438         return Owned(new (Context) CallExpr(Context, Fn, ArgExprs,
4439                                             Context.DependentTy, VK_RValue,
4440                                             RParenLoc));
4441       }
4442     }
4443 
4444     // Determine whether this is a call to an object (C++ [over.call.object]).
4445     if (Fn->getType()->isRecordType())
4446       return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc,
4447                                                 ArgExprs, RParenLoc));
4448 
4449     if (Fn->getType() == Context.UnknownAnyTy) {
4450       ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
4451       if (result.isInvalid()) return ExprError();
4452       Fn = result.take();
4453     }
4454 
4455     if (Fn->getType() == Context.BoundMemberTy) {
4456       return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs, RParenLoc);
4457     }
4458   }
4459 
4460   // Check for overloaded calls.  This can happen even in C due to extensions.
4461   if (Fn->getType() == Context.OverloadTy) {
4462     OverloadExpr::FindResult find = OverloadExpr::find(Fn);
4463 
4464     // We aren't supposed to apply this logic for if there's an '&' involved.
4465     if (!find.HasFormOfMemberPointer) {
4466       OverloadExpr *ovl = find.Expression;
4467       if (isa<UnresolvedLookupExpr>(ovl)) {
4468         UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
4469         return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, ArgExprs,
4470                                        RParenLoc, ExecConfig);
4471       } else {
4472         return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs,
4473                                          RParenLoc);
4474       }
4475     }
4476   }
4477 
4478   // If we're directly calling a function, get the appropriate declaration.
4479   if (Fn->getType() == Context.UnknownAnyTy) {
4480     ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
4481     if (result.isInvalid()) return ExprError();
4482     Fn = result.take();
4483   }
4484 
4485   Expr *NakedFn = Fn->IgnoreParens();
4486 
4487   NamedDecl *NDecl = 0;
4488   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
4489     if (UnOp->getOpcode() == UO_AddrOf)
4490       NakedFn = UnOp->getSubExpr()->IgnoreParens();
4491 
4492   if (isa<DeclRefExpr>(NakedFn))
4493     NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
4494   else if (isa<MemberExpr>(NakedFn))
4495     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
4496 
4497   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
4498                                ExecConfig, IsExecConfig);
4499 }
4500 
4501 ExprResult
4502 Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
4503                               MultiExprArg ExecConfig, SourceLocation GGGLoc) {
4504   FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
4505   if (!ConfigDecl)
4506     return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
4507                           << "cudaConfigureCall");
4508   QualType ConfigQTy = ConfigDecl->getType();
4509 
4510   DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
4511       ConfigDecl, false, ConfigQTy, VK_LValue, LLLLoc);
4512   MarkFunctionReferenced(LLLLoc, ConfigDecl);
4513 
4514   return ActOnCallExpr(S, ConfigDR, LLLLoc, ExecConfig, GGGLoc, 0,
4515                        /*IsExecConfig=*/true);
4516 }
4517 
4518 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
4519 ///
4520 /// __builtin_astype( value, dst type )
4521 ///
4522 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
4523                                  SourceLocation BuiltinLoc,
4524                                  SourceLocation RParenLoc) {
4525   ExprValueKind VK = VK_RValue;
4526   ExprObjectKind OK = OK_Ordinary;
4527   QualType DstTy = GetTypeFromParser(ParsedDestTy);
4528   QualType SrcTy = E->getType();
4529   if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
4530     return ExprError(Diag(BuiltinLoc,
4531                           diag::err_invalid_astype_of_different_size)
4532                      << DstTy
4533                      << SrcTy
4534                      << E->getSourceRange());
4535   return Owned(new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc,
4536                RParenLoc));
4537 }
4538 
4539 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
4540 /// provided arguments.
4541 ///
4542 /// __builtin_convertvector( value, dst type )
4543 ///
4544 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
4545                                         SourceLocation BuiltinLoc,
4546                                         SourceLocation RParenLoc) {
4547   TypeSourceInfo *TInfo;
4548   GetTypeFromParser(ParsedDestTy, &TInfo);
4549   return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
4550 }
4551 
4552 /// BuildResolvedCallExpr - Build a call to a resolved expression,
4553 /// i.e. an expression not of \p OverloadTy.  The expression should
4554 /// unary-convert to an expression of function-pointer or
4555 /// block-pointer type.
4556 ///
4557 /// \param NDecl the declaration being called, if available
4558 ExprResult
4559 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
4560                             SourceLocation LParenLoc,
4561                             ArrayRef<Expr *> Args,
4562                             SourceLocation RParenLoc,
4563                             Expr *Config, bool IsExecConfig) {
4564   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
4565   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
4566 
4567   // Promote the function operand.
4568   // We special-case function promotion here because we only allow promoting
4569   // builtin functions to function pointers in the callee of a call.
4570   ExprResult Result;
4571   if (BuiltinID &&
4572       Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
4573     Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()),
4574                                CK_BuiltinFnToFnPtr).take();
4575   } else {
4576     Result = UsualUnaryConversions(Fn);
4577   }
4578   if (Result.isInvalid())
4579     return ExprError();
4580   Fn = Result.take();
4581 
4582   // Make the call expr early, before semantic checks.  This guarantees cleanup
4583   // of arguments and function on error.
4584   CallExpr *TheCall;
4585   if (Config)
4586     TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
4587                                                cast<CallExpr>(Config), Args,
4588                                                Context.BoolTy, VK_RValue,
4589                                                RParenLoc);
4590   else
4591     TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy,
4592                                      VK_RValue, RParenLoc);
4593 
4594   // Bail out early if calling a builtin with custom typechecking.
4595   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
4596     return CheckBuiltinFunctionCall(BuiltinID, TheCall);
4597 
4598  retry:
4599   const FunctionType *FuncT;
4600   if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
4601     // C99 6.5.2.2p1 - "The expression that denotes the called function shall
4602     // have type pointer to function".
4603     FuncT = PT->getPointeeType()->getAs<FunctionType>();
4604     if (FuncT == 0)
4605       return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4606                          << Fn->getType() << Fn->getSourceRange());
4607   } else if (const BlockPointerType *BPT =
4608                Fn->getType()->getAs<BlockPointerType>()) {
4609     FuncT = BPT->getPointeeType()->castAs<FunctionType>();
4610   } else {
4611     // Handle calls to expressions of unknown-any type.
4612     if (Fn->getType() == Context.UnknownAnyTy) {
4613       ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
4614       if (rewrite.isInvalid()) return ExprError();
4615       Fn = rewrite.take();
4616       TheCall->setCallee(Fn);
4617       goto retry;
4618     }
4619 
4620     return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4621       << Fn->getType() << Fn->getSourceRange());
4622   }
4623 
4624   if (getLangOpts().CUDA) {
4625     if (Config) {
4626       // CUDA: Kernel calls must be to global functions
4627       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
4628         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
4629             << FDecl->getName() << Fn->getSourceRange());
4630 
4631       // CUDA: Kernel function must have 'void' return type
4632       if (!FuncT->getResultType()->isVoidType())
4633         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
4634             << Fn->getType() << Fn->getSourceRange());
4635     } else {
4636       // CUDA: Calls to global functions must be configured
4637       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
4638         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
4639             << FDecl->getName() << Fn->getSourceRange());
4640     }
4641   }
4642 
4643   // Check for a valid return type
4644   if (CheckCallReturnType(FuncT->getResultType(),
4645                           Fn->getLocStart(), TheCall,
4646                           FDecl))
4647     return ExprError();
4648 
4649   // We know the result type of the call, set it.
4650   TheCall->setType(FuncT->getCallResultType(Context));
4651   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
4652 
4653   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
4654   if (Proto) {
4655     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
4656                                 IsExecConfig))
4657       return ExprError();
4658   } else {
4659     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
4660 
4661     if (FDecl) {
4662       // Check if we have too few/too many template arguments, based
4663       // on our knowledge of the function definition.
4664       const FunctionDecl *Def = 0;
4665       if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
4666         Proto = Def->getType()->getAs<FunctionProtoType>();
4667        if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
4668           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
4669           << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
4670       }
4671 
4672       // If the function we're calling isn't a function prototype, but we have
4673       // a function prototype from a prior declaratiom, use that prototype.
4674       if (!FDecl->hasPrototype())
4675         Proto = FDecl->getType()->getAs<FunctionProtoType>();
4676     }
4677 
4678     // Promote the arguments (C99 6.5.2.2p6).
4679     for (unsigned i = 0, e = Args.size(); i != e; i++) {
4680       Expr *Arg = Args[i];
4681 
4682       if (Proto && i < Proto->getNumArgs()) {
4683         InitializedEntity Entity
4684           = InitializedEntity::InitializeParameter(Context,
4685                                                    Proto->getArgType(i),
4686                                                    Proto->isArgConsumed(i));
4687         ExprResult ArgE = PerformCopyInitialization(Entity,
4688                                                     SourceLocation(),
4689                                                     Owned(Arg));
4690         if (ArgE.isInvalid())
4691           return true;
4692 
4693         Arg = ArgE.takeAs<Expr>();
4694 
4695       } else {
4696         ExprResult ArgE = DefaultArgumentPromotion(Arg);
4697 
4698         if (ArgE.isInvalid())
4699           return true;
4700 
4701         Arg = ArgE.takeAs<Expr>();
4702       }
4703 
4704       if (RequireCompleteType(Arg->getLocStart(),
4705                               Arg->getType(),
4706                               diag::err_call_incomplete_argument, Arg))
4707         return ExprError();
4708 
4709       TheCall->setArg(i, Arg);
4710     }
4711   }
4712 
4713   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4714     if (!Method->isStatic())
4715       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
4716         << Fn->getSourceRange());
4717 
4718   // Check for sentinels
4719   if (NDecl)
4720     DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
4721 
4722   // Do special checking on direct calls to functions.
4723   if (FDecl) {
4724     if (CheckFunctionCall(FDecl, TheCall, Proto))
4725       return ExprError();
4726 
4727     if (BuiltinID)
4728       return CheckBuiltinFunctionCall(BuiltinID, TheCall);
4729   } else if (NDecl) {
4730     if (CheckPointerCall(NDecl, TheCall, Proto))
4731       return ExprError();
4732   } else {
4733     if (CheckOtherCall(TheCall, Proto))
4734       return ExprError();
4735   }
4736 
4737   return MaybeBindToTemporary(TheCall);
4738 }
4739 
4740 ExprResult
4741 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
4742                            SourceLocation RParenLoc, Expr *InitExpr) {
4743   assert(Ty && "ActOnCompoundLiteral(): missing type");
4744   // FIXME: put back this assert when initializers are worked out.
4745   //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
4746 
4747   TypeSourceInfo *TInfo;
4748   QualType literalType = GetTypeFromParser(Ty, &TInfo);
4749   if (!TInfo)
4750     TInfo = Context.getTrivialTypeSourceInfo(literalType);
4751 
4752   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
4753 }
4754 
4755 ExprResult
4756 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
4757                                SourceLocation RParenLoc, Expr *LiteralExpr) {
4758   QualType literalType = TInfo->getType();
4759 
4760   if (literalType->isArrayType()) {
4761     if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
4762           diag::err_illegal_decl_array_incomplete_type,
4763           SourceRange(LParenLoc,
4764                       LiteralExpr->getSourceRange().getEnd())))
4765       return ExprError();
4766     if (literalType->isVariableArrayType())
4767       return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
4768         << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
4769   } else if (!literalType->isDependentType() &&
4770              RequireCompleteType(LParenLoc, literalType,
4771                diag::err_typecheck_decl_incomplete_type,
4772                SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
4773     return ExprError();
4774 
4775   InitializedEntity Entity
4776     = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
4777   InitializationKind Kind
4778     = InitializationKind::CreateCStyleCast(LParenLoc,
4779                                            SourceRange(LParenLoc, RParenLoc),
4780                                            /*InitList=*/true);
4781   InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
4782   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
4783                                       &literalType);
4784   if (Result.isInvalid())
4785     return ExprError();
4786   LiteralExpr = Result.get();
4787 
4788   bool isFileScope = getCurFunctionOrMethodDecl() == 0;
4789   if (isFileScope &&
4790       !LiteralExpr->isTypeDependent() &&
4791       !LiteralExpr->isValueDependent() &&
4792       !literalType->isDependentType()) { // 6.5.2.5p3
4793     if (CheckForConstantInitializer(LiteralExpr, literalType))
4794       return ExprError();
4795   }
4796 
4797   // In C, compound literals are l-values for some reason.
4798   ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue;
4799 
4800   return MaybeBindToTemporary(
4801            new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
4802                                              VK, LiteralExpr, isFileScope));
4803 }
4804 
4805 ExprResult
4806 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
4807                     SourceLocation RBraceLoc) {
4808   // Immediately handle non-overload placeholders.  Overloads can be
4809   // resolved contextually, but everything else here can't.
4810   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
4811     if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
4812       ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
4813 
4814       // Ignore failures; dropping the entire initializer list because
4815       // of one failure would be terrible for indexing/etc.
4816       if (result.isInvalid()) continue;
4817 
4818       InitArgList[I] = result.take();
4819     }
4820   }
4821 
4822   // Semantic analysis for initializers is done by ActOnDeclarator() and
4823   // CheckInitializer() - it requires knowledge of the object being intialized.
4824 
4825   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
4826                                                RBraceLoc);
4827   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
4828   return Owned(E);
4829 }
4830 
4831 /// Do an explicit extend of the given block pointer if we're in ARC.
4832 static void maybeExtendBlockObject(Sema &S, ExprResult &E) {
4833   assert(E.get()->getType()->isBlockPointerType());
4834   assert(E.get()->isRValue());
4835 
4836   // Only do this in an r-value context.
4837   if (!S.getLangOpts().ObjCAutoRefCount) return;
4838 
4839   E = ImplicitCastExpr::Create(S.Context, E.get()->getType(),
4840                                CK_ARCExtendBlockObject, E.get(),
4841                                /*base path*/ 0, VK_RValue);
4842   S.ExprNeedsCleanups = true;
4843 }
4844 
4845 /// Prepare a conversion of the given expression to an ObjC object
4846 /// pointer type.
4847 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
4848   QualType type = E.get()->getType();
4849   if (type->isObjCObjectPointerType()) {
4850     return CK_BitCast;
4851   } else if (type->isBlockPointerType()) {
4852     maybeExtendBlockObject(*this, E);
4853     return CK_BlockPointerToObjCPointerCast;
4854   } else {
4855     assert(type->isPointerType());
4856     return CK_CPointerToObjCPointerCast;
4857   }
4858 }
4859 
4860 /// Prepares for a scalar cast, performing all the necessary stages
4861 /// except the final cast and returning the kind required.
4862 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
4863   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
4864   // Also, callers should have filtered out the invalid cases with
4865   // pointers.  Everything else should be possible.
4866 
4867   QualType SrcTy = Src.get()->getType();
4868   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
4869     return CK_NoOp;
4870 
4871   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
4872   case Type::STK_MemberPointer:
4873     llvm_unreachable("member pointer type in C");
4874 
4875   case Type::STK_CPointer:
4876   case Type::STK_BlockPointer:
4877   case Type::STK_ObjCObjectPointer:
4878     switch (DestTy->getScalarTypeKind()) {
4879     case Type::STK_CPointer:
4880       return CK_BitCast;
4881     case Type::STK_BlockPointer:
4882       return (SrcKind == Type::STK_BlockPointer
4883                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
4884     case Type::STK_ObjCObjectPointer:
4885       if (SrcKind == Type::STK_ObjCObjectPointer)
4886         return CK_BitCast;
4887       if (SrcKind == Type::STK_CPointer)
4888         return CK_CPointerToObjCPointerCast;
4889       maybeExtendBlockObject(*this, Src);
4890       return CK_BlockPointerToObjCPointerCast;
4891     case Type::STK_Bool:
4892       return CK_PointerToBoolean;
4893     case Type::STK_Integral:
4894       return CK_PointerToIntegral;
4895     case Type::STK_Floating:
4896     case Type::STK_FloatingComplex:
4897     case Type::STK_IntegralComplex:
4898     case Type::STK_MemberPointer:
4899       llvm_unreachable("illegal cast from pointer");
4900     }
4901     llvm_unreachable("Should have returned before this");
4902 
4903   case Type::STK_Bool: // casting from bool is like casting from an integer
4904   case Type::STK_Integral:
4905     switch (DestTy->getScalarTypeKind()) {
4906     case Type::STK_CPointer:
4907     case Type::STK_ObjCObjectPointer:
4908     case Type::STK_BlockPointer:
4909       if (Src.get()->isNullPointerConstant(Context,
4910                                            Expr::NPC_ValueDependentIsNull))
4911         return CK_NullToPointer;
4912       return CK_IntegralToPointer;
4913     case Type::STK_Bool:
4914       return CK_IntegralToBoolean;
4915     case Type::STK_Integral:
4916       return CK_IntegralCast;
4917     case Type::STK_Floating:
4918       return CK_IntegralToFloating;
4919     case Type::STK_IntegralComplex:
4920       Src = ImpCastExprToType(Src.take(),
4921                               DestTy->castAs<ComplexType>()->getElementType(),
4922                               CK_IntegralCast);
4923       return CK_IntegralRealToComplex;
4924     case Type::STK_FloatingComplex:
4925       Src = ImpCastExprToType(Src.take(),
4926                               DestTy->castAs<ComplexType>()->getElementType(),
4927                               CK_IntegralToFloating);
4928       return CK_FloatingRealToComplex;
4929     case Type::STK_MemberPointer:
4930       llvm_unreachable("member pointer type in C");
4931     }
4932     llvm_unreachable("Should have returned before this");
4933 
4934   case Type::STK_Floating:
4935     switch (DestTy->getScalarTypeKind()) {
4936     case Type::STK_Floating:
4937       return CK_FloatingCast;
4938     case Type::STK_Bool:
4939       return CK_FloatingToBoolean;
4940     case Type::STK_Integral:
4941       return CK_FloatingToIntegral;
4942     case Type::STK_FloatingComplex:
4943       Src = ImpCastExprToType(Src.take(),
4944                               DestTy->castAs<ComplexType>()->getElementType(),
4945                               CK_FloatingCast);
4946       return CK_FloatingRealToComplex;
4947     case Type::STK_IntegralComplex:
4948       Src = ImpCastExprToType(Src.take(),
4949                               DestTy->castAs<ComplexType>()->getElementType(),
4950                               CK_FloatingToIntegral);
4951       return CK_IntegralRealToComplex;
4952     case Type::STK_CPointer:
4953     case Type::STK_ObjCObjectPointer:
4954     case Type::STK_BlockPointer:
4955       llvm_unreachable("valid float->pointer cast?");
4956     case Type::STK_MemberPointer:
4957       llvm_unreachable("member pointer type in C");
4958     }
4959     llvm_unreachable("Should have returned before this");
4960 
4961   case Type::STK_FloatingComplex:
4962     switch (DestTy->getScalarTypeKind()) {
4963     case Type::STK_FloatingComplex:
4964       return CK_FloatingComplexCast;
4965     case Type::STK_IntegralComplex:
4966       return CK_FloatingComplexToIntegralComplex;
4967     case Type::STK_Floating: {
4968       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
4969       if (Context.hasSameType(ET, DestTy))
4970         return CK_FloatingComplexToReal;
4971       Src = ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal);
4972       return CK_FloatingCast;
4973     }
4974     case Type::STK_Bool:
4975       return CK_FloatingComplexToBoolean;
4976     case Type::STK_Integral:
4977       Src = ImpCastExprToType(Src.take(),
4978                               SrcTy->castAs<ComplexType>()->getElementType(),
4979                               CK_FloatingComplexToReal);
4980       return CK_FloatingToIntegral;
4981     case Type::STK_CPointer:
4982     case Type::STK_ObjCObjectPointer:
4983     case Type::STK_BlockPointer:
4984       llvm_unreachable("valid complex float->pointer cast?");
4985     case Type::STK_MemberPointer:
4986       llvm_unreachable("member pointer type in C");
4987     }
4988     llvm_unreachable("Should have returned before this");
4989 
4990   case Type::STK_IntegralComplex:
4991     switch (DestTy->getScalarTypeKind()) {
4992     case Type::STK_FloatingComplex:
4993       return CK_IntegralComplexToFloatingComplex;
4994     case Type::STK_IntegralComplex:
4995       return CK_IntegralComplexCast;
4996     case Type::STK_Integral: {
4997       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
4998       if (Context.hasSameType(ET, DestTy))
4999         return CK_IntegralComplexToReal;
5000       Src = ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal);
5001       return CK_IntegralCast;
5002     }
5003     case Type::STK_Bool:
5004       return CK_IntegralComplexToBoolean;
5005     case Type::STK_Floating:
5006       Src = ImpCastExprToType(Src.take(),
5007                               SrcTy->castAs<ComplexType>()->getElementType(),
5008                               CK_IntegralComplexToReal);
5009       return CK_IntegralToFloating;
5010     case Type::STK_CPointer:
5011     case Type::STK_ObjCObjectPointer:
5012     case Type::STK_BlockPointer:
5013       llvm_unreachable("valid complex int->pointer cast?");
5014     case Type::STK_MemberPointer:
5015       llvm_unreachable("member pointer type in C");
5016     }
5017     llvm_unreachable("Should have returned before this");
5018   }
5019 
5020   llvm_unreachable("Unhandled scalar cast");
5021 }
5022 
5023 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
5024                            CastKind &Kind) {
5025   assert(VectorTy->isVectorType() && "Not a vector type!");
5026 
5027   if (Ty->isVectorType() || Ty->isIntegerType()) {
5028     if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
5029       return Diag(R.getBegin(),
5030                   Ty->isVectorType() ?
5031                   diag::err_invalid_conversion_between_vectors :
5032                   diag::err_invalid_conversion_between_vector_and_integer)
5033         << VectorTy << Ty << R;
5034   } else
5035     return Diag(R.getBegin(),
5036                 diag::err_invalid_conversion_between_vector_and_scalar)
5037       << VectorTy << Ty << R;
5038 
5039   Kind = CK_BitCast;
5040   return false;
5041 }
5042 
5043 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
5044                                     Expr *CastExpr, CastKind &Kind) {
5045   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
5046 
5047   QualType SrcTy = CastExpr->getType();
5048 
5049   // If SrcTy is a VectorType, the total size must match to explicitly cast to
5050   // an ExtVectorType.
5051   // In OpenCL, casts between vectors of different types are not allowed.
5052   // (See OpenCL 6.2).
5053   if (SrcTy->isVectorType()) {
5054     if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)
5055         || (getLangOpts().OpenCL &&
5056             (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
5057       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
5058         << DestTy << SrcTy << R;
5059       return ExprError();
5060     }
5061     Kind = CK_BitCast;
5062     return Owned(CastExpr);
5063   }
5064 
5065   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
5066   // conversion will take place first from scalar to elt type, and then
5067   // splat from elt type to vector.
5068   if (SrcTy->isPointerType())
5069     return Diag(R.getBegin(),
5070                 diag::err_invalid_conversion_between_vector_and_scalar)
5071       << DestTy << SrcTy << R;
5072 
5073   QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
5074   ExprResult CastExprRes = Owned(CastExpr);
5075   CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy);
5076   if (CastExprRes.isInvalid())
5077     return ExprError();
5078   CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take();
5079 
5080   Kind = CK_VectorSplat;
5081   return Owned(CastExpr);
5082 }
5083 
5084 ExprResult
5085 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
5086                     Declarator &D, ParsedType &Ty,
5087                     SourceLocation RParenLoc, Expr *CastExpr) {
5088   assert(!D.isInvalidType() && (CastExpr != 0) &&
5089          "ActOnCastExpr(): missing type or expr");
5090 
5091   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
5092   if (D.isInvalidType())
5093     return ExprError();
5094 
5095   if (getLangOpts().CPlusPlus) {
5096     // Check that there are no default arguments (C++ only).
5097     CheckExtraCXXDefaultArguments(D);
5098   }
5099 
5100   checkUnusedDeclAttributes(D);
5101 
5102   QualType castType = castTInfo->getType();
5103   Ty = CreateParsedType(castType, castTInfo);
5104 
5105   bool isVectorLiteral = false;
5106 
5107   // Check for an altivec or OpenCL literal,
5108   // i.e. all the elements are integer constants.
5109   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
5110   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
5111   if ((getLangOpts().AltiVec || getLangOpts().OpenCL)
5112        && castType->isVectorType() && (PE || PLE)) {
5113     if (PLE && PLE->getNumExprs() == 0) {
5114       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
5115       return ExprError();
5116     }
5117     if (PE || PLE->getNumExprs() == 1) {
5118       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
5119       if (!E->getType()->isVectorType())
5120         isVectorLiteral = true;
5121     }
5122     else
5123       isVectorLiteral = true;
5124   }
5125 
5126   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
5127   // then handle it as such.
5128   if (isVectorLiteral)
5129     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
5130 
5131   // If the Expr being casted is a ParenListExpr, handle it specially.
5132   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
5133   // sequence of BinOp comma operators.
5134   if (isa<ParenListExpr>(CastExpr)) {
5135     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
5136     if (Result.isInvalid()) return ExprError();
5137     CastExpr = Result.take();
5138   }
5139 
5140   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
5141 }
5142 
5143 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
5144                                     SourceLocation RParenLoc, Expr *E,
5145                                     TypeSourceInfo *TInfo) {
5146   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
5147          "Expected paren or paren list expression");
5148 
5149   Expr **exprs;
5150   unsigned numExprs;
5151   Expr *subExpr;
5152   SourceLocation LiteralLParenLoc, LiteralRParenLoc;
5153   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
5154     LiteralLParenLoc = PE->getLParenLoc();
5155     LiteralRParenLoc = PE->getRParenLoc();
5156     exprs = PE->getExprs();
5157     numExprs = PE->getNumExprs();
5158   } else { // isa<ParenExpr> by assertion at function entrance
5159     LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
5160     LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
5161     subExpr = cast<ParenExpr>(E)->getSubExpr();
5162     exprs = &subExpr;
5163     numExprs = 1;
5164   }
5165 
5166   QualType Ty = TInfo->getType();
5167   assert(Ty->isVectorType() && "Expected vector type");
5168 
5169   SmallVector<Expr *, 8> initExprs;
5170   const VectorType *VTy = Ty->getAs<VectorType>();
5171   unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
5172 
5173   // '(...)' form of vector initialization in AltiVec: the number of
5174   // initializers must be one or must match the size of the vector.
5175   // If a single value is specified in the initializer then it will be
5176   // replicated to all the components of the vector
5177   if (VTy->getVectorKind() == VectorType::AltiVecVector) {
5178     // The number of initializers must be one or must match the size of the
5179     // vector. If a single value is specified in the initializer then it will
5180     // be replicated to all the components of the vector
5181     if (numExprs == 1) {
5182       QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
5183       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
5184       if (Literal.isInvalid())
5185         return ExprError();
5186       Literal = ImpCastExprToType(Literal.take(), ElemTy,
5187                                   PrepareScalarCast(Literal, ElemTy));
5188       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
5189     }
5190     else if (numExprs < numElems) {
5191       Diag(E->getExprLoc(),
5192            diag::err_incorrect_number_of_vector_initializers);
5193       return ExprError();
5194     }
5195     else
5196       initExprs.append(exprs, exprs + numExprs);
5197   }
5198   else {
5199     // For OpenCL, when the number of initializers is a single value,
5200     // it will be replicated to all components of the vector.
5201     if (getLangOpts().OpenCL &&
5202         VTy->getVectorKind() == VectorType::GenericVector &&
5203         numExprs == 1) {
5204         QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
5205         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
5206         if (Literal.isInvalid())
5207           return ExprError();
5208         Literal = ImpCastExprToType(Literal.take(), ElemTy,
5209                                     PrepareScalarCast(Literal, ElemTy));
5210         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
5211     }
5212 
5213     initExprs.append(exprs, exprs + numExprs);
5214   }
5215   // FIXME: This means that pretty-printing the final AST will produce curly
5216   // braces instead of the original commas.
5217   InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
5218                                                    initExprs, LiteralRParenLoc);
5219   initE->setType(Ty);
5220   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
5221 }
5222 
5223 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
5224 /// the ParenListExpr into a sequence of comma binary operators.
5225 ExprResult
5226 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
5227   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
5228   if (!E)
5229     return Owned(OrigExpr);
5230 
5231   ExprResult Result(E->getExpr(0));
5232 
5233   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
5234     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
5235                         E->getExpr(i));
5236 
5237   if (Result.isInvalid()) return ExprError();
5238 
5239   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
5240 }
5241 
5242 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
5243                                     SourceLocation R,
5244                                     MultiExprArg Val) {
5245   Expr *expr = new (Context) ParenListExpr(Context, L, Val, R);
5246   return Owned(expr);
5247 }
5248 
5249 /// \brief Emit a specialized diagnostic when one expression is a null pointer
5250 /// constant and the other is not a pointer.  Returns true if a diagnostic is
5251 /// emitted.
5252 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
5253                                       SourceLocation QuestionLoc) {
5254   Expr *NullExpr = LHSExpr;
5255   Expr *NonPointerExpr = RHSExpr;
5256   Expr::NullPointerConstantKind NullKind =
5257       NullExpr->isNullPointerConstant(Context,
5258                                       Expr::NPC_ValueDependentIsNotNull);
5259 
5260   if (NullKind == Expr::NPCK_NotNull) {
5261     NullExpr = RHSExpr;
5262     NonPointerExpr = LHSExpr;
5263     NullKind =
5264         NullExpr->isNullPointerConstant(Context,
5265                                         Expr::NPC_ValueDependentIsNotNull);
5266   }
5267 
5268   if (NullKind == Expr::NPCK_NotNull)
5269     return false;
5270 
5271   if (NullKind == Expr::NPCK_ZeroExpression)
5272     return false;
5273 
5274   if (NullKind == Expr::NPCK_ZeroLiteral) {
5275     // In this case, check to make sure that we got here from a "NULL"
5276     // string in the source code.
5277     NullExpr = NullExpr->IgnoreParenImpCasts();
5278     SourceLocation loc = NullExpr->getExprLoc();
5279     if (!findMacroSpelling(loc, "NULL"))
5280       return false;
5281   }
5282 
5283   int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
5284   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
5285       << NonPointerExpr->getType() << DiagType
5286       << NonPointerExpr->getSourceRange();
5287   return true;
5288 }
5289 
5290 /// \brief Return false if the condition expression is valid, true otherwise.
5291 static bool checkCondition(Sema &S, Expr *Cond) {
5292   QualType CondTy = Cond->getType();
5293 
5294   // C99 6.5.15p2
5295   if (CondTy->isScalarType()) return false;
5296 
5297   // OpenCL v1.1 s6.3.i says the condition is allowed to be a vector or scalar.
5298   if (S.getLangOpts().OpenCL && CondTy->isVectorType())
5299     return false;
5300 
5301   // Emit the proper error message.
5302   S.Diag(Cond->getLocStart(), S.getLangOpts().OpenCL ?
5303                               diag::err_typecheck_cond_expect_scalar :
5304                               diag::err_typecheck_cond_expect_scalar_or_vector)
5305     << CondTy;
5306   return true;
5307 }
5308 
5309 /// \brief Return false if the two expressions can be converted to a vector,
5310 /// true otherwise
5311 static bool checkConditionalConvertScalarsToVectors(Sema &S, ExprResult &LHS,
5312                                                     ExprResult &RHS,
5313                                                     QualType CondTy) {
5314   // Both operands should be of scalar type.
5315   if (!LHS.get()->getType()->isScalarType()) {
5316     S.Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
5317       << CondTy;
5318     return true;
5319   }
5320   if (!RHS.get()->getType()->isScalarType()) {
5321     S.Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
5322       << CondTy;
5323     return true;
5324   }
5325 
5326   // Implicity convert these scalars to the type of the condition.
5327   LHS = S.ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast);
5328   RHS = S.ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast);
5329   return false;
5330 }
5331 
5332 /// \brief Handle when one or both operands are void type.
5333 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
5334                                          ExprResult &RHS) {
5335     Expr *LHSExpr = LHS.get();
5336     Expr *RHSExpr = RHS.get();
5337 
5338     if (!LHSExpr->getType()->isVoidType())
5339       S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
5340         << RHSExpr->getSourceRange();
5341     if (!RHSExpr->getType()->isVoidType())
5342       S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
5343         << LHSExpr->getSourceRange();
5344     LHS = S.ImpCastExprToType(LHS.take(), S.Context.VoidTy, CK_ToVoid);
5345     RHS = S.ImpCastExprToType(RHS.take(), S.Context.VoidTy, CK_ToVoid);
5346     return S.Context.VoidTy;
5347 }
5348 
5349 /// \brief Return false if the NullExpr can be promoted to PointerTy,
5350 /// true otherwise.
5351 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
5352                                         QualType PointerTy) {
5353   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
5354       !NullExpr.get()->isNullPointerConstant(S.Context,
5355                                             Expr::NPC_ValueDependentIsNull))
5356     return true;
5357 
5358   NullExpr = S.ImpCastExprToType(NullExpr.take(), PointerTy, CK_NullToPointer);
5359   return false;
5360 }
5361 
5362 /// \brief Checks compatibility between two pointers and return the resulting
5363 /// type.
5364 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
5365                                                      ExprResult &RHS,
5366                                                      SourceLocation Loc) {
5367   QualType LHSTy = LHS.get()->getType();
5368   QualType RHSTy = RHS.get()->getType();
5369 
5370   if (S.Context.hasSameType(LHSTy, RHSTy)) {
5371     // Two identical pointers types are always compatible.
5372     return LHSTy;
5373   }
5374 
5375   QualType lhptee, rhptee;
5376 
5377   // Get the pointee types.
5378   bool IsBlockPointer = false;
5379   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
5380     lhptee = LHSBTy->getPointeeType();
5381     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
5382     IsBlockPointer = true;
5383   } else {
5384     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
5385     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
5386   }
5387 
5388   // C99 6.5.15p6: If both operands are pointers to compatible types or to
5389   // differently qualified versions of compatible types, the result type is
5390   // a pointer to an appropriately qualified version of the composite
5391   // type.
5392 
5393   // Only CVR-qualifiers exist in the standard, and the differently-qualified
5394   // clause doesn't make sense for our extensions. E.g. address space 2 should
5395   // be incompatible with address space 3: they may live on different devices or
5396   // anything.
5397   Qualifiers lhQual = lhptee.getQualifiers();
5398   Qualifiers rhQual = rhptee.getQualifiers();
5399 
5400   unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
5401   lhQual.removeCVRQualifiers();
5402   rhQual.removeCVRQualifiers();
5403 
5404   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
5405   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
5406 
5407   QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
5408 
5409   if (CompositeTy.isNull()) {
5410     S.Diag(Loc, diag::warn_typecheck_cond_incompatible_pointers)
5411       << LHSTy << RHSTy << LHS.get()->getSourceRange()
5412       << RHS.get()->getSourceRange();
5413     // In this situation, we assume void* type. No especially good
5414     // reason, but this is what gcc does, and we do have to pick
5415     // to get a consistent AST.
5416     QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy);
5417     LHS = S.ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
5418     RHS = S.ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
5419     return incompatTy;
5420   }
5421 
5422   // The pointer types are compatible.
5423   QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual);
5424   if (IsBlockPointer)
5425     ResultTy = S.Context.getBlockPointerType(ResultTy);
5426   else
5427     ResultTy = S.Context.getPointerType(ResultTy);
5428 
5429   LHS = S.ImpCastExprToType(LHS.take(), ResultTy, CK_BitCast);
5430   RHS = S.ImpCastExprToType(RHS.take(), ResultTy, CK_BitCast);
5431   return ResultTy;
5432 }
5433 
5434 /// \brief Return the resulting type when the operands are both block pointers.
5435 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
5436                                                           ExprResult &LHS,
5437                                                           ExprResult &RHS,
5438                                                           SourceLocation Loc) {
5439   QualType LHSTy = LHS.get()->getType();
5440   QualType RHSTy = RHS.get()->getType();
5441 
5442   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
5443     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
5444       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
5445       LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
5446       RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
5447       return destType;
5448     }
5449     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
5450       << LHSTy << RHSTy << LHS.get()->getSourceRange()
5451       << RHS.get()->getSourceRange();
5452     return QualType();
5453   }
5454 
5455   // We have 2 block pointer types.
5456   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
5457 }
5458 
5459 /// \brief Return the resulting type when the operands are both pointers.
5460 static QualType
5461 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
5462                                             ExprResult &RHS,
5463                                             SourceLocation Loc) {
5464   // get the pointer types
5465   QualType LHSTy = LHS.get()->getType();
5466   QualType RHSTy = RHS.get()->getType();
5467 
5468   // get the "pointed to" types
5469   QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5470   QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
5471 
5472   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
5473   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
5474     // Figure out necessary qualifiers (C99 6.5.15p6)
5475     QualType destPointee
5476       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
5477     QualType destType = S.Context.getPointerType(destPointee);
5478     // Add qualifiers if necessary.
5479     LHS = S.ImpCastExprToType(LHS.take(), destType, CK_NoOp);
5480     // Promote to void*.
5481     RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
5482     return destType;
5483   }
5484   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
5485     QualType destPointee
5486       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
5487     QualType destType = S.Context.getPointerType(destPointee);
5488     // Add qualifiers if necessary.
5489     RHS = S.ImpCastExprToType(RHS.take(), destType, CK_NoOp);
5490     // Promote to void*.
5491     LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
5492     return destType;
5493   }
5494 
5495   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
5496 }
5497 
5498 /// \brief Return false if the first expression is not an integer and the second
5499 /// expression is not a pointer, true otherwise.
5500 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
5501                                         Expr* PointerExpr, SourceLocation Loc,
5502                                         bool IsIntFirstExpr) {
5503   if (!PointerExpr->getType()->isPointerType() ||
5504       !Int.get()->getType()->isIntegerType())
5505     return false;
5506 
5507   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
5508   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
5509 
5510   S.Diag(Loc, diag::warn_typecheck_cond_pointer_integer_mismatch)
5511     << Expr1->getType() << Expr2->getType()
5512     << Expr1->getSourceRange() << Expr2->getSourceRange();
5513   Int = S.ImpCastExprToType(Int.take(), PointerExpr->getType(),
5514                             CK_IntegralToPointer);
5515   return true;
5516 }
5517 
5518 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
5519 /// In that case, LHS = cond.
5520 /// C99 6.5.15
5521 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
5522                                         ExprResult &RHS, ExprValueKind &VK,
5523                                         ExprObjectKind &OK,
5524                                         SourceLocation QuestionLoc) {
5525 
5526   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
5527   if (!LHSResult.isUsable()) return QualType();
5528   LHS = LHSResult;
5529 
5530   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
5531   if (!RHSResult.isUsable()) return QualType();
5532   RHS = RHSResult;
5533 
5534   // C++ is sufficiently different to merit its own checker.
5535   if (getLangOpts().CPlusPlus)
5536     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
5537 
5538   VK = VK_RValue;
5539   OK = OK_Ordinary;
5540 
5541   // First, check the condition.
5542   Cond = UsualUnaryConversions(Cond.take());
5543   if (Cond.isInvalid())
5544     return QualType();
5545   if (checkCondition(*this, Cond.get()))
5546     return QualType();
5547 
5548   // Now check the two expressions.
5549   if (LHS.get()->getType()->isVectorType() ||
5550       RHS.get()->getType()->isVectorType())
5551     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
5552 
5553   UsualArithmeticConversions(LHS, RHS);
5554   if (LHS.isInvalid() || RHS.isInvalid())
5555     return QualType();
5556 
5557   QualType CondTy = Cond.get()->getType();
5558   QualType LHSTy = LHS.get()->getType();
5559   QualType RHSTy = RHS.get()->getType();
5560 
5561   // If the condition is a vector, and both operands are scalar,
5562   // attempt to implicity convert them to the vector type to act like the
5563   // built in select. (OpenCL v1.1 s6.3.i)
5564   if (getLangOpts().OpenCL && CondTy->isVectorType())
5565     if (checkConditionalConvertScalarsToVectors(*this, LHS, RHS, CondTy))
5566       return QualType();
5567 
5568   // If both operands have arithmetic type, do the usual arithmetic conversions
5569   // to find a common type: C99 6.5.15p3,5.
5570   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType())
5571     return LHS.get()->getType();
5572 
5573   // If both operands are the same structure or union type, the result is that
5574   // type.
5575   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
5576     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
5577       if (LHSRT->getDecl() == RHSRT->getDecl())
5578         // "If both the operands have structure or union type, the result has
5579         // that type."  This implies that CV qualifiers are dropped.
5580         return LHSTy.getUnqualifiedType();
5581     // FIXME: Type of conditional expression must be complete in C mode.
5582   }
5583 
5584   // C99 6.5.15p5: "If both operands have void type, the result has void type."
5585   // The following || allows only one side to be void (a GCC-ism).
5586   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
5587     return checkConditionalVoidType(*this, LHS, RHS);
5588   }
5589 
5590   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
5591   // the type of the other operand."
5592   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
5593   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
5594 
5595   // All objective-c pointer type analysis is done here.
5596   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
5597                                                         QuestionLoc);
5598   if (LHS.isInvalid() || RHS.isInvalid())
5599     return QualType();
5600   if (!compositeType.isNull())
5601     return compositeType;
5602 
5603 
5604   // Handle block pointer types.
5605   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
5606     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
5607                                                      QuestionLoc);
5608 
5609   // Check constraints for C object pointers types (C99 6.5.15p3,6).
5610   if (LHSTy->isPointerType() && RHSTy->isPointerType())
5611     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
5612                                                        QuestionLoc);
5613 
5614   // GCC compatibility: soften pointer/integer mismatch.  Note that
5615   // null pointers have been filtered out by this point.
5616   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
5617       /*isIntFirstExpr=*/true))
5618     return RHSTy;
5619   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
5620       /*isIntFirstExpr=*/false))
5621     return LHSTy;
5622 
5623   // Emit a better diagnostic if one of the expressions is a null pointer
5624   // constant and the other is not a pointer type. In this case, the user most
5625   // likely forgot to take the address of the other expression.
5626   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
5627     return QualType();
5628 
5629   // Otherwise, the operands are not compatible.
5630   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
5631     << LHSTy << RHSTy << LHS.get()->getSourceRange()
5632     << RHS.get()->getSourceRange();
5633   return QualType();
5634 }
5635 
5636 /// FindCompositeObjCPointerType - Helper method to find composite type of
5637 /// two objective-c pointer types of the two input expressions.
5638 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
5639                                             SourceLocation QuestionLoc) {
5640   QualType LHSTy = LHS.get()->getType();
5641   QualType RHSTy = RHS.get()->getType();
5642 
5643   // Handle things like Class and struct objc_class*.  Here we case the result
5644   // to the pseudo-builtin, because that will be implicitly cast back to the
5645   // redefinition type if an attempt is made to access its fields.
5646   if (LHSTy->isObjCClassType() &&
5647       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
5648     RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
5649     return LHSTy;
5650   }
5651   if (RHSTy->isObjCClassType() &&
5652       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
5653     LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
5654     return RHSTy;
5655   }
5656   // And the same for struct objc_object* / id
5657   if (LHSTy->isObjCIdType() &&
5658       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
5659     RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
5660     return LHSTy;
5661   }
5662   if (RHSTy->isObjCIdType() &&
5663       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
5664     LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
5665     return RHSTy;
5666   }
5667   // And the same for struct objc_selector* / SEL
5668   if (Context.isObjCSelType(LHSTy) &&
5669       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
5670     RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
5671     return LHSTy;
5672   }
5673   if (Context.isObjCSelType(RHSTy) &&
5674       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
5675     LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
5676     return RHSTy;
5677   }
5678   // Check constraints for Objective-C object pointers types.
5679   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
5680 
5681     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5682       // Two identical object pointer types are always compatible.
5683       return LHSTy;
5684     }
5685     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
5686     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
5687     QualType compositeType = LHSTy;
5688 
5689     // If both operands are interfaces and either operand can be
5690     // assigned to the other, use that type as the composite
5691     // type. This allows
5692     //   xxx ? (A*) a : (B*) b
5693     // where B is a subclass of A.
5694     //
5695     // Additionally, as for assignment, if either type is 'id'
5696     // allow silent coercion. Finally, if the types are
5697     // incompatible then make sure to use 'id' as the composite
5698     // type so the result is acceptable for sending messages to.
5699 
5700     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
5701     // It could return the composite type.
5702     if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
5703       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
5704     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
5705       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
5706     } else if ((LHSTy->isObjCQualifiedIdType() ||
5707                 RHSTy->isObjCQualifiedIdType()) &&
5708                Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
5709       // Need to handle "id<xx>" explicitly.
5710       // GCC allows qualified id and any Objective-C type to devolve to
5711       // id. Currently localizing to here until clear this should be
5712       // part of ObjCQualifiedIdTypesAreCompatible.
5713       compositeType = Context.getObjCIdType();
5714     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
5715       compositeType = Context.getObjCIdType();
5716     } else if (!(compositeType =
5717                  Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
5718       ;
5719     else {
5720       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
5721       << LHSTy << RHSTy
5722       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5723       QualType incompatTy = Context.getObjCIdType();
5724       LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
5725       RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
5726       return incompatTy;
5727     }
5728     // The object pointer types are compatible.
5729     LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast);
5730     RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast);
5731     return compositeType;
5732   }
5733   // Check Objective-C object pointer types and 'void *'
5734   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
5735     if (getLangOpts().ObjCAutoRefCount) {
5736       // ARC forbids the implicit conversion of object pointers to 'void *',
5737       // so these types are not compatible.
5738       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
5739           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5740       LHS = RHS = true;
5741       return QualType();
5742     }
5743     QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5744     QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5745     QualType destPointee
5746     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
5747     QualType destType = Context.getPointerType(destPointee);
5748     // Add qualifiers if necessary.
5749     LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
5750     // Promote to void*.
5751     RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
5752     return destType;
5753   }
5754   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
5755     if (getLangOpts().ObjCAutoRefCount) {
5756       // ARC forbids the implicit conversion of object pointers to 'void *',
5757       // so these types are not compatible.
5758       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
5759           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5760       LHS = RHS = true;
5761       return QualType();
5762     }
5763     QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5764     QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
5765     QualType destPointee
5766     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
5767     QualType destType = Context.getPointerType(destPointee);
5768     // Add qualifiers if necessary.
5769     RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
5770     // Promote to void*.
5771     LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
5772     return destType;
5773   }
5774   return QualType();
5775 }
5776 
5777 /// SuggestParentheses - Emit a note with a fixit hint that wraps
5778 /// ParenRange in parentheses.
5779 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
5780                                const PartialDiagnostic &Note,
5781                                SourceRange ParenRange) {
5782   SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
5783   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
5784       EndLoc.isValid()) {
5785     Self.Diag(Loc, Note)
5786       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
5787       << FixItHint::CreateInsertion(EndLoc, ")");
5788   } else {
5789     // We can't display the parentheses, so just show the bare note.
5790     Self.Diag(Loc, Note) << ParenRange;
5791   }
5792 }
5793 
5794 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
5795   return Opc >= BO_Mul && Opc <= BO_Shr;
5796 }
5797 
5798 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
5799 /// expression, either using a built-in or overloaded operator,
5800 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
5801 /// expression.
5802 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
5803                                    Expr **RHSExprs) {
5804   // Don't strip parenthesis: we should not warn if E is in parenthesis.
5805   E = E->IgnoreImpCasts();
5806   E = E->IgnoreConversionOperator();
5807   E = E->IgnoreImpCasts();
5808 
5809   // Built-in binary operator.
5810   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
5811     if (IsArithmeticOp(OP->getOpcode())) {
5812       *Opcode = OP->getOpcode();
5813       *RHSExprs = OP->getRHS();
5814       return true;
5815     }
5816   }
5817 
5818   // Overloaded operator.
5819   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
5820     if (Call->getNumArgs() != 2)
5821       return false;
5822 
5823     // Make sure this is really a binary operator that is safe to pass into
5824     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
5825     OverloadedOperatorKind OO = Call->getOperator();
5826     if (OO < OO_Plus || OO > OO_Arrow ||
5827         OO == OO_PlusPlus || OO == OO_MinusMinus)
5828       return false;
5829 
5830     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
5831     if (IsArithmeticOp(OpKind)) {
5832       *Opcode = OpKind;
5833       *RHSExprs = Call->getArg(1);
5834       return true;
5835     }
5836   }
5837 
5838   return false;
5839 }
5840 
5841 static bool IsLogicOp(BinaryOperatorKind Opc) {
5842   return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
5843 }
5844 
5845 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
5846 /// or is a logical expression such as (x==y) which has int type, but is
5847 /// commonly interpreted as boolean.
5848 static bool ExprLooksBoolean(Expr *E) {
5849   E = E->IgnoreParenImpCasts();
5850 
5851   if (E->getType()->isBooleanType())
5852     return true;
5853   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
5854     return IsLogicOp(OP->getOpcode());
5855   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
5856     return OP->getOpcode() == UO_LNot;
5857 
5858   return false;
5859 }
5860 
5861 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
5862 /// and binary operator are mixed in a way that suggests the programmer assumed
5863 /// the conditional operator has higher precedence, for example:
5864 /// "int x = a + someBinaryCondition ? 1 : 2".
5865 static void DiagnoseConditionalPrecedence(Sema &Self,
5866                                           SourceLocation OpLoc,
5867                                           Expr *Condition,
5868                                           Expr *LHSExpr,
5869                                           Expr *RHSExpr) {
5870   BinaryOperatorKind CondOpcode;
5871   Expr *CondRHS;
5872 
5873   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
5874     return;
5875   if (!ExprLooksBoolean(CondRHS))
5876     return;
5877 
5878   // The condition is an arithmetic binary expression, with a right-
5879   // hand side that looks boolean, so warn.
5880 
5881   Self.Diag(OpLoc, diag::warn_precedence_conditional)
5882       << Condition->getSourceRange()
5883       << BinaryOperator::getOpcodeStr(CondOpcode);
5884 
5885   SuggestParentheses(Self, OpLoc,
5886     Self.PDiag(diag::note_precedence_silence)
5887       << BinaryOperator::getOpcodeStr(CondOpcode),
5888     SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
5889 
5890   SuggestParentheses(Self, OpLoc,
5891     Self.PDiag(diag::note_precedence_conditional_first),
5892     SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
5893 }
5894 
5895 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
5896 /// in the case of a the GNU conditional expr extension.
5897 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
5898                                     SourceLocation ColonLoc,
5899                                     Expr *CondExpr, Expr *LHSExpr,
5900                                     Expr *RHSExpr) {
5901   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
5902   // was the condition.
5903   OpaqueValueExpr *opaqueValue = 0;
5904   Expr *commonExpr = 0;
5905   if (LHSExpr == 0) {
5906     commonExpr = CondExpr;
5907     // Lower out placeholder types first.  This is important so that we don't
5908     // try to capture a placeholder. This happens in few cases in C++; such
5909     // as Objective-C++'s dictionary subscripting syntax.
5910     if (commonExpr->hasPlaceholderType()) {
5911       ExprResult result = CheckPlaceholderExpr(commonExpr);
5912       if (!result.isUsable()) return ExprError();
5913       commonExpr = result.take();
5914     }
5915     // We usually want to apply unary conversions *before* saving, except
5916     // in the special case of a C++ l-value conditional.
5917     if (!(getLangOpts().CPlusPlus
5918           && !commonExpr->isTypeDependent()
5919           && commonExpr->getValueKind() == RHSExpr->getValueKind()
5920           && commonExpr->isGLValue()
5921           && commonExpr->isOrdinaryOrBitFieldObject()
5922           && RHSExpr->isOrdinaryOrBitFieldObject()
5923           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
5924       ExprResult commonRes = UsualUnaryConversions(commonExpr);
5925       if (commonRes.isInvalid())
5926         return ExprError();
5927       commonExpr = commonRes.take();
5928     }
5929 
5930     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
5931                                                 commonExpr->getType(),
5932                                                 commonExpr->getValueKind(),
5933                                                 commonExpr->getObjectKind(),
5934                                                 commonExpr);
5935     LHSExpr = CondExpr = opaqueValue;
5936   }
5937 
5938   ExprValueKind VK = VK_RValue;
5939   ExprObjectKind OK = OK_Ordinary;
5940   ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
5941   QualType result = CheckConditionalOperands(Cond, LHS, RHS,
5942                                              VK, OK, QuestionLoc);
5943   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
5944       RHS.isInvalid())
5945     return ExprError();
5946 
5947   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
5948                                 RHS.get());
5949 
5950   if (!commonExpr)
5951     return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc,
5952                                                    LHS.take(), ColonLoc,
5953                                                    RHS.take(), result, VK, OK));
5954 
5955   return Owned(new (Context)
5956     BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(),
5957                               RHS.take(), QuestionLoc, ColonLoc, result, VK,
5958                               OK));
5959 }
5960 
5961 // checkPointerTypesForAssignment - This is a very tricky routine (despite
5962 // being closely modeled after the C99 spec:-). The odd characteristic of this
5963 // routine is it effectively iqnores the qualifiers on the top level pointee.
5964 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
5965 // FIXME: add a couple examples in this comment.
5966 static Sema::AssignConvertType
5967 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
5968   assert(LHSType.isCanonical() && "LHS not canonicalized!");
5969   assert(RHSType.isCanonical() && "RHS not canonicalized!");
5970 
5971   // get the "pointed to" type (ignoring qualifiers at the top level)
5972   const Type *lhptee, *rhptee;
5973   Qualifiers lhq, rhq;
5974   llvm::tie(lhptee, lhq) = cast<PointerType>(LHSType)->getPointeeType().split();
5975   llvm::tie(rhptee, rhq) = cast<PointerType>(RHSType)->getPointeeType().split();
5976 
5977   Sema::AssignConvertType ConvTy = Sema::Compatible;
5978 
5979   // C99 6.5.16.1p1: This following citation is common to constraints
5980   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
5981   // qualifiers of the type *pointed to* by the right;
5982   Qualifiers lq;
5983 
5984   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
5985   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
5986       lhq.compatiblyIncludesObjCLifetime(rhq)) {
5987     // Ignore lifetime for further calculation.
5988     lhq.removeObjCLifetime();
5989     rhq.removeObjCLifetime();
5990   }
5991 
5992   if (!lhq.compatiblyIncludes(rhq)) {
5993     // Treat address-space mismatches as fatal.  TODO: address subspaces
5994     if (lhq.getAddressSpace() != rhq.getAddressSpace())
5995       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5996 
5997     // It's okay to add or remove GC or lifetime qualifiers when converting to
5998     // and from void*.
5999     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
6000                         .compatiblyIncludes(
6001                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
6002              && (lhptee->isVoidType() || rhptee->isVoidType()))
6003       ; // keep old
6004 
6005     // Treat lifetime mismatches as fatal.
6006     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
6007       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
6008 
6009     // For GCC compatibility, other qualifier mismatches are treated
6010     // as still compatible in C.
6011     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
6012   }
6013 
6014   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
6015   // incomplete type and the other is a pointer to a qualified or unqualified
6016   // version of void...
6017   if (lhptee->isVoidType()) {
6018     if (rhptee->isIncompleteOrObjectType())
6019       return ConvTy;
6020 
6021     // As an extension, we allow cast to/from void* to function pointer.
6022     assert(rhptee->isFunctionType());
6023     return Sema::FunctionVoidPointer;
6024   }
6025 
6026   if (rhptee->isVoidType()) {
6027     if (lhptee->isIncompleteOrObjectType())
6028       return ConvTy;
6029 
6030     // As an extension, we allow cast to/from void* to function pointer.
6031     assert(lhptee->isFunctionType());
6032     return Sema::FunctionVoidPointer;
6033   }
6034 
6035   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
6036   // unqualified versions of compatible types, ...
6037   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
6038   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
6039     // Check if the pointee types are compatible ignoring the sign.
6040     // We explicitly check for char so that we catch "char" vs
6041     // "unsigned char" on systems where "char" is unsigned.
6042     if (lhptee->isCharType())
6043       ltrans = S.Context.UnsignedCharTy;
6044     else if (lhptee->hasSignedIntegerRepresentation())
6045       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
6046 
6047     if (rhptee->isCharType())
6048       rtrans = S.Context.UnsignedCharTy;
6049     else if (rhptee->hasSignedIntegerRepresentation())
6050       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
6051 
6052     if (ltrans == rtrans) {
6053       // Types are compatible ignoring the sign. Qualifier incompatibility
6054       // takes priority over sign incompatibility because the sign
6055       // warning can be disabled.
6056       if (ConvTy != Sema::Compatible)
6057         return ConvTy;
6058 
6059       return Sema::IncompatiblePointerSign;
6060     }
6061 
6062     // If we are a multi-level pointer, it's possible that our issue is simply
6063     // one of qualification - e.g. char ** -> const char ** is not allowed. If
6064     // the eventual target type is the same and the pointers have the same
6065     // level of indirection, this must be the issue.
6066     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
6067       do {
6068         lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
6069         rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
6070       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
6071 
6072       if (lhptee == rhptee)
6073         return Sema::IncompatibleNestedPointerQualifiers;
6074     }
6075 
6076     // General pointer incompatibility takes priority over qualifiers.
6077     return Sema::IncompatiblePointer;
6078   }
6079   if (!S.getLangOpts().CPlusPlus &&
6080       S.IsNoReturnConversion(ltrans, rtrans, ltrans))
6081     return Sema::IncompatiblePointer;
6082   return ConvTy;
6083 }
6084 
6085 /// checkBlockPointerTypesForAssignment - This routine determines whether two
6086 /// block pointer types are compatible or whether a block and normal pointer
6087 /// are compatible. It is more restrict than comparing two function pointer
6088 // types.
6089 static Sema::AssignConvertType
6090 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
6091                                     QualType RHSType) {
6092   assert(LHSType.isCanonical() && "LHS not canonicalized!");
6093   assert(RHSType.isCanonical() && "RHS not canonicalized!");
6094 
6095   QualType lhptee, rhptee;
6096 
6097   // get the "pointed to" type (ignoring qualifiers at the top level)
6098   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
6099   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
6100 
6101   // In C++, the types have to match exactly.
6102   if (S.getLangOpts().CPlusPlus)
6103     return Sema::IncompatibleBlockPointer;
6104 
6105   Sema::AssignConvertType ConvTy = Sema::Compatible;
6106 
6107   // For blocks we enforce that qualifiers are identical.
6108   if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
6109     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
6110 
6111   if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
6112     return Sema::IncompatibleBlockPointer;
6113 
6114   return ConvTy;
6115 }
6116 
6117 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
6118 /// for assignment compatibility.
6119 static Sema::AssignConvertType
6120 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
6121                                    QualType RHSType) {
6122   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
6123   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
6124 
6125   if (LHSType->isObjCBuiltinType()) {
6126     // Class is not compatible with ObjC object pointers.
6127     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
6128         !RHSType->isObjCQualifiedClassType())
6129       return Sema::IncompatiblePointer;
6130     return Sema::Compatible;
6131   }
6132   if (RHSType->isObjCBuiltinType()) {
6133     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
6134         !LHSType->isObjCQualifiedClassType())
6135       return Sema::IncompatiblePointer;
6136     return Sema::Compatible;
6137   }
6138   QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
6139   QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
6140 
6141   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
6142       // make an exception for id<P>
6143       !LHSType->isObjCQualifiedIdType())
6144     return Sema::CompatiblePointerDiscardsQualifiers;
6145 
6146   if (S.Context.typesAreCompatible(LHSType, RHSType))
6147     return Sema::Compatible;
6148   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
6149     return Sema::IncompatibleObjCQualifiedId;
6150   return Sema::IncompatiblePointer;
6151 }
6152 
6153 Sema::AssignConvertType
6154 Sema::CheckAssignmentConstraints(SourceLocation Loc,
6155                                  QualType LHSType, QualType RHSType) {
6156   // Fake up an opaque expression.  We don't actually care about what
6157   // cast operations are required, so if CheckAssignmentConstraints
6158   // adds casts to this they'll be wasted, but fortunately that doesn't
6159   // usually happen on valid code.
6160   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
6161   ExprResult RHSPtr = &RHSExpr;
6162   CastKind K = CK_Invalid;
6163 
6164   return CheckAssignmentConstraints(LHSType, RHSPtr, K);
6165 }
6166 
6167 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
6168 /// has code to accommodate several GCC extensions when type checking
6169 /// pointers. Here are some objectionable examples that GCC considers warnings:
6170 ///
6171 ///  int a, *pint;
6172 ///  short *pshort;
6173 ///  struct foo *pfoo;
6174 ///
6175 ///  pint = pshort; // warning: assignment from incompatible pointer type
6176 ///  a = pint; // warning: assignment makes integer from pointer without a cast
6177 ///  pint = a; // warning: assignment makes pointer from integer without a cast
6178 ///  pint = pfoo; // warning: assignment from incompatible pointer type
6179 ///
6180 /// As a result, the code for dealing with pointers is more complex than the
6181 /// C99 spec dictates.
6182 ///
6183 /// Sets 'Kind' for any result kind except Incompatible.
6184 Sema::AssignConvertType
6185 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
6186                                  CastKind &Kind) {
6187   QualType RHSType = RHS.get()->getType();
6188   QualType OrigLHSType = LHSType;
6189 
6190   // Get canonical types.  We're not formatting these types, just comparing
6191   // them.
6192   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
6193   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
6194 
6195   // Common case: no conversion required.
6196   if (LHSType == RHSType) {
6197     Kind = CK_NoOp;
6198     return Compatible;
6199   }
6200 
6201   // If we have an atomic type, try a non-atomic assignment, then just add an
6202   // atomic qualification step.
6203   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
6204     Sema::AssignConvertType result =
6205       CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
6206     if (result != Compatible)
6207       return result;
6208     if (Kind != CK_NoOp)
6209       RHS = ImpCastExprToType(RHS.take(), AtomicTy->getValueType(), Kind);
6210     Kind = CK_NonAtomicToAtomic;
6211     return Compatible;
6212   }
6213 
6214   // If the left-hand side is a reference type, then we are in a
6215   // (rare!) case where we've allowed the use of references in C,
6216   // e.g., as a parameter type in a built-in function. In this case,
6217   // just make sure that the type referenced is compatible with the
6218   // right-hand side type. The caller is responsible for adjusting
6219   // LHSType so that the resulting expression does not have reference
6220   // type.
6221   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
6222     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
6223       Kind = CK_LValueBitCast;
6224       return Compatible;
6225     }
6226     return Incompatible;
6227   }
6228 
6229   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
6230   // to the same ExtVector type.
6231   if (LHSType->isExtVectorType()) {
6232     if (RHSType->isExtVectorType())
6233       return Incompatible;
6234     if (RHSType->isArithmeticType()) {
6235       // CK_VectorSplat does T -> vector T, so first cast to the
6236       // element type.
6237       QualType elType = cast<ExtVectorType>(LHSType)->getElementType();
6238       if (elType != RHSType) {
6239         Kind = PrepareScalarCast(RHS, elType);
6240         RHS = ImpCastExprToType(RHS.take(), elType, Kind);
6241       }
6242       Kind = CK_VectorSplat;
6243       return Compatible;
6244     }
6245   }
6246 
6247   // Conversions to or from vector type.
6248   if (LHSType->isVectorType() || RHSType->isVectorType()) {
6249     if (LHSType->isVectorType() && RHSType->isVectorType()) {
6250       // Allow assignments of an AltiVec vector type to an equivalent GCC
6251       // vector type and vice versa
6252       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
6253         Kind = CK_BitCast;
6254         return Compatible;
6255       }
6256 
6257       // If we are allowing lax vector conversions, and LHS and RHS are both
6258       // vectors, the total size only needs to be the same. This is a bitcast;
6259       // no bits are changed but the result type is different.
6260       if (getLangOpts().LaxVectorConversions &&
6261           (Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType))) {
6262         Kind = CK_BitCast;
6263         return IncompatibleVectors;
6264       }
6265     }
6266     return Incompatible;
6267   }
6268 
6269   // Arithmetic conversions.
6270   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
6271       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
6272     Kind = PrepareScalarCast(RHS, LHSType);
6273     return Compatible;
6274   }
6275 
6276   // Conversions to normal pointers.
6277   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
6278     // U* -> T*
6279     if (isa<PointerType>(RHSType)) {
6280       Kind = CK_BitCast;
6281       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
6282     }
6283 
6284     // int -> T*
6285     if (RHSType->isIntegerType()) {
6286       Kind = CK_IntegralToPointer; // FIXME: null?
6287       return IntToPointer;
6288     }
6289 
6290     // C pointers are not compatible with ObjC object pointers,
6291     // with two exceptions:
6292     if (isa<ObjCObjectPointerType>(RHSType)) {
6293       //  - conversions to void*
6294       if (LHSPointer->getPointeeType()->isVoidType()) {
6295         Kind = CK_BitCast;
6296         return Compatible;
6297       }
6298 
6299       //  - conversions from 'Class' to the redefinition type
6300       if (RHSType->isObjCClassType() &&
6301           Context.hasSameType(LHSType,
6302                               Context.getObjCClassRedefinitionType())) {
6303         Kind = CK_BitCast;
6304         return Compatible;
6305       }
6306 
6307       Kind = CK_BitCast;
6308       return IncompatiblePointer;
6309     }
6310 
6311     // U^ -> void*
6312     if (RHSType->getAs<BlockPointerType>()) {
6313       if (LHSPointer->getPointeeType()->isVoidType()) {
6314         Kind = CK_BitCast;
6315         return Compatible;
6316       }
6317     }
6318 
6319     return Incompatible;
6320   }
6321 
6322   // Conversions to block pointers.
6323   if (isa<BlockPointerType>(LHSType)) {
6324     // U^ -> T^
6325     if (RHSType->isBlockPointerType()) {
6326       Kind = CK_BitCast;
6327       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
6328     }
6329 
6330     // int or null -> T^
6331     if (RHSType->isIntegerType()) {
6332       Kind = CK_IntegralToPointer; // FIXME: null
6333       return IntToBlockPointer;
6334     }
6335 
6336     // id -> T^
6337     if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
6338       Kind = CK_AnyPointerToBlockPointerCast;
6339       return Compatible;
6340     }
6341 
6342     // void* -> T^
6343     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
6344       if (RHSPT->getPointeeType()->isVoidType()) {
6345         Kind = CK_AnyPointerToBlockPointerCast;
6346         return Compatible;
6347       }
6348 
6349     return Incompatible;
6350   }
6351 
6352   // Conversions to Objective-C pointers.
6353   if (isa<ObjCObjectPointerType>(LHSType)) {
6354     // A* -> B*
6355     if (RHSType->isObjCObjectPointerType()) {
6356       Kind = CK_BitCast;
6357       Sema::AssignConvertType result =
6358         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
6359       if (getLangOpts().ObjCAutoRefCount &&
6360           result == Compatible &&
6361           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
6362         result = IncompatibleObjCWeakRef;
6363       return result;
6364     }
6365 
6366     // int or null -> A*
6367     if (RHSType->isIntegerType()) {
6368       Kind = CK_IntegralToPointer; // FIXME: null
6369       return IntToPointer;
6370     }
6371 
6372     // In general, C pointers are not compatible with ObjC object pointers,
6373     // with two exceptions:
6374     if (isa<PointerType>(RHSType)) {
6375       Kind = CK_CPointerToObjCPointerCast;
6376 
6377       //  - conversions from 'void*'
6378       if (RHSType->isVoidPointerType()) {
6379         return Compatible;
6380       }
6381 
6382       //  - conversions to 'Class' from its redefinition type
6383       if (LHSType->isObjCClassType() &&
6384           Context.hasSameType(RHSType,
6385                               Context.getObjCClassRedefinitionType())) {
6386         return Compatible;
6387       }
6388 
6389       return IncompatiblePointer;
6390     }
6391 
6392     // T^ -> A*
6393     if (RHSType->isBlockPointerType()) {
6394       maybeExtendBlockObject(*this, RHS);
6395       Kind = CK_BlockPointerToObjCPointerCast;
6396       return Compatible;
6397     }
6398 
6399     return Incompatible;
6400   }
6401 
6402   // Conversions from pointers that are not covered by the above.
6403   if (isa<PointerType>(RHSType)) {
6404     // T* -> _Bool
6405     if (LHSType == Context.BoolTy) {
6406       Kind = CK_PointerToBoolean;
6407       return Compatible;
6408     }
6409 
6410     // T* -> int
6411     if (LHSType->isIntegerType()) {
6412       Kind = CK_PointerToIntegral;
6413       return PointerToInt;
6414     }
6415 
6416     return Incompatible;
6417   }
6418 
6419   // Conversions from Objective-C pointers that are not covered by the above.
6420   if (isa<ObjCObjectPointerType>(RHSType)) {
6421     // T* -> _Bool
6422     if (LHSType == Context.BoolTy) {
6423       Kind = CK_PointerToBoolean;
6424       return Compatible;
6425     }
6426 
6427     // T* -> int
6428     if (LHSType->isIntegerType()) {
6429       Kind = CK_PointerToIntegral;
6430       return PointerToInt;
6431     }
6432 
6433     return Incompatible;
6434   }
6435 
6436   // struct A -> struct B
6437   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
6438     if (Context.typesAreCompatible(LHSType, RHSType)) {
6439       Kind = CK_NoOp;
6440       return Compatible;
6441     }
6442   }
6443 
6444   return Incompatible;
6445 }
6446 
6447 /// \brief Constructs a transparent union from an expression that is
6448 /// used to initialize the transparent union.
6449 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
6450                                       ExprResult &EResult, QualType UnionType,
6451                                       FieldDecl *Field) {
6452   // Build an initializer list that designates the appropriate member
6453   // of the transparent union.
6454   Expr *E = EResult.take();
6455   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
6456                                                    E, SourceLocation());
6457   Initializer->setType(UnionType);
6458   Initializer->setInitializedFieldInUnion(Field);
6459 
6460   // Build a compound literal constructing a value of the transparent
6461   // union type from this initializer list.
6462   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
6463   EResult = S.Owned(
6464     new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
6465                                 VK_RValue, Initializer, false));
6466 }
6467 
6468 Sema::AssignConvertType
6469 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
6470                                                ExprResult &RHS) {
6471   QualType RHSType = RHS.get()->getType();
6472 
6473   // If the ArgType is a Union type, we want to handle a potential
6474   // transparent_union GCC extension.
6475   const RecordType *UT = ArgType->getAsUnionType();
6476   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
6477     return Incompatible;
6478 
6479   // The field to initialize within the transparent union.
6480   RecordDecl *UD = UT->getDecl();
6481   FieldDecl *InitField = 0;
6482   // It's compatible if the expression matches any of the fields.
6483   for (RecordDecl::field_iterator it = UD->field_begin(),
6484          itend = UD->field_end();
6485        it != itend; ++it) {
6486     if (it->getType()->isPointerType()) {
6487       // If the transparent union contains a pointer type, we allow:
6488       // 1) void pointer
6489       // 2) null pointer constant
6490       if (RHSType->isPointerType())
6491         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
6492           RHS = ImpCastExprToType(RHS.take(), it->getType(), CK_BitCast);
6493           InitField = *it;
6494           break;
6495         }
6496 
6497       if (RHS.get()->isNullPointerConstant(Context,
6498                                            Expr::NPC_ValueDependentIsNull)) {
6499         RHS = ImpCastExprToType(RHS.take(), it->getType(),
6500                                 CK_NullToPointer);
6501         InitField = *it;
6502         break;
6503       }
6504     }
6505 
6506     CastKind Kind = CK_Invalid;
6507     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
6508           == Compatible) {
6509       RHS = ImpCastExprToType(RHS.take(), it->getType(), Kind);
6510       InitField = *it;
6511       break;
6512     }
6513   }
6514 
6515   if (!InitField)
6516     return Incompatible;
6517 
6518   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
6519   return Compatible;
6520 }
6521 
6522 Sema::AssignConvertType
6523 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS,
6524                                        bool Diagnose,
6525                                        bool DiagnoseCFAudited) {
6526   if (getLangOpts().CPlusPlus) {
6527     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
6528       // C++ 5.17p3: If the left operand is not of class type, the
6529       // expression is implicitly converted (C++ 4) to the
6530       // cv-unqualified type of the left operand.
6531       ExprResult Res;
6532       if (Diagnose) {
6533         Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
6534                                         AA_Assigning);
6535       } else {
6536         ImplicitConversionSequence ICS =
6537             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
6538                                   /*SuppressUserConversions=*/false,
6539                                   /*AllowExplicit=*/false,
6540                                   /*InOverloadResolution=*/false,
6541                                   /*CStyle=*/false,
6542                                   /*AllowObjCWritebackConversion=*/false);
6543         if (ICS.isFailure())
6544           return Incompatible;
6545         Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
6546                                         ICS, AA_Assigning);
6547       }
6548       if (Res.isInvalid())
6549         return Incompatible;
6550       Sema::AssignConvertType result = Compatible;
6551       if (getLangOpts().ObjCAutoRefCount &&
6552           !CheckObjCARCUnavailableWeakConversion(LHSType,
6553                                                  RHS.get()->getType()))
6554         result = IncompatibleObjCWeakRef;
6555       RHS = Res;
6556       return result;
6557     }
6558 
6559     // FIXME: Currently, we fall through and treat C++ classes like C
6560     // structures.
6561     // FIXME: We also fall through for atomics; not sure what should
6562     // happen there, though.
6563   }
6564 
6565   // C99 6.5.16.1p1: the left operand is a pointer and the right is
6566   // a null pointer constant.
6567   if ((LHSType->isPointerType() ||
6568        LHSType->isObjCObjectPointerType() ||
6569        LHSType->isBlockPointerType())
6570       && RHS.get()->isNullPointerConstant(Context,
6571                                           Expr::NPC_ValueDependentIsNull)) {
6572     RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
6573     return Compatible;
6574   }
6575 
6576   // This check seems unnatural, however it is necessary to ensure the proper
6577   // conversion of functions/arrays. If the conversion were done for all
6578   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
6579   // expressions that suppress this implicit conversion (&, sizeof).
6580   //
6581   // Suppress this for references: C++ 8.5.3p5.
6582   if (!LHSType->isReferenceType()) {
6583     RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
6584     if (RHS.isInvalid())
6585       return Incompatible;
6586   }
6587 
6588   CastKind Kind = CK_Invalid;
6589   Sema::AssignConvertType result =
6590     CheckAssignmentConstraints(LHSType, RHS, Kind);
6591 
6592   // C99 6.5.16.1p2: The value of the right operand is converted to the
6593   // type of the assignment expression.
6594   // CheckAssignmentConstraints allows the left-hand side to be a reference,
6595   // so that we can use references in built-in functions even in C.
6596   // The getNonReferenceType() call makes sure that the resulting expression
6597   // does not have reference type.
6598   if (result != Incompatible && RHS.get()->getType() != LHSType) {
6599     QualType Ty = LHSType.getNonLValueExprType(Context);
6600     Expr *E = RHS.take();
6601     if (getLangOpts().ObjCAutoRefCount)
6602       CheckObjCARCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
6603                              DiagnoseCFAudited);
6604     RHS = ImpCastExprToType(E, Ty, Kind);
6605   }
6606   return result;
6607 }
6608 
6609 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
6610                                ExprResult &RHS) {
6611   Diag(Loc, diag::err_typecheck_invalid_operands)
6612     << LHS.get()->getType() << RHS.get()->getType()
6613     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6614   return QualType();
6615 }
6616 
6617 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
6618                                    SourceLocation Loc, bool IsCompAssign) {
6619   if (!IsCompAssign) {
6620     LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
6621     if (LHS.isInvalid())
6622       return QualType();
6623   }
6624   RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
6625   if (RHS.isInvalid())
6626     return QualType();
6627 
6628   // For conversion purposes, we ignore any qualifiers.
6629   // For example, "const float" and "float" are equivalent.
6630   QualType LHSType =
6631     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
6632   QualType RHSType =
6633     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
6634 
6635   // If the vector types are identical, return.
6636   if (LHSType == RHSType)
6637     return LHSType;
6638 
6639   // Handle the case of equivalent AltiVec and GCC vector types
6640   if (LHSType->isVectorType() && RHSType->isVectorType() &&
6641       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
6642     if (LHSType->isExtVectorType()) {
6643       RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
6644       return LHSType;
6645     }
6646 
6647     if (!IsCompAssign)
6648       LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
6649     return RHSType;
6650   }
6651 
6652   if (getLangOpts().LaxVectorConversions &&
6653       Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType)) {
6654     // If we are allowing lax vector conversions, and LHS and RHS are both
6655     // vectors, the total size only needs to be the same. This is a
6656     // bitcast; no bits are changed but the result type is different.
6657     // FIXME: Should we really be allowing this?
6658     RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
6659     return LHSType;
6660   }
6661 
6662   // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
6663   // swap back (so that we don't reverse the inputs to a subtract, for instance.
6664   bool swapped = false;
6665   if (RHSType->isExtVectorType() && !IsCompAssign) {
6666     swapped = true;
6667     std::swap(RHS, LHS);
6668     std::swap(RHSType, LHSType);
6669   }
6670 
6671   // Handle the case of an ext vector and scalar.
6672   if (const ExtVectorType *LV = LHSType->getAs<ExtVectorType>()) {
6673     QualType EltTy = LV->getElementType();
6674     if (EltTy->isIntegralType(Context) && RHSType->isIntegralType(Context)) {
6675       int order = Context.getIntegerTypeOrder(EltTy, RHSType);
6676       if (order > 0)
6677         RHS = ImpCastExprToType(RHS.take(), EltTy, CK_IntegralCast);
6678       if (order >= 0) {
6679         RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
6680         if (swapped) std::swap(RHS, LHS);
6681         return LHSType;
6682       }
6683     }
6684     if (EltTy->isRealFloatingType() && RHSType->isScalarType()) {
6685       if (RHSType->isRealFloatingType()) {
6686         int order = Context.getFloatingTypeOrder(EltTy, RHSType);
6687         if (order > 0)
6688           RHS = ImpCastExprToType(RHS.take(), EltTy, CK_FloatingCast);
6689         if (order >= 0) {
6690           RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
6691           if (swapped) std::swap(RHS, LHS);
6692           return LHSType;
6693         }
6694       }
6695       if (RHSType->isIntegralType(Context)) {
6696         RHS = ImpCastExprToType(RHS.take(), EltTy, CK_IntegralToFloating);
6697         RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
6698         if (swapped) std::swap(RHS, LHS);
6699         return LHSType;
6700       }
6701     }
6702   }
6703 
6704   // Vectors of different size or scalar and non-ext-vector are errors.
6705   if (swapped) std::swap(RHS, LHS);
6706   Diag(Loc, diag::err_typecheck_vector_not_convertable)
6707     << LHS.get()->getType() << RHS.get()->getType()
6708     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6709   return QualType();
6710 }
6711 
6712 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
6713 // expression.  These are mainly cases where the null pointer is used as an
6714 // integer instead of a pointer.
6715 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
6716                                 SourceLocation Loc, bool IsCompare) {
6717   // The canonical way to check for a GNU null is with isNullPointerConstant,
6718   // but we use a bit of a hack here for speed; this is a relatively
6719   // hot path, and isNullPointerConstant is slow.
6720   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
6721   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
6722 
6723   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
6724 
6725   // Avoid analyzing cases where the result will either be invalid (and
6726   // diagnosed as such) or entirely valid and not something to warn about.
6727   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
6728       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
6729     return;
6730 
6731   // Comparison operations would not make sense with a null pointer no matter
6732   // what the other expression is.
6733   if (!IsCompare) {
6734     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
6735         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
6736         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
6737     return;
6738   }
6739 
6740   // The rest of the operations only make sense with a null pointer
6741   // if the other expression is a pointer.
6742   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
6743       NonNullType->canDecayToPointerType())
6744     return;
6745 
6746   S.Diag(Loc, diag::warn_null_in_comparison_operation)
6747       << LHSNull /* LHS is NULL */ << NonNullType
6748       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6749 }
6750 
6751 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
6752                                            SourceLocation Loc,
6753                                            bool IsCompAssign, bool IsDiv) {
6754   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6755 
6756   if (LHS.get()->getType()->isVectorType() ||
6757       RHS.get()->getType()->isVectorType())
6758     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
6759 
6760   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
6761   if (LHS.isInvalid() || RHS.isInvalid())
6762     return QualType();
6763 
6764 
6765   if (compType.isNull() || !compType->isArithmeticType())
6766     return InvalidOperands(Loc, LHS, RHS);
6767 
6768   // Check for division by zero.
6769   llvm::APSInt RHSValue;
6770   if (IsDiv && !RHS.get()->isValueDependent() &&
6771       RHS.get()->EvaluateAsInt(RHSValue, Context) && RHSValue == 0)
6772     DiagRuntimeBehavior(Loc, RHS.get(),
6773                         PDiag(diag::warn_division_by_zero)
6774                           << RHS.get()->getSourceRange());
6775 
6776   return compType;
6777 }
6778 
6779 QualType Sema::CheckRemainderOperands(
6780   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
6781   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6782 
6783   if (LHS.get()->getType()->isVectorType() ||
6784       RHS.get()->getType()->isVectorType()) {
6785     if (LHS.get()->getType()->hasIntegerRepresentation() &&
6786         RHS.get()->getType()->hasIntegerRepresentation())
6787       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
6788     return InvalidOperands(Loc, LHS, RHS);
6789   }
6790 
6791   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
6792   if (LHS.isInvalid() || RHS.isInvalid())
6793     return QualType();
6794 
6795   if (compType.isNull() || !compType->isIntegerType())
6796     return InvalidOperands(Loc, LHS, RHS);
6797 
6798   // Check for remainder by zero.
6799   llvm::APSInt RHSValue;
6800   if (!RHS.get()->isValueDependent() &&
6801       RHS.get()->EvaluateAsInt(RHSValue, Context) && RHSValue == 0)
6802     DiagRuntimeBehavior(Loc, RHS.get(),
6803                         PDiag(diag::warn_remainder_by_zero)
6804                           << RHS.get()->getSourceRange());
6805 
6806   return compType;
6807 }
6808 
6809 /// \brief Diagnose invalid arithmetic on two void pointers.
6810 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
6811                                                 Expr *LHSExpr, Expr *RHSExpr) {
6812   S.Diag(Loc, S.getLangOpts().CPlusPlus
6813                 ? diag::err_typecheck_pointer_arith_void_type
6814                 : diag::ext_gnu_void_ptr)
6815     << 1 /* two pointers */ << LHSExpr->getSourceRange()
6816                             << RHSExpr->getSourceRange();
6817 }
6818 
6819 /// \brief Diagnose invalid arithmetic on a void pointer.
6820 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
6821                                             Expr *Pointer) {
6822   S.Diag(Loc, S.getLangOpts().CPlusPlus
6823                 ? diag::err_typecheck_pointer_arith_void_type
6824                 : diag::ext_gnu_void_ptr)
6825     << 0 /* one pointer */ << Pointer->getSourceRange();
6826 }
6827 
6828 /// \brief Diagnose invalid arithmetic on two function pointers.
6829 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
6830                                                     Expr *LHS, Expr *RHS) {
6831   assert(LHS->getType()->isAnyPointerType());
6832   assert(RHS->getType()->isAnyPointerType());
6833   S.Diag(Loc, S.getLangOpts().CPlusPlus
6834                 ? diag::err_typecheck_pointer_arith_function_type
6835                 : diag::ext_gnu_ptr_func_arith)
6836     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
6837     // We only show the second type if it differs from the first.
6838     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
6839                                                    RHS->getType())
6840     << RHS->getType()->getPointeeType()
6841     << LHS->getSourceRange() << RHS->getSourceRange();
6842 }
6843 
6844 /// \brief Diagnose invalid arithmetic on a function pointer.
6845 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
6846                                                 Expr *Pointer) {
6847   assert(Pointer->getType()->isAnyPointerType());
6848   S.Diag(Loc, S.getLangOpts().CPlusPlus
6849                 ? diag::err_typecheck_pointer_arith_function_type
6850                 : diag::ext_gnu_ptr_func_arith)
6851     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
6852     << 0 /* one pointer, so only one type */
6853     << Pointer->getSourceRange();
6854 }
6855 
6856 /// \brief Emit error if Operand is incomplete pointer type
6857 ///
6858 /// \returns True if pointer has incomplete type
6859 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
6860                                                  Expr *Operand) {
6861   assert(Operand->getType()->isAnyPointerType() &&
6862          !Operand->getType()->isDependentType());
6863   QualType PointeeTy = Operand->getType()->getPointeeType();
6864   return S.RequireCompleteType(Loc, PointeeTy,
6865                                diag::err_typecheck_arithmetic_incomplete_type,
6866                                PointeeTy, Operand->getSourceRange());
6867 }
6868 
6869 /// \brief Check the validity of an arithmetic pointer operand.
6870 ///
6871 /// If the operand has pointer type, this code will check for pointer types
6872 /// which are invalid in arithmetic operations. These will be diagnosed
6873 /// appropriately, including whether or not the use is supported as an
6874 /// extension.
6875 ///
6876 /// \returns True when the operand is valid to use (even if as an extension).
6877 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
6878                                             Expr *Operand) {
6879   if (!Operand->getType()->isAnyPointerType()) return true;
6880 
6881   QualType PointeeTy = Operand->getType()->getPointeeType();
6882   if (PointeeTy->isVoidType()) {
6883     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
6884     return !S.getLangOpts().CPlusPlus;
6885   }
6886   if (PointeeTy->isFunctionType()) {
6887     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
6888     return !S.getLangOpts().CPlusPlus;
6889   }
6890 
6891   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
6892 
6893   return true;
6894 }
6895 
6896 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
6897 /// operands.
6898 ///
6899 /// This routine will diagnose any invalid arithmetic on pointer operands much
6900 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
6901 /// for emitting a single diagnostic even for operations where both LHS and RHS
6902 /// are (potentially problematic) pointers.
6903 ///
6904 /// \returns True when the operand is valid to use (even if as an extension).
6905 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
6906                                                 Expr *LHSExpr, Expr *RHSExpr) {
6907   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
6908   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
6909   if (!isLHSPointer && !isRHSPointer) return true;
6910 
6911   QualType LHSPointeeTy, RHSPointeeTy;
6912   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
6913   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
6914 
6915   // Check for arithmetic on pointers to incomplete types.
6916   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
6917   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
6918   if (isLHSVoidPtr || isRHSVoidPtr) {
6919     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
6920     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
6921     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
6922 
6923     return !S.getLangOpts().CPlusPlus;
6924   }
6925 
6926   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
6927   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
6928   if (isLHSFuncPtr || isRHSFuncPtr) {
6929     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
6930     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
6931                                                                 RHSExpr);
6932     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
6933 
6934     return !S.getLangOpts().CPlusPlus;
6935   }
6936 
6937   if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
6938     return false;
6939   if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
6940     return false;
6941 
6942   return true;
6943 }
6944 
6945 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
6946 /// literal.
6947 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
6948                                   Expr *LHSExpr, Expr *RHSExpr) {
6949   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
6950   Expr* IndexExpr = RHSExpr;
6951   if (!StrExpr) {
6952     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
6953     IndexExpr = LHSExpr;
6954   }
6955 
6956   bool IsStringPlusInt = StrExpr &&
6957       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
6958   if (!IsStringPlusInt)
6959     return;
6960 
6961   llvm::APSInt index;
6962   if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
6963     unsigned StrLenWithNull = StrExpr->getLength() + 1;
6964     if (index.isNonNegative() &&
6965         index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
6966                               index.isUnsigned()))
6967       return;
6968   }
6969 
6970   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
6971   Self.Diag(OpLoc, diag::warn_string_plus_int)
6972       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
6973 
6974   // Only print a fixit for "str" + int, not for int + "str".
6975   if (IndexExpr == RHSExpr) {
6976     SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd());
6977     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
6978         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
6979         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
6980         << FixItHint::CreateInsertion(EndLoc, "]");
6981   } else
6982     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
6983 }
6984 
6985 /// \brief Emit a warning when adding a char literal to a string.
6986 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
6987                                    Expr *LHSExpr, Expr *RHSExpr) {
6988   const DeclRefExpr *StringRefExpr =
6989       dyn_cast<DeclRefExpr>(LHSExpr->IgnoreImpCasts());
6990   const CharacterLiteral *CharExpr =
6991       dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
6992   if (!StringRefExpr) {
6993     StringRefExpr = dyn_cast<DeclRefExpr>(RHSExpr->IgnoreImpCasts());
6994     CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
6995   }
6996 
6997   if (!CharExpr || !StringRefExpr)
6998     return;
6999 
7000   const QualType StringType = StringRefExpr->getType();
7001 
7002   // Return if not a PointerType.
7003   if (!StringType->isAnyPointerType())
7004     return;
7005 
7006   // Return if not a CharacterType.
7007   if (!StringType->getPointeeType()->isAnyCharacterType())
7008     return;
7009 
7010   ASTContext &Ctx = Self.getASTContext();
7011   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
7012 
7013   const QualType CharType = CharExpr->getType();
7014   if (!CharType->isAnyCharacterType() &&
7015       CharType->isIntegerType() &&
7016       llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
7017     Self.Diag(OpLoc, diag::warn_string_plus_char)
7018         << DiagRange << Ctx.CharTy;
7019   } else {
7020     Self.Diag(OpLoc, diag::warn_string_plus_char)
7021         << DiagRange << CharExpr->getType();
7022   }
7023 
7024   // Only print a fixit for str + char, not for char + str.
7025   if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
7026     SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd());
7027     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
7028         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
7029         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
7030         << FixItHint::CreateInsertion(EndLoc, "]");
7031   } else {
7032     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
7033   }
7034 }
7035 
7036 /// \brief Emit error when two pointers are incompatible.
7037 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
7038                                            Expr *LHSExpr, Expr *RHSExpr) {
7039   assert(LHSExpr->getType()->isAnyPointerType());
7040   assert(RHSExpr->getType()->isAnyPointerType());
7041   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
7042     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
7043     << RHSExpr->getSourceRange();
7044 }
7045 
7046 QualType Sema::CheckAdditionOperands( // C99 6.5.6
7047     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc,
7048     QualType* CompLHSTy) {
7049   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7050 
7051   if (LHS.get()->getType()->isVectorType() ||
7052       RHS.get()->getType()->isVectorType()) {
7053     QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
7054     if (CompLHSTy) *CompLHSTy = compType;
7055     return compType;
7056   }
7057 
7058   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
7059   if (LHS.isInvalid() || RHS.isInvalid())
7060     return QualType();
7061 
7062   // Diagnose "string literal" '+' int and string '+' "char literal".
7063   if (Opc == BO_Add) {
7064     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
7065     diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
7066   }
7067 
7068   // handle the common case first (both operands are arithmetic).
7069   if (!compType.isNull() && compType->isArithmeticType()) {
7070     if (CompLHSTy) *CompLHSTy = compType;
7071     return compType;
7072   }
7073 
7074   // Type-checking.  Ultimately the pointer's going to be in PExp;
7075   // note that we bias towards the LHS being the pointer.
7076   Expr *PExp = LHS.get(), *IExp = RHS.get();
7077 
7078   bool isObjCPointer;
7079   if (PExp->getType()->isPointerType()) {
7080     isObjCPointer = false;
7081   } else if (PExp->getType()->isObjCObjectPointerType()) {
7082     isObjCPointer = true;
7083   } else {
7084     std::swap(PExp, IExp);
7085     if (PExp->getType()->isPointerType()) {
7086       isObjCPointer = false;
7087     } else if (PExp->getType()->isObjCObjectPointerType()) {
7088       isObjCPointer = true;
7089     } else {
7090       return InvalidOperands(Loc, LHS, RHS);
7091     }
7092   }
7093   assert(PExp->getType()->isAnyPointerType());
7094 
7095   if (!IExp->getType()->isIntegerType())
7096     return InvalidOperands(Loc, LHS, RHS);
7097 
7098   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
7099     return QualType();
7100 
7101   if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
7102     return QualType();
7103 
7104   // Check array bounds for pointer arithemtic
7105   CheckArrayAccess(PExp, IExp);
7106 
7107   if (CompLHSTy) {
7108     QualType LHSTy = Context.isPromotableBitField(LHS.get());
7109     if (LHSTy.isNull()) {
7110       LHSTy = LHS.get()->getType();
7111       if (LHSTy->isPromotableIntegerType())
7112         LHSTy = Context.getPromotedIntegerType(LHSTy);
7113     }
7114     *CompLHSTy = LHSTy;
7115   }
7116 
7117   return PExp->getType();
7118 }
7119 
7120 // C99 6.5.6
7121 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
7122                                         SourceLocation Loc,
7123                                         QualType* CompLHSTy) {
7124   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7125 
7126   if (LHS.get()->getType()->isVectorType() ||
7127       RHS.get()->getType()->isVectorType()) {
7128     QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
7129     if (CompLHSTy) *CompLHSTy = compType;
7130     return compType;
7131   }
7132 
7133   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
7134   if (LHS.isInvalid() || RHS.isInvalid())
7135     return QualType();
7136 
7137   // Enforce type constraints: C99 6.5.6p3.
7138 
7139   // Handle the common case first (both operands are arithmetic).
7140   if (!compType.isNull() && compType->isArithmeticType()) {
7141     if (CompLHSTy) *CompLHSTy = compType;
7142     return compType;
7143   }
7144 
7145   // Either ptr - int   or   ptr - ptr.
7146   if (LHS.get()->getType()->isAnyPointerType()) {
7147     QualType lpointee = LHS.get()->getType()->getPointeeType();
7148 
7149     // Diagnose bad cases where we step over interface counts.
7150     if (LHS.get()->getType()->isObjCObjectPointerType() &&
7151         checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
7152       return QualType();
7153 
7154     // The result type of a pointer-int computation is the pointer type.
7155     if (RHS.get()->getType()->isIntegerType()) {
7156       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
7157         return QualType();
7158 
7159       // Check array bounds for pointer arithemtic
7160       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/0,
7161                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
7162 
7163       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
7164       return LHS.get()->getType();
7165     }
7166 
7167     // Handle pointer-pointer subtractions.
7168     if (const PointerType *RHSPTy
7169           = RHS.get()->getType()->getAs<PointerType>()) {
7170       QualType rpointee = RHSPTy->getPointeeType();
7171 
7172       if (getLangOpts().CPlusPlus) {
7173         // Pointee types must be the same: C++ [expr.add]
7174         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
7175           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
7176         }
7177       } else {
7178         // Pointee types must be compatible C99 6.5.6p3
7179         if (!Context.typesAreCompatible(
7180                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
7181                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
7182           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
7183           return QualType();
7184         }
7185       }
7186 
7187       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
7188                                                LHS.get(), RHS.get()))
7189         return QualType();
7190 
7191       // The pointee type may have zero size.  As an extension, a structure or
7192       // union may have zero size or an array may have zero length.  In this
7193       // case subtraction does not make sense.
7194       if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
7195         CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
7196         if (ElementSize.isZero()) {
7197           Diag(Loc,diag::warn_sub_ptr_zero_size_types)
7198             << rpointee.getUnqualifiedType()
7199             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7200         }
7201       }
7202 
7203       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
7204       return Context.getPointerDiffType();
7205     }
7206   }
7207 
7208   return InvalidOperands(Loc, LHS, RHS);
7209 }
7210 
7211 static bool isScopedEnumerationType(QualType T) {
7212   if (const EnumType *ET = dyn_cast<EnumType>(T))
7213     return ET->getDecl()->isScoped();
7214   return false;
7215 }
7216 
7217 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
7218                                    SourceLocation Loc, unsigned Opc,
7219                                    QualType LHSType) {
7220   // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
7221   // so skip remaining warnings as we don't want to modify values within Sema.
7222   if (S.getLangOpts().OpenCL)
7223     return;
7224 
7225   llvm::APSInt Right;
7226   // Check right/shifter operand
7227   if (RHS.get()->isValueDependent() ||
7228       !RHS.get()->isIntegerConstantExpr(Right, S.Context))
7229     return;
7230 
7231   if (Right.isNegative()) {
7232     S.DiagRuntimeBehavior(Loc, RHS.get(),
7233                           S.PDiag(diag::warn_shift_negative)
7234                             << RHS.get()->getSourceRange());
7235     return;
7236   }
7237   llvm::APInt LeftBits(Right.getBitWidth(),
7238                        S.Context.getTypeSize(LHS.get()->getType()));
7239   if (Right.uge(LeftBits)) {
7240     S.DiagRuntimeBehavior(Loc, RHS.get(),
7241                           S.PDiag(diag::warn_shift_gt_typewidth)
7242                             << RHS.get()->getSourceRange());
7243     return;
7244   }
7245   if (Opc != BO_Shl)
7246     return;
7247 
7248   // When left shifting an ICE which is signed, we can check for overflow which
7249   // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
7250   // integers have defined behavior modulo one more than the maximum value
7251   // representable in the result type, so never warn for those.
7252   llvm::APSInt Left;
7253   if (LHS.get()->isValueDependent() ||
7254       !LHS.get()->isIntegerConstantExpr(Left, S.Context) ||
7255       LHSType->hasUnsignedIntegerRepresentation())
7256     return;
7257   llvm::APInt ResultBits =
7258       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
7259   if (LeftBits.uge(ResultBits))
7260     return;
7261   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
7262   Result = Result.shl(Right);
7263 
7264   // Print the bit representation of the signed integer as an unsigned
7265   // hexadecimal number.
7266   SmallString<40> HexResult;
7267   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
7268 
7269   // If we are only missing a sign bit, this is less likely to result in actual
7270   // bugs -- if the result is cast back to an unsigned type, it will have the
7271   // expected value. Thus we place this behind a different warning that can be
7272   // turned off separately if needed.
7273   if (LeftBits == ResultBits - 1) {
7274     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
7275         << HexResult.str() << LHSType
7276         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7277     return;
7278   }
7279 
7280   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
7281     << HexResult.str() << Result.getMinSignedBits() << LHSType
7282     << Left.getBitWidth() << LHS.get()->getSourceRange()
7283     << RHS.get()->getSourceRange();
7284 }
7285 
7286 // C99 6.5.7
7287 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
7288                                   SourceLocation Loc, unsigned Opc,
7289                                   bool IsCompAssign) {
7290   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7291 
7292   // Vector shifts promote their scalar inputs to vector type.
7293   if (LHS.get()->getType()->isVectorType() ||
7294       RHS.get()->getType()->isVectorType())
7295     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
7296 
7297   // Shifts don't perform usual arithmetic conversions, they just do integer
7298   // promotions on each operand. C99 6.5.7p3
7299 
7300   // For the LHS, do usual unary conversions, but then reset them away
7301   // if this is a compound assignment.
7302   ExprResult OldLHS = LHS;
7303   LHS = UsualUnaryConversions(LHS.take());
7304   if (LHS.isInvalid())
7305     return QualType();
7306   QualType LHSType = LHS.get()->getType();
7307   if (IsCompAssign) LHS = OldLHS;
7308 
7309   // The RHS is simpler.
7310   RHS = UsualUnaryConversions(RHS.take());
7311   if (RHS.isInvalid())
7312     return QualType();
7313   QualType RHSType = RHS.get()->getType();
7314 
7315   // C99 6.5.7p2: Each of the operands shall have integer type.
7316   if (!LHSType->hasIntegerRepresentation() ||
7317       !RHSType->hasIntegerRepresentation())
7318     return InvalidOperands(Loc, LHS, RHS);
7319 
7320   // C++0x: Don't allow scoped enums. FIXME: Use something better than
7321   // hasIntegerRepresentation() above instead of this.
7322   if (isScopedEnumerationType(LHSType) ||
7323       isScopedEnumerationType(RHSType)) {
7324     return InvalidOperands(Loc, LHS, RHS);
7325   }
7326   // Sanity-check shift operands
7327   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
7328 
7329   // "The type of the result is that of the promoted left operand."
7330   return LHSType;
7331 }
7332 
7333 static bool IsWithinTemplateSpecialization(Decl *D) {
7334   if (DeclContext *DC = D->getDeclContext()) {
7335     if (isa<ClassTemplateSpecializationDecl>(DC))
7336       return true;
7337     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
7338       return FD->isFunctionTemplateSpecialization();
7339   }
7340   return false;
7341 }
7342 
7343 /// If two different enums are compared, raise a warning.
7344 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS,
7345                                 Expr *RHS) {
7346   QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
7347   QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
7348 
7349   const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
7350   if (!LHSEnumType)
7351     return;
7352   const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
7353   if (!RHSEnumType)
7354     return;
7355 
7356   // Ignore anonymous enums.
7357   if (!LHSEnumType->getDecl()->getIdentifier())
7358     return;
7359   if (!RHSEnumType->getDecl()->getIdentifier())
7360     return;
7361 
7362   if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
7363     return;
7364 
7365   S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
7366       << LHSStrippedType << RHSStrippedType
7367       << LHS->getSourceRange() << RHS->getSourceRange();
7368 }
7369 
7370 /// \brief Diagnose bad pointer comparisons.
7371 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
7372                                               ExprResult &LHS, ExprResult &RHS,
7373                                               bool IsError) {
7374   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
7375                       : diag::ext_typecheck_comparison_of_distinct_pointers)
7376     << LHS.get()->getType() << RHS.get()->getType()
7377     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7378 }
7379 
7380 /// \brief Returns false if the pointers are converted to a composite type,
7381 /// true otherwise.
7382 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
7383                                            ExprResult &LHS, ExprResult &RHS) {
7384   // C++ [expr.rel]p2:
7385   //   [...] Pointer conversions (4.10) and qualification
7386   //   conversions (4.4) are performed on pointer operands (or on
7387   //   a pointer operand and a null pointer constant) to bring
7388   //   them to their composite pointer type. [...]
7389   //
7390   // C++ [expr.eq]p1 uses the same notion for (in)equality
7391   // comparisons of pointers.
7392 
7393   // C++ [expr.eq]p2:
7394   //   In addition, pointers to members can be compared, or a pointer to
7395   //   member and a null pointer constant. Pointer to member conversions
7396   //   (4.11) and qualification conversions (4.4) are performed to bring
7397   //   them to a common type. If one operand is a null pointer constant,
7398   //   the common type is the type of the other operand. Otherwise, the
7399   //   common type is a pointer to member type similar (4.4) to the type
7400   //   of one of the operands, with a cv-qualification signature (4.4)
7401   //   that is the union of the cv-qualification signatures of the operand
7402   //   types.
7403 
7404   QualType LHSType = LHS.get()->getType();
7405   QualType RHSType = RHS.get()->getType();
7406   assert((LHSType->isPointerType() && RHSType->isPointerType()) ||
7407          (LHSType->isMemberPointerType() && RHSType->isMemberPointerType()));
7408 
7409   bool NonStandardCompositeType = false;
7410   bool *BoolPtr = S.isSFINAEContext() ? 0 : &NonStandardCompositeType;
7411   QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr);
7412   if (T.isNull()) {
7413     diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
7414     return true;
7415   }
7416 
7417   if (NonStandardCompositeType)
7418     S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
7419       << LHSType << RHSType << T << LHS.get()->getSourceRange()
7420       << RHS.get()->getSourceRange();
7421 
7422   LHS = S.ImpCastExprToType(LHS.take(), T, CK_BitCast);
7423   RHS = S.ImpCastExprToType(RHS.take(), T, CK_BitCast);
7424   return false;
7425 }
7426 
7427 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
7428                                                     ExprResult &LHS,
7429                                                     ExprResult &RHS,
7430                                                     bool IsError) {
7431   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
7432                       : diag::ext_typecheck_comparison_of_fptr_to_void)
7433     << LHS.get()->getType() << RHS.get()->getType()
7434     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7435 }
7436 
7437 static bool isObjCObjectLiteral(ExprResult &E) {
7438   switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
7439   case Stmt::ObjCArrayLiteralClass:
7440   case Stmt::ObjCDictionaryLiteralClass:
7441   case Stmt::ObjCStringLiteralClass:
7442   case Stmt::ObjCBoxedExprClass:
7443     return true;
7444   default:
7445     // Note that ObjCBoolLiteral is NOT an object literal!
7446     return false;
7447   }
7448 }
7449 
7450 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
7451   const ObjCObjectPointerType *Type =
7452     LHS->getType()->getAs<ObjCObjectPointerType>();
7453 
7454   // If this is not actually an Objective-C object, bail out.
7455   if (!Type)
7456     return false;
7457 
7458   // Get the LHS object's interface type.
7459   QualType InterfaceType = Type->getPointeeType();
7460   if (const ObjCObjectType *iQFaceTy =
7461       InterfaceType->getAsObjCQualifiedInterfaceType())
7462     InterfaceType = iQFaceTy->getBaseType();
7463 
7464   // If the RHS isn't an Objective-C object, bail out.
7465   if (!RHS->getType()->isObjCObjectPointerType())
7466     return false;
7467 
7468   // Try to find the -isEqual: method.
7469   Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
7470   ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
7471                                                       InterfaceType,
7472                                                       /*instance=*/true);
7473   if (!Method) {
7474     if (Type->isObjCIdType()) {
7475       // For 'id', just check the global pool.
7476       Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
7477                                                   /*receiverId=*/true,
7478                                                   /*warn=*/false);
7479     } else {
7480       // Check protocols.
7481       Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
7482                                              /*instance=*/true);
7483     }
7484   }
7485 
7486   if (!Method)
7487     return false;
7488 
7489   QualType T = Method->param_begin()[0]->getType();
7490   if (!T->isObjCObjectPointerType())
7491     return false;
7492 
7493   QualType R = Method->getResultType();
7494   if (!R->isScalarType())
7495     return false;
7496 
7497   return true;
7498 }
7499 
7500 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
7501   FromE = FromE->IgnoreParenImpCasts();
7502   switch (FromE->getStmtClass()) {
7503     default:
7504       break;
7505     case Stmt::ObjCStringLiteralClass:
7506       // "string literal"
7507       return LK_String;
7508     case Stmt::ObjCArrayLiteralClass:
7509       // "array literal"
7510       return LK_Array;
7511     case Stmt::ObjCDictionaryLiteralClass:
7512       // "dictionary literal"
7513       return LK_Dictionary;
7514     case Stmt::BlockExprClass:
7515       return LK_Block;
7516     case Stmt::ObjCBoxedExprClass: {
7517       Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
7518       switch (Inner->getStmtClass()) {
7519         case Stmt::IntegerLiteralClass:
7520         case Stmt::FloatingLiteralClass:
7521         case Stmt::CharacterLiteralClass:
7522         case Stmt::ObjCBoolLiteralExprClass:
7523         case Stmt::CXXBoolLiteralExprClass:
7524           // "numeric literal"
7525           return LK_Numeric;
7526         case Stmt::ImplicitCastExprClass: {
7527           CastKind CK = cast<CastExpr>(Inner)->getCastKind();
7528           // Boolean literals can be represented by implicit casts.
7529           if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
7530             return LK_Numeric;
7531           break;
7532         }
7533         default:
7534           break;
7535       }
7536       return LK_Boxed;
7537     }
7538   }
7539   return LK_None;
7540 }
7541 
7542 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
7543                                           ExprResult &LHS, ExprResult &RHS,
7544                                           BinaryOperator::Opcode Opc){
7545   Expr *Literal;
7546   Expr *Other;
7547   if (isObjCObjectLiteral(LHS)) {
7548     Literal = LHS.get();
7549     Other = RHS.get();
7550   } else {
7551     Literal = RHS.get();
7552     Other = LHS.get();
7553   }
7554 
7555   // Don't warn on comparisons against nil.
7556   Other = Other->IgnoreParenCasts();
7557   if (Other->isNullPointerConstant(S.getASTContext(),
7558                                    Expr::NPC_ValueDependentIsNotNull))
7559     return;
7560 
7561   // This should be kept in sync with warn_objc_literal_comparison.
7562   // LK_String should always be after the other literals, since it has its own
7563   // warning flag.
7564   Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
7565   assert(LiteralKind != Sema::LK_Block);
7566   if (LiteralKind == Sema::LK_None) {
7567     llvm_unreachable("Unknown Objective-C object literal kind");
7568   }
7569 
7570   if (LiteralKind == Sema::LK_String)
7571     S.Diag(Loc, diag::warn_objc_string_literal_comparison)
7572       << Literal->getSourceRange();
7573   else
7574     S.Diag(Loc, diag::warn_objc_literal_comparison)
7575       << LiteralKind << Literal->getSourceRange();
7576 
7577   if (BinaryOperator::isEqualityOp(Opc) &&
7578       hasIsEqualMethod(S, LHS.get(), RHS.get())) {
7579     SourceLocation Start = LHS.get()->getLocStart();
7580     SourceLocation End = S.PP.getLocForEndOfToken(RHS.get()->getLocEnd());
7581     CharSourceRange OpRange =
7582       CharSourceRange::getCharRange(Loc, S.PP.getLocForEndOfToken(Loc));
7583 
7584     S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
7585       << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
7586       << FixItHint::CreateReplacement(OpRange, " isEqual:")
7587       << FixItHint::CreateInsertion(End, "]");
7588   }
7589 }
7590 
7591 static void diagnoseLogicalNotOnLHSofComparison(Sema &S, ExprResult &LHS,
7592                                                 ExprResult &RHS,
7593                                                 SourceLocation Loc,
7594                                                 unsigned OpaqueOpc) {
7595   // This checking requires bools.
7596   if (!S.getLangOpts().Bool) return;
7597 
7598   // Check that left hand side is !something.
7599   UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
7600   if (!UO || UO->getOpcode() != UO_LNot) return;
7601 
7602   // Only check if the right hand side is non-bool arithmetic type.
7603   if (RHS.get()->getType()->isBooleanType()) return;
7604 
7605   // Make sure that the something in !something is not bool.
7606   Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
7607   if (SubExpr->getType()->isBooleanType()) return;
7608 
7609   // Emit warning.
7610   S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_comparison)
7611       << Loc;
7612 
7613   // First note suggest !(x < y)
7614   SourceLocation FirstOpen = SubExpr->getLocStart();
7615   SourceLocation FirstClose = RHS.get()->getLocEnd();
7616   FirstClose = S.getPreprocessor().getLocForEndOfToken(FirstClose);
7617   if (FirstClose.isInvalid())
7618     FirstOpen = SourceLocation();
7619   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
7620       << FixItHint::CreateInsertion(FirstOpen, "(")
7621       << FixItHint::CreateInsertion(FirstClose, ")");
7622 
7623   // Second note suggests (!x) < y
7624   SourceLocation SecondOpen = LHS.get()->getLocStart();
7625   SourceLocation SecondClose = LHS.get()->getLocEnd();
7626   SecondClose = S.getPreprocessor().getLocForEndOfToken(SecondClose);
7627   if (SecondClose.isInvalid())
7628     SecondOpen = SourceLocation();
7629   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
7630       << FixItHint::CreateInsertion(SecondOpen, "(")
7631       << FixItHint::CreateInsertion(SecondClose, ")");
7632 }
7633 
7634 // Get the decl for a simple expression: a reference to a variable,
7635 // an implicit C++ field reference, or an implicit ObjC ivar reference.
7636 static ValueDecl *getCompareDecl(Expr *E) {
7637   if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E))
7638     return DR->getDecl();
7639   if (ObjCIvarRefExpr* Ivar = dyn_cast<ObjCIvarRefExpr>(E)) {
7640     if (Ivar->isFreeIvar())
7641       return Ivar->getDecl();
7642   }
7643   if (MemberExpr* Mem = dyn_cast<MemberExpr>(E)) {
7644     if (Mem->isImplicitAccess())
7645       return Mem->getMemberDecl();
7646   }
7647   return 0;
7648 }
7649 
7650 // C99 6.5.8, C++ [expr.rel]
7651 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
7652                                     SourceLocation Loc, unsigned OpaqueOpc,
7653                                     bool IsRelational) {
7654   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
7655 
7656   BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
7657 
7658   // Handle vector comparisons separately.
7659   if (LHS.get()->getType()->isVectorType() ||
7660       RHS.get()->getType()->isVectorType())
7661     return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
7662 
7663   QualType LHSType = LHS.get()->getType();
7664   QualType RHSType = RHS.get()->getType();
7665 
7666   Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
7667   Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
7668 
7669   checkEnumComparison(*this, Loc, LHS.get(), RHS.get());
7670   diagnoseLogicalNotOnLHSofComparison(*this, LHS, RHS, Loc, OpaqueOpc);
7671 
7672   if (!LHSType->hasFloatingRepresentation() &&
7673       !(LHSType->isBlockPointerType() && IsRelational) &&
7674       !LHS.get()->getLocStart().isMacroID() &&
7675       !RHS.get()->getLocStart().isMacroID() &&
7676       ActiveTemplateInstantiations.empty()) {
7677     // For non-floating point types, check for self-comparisons of the form
7678     // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
7679     // often indicate logic errors in the program.
7680     //
7681     // NOTE: Don't warn about comparison expressions resulting from macro
7682     // expansion. Also don't warn about comparisons which are only self
7683     // comparisons within a template specialization. The warnings should catch
7684     // obvious cases in the definition of the template anyways. The idea is to
7685     // warn when the typed comparison operator will always evaluate to the same
7686     // result.
7687     ValueDecl *DL = getCompareDecl(LHSStripped);
7688     ValueDecl *DR = getCompareDecl(RHSStripped);
7689     if (DL && DR && DL == DR && !IsWithinTemplateSpecialization(DL)) {
7690       DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
7691                           << 0 // self-
7692                           << (Opc == BO_EQ
7693                               || Opc == BO_LE
7694                               || Opc == BO_GE));
7695     } else if (DL && DR && LHSType->isArrayType() && RHSType->isArrayType() &&
7696                !DL->getType()->isReferenceType() &&
7697                !DR->getType()->isReferenceType()) {
7698         // what is it always going to eval to?
7699         char always_evals_to;
7700         switch(Opc) {
7701         case BO_EQ: // e.g. array1 == array2
7702           always_evals_to = 0; // false
7703           break;
7704         case BO_NE: // e.g. array1 != array2
7705           always_evals_to = 1; // true
7706           break;
7707         default:
7708           // best we can say is 'a constant'
7709           always_evals_to = 2; // e.g. array1 <= array2
7710           break;
7711         }
7712         DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
7713                             << 1 // array
7714                             << always_evals_to);
7715     }
7716 
7717     if (isa<CastExpr>(LHSStripped))
7718       LHSStripped = LHSStripped->IgnoreParenCasts();
7719     if (isa<CastExpr>(RHSStripped))
7720       RHSStripped = RHSStripped->IgnoreParenCasts();
7721 
7722     // Warn about comparisons against a string constant (unless the other
7723     // operand is null), the user probably wants strcmp.
7724     Expr *literalString = 0;
7725     Expr *literalStringStripped = 0;
7726     if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
7727         !RHSStripped->isNullPointerConstant(Context,
7728                                             Expr::NPC_ValueDependentIsNull)) {
7729       literalString = LHS.get();
7730       literalStringStripped = LHSStripped;
7731     } else if ((isa<StringLiteral>(RHSStripped) ||
7732                 isa<ObjCEncodeExpr>(RHSStripped)) &&
7733                !LHSStripped->isNullPointerConstant(Context,
7734                                             Expr::NPC_ValueDependentIsNull)) {
7735       literalString = RHS.get();
7736       literalStringStripped = RHSStripped;
7737     }
7738 
7739     if (literalString) {
7740       DiagRuntimeBehavior(Loc, 0,
7741         PDiag(diag::warn_stringcompare)
7742           << isa<ObjCEncodeExpr>(literalStringStripped)
7743           << literalString->getSourceRange());
7744     }
7745   }
7746 
7747   // C99 6.5.8p3 / C99 6.5.9p4
7748   UsualArithmeticConversions(LHS, RHS);
7749   if (LHS.isInvalid() || RHS.isInvalid())
7750     return QualType();
7751 
7752   LHSType = LHS.get()->getType();
7753   RHSType = RHS.get()->getType();
7754 
7755   // The result of comparisons is 'bool' in C++, 'int' in C.
7756   QualType ResultTy = Context.getLogicalOperationType();
7757 
7758   if (IsRelational) {
7759     if (LHSType->isRealType() && RHSType->isRealType())
7760       return ResultTy;
7761   } else {
7762     // Check for comparisons of floating point operands using != and ==.
7763     if (LHSType->hasFloatingRepresentation())
7764       CheckFloatComparison(Loc, LHS.get(), RHS.get());
7765 
7766     if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
7767       return ResultTy;
7768   }
7769 
7770   bool LHSIsNull = LHS.get()->isNullPointerConstant(Context,
7771                                               Expr::NPC_ValueDependentIsNull);
7772   bool RHSIsNull = RHS.get()->isNullPointerConstant(Context,
7773                                               Expr::NPC_ValueDependentIsNull);
7774 
7775   // All of the following pointer-related warnings are GCC extensions, except
7776   // when handling null pointer constants.
7777   if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2
7778     QualType LCanPointeeTy =
7779       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
7780     QualType RCanPointeeTy =
7781       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
7782 
7783     if (getLangOpts().CPlusPlus) {
7784       if (LCanPointeeTy == RCanPointeeTy)
7785         return ResultTy;
7786       if (!IsRelational &&
7787           (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7788         // Valid unless comparison between non-null pointer and function pointer
7789         // This is a gcc extension compatibility comparison.
7790         // In a SFINAE context, we treat this as a hard error to maintain
7791         // conformance with the C++ standard.
7792         if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
7793             && !LHSIsNull && !RHSIsNull) {
7794           diagnoseFunctionPointerToVoidComparison(
7795               *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
7796 
7797           if (isSFINAEContext())
7798             return QualType();
7799 
7800           RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
7801           return ResultTy;
7802         }
7803       }
7804 
7805       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
7806         return QualType();
7807       else
7808         return ResultTy;
7809     }
7810     // C99 6.5.9p2 and C99 6.5.8p2
7811     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
7812                                    RCanPointeeTy.getUnqualifiedType())) {
7813       // Valid unless a relational comparison of function pointers
7814       if (IsRelational && LCanPointeeTy->isFunctionType()) {
7815         Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
7816           << LHSType << RHSType << LHS.get()->getSourceRange()
7817           << RHS.get()->getSourceRange();
7818       }
7819     } else if (!IsRelational &&
7820                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7821       // Valid unless comparison between non-null pointer and function pointer
7822       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
7823           && !LHSIsNull && !RHSIsNull)
7824         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
7825                                                 /*isError*/false);
7826     } else {
7827       // Invalid
7828       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
7829     }
7830     if (LCanPointeeTy != RCanPointeeTy) {
7831       if (LHSIsNull && !RHSIsNull)
7832         LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
7833       else
7834         RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
7835     }
7836     return ResultTy;
7837   }
7838 
7839   if (getLangOpts().CPlusPlus) {
7840     // Comparison of nullptr_t with itself.
7841     if (LHSType->isNullPtrType() && RHSType->isNullPtrType())
7842       return ResultTy;
7843 
7844     // Comparison of pointers with null pointer constants and equality
7845     // comparisons of member pointers to null pointer constants.
7846     if (RHSIsNull &&
7847         ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) ||
7848          (!IsRelational &&
7849           (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) {
7850       RHS = ImpCastExprToType(RHS.take(), LHSType,
7851                         LHSType->isMemberPointerType()
7852                           ? CK_NullToMemberPointer
7853                           : CK_NullToPointer);
7854       return ResultTy;
7855     }
7856     if (LHSIsNull &&
7857         ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) ||
7858          (!IsRelational &&
7859           (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) {
7860       LHS = ImpCastExprToType(LHS.take(), RHSType,
7861                         RHSType->isMemberPointerType()
7862                           ? CK_NullToMemberPointer
7863                           : CK_NullToPointer);
7864       return ResultTy;
7865     }
7866 
7867     // Comparison of member pointers.
7868     if (!IsRelational &&
7869         LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) {
7870       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
7871         return QualType();
7872       else
7873         return ResultTy;
7874     }
7875 
7876     // Handle scoped enumeration types specifically, since they don't promote
7877     // to integers.
7878     if (LHS.get()->getType()->isEnumeralType() &&
7879         Context.hasSameUnqualifiedType(LHS.get()->getType(),
7880                                        RHS.get()->getType()))
7881       return ResultTy;
7882   }
7883 
7884   // Handle block pointer types.
7885   if (!IsRelational && LHSType->isBlockPointerType() &&
7886       RHSType->isBlockPointerType()) {
7887     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
7888     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
7889 
7890     if (!LHSIsNull && !RHSIsNull &&
7891         !Context.typesAreCompatible(lpointee, rpointee)) {
7892       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
7893         << LHSType << RHSType << LHS.get()->getSourceRange()
7894         << RHS.get()->getSourceRange();
7895     }
7896     RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
7897     return ResultTy;
7898   }
7899 
7900   // Allow block pointers to be compared with null pointer constants.
7901   if (!IsRelational
7902       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
7903           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
7904     if (!LHSIsNull && !RHSIsNull) {
7905       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
7906              ->getPointeeType()->isVoidType())
7907             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
7908                 ->getPointeeType()->isVoidType())))
7909         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
7910           << LHSType << RHSType << LHS.get()->getSourceRange()
7911           << RHS.get()->getSourceRange();
7912     }
7913     if (LHSIsNull && !RHSIsNull)
7914       LHS = ImpCastExprToType(LHS.take(), RHSType,
7915                               RHSType->isPointerType() ? CK_BitCast
7916                                 : CK_AnyPointerToBlockPointerCast);
7917     else
7918       RHS = ImpCastExprToType(RHS.take(), LHSType,
7919                               LHSType->isPointerType() ? CK_BitCast
7920                                 : CK_AnyPointerToBlockPointerCast);
7921     return ResultTy;
7922   }
7923 
7924   if (LHSType->isObjCObjectPointerType() ||
7925       RHSType->isObjCObjectPointerType()) {
7926     const PointerType *LPT = LHSType->getAs<PointerType>();
7927     const PointerType *RPT = RHSType->getAs<PointerType>();
7928     if (LPT || RPT) {
7929       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
7930       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
7931 
7932       if (!LPtrToVoid && !RPtrToVoid &&
7933           !Context.typesAreCompatible(LHSType, RHSType)) {
7934         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
7935                                           /*isError*/false);
7936       }
7937       if (LHSIsNull && !RHSIsNull) {
7938         Expr *E = LHS.take();
7939         if (getLangOpts().ObjCAutoRefCount)
7940           CheckObjCARCConversion(SourceRange(), RHSType, E, CCK_ImplicitConversion);
7941         LHS = ImpCastExprToType(E, RHSType,
7942                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
7943       }
7944       else {
7945         Expr *E = RHS.take();
7946         if (getLangOpts().ObjCAutoRefCount)
7947           CheckObjCARCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion);
7948         RHS = ImpCastExprToType(E, LHSType,
7949                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
7950       }
7951       return ResultTy;
7952     }
7953     if (LHSType->isObjCObjectPointerType() &&
7954         RHSType->isObjCObjectPointerType()) {
7955       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
7956         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
7957                                           /*isError*/false);
7958       if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
7959         diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
7960 
7961       if (LHSIsNull && !RHSIsNull)
7962         LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
7963       else
7964         RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
7965       return ResultTy;
7966     }
7967   }
7968   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
7969       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
7970     unsigned DiagID = 0;
7971     bool isError = false;
7972     if (LangOpts.DebuggerSupport) {
7973       // Under a debugger, allow the comparison of pointers to integers,
7974       // since users tend to want to compare addresses.
7975     } else if ((LHSIsNull && LHSType->isIntegerType()) ||
7976         (RHSIsNull && RHSType->isIntegerType())) {
7977       if (IsRelational && !getLangOpts().CPlusPlus)
7978         DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
7979     } else if (IsRelational && !getLangOpts().CPlusPlus)
7980       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
7981     else if (getLangOpts().CPlusPlus) {
7982       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
7983       isError = true;
7984     } else
7985       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
7986 
7987     if (DiagID) {
7988       Diag(Loc, DiagID)
7989         << LHSType << RHSType << LHS.get()->getSourceRange()
7990         << RHS.get()->getSourceRange();
7991       if (isError)
7992         return QualType();
7993     }
7994 
7995     if (LHSType->isIntegerType())
7996       LHS = ImpCastExprToType(LHS.take(), RHSType,
7997                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
7998     else
7999       RHS = ImpCastExprToType(RHS.take(), LHSType,
8000                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
8001     return ResultTy;
8002   }
8003 
8004   // Handle block pointers.
8005   if (!IsRelational && RHSIsNull
8006       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
8007     RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
8008     return ResultTy;
8009   }
8010   if (!IsRelational && LHSIsNull
8011       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
8012     LHS = ImpCastExprToType(LHS.take(), RHSType, CK_NullToPointer);
8013     return ResultTy;
8014   }
8015 
8016   return InvalidOperands(Loc, LHS, RHS);
8017 }
8018 
8019 
8020 // Return a signed type that is of identical size and number of elements.
8021 // For floating point vectors, return an integer type of identical size
8022 // and number of elements.
8023 QualType Sema::GetSignedVectorType(QualType V) {
8024   const VectorType *VTy = V->getAs<VectorType>();
8025   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
8026   if (TypeSize == Context.getTypeSize(Context.CharTy))
8027     return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
8028   else if (TypeSize == Context.getTypeSize(Context.ShortTy))
8029     return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
8030   else if (TypeSize == Context.getTypeSize(Context.IntTy))
8031     return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
8032   else if (TypeSize == Context.getTypeSize(Context.LongTy))
8033     return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
8034   assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
8035          "Unhandled vector element size in vector compare");
8036   return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
8037 }
8038 
8039 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
8040 /// operates on extended vector types.  Instead of producing an IntTy result,
8041 /// like a scalar comparison, a vector comparison produces a vector of integer
8042 /// types.
8043 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
8044                                           SourceLocation Loc,
8045                                           bool IsRelational) {
8046   // Check to make sure we're operating on vectors of the same type and width,
8047   // Allowing one side to be a scalar of element type.
8048   QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false);
8049   if (vType.isNull())
8050     return vType;
8051 
8052   QualType LHSType = LHS.get()->getType();
8053 
8054   // If AltiVec, the comparison results in a numeric type, i.e.
8055   // bool for C++, int for C
8056   if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
8057     return Context.getLogicalOperationType();
8058 
8059   // For non-floating point types, check for self-comparisons of the form
8060   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
8061   // often indicate logic errors in the program.
8062   if (!LHSType->hasFloatingRepresentation() &&
8063       ActiveTemplateInstantiations.empty()) {
8064     if (DeclRefExpr* DRL
8065           = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
8066       if (DeclRefExpr* DRR
8067             = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
8068         if (DRL->getDecl() == DRR->getDecl())
8069           DiagRuntimeBehavior(Loc, 0,
8070                               PDiag(diag::warn_comparison_always)
8071                                 << 0 // self-
8072                                 << 2 // "a constant"
8073                               );
8074   }
8075 
8076   // Check for comparisons of floating point operands using != and ==.
8077   if (!IsRelational && LHSType->hasFloatingRepresentation()) {
8078     assert (RHS.get()->getType()->hasFloatingRepresentation());
8079     CheckFloatComparison(Loc, LHS.get(), RHS.get());
8080   }
8081 
8082   // Return a signed type for the vector.
8083   return GetSignedVectorType(LHSType);
8084 }
8085 
8086 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
8087                                           SourceLocation Loc) {
8088   // Ensure that either both operands are of the same vector type, or
8089   // one operand is of a vector type and the other is of its element type.
8090   QualType vType = CheckVectorOperands(LHS, RHS, Loc, false);
8091   if (vType.isNull())
8092     return InvalidOperands(Loc, LHS, RHS);
8093   if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
8094       vType->hasFloatingRepresentation())
8095     return InvalidOperands(Loc, LHS, RHS);
8096 
8097   return GetSignedVectorType(LHS.get()->getType());
8098 }
8099 
8100 inline QualType Sema::CheckBitwiseOperands(
8101   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
8102   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8103 
8104   if (LHS.get()->getType()->isVectorType() ||
8105       RHS.get()->getType()->isVectorType()) {
8106     if (LHS.get()->getType()->hasIntegerRepresentation() &&
8107         RHS.get()->getType()->hasIntegerRepresentation())
8108       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
8109 
8110     return InvalidOperands(Loc, LHS, RHS);
8111   }
8112 
8113   ExprResult LHSResult = Owned(LHS), RHSResult = Owned(RHS);
8114   QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
8115                                                  IsCompAssign);
8116   if (LHSResult.isInvalid() || RHSResult.isInvalid())
8117     return QualType();
8118   LHS = LHSResult.take();
8119   RHS = RHSResult.take();
8120 
8121   if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
8122     return compType;
8123   return InvalidOperands(Loc, LHS, RHS);
8124 }
8125 
8126 inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
8127   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) {
8128 
8129   // Check vector operands differently.
8130   if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
8131     return CheckVectorLogicalOperands(LHS, RHS, Loc);
8132 
8133   // Diagnose cases where the user write a logical and/or but probably meant a
8134   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
8135   // is a constant.
8136   if (LHS.get()->getType()->isIntegerType() &&
8137       !LHS.get()->getType()->isBooleanType() &&
8138       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
8139       // Don't warn in macros or template instantiations.
8140       !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
8141     // If the RHS can be constant folded, and if it constant folds to something
8142     // that isn't 0 or 1 (which indicate a potential logical operation that
8143     // happened to fold to true/false) then warn.
8144     // Parens on the RHS are ignored.
8145     llvm::APSInt Result;
8146     if (RHS.get()->EvaluateAsInt(Result, Context))
8147       if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType()) ||
8148           (Result != 0 && Result != 1)) {
8149         Diag(Loc, diag::warn_logical_instead_of_bitwise)
8150           << RHS.get()->getSourceRange()
8151           << (Opc == BO_LAnd ? "&&" : "||");
8152         // Suggest replacing the logical operator with the bitwise version
8153         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
8154             << (Opc == BO_LAnd ? "&" : "|")
8155             << FixItHint::CreateReplacement(SourceRange(
8156                 Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(),
8157                                                 getLangOpts())),
8158                                             Opc == BO_LAnd ? "&" : "|");
8159         if (Opc == BO_LAnd)
8160           // Suggest replacing "Foo() && kNonZero" with "Foo()"
8161           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
8162               << FixItHint::CreateRemoval(
8163                   SourceRange(
8164                       Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(),
8165                                                  0, getSourceManager(),
8166                                                  getLangOpts()),
8167                       RHS.get()->getLocEnd()));
8168       }
8169   }
8170 
8171   if (!Context.getLangOpts().CPlusPlus) {
8172     // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
8173     // not operate on the built-in scalar and vector float types.
8174     if (Context.getLangOpts().OpenCL &&
8175         Context.getLangOpts().OpenCLVersion < 120) {
8176       if (LHS.get()->getType()->isFloatingType() ||
8177           RHS.get()->getType()->isFloatingType())
8178         return InvalidOperands(Loc, LHS, RHS);
8179     }
8180 
8181     LHS = UsualUnaryConversions(LHS.take());
8182     if (LHS.isInvalid())
8183       return QualType();
8184 
8185     RHS = UsualUnaryConversions(RHS.take());
8186     if (RHS.isInvalid())
8187       return QualType();
8188 
8189     if (!LHS.get()->getType()->isScalarType() ||
8190         !RHS.get()->getType()->isScalarType())
8191       return InvalidOperands(Loc, LHS, RHS);
8192 
8193     return Context.IntTy;
8194   }
8195 
8196   // The following is safe because we only use this method for
8197   // non-overloadable operands.
8198 
8199   // C++ [expr.log.and]p1
8200   // C++ [expr.log.or]p1
8201   // The operands are both contextually converted to type bool.
8202   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
8203   if (LHSRes.isInvalid())
8204     return InvalidOperands(Loc, LHS, RHS);
8205   LHS = LHSRes;
8206 
8207   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
8208   if (RHSRes.isInvalid())
8209     return InvalidOperands(Loc, LHS, RHS);
8210   RHS = RHSRes;
8211 
8212   // C++ [expr.log.and]p2
8213   // C++ [expr.log.or]p2
8214   // The result is a bool.
8215   return Context.BoolTy;
8216 }
8217 
8218 static bool IsReadonlyMessage(Expr *E, Sema &S) {
8219   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
8220   if (!ME) return false;
8221   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
8222   ObjCMessageExpr *Base =
8223     dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts());
8224   if (!Base) return false;
8225   return Base->getMethodDecl() != 0;
8226 }
8227 
8228 /// Is the given expression (which must be 'const') a reference to a
8229 /// variable which was originally non-const, but which has become
8230 /// 'const' due to being captured within a block?
8231 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
8232 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
8233   assert(E->isLValue() && E->getType().isConstQualified());
8234   E = E->IgnoreParens();
8235 
8236   // Must be a reference to a declaration from an enclosing scope.
8237   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
8238   if (!DRE) return NCCK_None;
8239   if (!DRE->refersToEnclosingLocal()) return NCCK_None;
8240 
8241   // The declaration must be a variable which is not declared 'const'.
8242   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
8243   if (!var) return NCCK_None;
8244   if (var->getType().isConstQualified()) return NCCK_None;
8245   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
8246 
8247   // Decide whether the first capture was for a block or a lambda.
8248   DeclContext *DC = S.CurContext, *Prev = 0;
8249   while (DC != var->getDeclContext()) {
8250     Prev = DC;
8251     DC = DC->getParent();
8252   }
8253   // Unless we have an init-capture, we've gone one step too far.
8254   if (!var->isInitCapture())
8255     DC = Prev;
8256   return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
8257 }
8258 
8259 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
8260 /// emit an error and return true.  If so, return false.
8261 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
8262   assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
8263   SourceLocation OrigLoc = Loc;
8264   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
8265                                                               &Loc);
8266   if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
8267     IsLV = Expr::MLV_InvalidMessageExpression;
8268   if (IsLV == Expr::MLV_Valid)
8269     return false;
8270 
8271   unsigned Diag = 0;
8272   bool NeedType = false;
8273   switch (IsLV) { // C99 6.5.16p2
8274   case Expr::MLV_ConstQualified:
8275     Diag = diag::err_typecheck_assign_const;
8276 
8277     // Use a specialized diagnostic when we're assigning to an object
8278     // from an enclosing function or block.
8279     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
8280       if (NCCK == NCCK_Block)
8281         Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
8282       else
8283         Diag = diag::err_lambda_decl_ref_not_modifiable_lvalue;
8284       break;
8285     }
8286 
8287     // In ARC, use some specialized diagnostics for occasions where we
8288     // infer 'const'.  These are always pseudo-strong variables.
8289     if (S.getLangOpts().ObjCAutoRefCount) {
8290       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
8291       if (declRef && isa<VarDecl>(declRef->getDecl())) {
8292         VarDecl *var = cast<VarDecl>(declRef->getDecl());
8293 
8294         // Use the normal diagnostic if it's pseudo-__strong but the
8295         // user actually wrote 'const'.
8296         if (var->isARCPseudoStrong() &&
8297             (!var->getTypeSourceInfo() ||
8298              !var->getTypeSourceInfo()->getType().isConstQualified())) {
8299           // There are two pseudo-strong cases:
8300           //  - self
8301           ObjCMethodDecl *method = S.getCurMethodDecl();
8302           if (method && var == method->getSelfDecl())
8303             Diag = method->isClassMethod()
8304               ? diag::err_typecheck_arc_assign_self_class_method
8305               : diag::err_typecheck_arc_assign_self;
8306 
8307           //  - fast enumeration variables
8308           else
8309             Diag = diag::err_typecheck_arr_assign_enumeration;
8310 
8311           SourceRange Assign;
8312           if (Loc != OrigLoc)
8313             Assign = SourceRange(OrigLoc, OrigLoc);
8314           S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
8315           // We need to preserve the AST regardless, so migration tool
8316           // can do its job.
8317           return false;
8318         }
8319       }
8320     }
8321 
8322     break;
8323   case Expr::MLV_ArrayType:
8324   case Expr::MLV_ArrayTemporary:
8325     Diag = diag::err_typecheck_array_not_modifiable_lvalue;
8326     NeedType = true;
8327     break;
8328   case Expr::MLV_NotObjectType:
8329     Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
8330     NeedType = true;
8331     break;
8332   case Expr::MLV_LValueCast:
8333     Diag = diag::err_typecheck_lvalue_casts_not_supported;
8334     break;
8335   case Expr::MLV_Valid:
8336     llvm_unreachable("did not take early return for MLV_Valid");
8337   case Expr::MLV_InvalidExpression:
8338   case Expr::MLV_MemberFunction:
8339   case Expr::MLV_ClassTemporary:
8340     Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
8341     break;
8342   case Expr::MLV_IncompleteType:
8343   case Expr::MLV_IncompleteVoidType:
8344     return S.RequireCompleteType(Loc, E->getType(),
8345              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
8346   case Expr::MLV_DuplicateVectorComponents:
8347     Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
8348     break;
8349   case Expr::MLV_NoSetterProperty:
8350     llvm_unreachable("readonly properties should be processed differently");
8351   case Expr::MLV_InvalidMessageExpression:
8352     Diag = diag::error_readonly_message_assignment;
8353     break;
8354   case Expr::MLV_SubObjCPropertySetting:
8355     Diag = diag::error_no_subobject_property_setting;
8356     break;
8357   }
8358 
8359   SourceRange Assign;
8360   if (Loc != OrigLoc)
8361     Assign = SourceRange(OrigLoc, OrigLoc);
8362   if (NeedType)
8363     S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
8364   else
8365     S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
8366   return true;
8367 }
8368 
8369 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
8370                                          SourceLocation Loc,
8371                                          Sema &Sema) {
8372   // C / C++ fields
8373   MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
8374   MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
8375   if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) {
8376     if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))
8377       Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
8378   }
8379 
8380   // Objective-C instance variables
8381   ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
8382   ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
8383   if (OL && OR && OL->getDecl() == OR->getDecl()) {
8384     DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
8385     DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
8386     if (RL && RR && RL->getDecl() == RR->getDecl())
8387       Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
8388   }
8389 }
8390 
8391 // C99 6.5.16.1
8392 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
8393                                        SourceLocation Loc,
8394                                        QualType CompoundType) {
8395   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
8396 
8397   // Verify that LHS is a modifiable lvalue, and emit error if not.
8398   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
8399     return QualType();
8400 
8401   QualType LHSType = LHSExpr->getType();
8402   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
8403                                              CompoundType;
8404   AssignConvertType ConvTy;
8405   if (CompoundType.isNull()) {
8406     Expr *RHSCheck = RHS.get();
8407 
8408     CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
8409 
8410     QualType LHSTy(LHSType);
8411     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
8412     if (RHS.isInvalid())
8413       return QualType();
8414     // Special case of NSObject attributes on c-style pointer types.
8415     if (ConvTy == IncompatiblePointer &&
8416         ((Context.isObjCNSObjectType(LHSType) &&
8417           RHSType->isObjCObjectPointerType()) ||
8418          (Context.isObjCNSObjectType(RHSType) &&
8419           LHSType->isObjCObjectPointerType())))
8420       ConvTy = Compatible;
8421 
8422     if (ConvTy == Compatible &&
8423         LHSType->isObjCObjectType())
8424         Diag(Loc, diag::err_objc_object_assignment)
8425           << LHSType;
8426 
8427     // If the RHS is a unary plus or minus, check to see if they = and + are
8428     // right next to each other.  If so, the user may have typo'd "x =+ 4"
8429     // instead of "x += 4".
8430     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
8431       RHSCheck = ICE->getSubExpr();
8432     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
8433       if ((UO->getOpcode() == UO_Plus ||
8434            UO->getOpcode() == UO_Minus) &&
8435           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
8436           // Only if the two operators are exactly adjacent.
8437           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
8438           // And there is a space or other character before the subexpr of the
8439           // unary +/-.  We don't want to warn on "x=-1".
8440           Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
8441           UO->getSubExpr()->getLocStart().isFileID()) {
8442         Diag(Loc, diag::warn_not_compound_assign)
8443           << (UO->getOpcode() == UO_Plus ? "+" : "-")
8444           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
8445       }
8446     }
8447 
8448     if (ConvTy == Compatible) {
8449       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
8450         // Warn about retain cycles where a block captures the LHS, but
8451         // not if the LHS is a simple variable into which the block is
8452         // being stored...unless that variable can be captured by reference!
8453         const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
8454         const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
8455         if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
8456           checkRetainCycles(LHSExpr, RHS.get());
8457 
8458         // It is safe to assign a weak reference into a strong variable.
8459         // Although this code can still have problems:
8460         //   id x = self.weakProp;
8461         //   id y = self.weakProp;
8462         // we do not warn to warn spuriously when 'x' and 'y' are on separate
8463         // paths through the function. This should be revisited if
8464         // -Wrepeated-use-of-weak is made flow-sensitive.
8465         DiagnosticsEngine::Level Level =
8466           Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
8467                                    RHS.get()->getLocStart());
8468         if (Level != DiagnosticsEngine::Ignored)
8469           getCurFunction()->markSafeWeakUse(RHS.get());
8470 
8471       } else if (getLangOpts().ObjCAutoRefCount) {
8472         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
8473       }
8474     }
8475   } else {
8476     // Compound assignment "x += y"
8477     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
8478   }
8479 
8480   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
8481                                RHS.get(), AA_Assigning))
8482     return QualType();
8483 
8484   CheckForNullPointerDereference(*this, LHSExpr);
8485 
8486   // C99 6.5.16p3: The type of an assignment expression is the type of the
8487   // left operand unless the left operand has qualified type, in which case
8488   // it is the unqualified version of the type of the left operand.
8489   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
8490   // is converted to the type of the assignment expression (above).
8491   // C++ 5.17p1: the type of the assignment expression is that of its left
8492   // operand.
8493   return (getLangOpts().CPlusPlus
8494           ? LHSType : LHSType.getUnqualifiedType());
8495 }
8496 
8497 // C99 6.5.17
8498 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
8499                                    SourceLocation Loc) {
8500   LHS = S.CheckPlaceholderExpr(LHS.take());
8501   RHS = S.CheckPlaceholderExpr(RHS.take());
8502   if (LHS.isInvalid() || RHS.isInvalid())
8503     return QualType();
8504 
8505   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
8506   // operands, but not unary promotions.
8507   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
8508 
8509   // So we treat the LHS as a ignored value, and in C++ we allow the
8510   // containing site to determine what should be done with the RHS.
8511   LHS = S.IgnoredValueConversions(LHS.take());
8512   if (LHS.isInvalid())
8513     return QualType();
8514 
8515   S.DiagnoseUnusedExprResult(LHS.get());
8516 
8517   if (!S.getLangOpts().CPlusPlus) {
8518     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take());
8519     if (RHS.isInvalid())
8520       return QualType();
8521     if (!RHS.get()->getType()->isVoidType())
8522       S.RequireCompleteType(Loc, RHS.get()->getType(),
8523                             diag::err_incomplete_type);
8524   }
8525 
8526   return RHS.get()->getType();
8527 }
8528 
8529 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
8530 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
8531 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
8532                                                ExprValueKind &VK,
8533                                                SourceLocation OpLoc,
8534                                                bool IsInc, bool IsPrefix) {
8535   if (Op->isTypeDependent())
8536     return S.Context.DependentTy;
8537 
8538   QualType ResType = Op->getType();
8539   // Atomic types can be used for increment / decrement where the non-atomic
8540   // versions can, so ignore the _Atomic() specifier for the purpose of
8541   // checking.
8542   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
8543     ResType = ResAtomicType->getValueType();
8544 
8545   assert(!ResType.isNull() && "no type for increment/decrement expression");
8546 
8547   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
8548     // Decrement of bool is not allowed.
8549     if (!IsInc) {
8550       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
8551       return QualType();
8552     }
8553     // Increment of bool sets it to true, but is deprecated.
8554     S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
8555   } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
8556     // Error on enum increments and decrements in C++ mode
8557     S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
8558     return QualType();
8559   } else if (ResType->isRealType()) {
8560     // OK!
8561   } else if (ResType->isPointerType()) {
8562     // C99 6.5.2.4p2, 6.5.6p2
8563     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
8564       return QualType();
8565   } else if (ResType->isObjCObjectPointerType()) {
8566     // On modern runtimes, ObjC pointer arithmetic is forbidden.
8567     // Otherwise, we just need a complete type.
8568     if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
8569         checkArithmeticOnObjCPointer(S, OpLoc, Op))
8570       return QualType();
8571   } else if (ResType->isAnyComplexType()) {
8572     // C99 does not support ++/-- on complex types, we allow as an extension.
8573     S.Diag(OpLoc, diag::ext_integer_increment_complex)
8574       << ResType << Op->getSourceRange();
8575   } else if (ResType->isPlaceholderType()) {
8576     ExprResult PR = S.CheckPlaceholderExpr(Op);
8577     if (PR.isInvalid()) return QualType();
8578     return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
8579                                           IsInc, IsPrefix);
8580   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
8581     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
8582   } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
8583             ResType->getAs<VectorType>()->getElementType()->isIntegerType()) {
8584     // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
8585   } else {
8586     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
8587       << ResType << int(IsInc) << Op->getSourceRange();
8588     return QualType();
8589   }
8590   // At this point, we know we have a real, complex or pointer type.
8591   // Now make sure the operand is a modifiable lvalue.
8592   if (CheckForModifiableLvalue(Op, OpLoc, S))
8593     return QualType();
8594   // In C++, a prefix increment is the same type as the operand. Otherwise
8595   // (in C or with postfix), the increment is the unqualified type of the
8596   // operand.
8597   if (IsPrefix && S.getLangOpts().CPlusPlus) {
8598     VK = VK_LValue;
8599     return ResType;
8600   } else {
8601     VK = VK_RValue;
8602     return ResType.getUnqualifiedType();
8603   }
8604 }
8605 
8606 
8607 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
8608 /// This routine allows us to typecheck complex/recursive expressions
8609 /// where the declaration is needed for type checking. We only need to
8610 /// handle cases when the expression references a function designator
8611 /// or is an lvalue. Here are some examples:
8612 ///  - &(x) => x
8613 ///  - &*****f => f for f a function designator.
8614 ///  - &s.xx => s
8615 ///  - &s.zz[1].yy -> s, if zz is an array
8616 ///  - *(x + 1) -> x, if x is an array
8617 ///  - &"123"[2] -> 0
8618 ///  - & __real__ x -> x
8619 static ValueDecl *getPrimaryDecl(Expr *E) {
8620   switch (E->getStmtClass()) {
8621   case Stmt::DeclRefExprClass:
8622     return cast<DeclRefExpr>(E)->getDecl();
8623   case Stmt::MemberExprClass:
8624     // If this is an arrow operator, the address is an offset from
8625     // the base's value, so the object the base refers to is
8626     // irrelevant.
8627     if (cast<MemberExpr>(E)->isArrow())
8628       return 0;
8629     // Otherwise, the expression refers to a part of the base
8630     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
8631   case Stmt::ArraySubscriptExprClass: {
8632     // FIXME: This code shouldn't be necessary!  We should catch the implicit
8633     // promotion of register arrays earlier.
8634     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
8635     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
8636       if (ICE->getSubExpr()->getType()->isArrayType())
8637         return getPrimaryDecl(ICE->getSubExpr());
8638     }
8639     return 0;
8640   }
8641   case Stmt::UnaryOperatorClass: {
8642     UnaryOperator *UO = cast<UnaryOperator>(E);
8643 
8644     switch(UO->getOpcode()) {
8645     case UO_Real:
8646     case UO_Imag:
8647     case UO_Extension:
8648       return getPrimaryDecl(UO->getSubExpr());
8649     default:
8650       return 0;
8651     }
8652   }
8653   case Stmt::ParenExprClass:
8654     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
8655   case Stmt::ImplicitCastExprClass:
8656     // If the result of an implicit cast is an l-value, we care about
8657     // the sub-expression; otherwise, the result here doesn't matter.
8658     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
8659   default:
8660     return 0;
8661   }
8662 }
8663 
8664 namespace {
8665   enum {
8666     AO_Bit_Field = 0,
8667     AO_Vector_Element = 1,
8668     AO_Property_Expansion = 2,
8669     AO_Register_Variable = 3,
8670     AO_No_Error = 4
8671   };
8672 }
8673 /// \brief Diagnose invalid operand for address of operations.
8674 ///
8675 /// \param Type The type of operand which cannot have its address taken.
8676 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
8677                                          Expr *E, unsigned Type) {
8678   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
8679 }
8680 
8681 /// CheckAddressOfOperand - The operand of & must be either a function
8682 /// designator or an lvalue designating an object. If it is an lvalue, the
8683 /// object cannot be declared with storage class register or be a bit field.
8684 /// Note: The usual conversions are *not* applied to the operand of the &
8685 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
8686 /// In C++, the operand might be an overloaded function name, in which case
8687 /// we allow the '&' but retain the overloaded-function type.
8688 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
8689   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
8690     if (PTy->getKind() == BuiltinType::Overload) {
8691       Expr *E = OrigOp.get()->IgnoreParens();
8692       if (!isa<OverloadExpr>(E)) {
8693         assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
8694         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
8695           << OrigOp.get()->getSourceRange();
8696         return QualType();
8697       }
8698 
8699       OverloadExpr *Ovl = cast<OverloadExpr>(E);
8700       if (isa<UnresolvedMemberExpr>(Ovl))
8701         if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
8702           Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
8703             << OrigOp.get()->getSourceRange();
8704           return QualType();
8705         }
8706 
8707       return Context.OverloadTy;
8708     }
8709 
8710     if (PTy->getKind() == BuiltinType::UnknownAny)
8711       return Context.UnknownAnyTy;
8712 
8713     if (PTy->getKind() == BuiltinType::BoundMember) {
8714       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
8715         << OrigOp.get()->getSourceRange();
8716       return QualType();
8717     }
8718 
8719     OrigOp = CheckPlaceholderExpr(OrigOp.take());
8720     if (OrigOp.isInvalid()) return QualType();
8721   }
8722 
8723   if (OrigOp.get()->isTypeDependent())
8724     return Context.DependentTy;
8725 
8726   assert(!OrigOp.get()->getType()->isPlaceholderType());
8727 
8728   // Make sure to ignore parentheses in subsequent checks
8729   Expr *op = OrigOp.get()->IgnoreParens();
8730 
8731   if (getLangOpts().C99) {
8732     // Implement C99-only parts of addressof rules.
8733     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
8734       if (uOp->getOpcode() == UO_Deref)
8735         // Per C99 6.5.3.2, the address of a deref always returns a valid result
8736         // (assuming the deref expression is valid).
8737         return uOp->getSubExpr()->getType();
8738     }
8739     // Technically, there should be a check for array subscript
8740     // expressions here, but the result of one is always an lvalue anyway.
8741   }
8742   ValueDecl *dcl = getPrimaryDecl(op);
8743   Expr::LValueClassification lval = op->ClassifyLValue(Context);
8744   unsigned AddressOfError = AO_No_Error;
8745 
8746   if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
8747     bool sfinae = (bool)isSFINAEContext();
8748     Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
8749                                   : diag::ext_typecheck_addrof_temporary)
8750       << op->getType() << op->getSourceRange();
8751     if (sfinae)
8752       return QualType();
8753     // Materialize the temporary as an lvalue so that we can take its address.
8754     OrigOp = op = new (Context)
8755         MaterializeTemporaryExpr(op->getType(), OrigOp.take(), true, 0);
8756   } else if (isa<ObjCSelectorExpr>(op)) {
8757     return Context.getPointerType(op->getType());
8758   } else if (lval == Expr::LV_MemberFunction) {
8759     // If it's an instance method, make a member pointer.
8760     // The expression must have exactly the form &A::foo.
8761 
8762     // If the underlying expression isn't a decl ref, give up.
8763     if (!isa<DeclRefExpr>(op)) {
8764       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
8765         << OrigOp.get()->getSourceRange();
8766       return QualType();
8767     }
8768     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
8769     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
8770 
8771     // The id-expression was parenthesized.
8772     if (OrigOp.get() != DRE) {
8773       Diag(OpLoc, diag::err_parens_pointer_member_function)
8774         << OrigOp.get()->getSourceRange();
8775 
8776     // The method was named without a qualifier.
8777     } else if (!DRE->getQualifier()) {
8778       if (MD->getParent()->getName().empty())
8779         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
8780           << op->getSourceRange();
8781       else {
8782         SmallString<32> Str;
8783         StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
8784         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
8785           << op->getSourceRange()
8786           << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
8787       }
8788     }
8789 
8790     // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
8791     if (isa<CXXDestructorDecl>(MD))
8792       Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
8793 
8794     return Context.getMemberPointerType(op->getType(),
8795               Context.getTypeDeclType(MD->getParent()).getTypePtr());
8796   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
8797     // C99 6.5.3.2p1
8798     // The operand must be either an l-value or a function designator
8799     if (!op->getType()->isFunctionType()) {
8800       // Use a special diagnostic for loads from property references.
8801       if (isa<PseudoObjectExpr>(op)) {
8802         AddressOfError = AO_Property_Expansion;
8803       } else {
8804         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
8805           << op->getType() << op->getSourceRange();
8806         return QualType();
8807       }
8808     }
8809   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
8810     // The operand cannot be a bit-field
8811     AddressOfError = AO_Bit_Field;
8812   } else if (op->getObjectKind() == OK_VectorComponent) {
8813     // The operand cannot be an element of a vector
8814     AddressOfError = AO_Vector_Element;
8815   } else if (dcl) { // C99 6.5.3.2p1
8816     // We have an lvalue with a decl. Make sure the decl is not declared
8817     // with the register storage-class specifier.
8818     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
8819       // in C++ it is not error to take address of a register
8820       // variable (c++03 7.1.1P3)
8821       if (vd->getStorageClass() == SC_Register &&
8822           !getLangOpts().CPlusPlus) {
8823         AddressOfError = AO_Register_Variable;
8824       }
8825     } else if (isa<FunctionTemplateDecl>(dcl)) {
8826       return Context.OverloadTy;
8827     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
8828       // Okay: we can take the address of a field.
8829       // Could be a pointer to member, though, if there is an explicit
8830       // scope qualifier for the class.
8831       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
8832         DeclContext *Ctx = dcl->getDeclContext();
8833         if (Ctx && Ctx->isRecord()) {
8834           if (dcl->getType()->isReferenceType()) {
8835             Diag(OpLoc,
8836                  diag::err_cannot_form_pointer_to_member_of_reference_type)
8837               << dcl->getDeclName() << dcl->getType();
8838             return QualType();
8839           }
8840 
8841           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
8842             Ctx = Ctx->getParent();
8843           return Context.getMemberPointerType(op->getType(),
8844                 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
8845         }
8846       }
8847     } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl))
8848       llvm_unreachable("Unknown/unexpected decl type");
8849   }
8850 
8851   if (AddressOfError != AO_No_Error) {
8852     diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
8853     return QualType();
8854   }
8855 
8856   if (lval == Expr::LV_IncompleteVoidType) {
8857     // Taking the address of a void variable is technically illegal, but we
8858     // allow it in cases which are otherwise valid.
8859     // Example: "extern void x; void* y = &x;".
8860     Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
8861   }
8862 
8863   // If the operand has type "type", the result has type "pointer to type".
8864   if (op->getType()->isObjCObjectType())
8865     return Context.getObjCObjectPointerType(op->getType());
8866   return Context.getPointerType(op->getType());
8867 }
8868 
8869 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
8870 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
8871                                         SourceLocation OpLoc) {
8872   if (Op->isTypeDependent())
8873     return S.Context.DependentTy;
8874 
8875   ExprResult ConvResult = S.UsualUnaryConversions(Op);
8876   if (ConvResult.isInvalid())
8877     return QualType();
8878   Op = ConvResult.take();
8879   QualType OpTy = Op->getType();
8880   QualType Result;
8881 
8882   if (isa<CXXReinterpretCastExpr>(Op)) {
8883     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
8884     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
8885                                      Op->getSourceRange());
8886   }
8887 
8888   // Note that per both C89 and C99, indirection is always legal, even if OpTy
8889   // is an incomplete type or void.  It would be possible to warn about
8890   // dereferencing a void pointer, but it's completely well-defined, and such a
8891   // warning is unlikely to catch any mistakes.
8892   if (const PointerType *PT = OpTy->getAs<PointerType>())
8893     Result = PT->getPointeeType();
8894   else if (const ObjCObjectPointerType *OPT =
8895              OpTy->getAs<ObjCObjectPointerType>())
8896     Result = OPT->getPointeeType();
8897   else {
8898     ExprResult PR = S.CheckPlaceholderExpr(Op);
8899     if (PR.isInvalid()) return QualType();
8900     if (PR.take() != Op)
8901       return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
8902   }
8903 
8904   if (Result.isNull()) {
8905     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
8906       << OpTy << Op->getSourceRange();
8907     return QualType();
8908   }
8909 
8910   // Dereferences are usually l-values...
8911   VK = VK_LValue;
8912 
8913   // ...except that certain expressions are never l-values in C.
8914   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
8915     VK = VK_RValue;
8916 
8917   return Result;
8918 }
8919 
8920 static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
8921   tok::TokenKind Kind) {
8922   BinaryOperatorKind Opc;
8923   switch (Kind) {
8924   default: llvm_unreachable("Unknown binop!");
8925   case tok::periodstar:           Opc = BO_PtrMemD; break;
8926   case tok::arrowstar:            Opc = BO_PtrMemI; break;
8927   case tok::star:                 Opc = BO_Mul; break;
8928   case tok::slash:                Opc = BO_Div; break;
8929   case tok::percent:              Opc = BO_Rem; break;
8930   case tok::plus:                 Opc = BO_Add; break;
8931   case tok::minus:                Opc = BO_Sub; break;
8932   case tok::lessless:             Opc = BO_Shl; break;
8933   case tok::greatergreater:       Opc = BO_Shr; break;
8934   case tok::lessequal:            Opc = BO_LE; break;
8935   case tok::less:                 Opc = BO_LT; break;
8936   case tok::greaterequal:         Opc = BO_GE; break;
8937   case tok::greater:              Opc = BO_GT; break;
8938   case tok::exclaimequal:         Opc = BO_NE; break;
8939   case tok::equalequal:           Opc = BO_EQ; break;
8940   case tok::amp:                  Opc = BO_And; break;
8941   case tok::caret:                Opc = BO_Xor; break;
8942   case tok::pipe:                 Opc = BO_Or; break;
8943   case tok::ampamp:               Opc = BO_LAnd; break;
8944   case tok::pipepipe:             Opc = BO_LOr; break;
8945   case tok::equal:                Opc = BO_Assign; break;
8946   case tok::starequal:            Opc = BO_MulAssign; break;
8947   case tok::slashequal:           Opc = BO_DivAssign; break;
8948   case tok::percentequal:         Opc = BO_RemAssign; break;
8949   case tok::plusequal:            Opc = BO_AddAssign; break;
8950   case tok::minusequal:           Opc = BO_SubAssign; break;
8951   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
8952   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
8953   case tok::ampequal:             Opc = BO_AndAssign; break;
8954   case tok::caretequal:           Opc = BO_XorAssign; break;
8955   case tok::pipeequal:            Opc = BO_OrAssign; break;
8956   case tok::comma:                Opc = BO_Comma; break;
8957   }
8958   return Opc;
8959 }
8960 
8961 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
8962   tok::TokenKind Kind) {
8963   UnaryOperatorKind Opc;
8964   switch (Kind) {
8965   default: llvm_unreachable("Unknown unary op!");
8966   case tok::plusplus:     Opc = UO_PreInc; break;
8967   case tok::minusminus:   Opc = UO_PreDec; break;
8968   case tok::amp:          Opc = UO_AddrOf; break;
8969   case tok::star:         Opc = UO_Deref; break;
8970   case tok::plus:         Opc = UO_Plus; break;
8971   case tok::minus:        Opc = UO_Minus; break;
8972   case tok::tilde:        Opc = UO_Not; break;
8973   case tok::exclaim:      Opc = UO_LNot; break;
8974   case tok::kw___real:    Opc = UO_Real; break;
8975   case tok::kw___imag:    Opc = UO_Imag; break;
8976   case tok::kw___extension__: Opc = UO_Extension; break;
8977   }
8978   return Opc;
8979 }
8980 
8981 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
8982 /// This warning is only emitted for builtin assignment operations. It is also
8983 /// suppressed in the event of macro expansions.
8984 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
8985                                    SourceLocation OpLoc) {
8986   if (!S.ActiveTemplateInstantiations.empty())
8987     return;
8988   if (OpLoc.isInvalid() || OpLoc.isMacroID())
8989     return;
8990   LHSExpr = LHSExpr->IgnoreParenImpCasts();
8991   RHSExpr = RHSExpr->IgnoreParenImpCasts();
8992   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
8993   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
8994   if (!LHSDeclRef || !RHSDeclRef ||
8995       LHSDeclRef->getLocation().isMacroID() ||
8996       RHSDeclRef->getLocation().isMacroID())
8997     return;
8998   const ValueDecl *LHSDecl =
8999     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
9000   const ValueDecl *RHSDecl =
9001     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
9002   if (LHSDecl != RHSDecl)
9003     return;
9004   if (LHSDecl->getType().isVolatileQualified())
9005     return;
9006   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
9007     if (RefTy->getPointeeType().isVolatileQualified())
9008       return;
9009 
9010   S.Diag(OpLoc, diag::warn_self_assignment)
9011       << LHSDeclRef->getType()
9012       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
9013 }
9014 
9015 /// Check if a bitwise-& is performed on an Objective-C pointer.  This
9016 /// is usually indicative of introspection within the Objective-C pointer.
9017 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
9018                                           SourceLocation OpLoc) {
9019   if (!S.getLangOpts().ObjC1)
9020     return;
9021 
9022   const Expr *ObjCPointerExpr = 0, *OtherExpr = 0;
9023   const Expr *LHS = L.get();
9024   const Expr *RHS = R.get();
9025 
9026   if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
9027     ObjCPointerExpr = LHS;
9028     OtherExpr = RHS;
9029   }
9030   else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
9031     ObjCPointerExpr = RHS;
9032     OtherExpr = LHS;
9033   }
9034 
9035   // This warning is deliberately made very specific to reduce false
9036   // positives with logic that uses '&' for hashing.  This logic mainly
9037   // looks for code trying to introspect into tagged pointers, which
9038   // code should generally never do.
9039   if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
9040     unsigned Diag = diag::warn_objc_pointer_masking;
9041     // Determine if we are introspecting the result of performSelectorXXX.
9042     const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
9043     // Special case messages to -performSelector and friends, which
9044     // can return non-pointer values boxed in a pointer value.
9045     // Some clients may wish to silence warnings in this subcase.
9046     if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
9047       Selector S = ME->getSelector();
9048       StringRef SelArg0 = S.getNameForSlot(0);
9049       if (SelArg0.startswith("performSelector"))
9050         Diag = diag::warn_objc_pointer_masking_performSelector;
9051     }
9052 
9053     S.Diag(OpLoc, Diag)
9054       << ObjCPointerExpr->getSourceRange();
9055   }
9056 }
9057 
9058 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
9059 /// operator @p Opc at location @c TokLoc. This routine only supports
9060 /// built-in operations; ActOnBinOp handles overloaded operators.
9061 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
9062                                     BinaryOperatorKind Opc,
9063                                     Expr *LHSExpr, Expr *RHSExpr) {
9064   if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
9065     // The syntax only allows initializer lists on the RHS of assignment,
9066     // so we don't need to worry about accepting invalid code for
9067     // non-assignment operators.
9068     // C++11 5.17p9:
9069     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
9070     //   of x = {} is x = T().
9071     InitializationKind Kind =
9072         InitializationKind::CreateDirectList(RHSExpr->getLocStart());
9073     InitializedEntity Entity =
9074         InitializedEntity::InitializeTemporary(LHSExpr->getType());
9075     InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
9076     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
9077     if (Init.isInvalid())
9078       return Init;
9079     RHSExpr = Init.take();
9080   }
9081 
9082   ExprResult LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
9083   QualType ResultTy;     // Result type of the binary operator.
9084   // The following two variables are used for compound assignment operators
9085   QualType CompLHSTy;    // Type of LHS after promotions for computation
9086   QualType CompResultTy; // Type of computation result
9087   ExprValueKind VK = VK_RValue;
9088   ExprObjectKind OK = OK_Ordinary;
9089 
9090   switch (Opc) {
9091   case BO_Assign:
9092     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
9093     if (getLangOpts().CPlusPlus &&
9094         LHS.get()->getObjectKind() != OK_ObjCProperty) {
9095       VK = LHS.get()->getValueKind();
9096       OK = LHS.get()->getObjectKind();
9097     }
9098     if (!ResultTy.isNull())
9099       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
9100     break;
9101   case BO_PtrMemD:
9102   case BO_PtrMemI:
9103     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
9104                                             Opc == BO_PtrMemI);
9105     break;
9106   case BO_Mul:
9107   case BO_Div:
9108     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
9109                                            Opc == BO_Div);
9110     break;
9111   case BO_Rem:
9112     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
9113     break;
9114   case BO_Add:
9115     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
9116     break;
9117   case BO_Sub:
9118     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
9119     break;
9120   case BO_Shl:
9121   case BO_Shr:
9122     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
9123     break;
9124   case BO_LE:
9125   case BO_LT:
9126   case BO_GE:
9127   case BO_GT:
9128     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
9129     break;
9130   case BO_EQ:
9131   case BO_NE:
9132     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
9133     break;
9134   case BO_And:
9135     checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
9136   case BO_Xor:
9137   case BO_Or:
9138     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc);
9139     break;
9140   case BO_LAnd:
9141   case BO_LOr:
9142     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
9143     break;
9144   case BO_MulAssign:
9145   case BO_DivAssign:
9146     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
9147                                                Opc == BO_DivAssign);
9148     CompLHSTy = CompResultTy;
9149     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
9150       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
9151     break;
9152   case BO_RemAssign:
9153     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
9154     CompLHSTy = CompResultTy;
9155     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
9156       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
9157     break;
9158   case BO_AddAssign:
9159     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
9160     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
9161       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
9162     break;
9163   case BO_SubAssign:
9164     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
9165     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
9166       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
9167     break;
9168   case BO_ShlAssign:
9169   case BO_ShrAssign:
9170     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
9171     CompLHSTy = CompResultTy;
9172     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
9173       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
9174     break;
9175   case BO_AndAssign:
9176   case BO_XorAssign:
9177   case BO_OrAssign:
9178     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true);
9179     CompLHSTy = CompResultTy;
9180     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
9181       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
9182     break;
9183   case BO_Comma:
9184     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
9185     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
9186       VK = RHS.get()->getValueKind();
9187       OK = RHS.get()->getObjectKind();
9188     }
9189     break;
9190   }
9191   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
9192     return ExprError();
9193 
9194   // Check for array bounds violations for both sides of the BinaryOperator
9195   CheckArrayAccess(LHS.get());
9196   CheckArrayAccess(RHS.get());
9197 
9198   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
9199     NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
9200                                                  &Context.Idents.get("object_setClass"),
9201                                                  SourceLocation(), LookupOrdinaryName);
9202     if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
9203       SourceLocation RHSLocEnd = PP.getLocForEndOfToken(RHS.get()->getLocEnd());
9204       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) <<
9205       FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") <<
9206       FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") <<
9207       FixItHint::CreateInsertion(RHSLocEnd, ")");
9208     }
9209     else
9210       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
9211   }
9212   else if (const ObjCIvarRefExpr *OIRE =
9213            dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
9214     DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
9215 
9216   if (CompResultTy.isNull())
9217     return Owned(new (Context) BinaryOperator(LHS.take(), RHS.take(), Opc,
9218                                               ResultTy, VK, OK, OpLoc,
9219                                               FPFeatures.fp_contract));
9220   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
9221       OK_ObjCProperty) {
9222     VK = VK_LValue;
9223     OK = LHS.get()->getObjectKind();
9224   }
9225   return Owned(new (Context) CompoundAssignOperator(LHS.take(), RHS.take(), Opc,
9226                                                     ResultTy, VK, OK, CompLHSTy,
9227                                                     CompResultTy, OpLoc,
9228                                                     FPFeatures.fp_contract));
9229 }
9230 
9231 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
9232 /// operators are mixed in a way that suggests that the programmer forgot that
9233 /// comparison operators have higher precedence. The most typical example of
9234 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
9235 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
9236                                       SourceLocation OpLoc, Expr *LHSExpr,
9237                                       Expr *RHSExpr) {
9238   BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
9239   BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
9240 
9241   // Check that one of the sides is a comparison operator.
9242   bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
9243   bool isRightComp = RHSBO && RHSBO->isComparisonOp();
9244   if (!isLeftComp && !isRightComp)
9245     return;
9246 
9247   // Bitwise operations are sometimes used as eager logical ops.
9248   // Don't diagnose this.
9249   bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
9250   bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
9251   if ((isLeftComp || isLeftBitwise) && (isRightComp || isRightBitwise))
9252     return;
9253 
9254   SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
9255                                                    OpLoc)
9256                                      : SourceRange(OpLoc, RHSExpr->getLocEnd());
9257   StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
9258   SourceRange ParensRange = isLeftComp ?
9259       SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd())
9260     : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocStart());
9261 
9262   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
9263     << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
9264   SuggestParentheses(Self, OpLoc,
9265     Self.PDiag(diag::note_precedence_silence) << OpStr,
9266     (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
9267   SuggestParentheses(Self, OpLoc,
9268     Self.PDiag(diag::note_precedence_bitwise_first)
9269       << BinaryOperator::getOpcodeStr(Opc),
9270     ParensRange);
9271 }
9272 
9273 /// \brief It accepts a '&' expr that is inside a '|' one.
9274 /// Emit a diagnostic together with a fixit hint that wraps the '&' expression
9275 /// in parentheses.
9276 static void
9277 EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc,
9278                                        BinaryOperator *Bop) {
9279   assert(Bop->getOpcode() == BO_And);
9280   Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or)
9281       << Bop->getSourceRange() << OpLoc;
9282   SuggestParentheses(Self, Bop->getOperatorLoc(),
9283     Self.PDiag(diag::note_precedence_silence)
9284       << Bop->getOpcodeStr(),
9285     Bop->getSourceRange());
9286 }
9287 
9288 /// \brief It accepts a '&&' expr that is inside a '||' one.
9289 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
9290 /// in parentheses.
9291 static void
9292 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
9293                                        BinaryOperator *Bop) {
9294   assert(Bop->getOpcode() == BO_LAnd);
9295   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
9296       << Bop->getSourceRange() << OpLoc;
9297   SuggestParentheses(Self, Bop->getOperatorLoc(),
9298     Self.PDiag(diag::note_precedence_silence)
9299       << Bop->getOpcodeStr(),
9300     Bop->getSourceRange());
9301 }
9302 
9303 /// \brief Returns true if the given expression can be evaluated as a constant
9304 /// 'true'.
9305 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
9306   bool Res;
9307   return !E->isValueDependent() &&
9308          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
9309 }
9310 
9311 /// \brief Returns true if the given expression can be evaluated as a constant
9312 /// 'false'.
9313 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
9314   bool Res;
9315   return !E->isValueDependent() &&
9316          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
9317 }
9318 
9319 /// \brief Look for '&&' in the left hand of a '||' expr.
9320 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
9321                                              Expr *LHSExpr, Expr *RHSExpr) {
9322   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
9323     if (Bop->getOpcode() == BO_LAnd) {
9324       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
9325       if (EvaluatesAsFalse(S, RHSExpr))
9326         return;
9327       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
9328       if (!EvaluatesAsTrue(S, Bop->getLHS()))
9329         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
9330     } else if (Bop->getOpcode() == BO_LOr) {
9331       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
9332         // If it's "a || b && 1 || c" we didn't warn earlier for
9333         // "a || b && 1", but warn now.
9334         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
9335           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
9336       }
9337     }
9338   }
9339 }
9340 
9341 /// \brief Look for '&&' in the right hand of a '||' expr.
9342 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
9343                                              Expr *LHSExpr, Expr *RHSExpr) {
9344   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
9345     if (Bop->getOpcode() == BO_LAnd) {
9346       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
9347       if (EvaluatesAsFalse(S, LHSExpr))
9348         return;
9349       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
9350       if (!EvaluatesAsTrue(S, Bop->getRHS()))
9351         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
9352     }
9353   }
9354 }
9355 
9356 /// \brief Look for '&' in the left or right hand of a '|' expr.
9357 static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc,
9358                                              Expr *OrArg) {
9359   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) {
9360     if (Bop->getOpcode() == BO_And)
9361       return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop);
9362   }
9363 }
9364 
9365 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
9366                                     Expr *SubExpr, StringRef Shift) {
9367   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
9368     if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
9369       StringRef Op = Bop->getOpcodeStr();
9370       S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
9371           << Bop->getSourceRange() << OpLoc << Shift << Op;
9372       SuggestParentheses(S, Bop->getOperatorLoc(),
9373           S.PDiag(diag::note_precedence_silence) << Op,
9374           Bop->getSourceRange());
9375     }
9376   }
9377 }
9378 
9379 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
9380                                  Expr *LHSExpr, Expr *RHSExpr) {
9381   CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
9382   if (!OCE)
9383     return;
9384 
9385   FunctionDecl *FD = OCE->getDirectCallee();
9386   if (!FD || !FD->isOverloadedOperator())
9387     return;
9388 
9389   OverloadedOperatorKind Kind = FD->getOverloadedOperator();
9390   if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
9391     return;
9392 
9393   S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
9394       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
9395       << (Kind == OO_LessLess);
9396   SuggestParentheses(S, OCE->getOperatorLoc(),
9397                      S.PDiag(diag::note_precedence_silence)
9398                          << (Kind == OO_LessLess ? "<<" : ">>"),
9399                      OCE->getSourceRange());
9400   SuggestParentheses(S, OpLoc,
9401                      S.PDiag(diag::note_evaluate_comparison_first),
9402                      SourceRange(OCE->getArg(1)->getLocStart(),
9403                                  RHSExpr->getLocEnd()));
9404 }
9405 
9406 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
9407 /// precedence.
9408 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
9409                                     SourceLocation OpLoc, Expr *LHSExpr,
9410                                     Expr *RHSExpr){
9411   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
9412   if (BinaryOperator::isBitwiseOp(Opc))
9413     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
9414 
9415   // Diagnose "arg1 & arg2 | arg3"
9416   if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) {
9417     DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr);
9418     DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr);
9419   }
9420 
9421   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
9422   // We don't warn for 'assert(a || b && "bad")' since this is safe.
9423   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
9424     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
9425     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
9426   }
9427 
9428   if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
9429       || Opc == BO_Shr) {
9430     StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
9431     DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
9432     DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
9433   }
9434 
9435   // Warn on overloaded shift operators and comparisons, such as:
9436   // cout << 5 == 4;
9437   if (BinaryOperator::isComparisonOp(Opc))
9438     DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
9439 }
9440 
9441 // Binary Operators.  'Tok' is the token for the operator.
9442 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
9443                             tok::TokenKind Kind,
9444                             Expr *LHSExpr, Expr *RHSExpr) {
9445   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
9446   assert((LHSExpr != 0) && "ActOnBinOp(): missing left expression");
9447   assert((RHSExpr != 0) && "ActOnBinOp(): missing right expression");
9448 
9449   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
9450   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
9451 
9452   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
9453 }
9454 
9455 /// Build an overloaded binary operator expression in the given scope.
9456 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
9457                                        BinaryOperatorKind Opc,
9458                                        Expr *LHS, Expr *RHS) {
9459   // Find all of the overloaded operators visible from this
9460   // point. We perform both an operator-name lookup from the local
9461   // scope and an argument-dependent lookup based on the types of
9462   // the arguments.
9463   UnresolvedSet<16> Functions;
9464   OverloadedOperatorKind OverOp
9465     = BinaryOperator::getOverloadedOperator(Opc);
9466   if (Sc && OverOp != OO_None)
9467     S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
9468                                    RHS->getType(), Functions);
9469 
9470   // Build the (potentially-overloaded, potentially-dependent)
9471   // binary operation.
9472   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
9473 }
9474 
9475 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
9476                             BinaryOperatorKind Opc,
9477                             Expr *LHSExpr, Expr *RHSExpr) {
9478   // We want to end up calling one of checkPseudoObjectAssignment
9479   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
9480   // both expressions are overloadable or either is type-dependent),
9481   // or CreateBuiltinBinOp (in any other case).  We also want to get
9482   // any placeholder types out of the way.
9483 
9484   // Handle pseudo-objects in the LHS.
9485   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
9486     // Assignments with a pseudo-object l-value need special analysis.
9487     if (pty->getKind() == BuiltinType::PseudoObject &&
9488         BinaryOperator::isAssignmentOp(Opc))
9489       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
9490 
9491     // Don't resolve overloads if the other type is overloadable.
9492     if (pty->getKind() == BuiltinType::Overload) {
9493       // We can't actually test that if we still have a placeholder,
9494       // though.  Fortunately, none of the exceptions we see in that
9495       // code below are valid when the LHS is an overload set.  Note
9496       // that an overload set can be dependently-typed, but it never
9497       // instantiates to having an overloadable type.
9498       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
9499       if (resolvedRHS.isInvalid()) return ExprError();
9500       RHSExpr = resolvedRHS.take();
9501 
9502       if (RHSExpr->isTypeDependent() ||
9503           RHSExpr->getType()->isOverloadableType())
9504         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9505     }
9506 
9507     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
9508     if (LHS.isInvalid()) return ExprError();
9509     LHSExpr = LHS.take();
9510   }
9511 
9512   // Handle pseudo-objects in the RHS.
9513   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
9514     // An overload in the RHS can potentially be resolved by the type
9515     // being assigned to.
9516     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
9517       if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
9518         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9519 
9520       if (LHSExpr->getType()->isOverloadableType())
9521         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9522 
9523       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
9524     }
9525 
9526     // Don't resolve overloads if the other type is overloadable.
9527     if (pty->getKind() == BuiltinType::Overload &&
9528         LHSExpr->getType()->isOverloadableType())
9529       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9530 
9531     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
9532     if (!resolvedRHS.isUsable()) return ExprError();
9533     RHSExpr = resolvedRHS.take();
9534   }
9535 
9536   if (getLangOpts().CPlusPlus) {
9537     // If either expression is type-dependent, always build an
9538     // overloaded op.
9539     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
9540       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9541 
9542     // Otherwise, build an overloaded op if either expression has an
9543     // overloadable type.
9544     if (LHSExpr->getType()->isOverloadableType() ||
9545         RHSExpr->getType()->isOverloadableType())
9546       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9547   }
9548 
9549   // Build a built-in binary operation.
9550   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
9551 }
9552 
9553 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
9554                                       UnaryOperatorKind Opc,
9555                                       Expr *InputExpr) {
9556   ExprResult Input = Owned(InputExpr);
9557   ExprValueKind VK = VK_RValue;
9558   ExprObjectKind OK = OK_Ordinary;
9559   QualType resultType;
9560   switch (Opc) {
9561   case UO_PreInc:
9562   case UO_PreDec:
9563   case UO_PostInc:
9564   case UO_PostDec:
9565     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc,
9566                                                 Opc == UO_PreInc ||
9567                                                 Opc == UO_PostInc,
9568                                                 Opc == UO_PreInc ||
9569                                                 Opc == UO_PreDec);
9570     break;
9571   case UO_AddrOf:
9572     resultType = CheckAddressOfOperand(Input, OpLoc);
9573     break;
9574   case UO_Deref: {
9575     Input = DefaultFunctionArrayLvalueConversion(Input.take());
9576     if (Input.isInvalid()) return ExprError();
9577     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
9578     break;
9579   }
9580   case UO_Plus:
9581   case UO_Minus:
9582     Input = UsualUnaryConversions(Input.take());
9583     if (Input.isInvalid()) return ExprError();
9584     resultType = Input.get()->getType();
9585     if (resultType->isDependentType())
9586       break;
9587     if (resultType->isArithmeticType() || // C99 6.5.3.3p1
9588         resultType->isVectorType())
9589       break;
9590     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
9591              Opc == UO_Plus &&
9592              resultType->isPointerType())
9593       break;
9594 
9595     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9596       << resultType << Input.get()->getSourceRange());
9597 
9598   case UO_Not: // bitwise complement
9599     Input = UsualUnaryConversions(Input.take());
9600     if (Input.isInvalid())
9601       return ExprError();
9602     resultType = Input.get()->getType();
9603     if (resultType->isDependentType())
9604       break;
9605     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
9606     if (resultType->isComplexType() || resultType->isComplexIntegerType())
9607       // C99 does not support '~' for complex conjugation.
9608       Diag(OpLoc, diag::ext_integer_complement_complex)
9609           << resultType << Input.get()->getSourceRange();
9610     else if (resultType->hasIntegerRepresentation())
9611       break;
9612     else if (resultType->isExtVectorType()) {
9613       if (Context.getLangOpts().OpenCL) {
9614         // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
9615         // on vector float types.
9616         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
9617         if (!T->isIntegerType())
9618           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9619                            << resultType << Input.get()->getSourceRange());
9620       }
9621       break;
9622     } else {
9623       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9624                        << resultType << Input.get()->getSourceRange());
9625     }
9626     break;
9627 
9628   case UO_LNot: // logical negation
9629     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
9630     Input = DefaultFunctionArrayLvalueConversion(Input.take());
9631     if (Input.isInvalid()) return ExprError();
9632     resultType = Input.get()->getType();
9633 
9634     // Though we still have to promote half FP to float...
9635     if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
9636       Input = ImpCastExprToType(Input.take(), Context.FloatTy, CK_FloatingCast).take();
9637       resultType = Context.FloatTy;
9638     }
9639 
9640     if (resultType->isDependentType())
9641       break;
9642     if (resultType->isScalarType()) {
9643       // C99 6.5.3.3p1: ok, fallthrough;
9644       if (Context.getLangOpts().CPlusPlus) {
9645         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
9646         // operand contextually converted to bool.
9647         Input = ImpCastExprToType(Input.take(), Context.BoolTy,
9648                                   ScalarTypeToBooleanCastKind(resultType));
9649       } else if (Context.getLangOpts().OpenCL &&
9650                  Context.getLangOpts().OpenCLVersion < 120) {
9651         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
9652         // operate on scalar float types.
9653         if (!resultType->isIntegerType())
9654           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9655                            << resultType << Input.get()->getSourceRange());
9656       }
9657     } else if (resultType->isExtVectorType()) {
9658       if (Context.getLangOpts().OpenCL &&
9659           Context.getLangOpts().OpenCLVersion < 120) {
9660         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
9661         // operate on vector float types.
9662         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
9663         if (!T->isIntegerType())
9664           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9665                            << resultType << Input.get()->getSourceRange());
9666       }
9667       // Vector logical not returns the signed variant of the operand type.
9668       resultType = GetSignedVectorType(resultType);
9669       break;
9670     } else {
9671       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9672         << resultType << Input.get()->getSourceRange());
9673     }
9674 
9675     // LNot always has type int. C99 6.5.3.3p5.
9676     // In C++, it's bool. C++ 5.3.1p8
9677     resultType = Context.getLogicalOperationType();
9678     break;
9679   case UO_Real:
9680   case UO_Imag:
9681     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
9682     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
9683     // complex l-values to ordinary l-values and all other values to r-values.
9684     if (Input.isInvalid()) return ExprError();
9685     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
9686       if (Input.get()->getValueKind() != VK_RValue &&
9687           Input.get()->getObjectKind() == OK_Ordinary)
9688         VK = Input.get()->getValueKind();
9689     } else if (!getLangOpts().CPlusPlus) {
9690       // In C, a volatile scalar is read by __imag. In C++, it is not.
9691       Input = DefaultLvalueConversion(Input.take());
9692     }
9693     break;
9694   case UO_Extension:
9695     resultType = Input.get()->getType();
9696     VK = Input.get()->getValueKind();
9697     OK = Input.get()->getObjectKind();
9698     break;
9699   }
9700   if (resultType.isNull() || Input.isInvalid())
9701     return ExprError();
9702 
9703   // Check for array bounds violations in the operand of the UnaryOperator,
9704   // except for the '*' and '&' operators that have to be handled specially
9705   // by CheckArrayAccess (as there are special cases like &array[arraysize]
9706   // that are explicitly defined as valid by the standard).
9707   if (Opc != UO_AddrOf && Opc != UO_Deref)
9708     CheckArrayAccess(Input.get());
9709 
9710   return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType,
9711                                            VK, OK, OpLoc));
9712 }
9713 
9714 /// \brief Determine whether the given expression is a qualified member
9715 /// access expression, of a form that could be turned into a pointer to member
9716 /// with the address-of operator.
9717 static bool isQualifiedMemberAccess(Expr *E) {
9718   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
9719     if (!DRE->getQualifier())
9720       return false;
9721 
9722     ValueDecl *VD = DRE->getDecl();
9723     if (!VD->isCXXClassMember())
9724       return false;
9725 
9726     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
9727       return true;
9728     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
9729       return Method->isInstance();
9730 
9731     return false;
9732   }
9733 
9734   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
9735     if (!ULE->getQualifier())
9736       return false;
9737 
9738     for (UnresolvedLookupExpr::decls_iterator D = ULE->decls_begin(),
9739                                            DEnd = ULE->decls_end();
9740          D != DEnd; ++D) {
9741       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*D)) {
9742         if (Method->isInstance())
9743           return true;
9744       } else {
9745         // Overload set does not contain methods.
9746         break;
9747       }
9748     }
9749 
9750     return false;
9751   }
9752 
9753   return false;
9754 }
9755 
9756 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
9757                               UnaryOperatorKind Opc, Expr *Input) {
9758   // First things first: handle placeholders so that the
9759   // overloaded-operator check considers the right type.
9760   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
9761     // Increment and decrement of pseudo-object references.
9762     if (pty->getKind() == BuiltinType::PseudoObject &&
9763         UnaryOperator::isIncrementDecrementOp(Opc))
9764       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
9765 
9766     // extension is always a builtin operator.
9767     if (Opc == UO_Extension)
9768       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
9769 
9770     // & gets special logic for several kinds of placeholder.
9771     // The builtin code knows what to do.
9772     if (Opc == UO_AddrOf &&
9773         (pty->getKind() == BuiltinType::Overload ||
9774          pty->getKind() == BuiltinType::UnknownAny ||
9775          pty->getKind() == BuiltinType::BoundMember))
9776       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
9777 
9778     // Anything else needs to be handled now.
9779     ExprResult Result = CheckPlaceholderExpr(Input);
9780     if (Result.isInvalid()) return ExprError();
9781     Input = Result.take();
9782   }
9783 
9784   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
9785       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
9786       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
9787     // Find all of the overloaded operators visible from this
9788     // point. We perform both an operator-name lookup from the local
9789     // scope and an argument-dependent lookup based on the types of
9790     // the arguments.
9791     UnresolvedSet<16> Functions;
9792     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
9793     if (S && OverOp != OO_None)
9794       LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
9795                                    Functions);
9796 
9797     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
9798   }
9799 
9800   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
9801 }
9802 
9803 // Unary Operators.  'Tok' is the token for the operator.
9804 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
9805                               tok::TokenKind Op, Expr *Input) {
9806   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
9807 }
9808 
9809 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
9810 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
9811                                 LabelDecl *TheDecl) {
9812   TheDecl->markUsed(Context);
9813   // Create the AST node.  The address of a label always has type 'void*'.
9814   return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
9815                                        Context.getPointerType(Context.VoidTy)));
9816 }
9817 
9818 /// Given the last statement in a statement-expression, check whether
9819 /// the result is a producing expression (like a call to an
9820 /// ns_returns_retained function) and, if so, rebuild it to hoist the
9821 /// release out of the full-expression.  Otherwise, return null.
9822 /// Cannot fail.
9823 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
9824   // Should always be wrapped with one of these.
9825   ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
9826   if (!cleanups) return 0;
9827 
9828   ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
9829   if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
9830     return 0;
9831 
9832   // Splice out the cast.  This shouldn't modify any interesting
9833   // features of the statement.
9834   Expr *producer = cast->getSubExpr();
9835   assert(producer->getType() == cast->getType());
9836   assert(producer->getValueKind() == cast->getValueKind());
9837   cleanups->setSubExpr(producer);
9838   return cleanups;
9839 }
9840 
9841 void Sema::ActOnStartStmtExpr() {
9842   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
9843 }
9844 
9845 void Sema::ActOnStmtExprError() {
9846   // Note that function is also called by TreeTransform when leaving a
9847   // StmtExpr scope without rebuilding anything.
9848 
9849   DiscardCleanupsInEvaluationContext();
9850   PopExpressionEvaluationContext();
9851 }
9852 
9853 ExprResult
9854 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
9855                     SourceLocation RPLoc) { // "({..})"
9856   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
9857   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
9858 
9859   if (hasAnyUnrecoverableErrorsInThisFunction())
9860     DiscardCleanupsInEvaluationContext();
9861   assert(!ExprNeedsCleanups && "cleanups within StmtExpr not correctly bound!");
9862   PopExpressionEvaluationContext();
9863 
9864   bool isFileScope
9865     = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
9866   if (isFileScope)
9867     return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
9868 
9869   // FIXME: there are a variety of strange constraints to enforce here, for
9870   // example, it is not possible to goto into a stmt expression apparently.
9871   // More semantic analysis is needed.
9872 
9873   // If there are sub stmts in the compound stmt, take the type of the last one
9874   // as the type of the stmtexpr.
9875   QualType Ty = Context.VoidTy;
9876   bool StmtExprMayBindToTemp = false;
9877   if (!Compound->body_empty()) {
9878     Stmt *LastStmt = Compound->body_back();
9879     LabelStmt *LastLabelStmt = 0;
9880     // If LastStmt is a label, skip down through into the body.
9881     while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
9882       LastLabelStmt = Label;
9883       LastStmt = Label->getSubStmt();
9884     }
9885 
9886     if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
9887       // Do function/array conversion on the last expression, but not
9888       // lvalue-to-rvalue.  However, initialize an unqualified type.
9889       ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
9890       if (LastExpr.isInvalid())
9891         return ExprError();
9892       Ty = LastExpr.get()->getType().getUnqualifiedType();
9893 
9894       if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
9895         // In ARC, if the final expression ends in a consume, splice
9896         // the consume out and bind it later.  In the alternate case
9897         // (when dealing with a retainable type), the result
9898         // initialization will create a produce.  In both cases the
9899         // result will be +1, and we'll need to balance that out with
9900         // a bind.
9901         if (Expr *rebuiltLastStmt
9902               = maybeRebuildARCConsumingStmt(LastExpr.get())) {
9903           LastExpr = rebuiltLastStmt;
9904         } else {
9905           LastExpr = PerformCopyInitialization(
9906                             InitializedEntity::InitializeResult(LPLoc,
9907                                                                 Ty,
9908                                                                 false),
9909                                                    SourceLocation(),
9910                                                LastExpr);
9911         }
9912 
9913         if (LastExpr.isInvalid())
9914           return ExprError();
9915         if (LastExpr.get() != 0) {
9916           if (!LastLabelStmt)
9917             Compound->setLastStmt(LastExpr.take());
9918           else
9919             LastLabelStmt->setSubStmt(LastExpr.take());
9920           StmtExprMayBindToTemp = true;
9921         }
9922       }
9923     }
9924   }
9925 
9926   // FIXME: Check that expression type is complete/non-abstract; statement
9927   // expressions are not lvalues.
9928   Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
9929   if (StmtExprMayBindToTemp)
9930     return MaybeBindToTemporary(ResStmtExpr);
9931   return Owned(ResStmtExpr);
9932 }
9933 
9934 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
9935                                       TypeSourceInfo *TInfo,
9936                                       OffsetOfComponent *CompPtr,
9937                                       unsigned NumComponents,
9938                                       SourceLocation RParenLoc) {
9939   QualType ArgTy = TInfo->getType();
9940   bool Dependent = ArgTy->isDependentType();
9941   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
9942 
9943   // We must have at least one component that refers to the type, and the first
9944   // one is known to be a field designator.  Verify that the ArgTy represents
9945   // a struct/union/class.
9946   if (!Dependent && !ArgTy->isRecordType())
9947     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
9948                        << ArgTy << TypeRange);
9949 
9950   // Type must be complete per C99 7.17p3 because a declaring a variable
9951   // with an incomplete type would be ill-formed.
9952   if (!Dependent
9953       && RequireCompleteType(BuiltinLoc, ArgTy,
9954                              diag::err_offsetof_incomplete_type, TypeRange))
9955     return ExprError();
9956 
9957   // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
9958   // GCC extension, diagnose them.
9959   // FIXME: This diagnostic isn't actually visible because the location is in
9960   // a system header!
9961   if (NumComponents != 1)
9962     Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
9963       << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
9964 
9965   bool DidWarnAboutNonPOD = false;
9966   QualType CurrentType = ArgTy;
9967   typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
9968   SmallVector<OffsetOfNode, 4> Comps;
9969   SmallVector<Expr*, 4> Exprs;
9970   for (unsigned i = 0; i != NumComponents; ++i) {
9971     const OffsetOfComponent &OC = CompPtr[i];
9972     if (OC.isBrackets) {
9973       // Offset of an array sub-field.  TODO: Should we allow vector elements?
9974       if (!CurrentType->isDependentType()) {
9975         const ArrayType *AT = Context.getAsArrayType(CurrentType);
9976         if(!AT)
9977           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
9978                            << CurrentType);
9979         CurrentType = AT->getElementType();
9980       } else
9981         CurrentType = Context.DependentTy;
9982 
9983       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
9984       if (IdxRval.isInvalid())
9985         return ExprError();
9986       Expr *Idx = IdxRval.take();
9987 
9988       // The expression must be an integral expression.
9989       // FIXME: An integral constant expression?
9990       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
9991           !Idx->getType()->isIntegerType())
9992         return ExprError(Diag(Idx->getLocStart(),
9993                               diag::err_typecheck_subscript_not_integer)
9994                          << Idx->getSourceRange());
9995 
9996       // Record this array index.
9997       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
9998       Exprs.push_back(Idx);
9999       continue;
10000     }
10001 
10002     // Offset of a field.
10003     if (CurrentType->isDependentType()) {
10004       // We have the offset of a field, but we can't look into the dependent
10005       // type. Just record the identifier of the field.
10006       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
10007       CurrentType = Context.DependentTy;
10008       continue;
10009     }
10010 
10011     // We need to have a complete type to look into.
10012     if (RequireCompleteType(OC.LocStart, CurrentType,
10013                             diag::err_offsetof_incomplete_type))
10014       return ExprError();
10015 
10016     // Look for the designated field.
10017     const RecordType *RC = CurrentType->getAs<RecordType>();
10018     if (!RC)
10019       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
10020                        << CurrentType);
10021     RecordDecl *RD = RC->getDecl();
10022 
10023     // C++ [lib.support.types]p5:
10024     //   The macro offsetof accepts a restricted set of type arguments in this
10025     //   International Standard. type shall be a POD structure or a POD union
10026     //   (clause 9).
10027     // C++11 [support.types]p4:
10028     //   If type is not a standard-layout class (Clause 9), the results are
10029     //   undefined.
10030     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
10031       bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
10032       unsigned DiagID =
10033         LangOpts.CPlusPlus11? diag::warn_offsetof_non_standardlayout_type
10034                             : diag::warn_offsetof_non_pod_type;
10035 
10036       if (!IsSafe && !DidWarnAboutNonPOD &&
10037           DiagRuntimeBehavior(BuiltinLoc, 0,
10038                               PDiag(DiagID)
10039                               << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
10040                               << CurrentType))
10041         DidWarnAboutNonPOD = true;
10042     }
10043 
10044     // Look for the field.
10045     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
10046     LookupQualifiedName(R, RD);
10047     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
10048     IndirectFieldDecl *IndirectMemberDecl = 0;
10049     if (!MemberDecl) {
10050       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
10051         MemberDecl = IndirectMemberDecl->getAnonField();
10052     }
10053 
10054     if (!MemberDecl)
10055       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
10056                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
10057                                                               OC.LocEnd));
10058 
10059     // C99 7.17p3:
10060     //   (If the specified member is a bit-field, the behavior is undefined.)
10061     //
10062     // We diagnose this as an error.
10063     if (MemberDecl->isBitField()) {
10064       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
10065         << MemberDecl->getDeclName()
10066         << SourceRange(BuiltinLoc, RParenLoc);
10067       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
10068       return ExprError();
10069     }
10070 
10071     RecordDecl *Parent = MemberDecl->getParent();
10072     if (IndirectMemberDecl)
10073       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
10074 
10075     // If the member was found in a base class, introduce OffsetOfNodes for
10076     // the base class indirections.
10077     CXXBasePaths Paths;
10078     if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
10079       if (Paths.getDetectedVirtual()) {
10080         Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
10081           << MemberDecl->getDeclName()
10082           << SourceRange(BuiltinLoc, RParenLoc);
10083         return ExprError();
10084       }
10085 
10086       CXXBasePath &Path = Paths.front();
10087       for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
10088            B != BEnd; ++B)
10089         Comps.push_back(OffsetOfNode(B->Base));
10090     }
10091 
10092     if (IndirectMemberDecl) {
10093       for (IndirectFieldDecl::chain_iterator FI =
10094            IndirectMemberDecl->chain_begin(),
10095            FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
10096         assert(isa<FieldDecl>(*FI));
10097         Comps.push_back(OffsetOfNode(OC.LocStart,
10098                                      cast<FieldDecl>(*FI), OC.LocEnd));
10099       }
10100     } else
10101       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
10102 
10103     CurrentType = MemberDecl->getType().getNonReferenceType();
10104   }
10105 
10106   return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
10107                                     TInfo, Comps, Exprs, RParenLoc));
10108 }
10109 
10110 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
10111                                       SourceLocation BuiltinLoc,
10112                                       SourceLocation TypeLoc,
10113                                       ParsedType ParsedArgTy,
10114                                       OffsetOfComponent *CompPtr,
10115                                       unsigned NumComponents,
10116                                       SourceLocation RParenLoc) {
10117 
10118   TypeSourceInfo *ArgTInfo;
10119   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
10120   if (ArgTy.isNull())
10121     return ExprError();
10122 
10123   if (!ArgTInfo)
10124     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
10125 
10126   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
10127                               RParenLoc);
10128 }
10129 
10130 
10131 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
10132                                  Expr *CondExpr,
10133                                  Expr *LHSExpr, Expr *RHSExpr,
10134                                  SourceLocation RPLoc) {
10135   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
10136 
10137   ExprValueKind VK = VK_RValue;
10138   ExprObjectKind OK = OK_Ordinary;
10139   QualType resType;
10140   bool ValueDependent = false;
10141   bool CondIsTrue = false;
10142   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
10143     resType = Context.DependentTy;
10144     ValueDependent = true;
10145   } else {
10146     // The conditional expression is required to be a constant expression.
10147     llvm::APSInt condEval(32);
10148     ExprResult CondICE
10149       = VerifyIntegerConstantExpression(CondExpr, &condEval,
10150           diag::err_typecheck_choose_expr_requires_constant, false);
10151     if (CondICE.isInvalid())
10152       return ExprError();
10153     CondExpr = CondICE.take();
10154     CondIsTrue = condEval.getZExtValue();
10155 
10156     // If the condition is > zero, then the AST type is the same as the LSHExpr.
10157     Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
10158 
10159     resType = ActiveExpr->getType();
10160     ValueDependent = ActiveExpr->isValueDependent();
10161     VK = ActiveExpr->getValueKind();
10162     OK = ActiveExpr->getObjectKind();
10163   }
10164 
10165   return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
10166                                         resType, VK, OK, RPLoc, CondIsTrue,
10167                                         resType->isDependentType(),
10168                                         ValueDependent));
10169 }
10170 
10171 //===----------------------------------------------------------------------===//
10172 // Clang Extensions.
10173 //===----------------------------------------------------------------------===//
10174 
10175 /// ActOnBlockStart - This callback is invoked when a block literal is started.
10176 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
10177   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
10178 
10179   if (LangOpts.CPlusPlus) {
10180     Decl *ManglingContextDecl;
10181     if (MangleNumberingContext *MCtx =
10182             getCurrentMangleNumberContext(Block->getDeclContext(),
10183                                           ManglingContextDecl)) {
10184       unsigned ManglingNumber = MCtx->getManglingNumber(Block);
10185       Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
10186     }
10187   }
10188 
10189   PushBlockScope(CurScope, Block);
10190   CurContext->addDecl(Block);
10191   if (CurScope)
10192     PushDeclContext(CurScope, Block);
10193   else
10194     CurContext = Block;
10195 
10196   getCurBlock()->HasImplicitReturnType = true;
10197 
10198   // Enter a new evaluation context to insulate the block from any
10199   // cleanups from the enclosing full-expression.
10200   PushExpressionEvaluationContext(PotentiallyEvaluated);
10201 }
10202 
10203 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
10204                                Scope *CurScope) {
10205   assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
10206   assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
10207   BlockScopeInfo *CurBlock = getCurBlock();
10208 
10209   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
10210   QualType T = Sig->getType();
10211 
10212   // FIXME: We should allow unexpanded parameter packs here, but that would,
10213   // in turn, make the block expression contain unexpanded parameter packs.
10214   if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
10215     // Drop the parameters.
10216     FunctionProtoType::ExtProtoInfo EPI;
10217     EPI.HasTrailingReturn = false;
10218     EPI.TypeQuals |= DeclSpec::TQ_const;
10219     T = Context.getFunctionType(Context.DependentTy, None, EPI);
10220     Sig = Context.getTrivialTypeSourceInfo(T);
10221   }
10222 
10223   // GetTypeForDeclarator always produces a function type for a block
10224   // literal signature.  Furthermore, it is always a FunctionProtoType
10225   // unless the function was written with a typedef.
10226   assert(T->isFunctionType() &&
10227          "GetTypeForDeclarator made a non-function block signature");
10228 
10229   // Look for an explicit signature in that function type.
10230   FunctionProtoTypeLoc ExplicitSignature;
10231 
10232   TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
10233   if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) {
10234 
10235     // Check whether that explicit signature was synthesized by
10236     // GetTypeForDeclarator.  If so, don't save that as part of the
10237     // written signature.
10238     if (ExplicitSignature.getLocalRangeBegin() ==
10239         ExplicitSignature.getLocalRangeEnd()) {
10240       // This would be much cheaper if we stored TypeLocs instead of
10241       // TypeSourceInfos.
10242       TypeLoc Result = ExplicitSignature.getResultLoc();
10243       unsigned Size = Result.getFullDataSize();
10244       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
10245       Sig->getTypeLoc().initializeFullCopy(Result, Size);
10246 
10247       ExplicitSignature = FunctionProtoTypeLoc();
10248     }
10249   }
10250 
10251   CurBlock->TheDecl->setSignatureAsWritten(Sig);
10252   CurBlock->FunctionType = T;
10253 
10254   const FunctionType *Fn = T->getAs<FunctionType>();
10255   QualType RetTy = Fn->getResultType();
10256   bool isVariadic =
10257     (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
10258 
10259   CurBlock->TheDecl->setIsVariadic(isVariadic);
10260 
10261   // Context.DependentTy is used as a placeholder for a missing block
10262   // return type.  TODO:  what should we do with declarators like:
10263   //   ^ * { ... }
10264   // If the answer is "apply template argument deduction"....
10265   if (RetTy != Context.DependentTy) {
10266     CurBlock->ReturnType = RetTy;
10267     CurBlock->TheDecl->setBlockMissingReturnType(false);
10268     CurBlock->HasImplicitReturnType = false;
10269   }
10270 
10271   // Push block parameters from the declarator if we had them.
10272   SmallVector<ParmVarDecl*, 8> Params;
10273   if (ExplicitSignature) {
10274     for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
10275       ParmVarDecl *Param = ExplicitSignature.getArg(I);
10276       if (Param->getIdentifier() == 0 &&
10277           !Param->isImplicit() &&
10278           !Param->isInvalidDecl() &&
10279           !getLangOpts().CPlusPlus)
10280         Diag(Param->getLocation(), diag::err_parameter_name_omitted);
10281       Params.push_back(Param);
10282     }
10283 
10284   // Fake up parameter variables if we have a typedef, like
10285   //   ^ fntype { ... }
10286   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
10287     for (FunctionProtoType::arg_type_iterator
10288            I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
10289       ParmVarDecl *Param =
10290         BuildParmVarDeclForTypedef(CurBlock->TheDecl,
10291                                    ParamInfo.getLocStart(),
10292                                    *I);
10293       Params.push_back(Param);
10294     }
10295   }
10296 
10297   // Set the parameters on the block decl.
10298   if (!Params.empty()) {
10299     CurBlock->TheDecl->setParams(Params);
10300     CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
10301                              CurBlock->TheDecl->param_end(),
10302                              /*CheckParameterNames=*/false);
10303   }
10304 
10305   // Finally we can process decl attributes.
10306   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
10307 
10308   // Put the parameter variables in scope.
10309   for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
10310          E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
10311     (*AI)->setOwningFunction(CurBlock->TheDecl);
10312 
10313     // If this has an identifier, add it to the scope stack.
10314     if ((*AI)->getIdentifier()) {
10315       CheckShadow(CurBlock->TheScope, *AI);
10316 
10317       PushOnScopeChains(*AI, CurBlock->TheScope);
10318     }
10319   }
10320 }
10321 
10322 /// ActOnBlockError - If there is an error parsing a block, this callback
10323 /// is invoked to pop the information about the block from the action impl.
10324 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
10325   // Leave the expression-evaluation context.
10326   DiscardCleanupsInEvaluationContext();
10327   PopExpressionEvaluationContext();
10328 
10329   // Pop off CurBlock, handle nested blocks.
10330   PopDeclContext();
10331   PopFunctionScopeInfo();
10332 }
10333 
10334 /// ActOnBlockStmtExpr - This is called when the body of a block statement
10335 /// literal was successfully completed.  ^(int x){...}
10336 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
10337                                     Stmt *Body, Scope *CurScope) {
10338   // If blocks are disabled, emit an error.
10339   if (!LangOpts.Blocks)
10340     Diag(CaretLoc, diag::err_blocks_disable);
10341 
10342   // Leave the expression-evaluation context.
10343   if (hasAnyUnrecoverableErrorsInThisFunction())
10344     DiscardCleanupsInEvaluationContext();
10345   assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!");
10346   PopExpressionEvaluationContext();
10347 
10348   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
10349 
10350   if (BSI->HasImplicitReturnType)
10351     deduceClosureReturnType(*BSI);
10352 
10353   PopDeclContext();
10354 
10355   QualType RetTy = Context.VoidTy;
10356   if (!BSI->ReturnType.isNull())
10357     RetTy = BSI->ReturnType;
10358 
10359   bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
10360   QualType BlockTy;
10361 
10362   // Set the captured variables on the block.
10363   // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
10364   SmallVector<BlockDecl::Capture, 4> Captures;
10365   for (unsigned i = 0, e = BSI->Captures.size(); i != e; i++) {
10366     CapturingScopeInfo::Capture &Cap = BSI->Captures[i];
10367     if (Cap.isThisCapture())
10368       continue;
10369     BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
10370                               Cap.isNested(), Cap.getInitExpr());
10371     Captures.push_back(NewCap);
10372   }
10373   BSI->TheDecl->setCaptures(Context, Captures.begin(), Captures.end(),
10374                             BSI->CXXThisCaptureIndex != 0);
10375 
10376   // If the user wrote a function type in some form, try to use that.
10377   if (!BSI->FunctionType.isNull()) {
10378     const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
10379 
10380     FunctionType::ExtInfo Ext = FTy->getExtInfo();
10381     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
10382 
10383     // Turn protoless block types into nullary block types.
10384     if (isa<FunctionNoProtoType>(FTy)) {
10385       FunctionProtoType::ExtProtoInfo EPI;
10386       EPI.ExtInfo = Ext;
10387       BlockTy = Context.getFunctionType(RetTy, None, EPI);
10388 
10389     // Otherwise, if we don't need to change anything about the function type,
10390     // preserve its sugar structure.
10391     } else if (FTy->getResultType() == RetTy &&
10392                (!NoReturn || FTy->getNoReturnAttr())) {
10393       BlockTy = BSI->FunctionType;
10394 
10395     // Otherwise, make the minimal modifications to the function type.
10396     } else {
10397       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
10398       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10399       EPI.TypeQuals = 0; // FIXME: silently?
10400       EPI.ExtInfo = Ext;
10401       BlockTy = Context.getFunctionType(RetTy, FPT->getArgTypes(), EPI);
10402     }
10403 
10404   // If we don't have a function type, just build one from nothing.
10405   } else {
10406     FunctionProtoType::ExtProtoInfo EPI;
10407     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
10408     BlockTy = Context.getFunctionType(RetTy, None, EPI);
10409   }
10410 
10411   DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
10412                            BSI->TheDecl->param_end());
10413   BlockTy = Context.getBlockPointerType(BlockTy);
10414 
10415   // If needed, diagnose invalid gotos and switches in the block.
10416   if (getCurFunction()->NeedsScopeChecking() &&
10417       !hasAnyUnrecoverableErrorsInThisFunction() &&
10418       !PP.isCodeCompletionEnabled())
10419     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
10420 
10421   BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
10422 
10423   // Try to apply the named return value optimization. We have to check again
10424   // if we can do this, though, because blocks keep return statements around
10425   // to deduce an implicit return type.
10426   if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
10427       !BSI->TheDecl->isDependentContext())
10428     computeNRVO(Body, getCurBlock());
10429 
10430   BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
10431   AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
10432   PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
10433 
10434   // If the block isn't obviously global, i.e. it captures anything at
10435   // all, then we need to do a few things in the surrounding context:
10436   if (Result->getBlockDecl()->hasCaptures()) {
10437     // First, this expression has a new cleanup object.
10438     ExprCleanupObjects.push_back(Result->getBlockDecl());
10439     ExprNeedsCleanups = true;
10440 
10441     // It also gets a branch-protected scope if any of the captured
10442     // variables needs destruction.
10443     for (BlockDecl::capture_const_iterator
10444            ci = Result->getBlockDecl()->capture_begin(),
10445            ce = Result->getBlockDecl()->capture_end(); ci != ce; ++ci) {
10446       const VarDecl *var = ci->getVariable();
10447       if (var->getType().isDestructedType() != QualType::DK_none) {
10448         getCurFunction()->setHasBranchProtectedScope();
10449         break;
10450       }
10451     }
10452   }
10453 
10454   return Owned(Result);
10455 }
10456 
10457 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
10458                                         Expr *E, ParsedType Ty,
10459                                         SourceLocation RPLoc) {
10460   TypeSourceInfo *TInfo;
10461   GetTypeFromParser(Ty, &TInfo);
10462   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
10463 }
10464 
10465 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
10466                                 Expr *E, TypeSourceInfo *TInfo,
10467                                 SourceLocation RPLoc) {
10468   Expr *OrigExpr = E;
10469 
10470   // Get the va_list type
10471   QualType VaListType = Context.getBuiltinVaListType();
10472   if (VaListType->isArrayType()) {
10473     // Deal with implicit array decay; for example, on x86-64,
10474     // va_list is an array, but it's supposed to decay to
10475     // a pointer for va_arg.
10476     VaListType = Context.getArrayDecayedType(VaListType);
10477     // Make sure the input expression also decays appropriately.
10478     ExprResult Result = UsualUnaryConversions(E);
10479     if (Result.isInvalid())
10480       return ExprError();
10481     E = Result.take();
10482   } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
10483     // If va_list is a record type and we are compiling in C++ mode,
10484     // check the argument using reference binding.
10485     InitializedEntity Entity
10486       = InitializedEntity::InitializeParameter(Context,
10487           Context.getLValueReferenceType(VaListType), false);
10488     ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
10489     if (Init.isInvalid())
10490       return ExprError();
10491     E = Init.takeAs<Expr>();
10492   } else {
10493     // Otherwise, the va_list argument must be an l-value because
10494     // it is modified by va_arg.
10495     if (!E->isTypeDependent() &&
10496         CheckForModifiableLvalue(E, BuiltinLoc, *this))
10497       return ExprError();
10498   }
10499 
10500   if (!E->isTypeDependent() &&
10501       !Context.hasSameType(VaListType, E->getType())) {
10502     return ExprError(Diag(E->getLocStart(),
10503                          diag::err_first_argument_to_va_arg_not_of_type_va_list)
10504       << OrigExpr->getType() << E->getSourceRange());
10505   }
10506 
10507   if (!TInfo->getType()->isDependentType()) {
10508     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
10509                             diag::err_second_parameter_to_va_arg_incomplete,
10510                             TInfo->getTypeLoc()))
10511       return ExprError();
10512 
10513     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
10514                                TInfo->getType(),
10515                                diag::err_second_parameter_to_va_arg_abstract,
10516                                TInfo->getTypeLoc()))
10517       return ExprError();
10518 
10519     if (!TInfo->getType().isPODType(Context)) {
10520       Diag(TInfo->getTypeLoc().getBeginLoc(),
10521            TInfo->getType()->isObjCLifetimeType()
10522              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
10523              : diag::warn_second_parameter_to_va_arg_not_pod)
10524         << TInfo->getType()
10525         << TInfo->getTypeLoc().getSourceRange();
10526     }
10527 
10528     // Check for va_arg where arguments of the given type will be promoted
10529     // (i.e. this va_arg is guaranteed to have undefined behavior).
10530     QualType PromoteType;
10531     if (TInfo->getType()->isPromotableIntegerType()) {
10532       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
10533       if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
10534         PromoteType = QualType();
10535     }
10536     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
10537       PromoteType = Context.DoubleTy;
10538     if (!PromoteType.isNull())
10539       DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
10540                   PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
10541                           << TInfo->getType()
10542                           << PromoteType
10543                           << TInfo->getTypeLoc().getSourceRange());
10544   }
10545 
10546   QualType T = TInfo->getType().getNonLValueExprType(Context);
10547   return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
10548 }
10549 
10550 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
10551   // The type of __null will be int or long, depending on the size of
10552   // pointers on the target.
10553   QualType Ty;
10554   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
10555   if (pw == Context.getTargetInfo().getIntWidth())
10556     Ty = Context.IntTy;
10557   else if (pw == Context.getTargetInfo().getLongWidth())
10558     Ty = Context.LongTy;
10559   else if (pw == Context.getTargetInfo().getLongLongWidth())
10560     Ty = Context.LongLongTy;
10561   else {
10562     llvm_unreachable("I don't know size of pointer!");
10563   }
10564 
10565   return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
10566 }
10567 
10568 static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
10569                                            Expr *SrcExpr, FixItHint &Hint,
10570                                            bool &IsNSString) {
10571   if (!SemaRef.getLangOpts().ObjC1)
10572     return;
10573 
10574   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
10575   if (!PT)
10576     return;
10577 
10578   // Check if the destination is of type 'id'.
10579   if (!PT->isObjCIdType()) {
10580     // Check if the destination is the 'NSString' interface.
10581     const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
10582     if (!ID || !ID->getIdentifier()->isStr("NSString"))
10583       return;
10584     IsNSString = true;
10585   }
10586 
10587   // Ignore any parens, implicit casts (should only be
10588   // array-to-pointer decays), and not-so-opaque values.  The last is
10589   // important for making this trigger for property assignments.
10590   SrcExpr = SrcExpr->IgnoreParenImpCasts();
10591   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
10592     if (OV->getSourceExpr())
10593       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
10594 
10595   StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
10596   if (!SL || !SL->isAscii())
10597     return;
10598 
10599   Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
10600 }
10601 
10602 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
10603                                     SourceLocation Loc,
10604                                     QualType DstType, QualType SrcType,
10605                                     Expr *SrcExpr, AssignmentAction Action,
10606                                     bool *Complained) {
10607   if (Complained)
10608     *Complained = false;
10609 
10610   // Decode the result (notice that AST's are still created for extensions).
10611   bool CheckInferredResultType = false;
10612   bool isInvalid = false;
10613   unsigned DiagKind = 0;
10614   FixItHint Hint;
10615   ConversionFixItGenerator ConvHints;
10616   bool MayHaveConvFixit = false;
10617   bool MayHaveFunctionDiff = false;
10618   bool IsNSString = false;
10619 
10620   switch (ConvTy) {
10621   case Compatible:
10622       DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
10623       return false;
10624 
10625   case PointerToInt:
10626     DiagKind = diag::ext_typecheck_convert_pointer_int;
10627     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
10628     MayHaveConvFixit = true;
10629     break;
10630   case IntToPointer:
10631     DiagKind = diag::ext_typecheck_convert_int_pointer;
10632     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
10633     MayHaveConvFixit = true;
10634     break;
10635   case IncompatiblePointer:
10636     MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint, IsNSString);
10637       DiagKind =
10638         (Action == AA_Passing_CFAudited ?
10639           diag::err_arc_typecheck_convert_incompatible_pointer :
10640           diag::ext_typecheck_convert_incompatible_pointer);
10641     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
10642       SrcType->isObjCObjectPointerType();
10643     if (Hint.isNull() && !CheckInferredResultType) {
10644       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
10645     }
10646     else if (CheckInferredResultType) {
10647       SrcType = SrcType.getUnqualifiedType();
10648       DstType = DstType.getUnqualifiedType();
10649     }
10650     else if (IsNSString && !Hint.isNull())
10651       DiagKind = diag::warn_missing_atsign_prefix;
10652     MayHaveConvFixit = true;
10653     break;
10654   case IncompatiblePointerSign:
10655     DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
10656     break;
10657   case FunctionVoidPointer:
10658     DiagKind = diag::ext_typecheck_convert_pointer_void_func;
10659     break;
10660   case IncompatiblePointerDiscardsQualifiers: {
10661     // Perform array-to-pointer decay if necessary.
10662     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
10663 
10664     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
10665     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
10666     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
10667       DiagKind = diag::err_typecheck_incompatible_address_space;
10668       break;
10669 
10670 
10671     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
10672       DiagKind = diag::err_typecheck_incompatible_ownership;
10673       break;
10674     }
10675 
10676     llvm_unreachable("unknown error case for discarding qualifiers!");
10677     // fallthrough
10678   }
10679   case CompatiblePointerDiscardsQualifiers:
10680     // If the qualifiers lost were because we were applying the
10681     // (deprecated) C++ conversion from a string literal to a char*
10682     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
10683     // Ideally, this check would be performed in
10684     // checkPointerTypesForAssignment. However, that would require a
10685     // bit of refactoring (so that the second argument is an
10686     // expression, rather than a type), which should be done as part
10687     // of a larger effort to fix checkPointerTypesForAssignment for
10688     // C++ semantics.
10689     if (getLangOpts().CPlusPlus &&
10690         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
10691       return false;
10692     DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
10693     break;
10694   case IncompatibleNestedPointerQualifiers:
10695     DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
10696     break;
10697   case IntToBlockPointer:
10698     DiagKind = diag::err_int_to_block_pointer;
10699     break;
10700   case IncompatibleBlockPointer:
10701     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
10702     break;
10703   case IncompatibleObjCQualifiedId:
10704     // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
10705     // it can give a more specific diagnostic.
10706     DiagKind = diag::warn_incompatible_qualified_id;
10707     break;
10708   case IncompatibleVectors:
10709     DiagKind = diag::warn_incompatible_vectors;
10710     break;
10711   case IncompatibleObjCWeakRef:
10712     DiagKind = diag::err_arc_weak_unavailable_assign;
10713     break;
10714   case Incompatible:
10715     DiagKind = diag::err_typecheck_convert_incompatible;
10716     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
10717     MayHaveConvFixit = true;
10718     isInvalid = true;
10719     MayHaveFunctionDiff = true;
10720     break;
10721   }
10722 
10723   QualType FirstType, SecondType;
10724   switch (Action) {
10725   case AA_Assigning:
10726   case AA_Initializing:
10727     // The destination type comes first.
10728     FirstType = DstType;
10729     SecondType = SrcType;
10730     break;
10731 
10732   case AA_Returning:
10733   case AA_Passing:
10734   case AA_Passing_CFAudited:
10735   case AA_Converting:
10736   case AA_Sending:
10737   case AA_Casting:
10738     // The source type comes first.
10739     FirstType = SrcType;
10740     SecondType = DstType;
10741     break;
10742   }
10743 
10744   PartialDiagnostic FDiag = PDiag(DiagKind);
10745   if (Action == AA_Passing_CFAudited)
10746     FDiag << FirstType << SecondType << SrcExpr->getSourceRange();
10747   else
10748     FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
10749 
10750   // If we can fix the conversion, suggest the FixIts.
10751   assert(ConvHints.isNull() || Hint.isNull());
10752   if (!ConvHints.isNull()) {
10753     for (std::vector<FixItHint>::iterator HI = ConvHints.Hints.begin(),
10754          HE = ConvHints.Hints.end(); HI != HE; ++HI)
10755       FDiag << *HI;
10756   } else {
10757     FDiag << Hint;
10758   }
10759   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
10760 
10761   if (MayHaveFunctionDiff)
10762     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
10763 
10764   Diag(Loc, FDiag);
10765 
10766   if (SecondType == Context.OverloadTy)
10767     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
10768                               FirstType);
10769 
10770   if (CheckInferredResultType)
10771     EmitRelatedResultTypeNote(SrcExpr);
10772 
10773   if (Action == AA_Returning && ConvTy == IncompatiblePointer)
10774     EmitRelatedResultTypeNoteForReturn(DstType);
10775 
10776   if (Complained)
10777     *Complained = true;
10778   return isInvalid;
10779 }
10780 
10781 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
10782                                                  llvm::APSInt *Result) {
10783   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
10784   public:
10785     virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
10786       S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
10787     }
10788   } Diagnoser;
10789 
10790   return VerifyIntegerConstantExpression(E, Result, Diagnoser);
10791 }
10792 
10793 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
10794                                                  llvm::APSInt *Result,
10795                                                  unsigned DiagID,
10796                                                  bool AllowFold) {
10797   class IDDiagnoser : public VerifyICEDiagnoser {
10798     unsigned DiagID;
10799 
10800   public:
10801     IDDiagnoser(unsigned DiagID)
10802       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
10803 
10804     virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
10805       S.Diag(Loc, DiagID) << SR;
10806     }
10807   } Diagnoser(DiagID);
10808 
10809   return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
10810 }
10811 
10812 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
10813                                             SourceRange SR) {
10814   S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
10815 }
10816 
10817 ExprResult
10818 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
10819                                       VerifyICEDiagnoser &Diagnoser,
10820                                       bool AllowFold) {
10821   SourceLocation DiagLoc = E->getLocStart();
10822 
10823   if (getLangOpts().CPlusPlus11) {
10824     // C++11 [expr.const]p5:
10825     //   If an expression of literal class type is used in a context where an
10826     //   integral constant expression is required, then that class type shall
10827     //   have a single non-explicit conversion function to an integral or
10828     //   unscoped enumeration type
10829     ExprResult Converted;
10830     class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
10831     public:
10832       CXX11ConvertDiagnoser(bool Silent)
10833           : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
10834                                 Silent, true) {}
10835 
10836       virtual SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
10837                                                    QualType T) {
10838         return S.Diag(Loc, diag::err_ice_not_integral) << T;
10839       }
10840 
10841       virtual SemaDiagnosticBuilder diagnoseIncomplete(
10842           Sema &S, SourceLocation Loc, QualType T) {
10843         return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
10844       }
10845 
10846       virtual SemaDiagnosticBuilder diagnoseExplicitConv(
10847           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) {
10848         return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
10849       }
10850 
10851       virtual SemaDiagnosticBuilder noteExplicitConv(
10852           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) {
10853         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
10854                  << ConvTy->isEnumeralType() << ConvTy;
10855       }
10856 
10857       virtual SemaDiagnosticBuilder diagnoseAmbiguous(
10858           Sema &S, SourceLocation Loc, QualType T) {
10859         return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
10860       }
10861 
10862       virtual SemaDiagnosticBuilder noteAmbiguous(
10863           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) {
10864         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
10865                  << ConvTy->isEnumeralType() << ConvTy;
10866       }
10867 
10868       virtual SemaDiagnosticBuilder diagnoseConversion(
10869           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) {
10870         llvm_unreachable("conversion functions are permitted");
10871       }
10872     } ConvertDiagnoser(Diagnoser.Suppress);
10873 
10874     Converted = PerformContextualImplicitConversion(DiagLoc, E,
10875                                                     ConvertDiagnoser);
10876     if (Converted.isInvalid())
10877       return Converted;
10878     E = Converted.take();
10879     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
10880       return ExprError();
10881   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
10882     // An ICE must be of integral or unscoped enumeration type.
10883     if (!Diagnoser.Suppress)
10884       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
10885     return ExprError();
10886   }
10887 
10888   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
10889   // in the non-ICE case.
10890   if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
10891     if (Result)
10892       *Result = E->EvaluateKnownConstInt(Context);
10893     return Owned(E);
10894   }
10895 
10896   Expr::EvalResult EvalResult;
10897   SmallVector<PartialDiagnosticAt, 8> Notes;
10898   EvalResult.Diag = &Notes;
10899 
10900   // Try to evaluate the expression, and produce diagnostics explaining why it's
10901   // not a constant expression as a side-effect.
10902   bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
10903                 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
10904 
10905   // In C++11, we can rely on diagnostics being produced for any expression
10906   // which is not a constant expression. If no diagnostics were produced, then
10907   // this is a constant expression.
10908   if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
10909     if (Result)
10910       *Result = EvalResult.Val.getInt();
10911     return Owned(E);
10912   }
10913 
10914   // If our only note is the usual "invalid subexpression" note, just point
10915   // the caret at its location rather than producing an essentially
10916   // redundant note.
10917   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
10918         diag::note_invalid_subexpr_in_const_expr) {
10919     DiagLoc = Notes[0].first;
10920     Notes.clear();
10921   }
10922 
10923   if (!Folded || !AllowFold) {
10924     if (!Diagnoser.Suppress) {
10925       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
10926       for (unsigned I = 0, N = Notes.size(); I != N; ++I)
10927         Diag(Notes[I].first, Notes[I].second);
10928     }
10929 
10930     return ExprError();
10931   }
10932 
10933   Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
10934   for (unsigned I = 0, N = Notes.size(); I != N; ++I)
10935     Diag(Notes[I].first, Notes[I].second);
10936 
10937   if (Result)
10938     *Result = EvalResult.Val.getInt();
10939   return Owned(E);
10940 }
10941 
10942 namespace {
10943   // Handle the case where we conclude a expression which we speculatively
10944   // considered to be unevaluated is actually evaluated.
10945   class TransformToPE : public TreeTransform<TransformToPE> {
10946     typedef TreeTransform<TransformToPE> BaseTransform;
10947 
10948   public:
10949     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
10950 
10951     // Make sure we redo semantic analysis
10952     bool AlwaysRebuild() { return true; }
10953 
10954     // Make sure we handle LabelStmts correctly.
10955     // FIXME: This does the right thing, but maybe we need a more general
10956     // fix to TreeTransform?
10957     StmtResult TransformLabelStmt(LabelStmt *S) {
10958       S->getDecl()->setStmt(0);
10959       return BaseTransform::TransformLabelStmt(S);
10960     }
10961 
10962     // We need to special-case DeclRefExprs referring to FieldDecls which
10963     // are not part of a member pointer formation; normal TreeTransforming
10964     // doesn't catch this case because of the way we represent them in the AST.
10965     // FIXME: This is a bit ugly; is it really the best way to handle this
10966     // case?
10967     //
10968     // Error on DeclRefExprs referring to FieldDecls.
10969     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
10970       if (isa<FieldDecl>(E->getDecl()) &&
10971           !SemaRef.isUnevaluatedContext())
10972         return SemaRef.Diag(E->getLocation(),
10973                             diag::err_invalid_non_static_member_use)
10974             << E->getDecl() << E->getSourceRange();
10975 
10976       return BaseTransform::TransformDeclRefExpr(E);
10977     }
10978 
10979     // Exception: filter out member pointer formation
10980     ExprResult TransformUnaryOperator(UnaryOperator *E) {
10981       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
10982         return E;
10983 
10984       return BaseTransform::TransformUnaryOperator(E);
10985     }
10986 
10987     ExprResult TransformLambdaExpr(LambdaExpr *E) {
10988       // Lambdas never need to be transformed.
10989       return E;
10990     }
10991   };
10992 }
10993 
10994 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
10995   assert(isUnevaluatedContext() &&
10996          "Should only transform unevaluated expressions");
10997   ExprEvalContexts.back().Context =
10998       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
10999   if (isUnevaluatedContext())
11000     return E;
11001   return TransformToPE(*this).TransformExpr(E);
11002 }
11003 
11004 void
11005 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
11006                                       Decl *LambdaContextDecl,
11007                                       bool IsDecltype) {
11008   ExprEvalContexts.push_back(
11009              ExpressionEvaluationContextRecord(NewContext,
11010                                                ExprCleanupObjects.size(),
11011                                                ExprNeedsCleanups,
11012                                                LambdaContextDecl,
11013                                                IsDecltype));
11014   ExprNeedsCleanups = false;
11015   if (!MaybeODRUseExprs.empty())
11016     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
11017 }
11018 
11019 void
11020 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
11021                                       ReuseLambdaContextDecl_t,
11022                                       bool IsDecltype) {
11023   Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
11024   PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype);
11025 }
11026 
11027 void Sema::PopExpressionEvaluationContext() {
11028   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
11029 
11030   if (!Rec.Lambdas.empty()) {
11031     if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) {
11032       unsigned D;
11033       if (Rec.isUnevaluated()) {
11034         // C++11 [expr.prim.lambda]p2:
11035         //   A lambda-expression shall not appear in an unevaluated operand
11036         //   (Clause 5).
11037         D = diag::err_lambda_unevaluated_operand;
11038       } else {
11039         // C++1y [expr.const]p2:
11040         //   A conditional-expression e is a core constant expression unless the
11041         //   evaluation of e, following the rules of the abstract machine, would
11042         //   evaluate [...] a lambda-expression.
11043         D = diag::err_lambda_in_constant_expression;
11044       }
11045       for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I)
11046         Diag(Rec.Lambdas[I]->getLocStart(), D);
11047     } else {
11048       // Mark the capture expressions odr-used. This was deferred
11049       // during lambda expression creation.
11050       for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I) {
11051         LambdaExpr *Lambda = Rec.Lambdas[I];
11052         for (LambdaExpr::capture_init_iterator
11053                   C = Lambda->capture_init_begin(),
11054                CEnd = Lambda->capture_init_end();
11055              C != CEnd; ++C) {
11056           MarkDeclarationsReferencedInExpr(*C);
11057         }
11058       }
11059     }
11060   }
11061 
11062   // When are coming out of an unevaluated context, clear out any
11063   // temporaries that we may have created as part of the evaluation of
11064   // the expression in that context: they aren't relevant because they
11065   // will never be constructed.
11066   if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) {
11067     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
11068                              ExprCleanupObjects.end());
11069     ExprNeedsCleanups = Rec.ParentNeedsCleanups;
11070     CleanupVarDeclMarking();
11071     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
11072   // Otherwise, merge the contexts together.
11073   } else {
11074     ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
11075     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
11076                             Rec.SavedMaybeODRUseExprs.end());
11077   }
11078 
11079   // Pop the current expression evaluation context off the stack.
11080   ExprEvalContexts.pop_back();
11081 }
11082 
11083 void Sema::DiscardCleanupsInEvaluationContext() {
11084   ExprCleanupObjects.erase(
11085          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
11086          ExprCleanupObjects.end());
11087   ExprNeedsCleanups = false;
11088   MaybeODRUseExprs.clear();
11089 }
11090 
11091 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
11092   if (!E->getType()->isVariablyModifiedType())
11093     return E;
11094   return TransformToPotentiallyEvaluated(E);
11095 }
11096 
11097 static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) {
11098   // Do not mark anything as "used" within a dependent context; wait for
11099   // an instantiation.
11100   if (SemaRef.CurContext->isDependentContext())
11101     return false;
11102 
11103   switch (SemaRef.ExprEvalContexts.back().Context) {
11104     case Sema::Unevaluated:
11105     case Sema::UnevaluatedAbstract:
11106       // We are in an expression that is not potentially evaluated; do nothing.
11107       // (Depending on how you read the standard, we actually do need to do
11108       // something here for null pointer constants, but the standard's
11109       // definition of a null pointer constant is completely crazy.)
11110       return false;
11111 
11112     case Sema::ConstantEvaluated:
11113     case Sema::PotentiallyEvaluated:
11114       // We are in a potentially evaluated expression (or a constant-expression
11115       // in C++03); we need to do implicit template instantiation, implicitly
11116       // define class members, and mark most declarations as used.
11117       return true;
11118 
11119     case Sema::PotentiallyEvaluatedIfUsed:
11120       // Referenced declarations will only be used if the construct in the
11121       // containing expression is used.
11122       return false;
11123   }
11124   llvm_unreachable("Invalid context");
11125 }
11126 
11127 /// \brief Mark a function referenced, and check whether it is odr-used
11128 /// (C++ [basic.def.odr]p2, C99 6.9p3)
11129 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func) {
11130   assert(Func && "No function?");
11131 
11132   Func->setReferenced();
11133 
11134   // C++11 [basic.def.odr]p3:
11135   //   A function whose name appears as a potentially-evaluated expression is
11136   //   odr-used if it is the unique lookup result or the selected member of a
11137   //   set of overloaded functions [...].
11138   //
11139   // We (incorrectly) mark overload resolution as an unevaluated context, so we
11140   // can just check that here. Skip the rest of this function if we've already
11141   // marked the function as used.
11142   if (Func->isUsed(false) || !IsPotentiallyEvaluatedContext(*this)) {
11143     // C++11 [temp.inst]p3:
11144     //   Unless a function template specialization has been explicitly
11145     //   instantiated or explicitly specialized, the function template
11146     //   specialization is implicitly instantiated when the specialization is
11147     //   referenced in a context that requires a function definition to exist.
11148     //
11149     // We consider constexpr function templates to be referenced in a context
11150     // that requires a definition to exist whenever they are referenced.
11151     //
11152     // FIXME: This instantiates constexpr functions too frequently. If this is
11153     // really an unevaluated context (and we're not just in the definition of a
11154     // function template or overload resolution or other cases which we
11155     // incorrectly consider to be unevaluated contexts), and we're not in a
11156     // subexpression which we actually need to evaluate (for instance, a
11157     // template argument, array bound or an expression in a braced-init-list),
11158     // we are not permitted to instantiate this constexpr function definition.
11159     //
11160     // FIXME: This also implicitly defines special members too frequently. They
11161     // are only supposed to be implicitly defined if they are odr-used, but they
11162     // are not odr-used from constant expressions in unevaluated contexts.
11163     // However, they cannot be referenced if they are deleted, and they are
11164     // deleted whenever the implicit definition of the special member would
11165     // fail.
11166     if (!Func->isConstexpr() || Func->getBody())
11167       return;
11168     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
11169     if (!Func->isImplicitlyInstantiable() && (!MD || MD->isUserProvided()))
11170       return;
11171   }
11172 
11173   // Note that this declaration has been used.
11174   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
11175     if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
11176       if (Constructor->isDefaultConstructor()) {
11177         if (Constructor->isTrivial())
11178           return;
11179         if (!Constructor->isUsed(false))
11180           DefineImplicitDefaultConstructor(Loc, Constructor);
11181       } else if (Constructor->isCopyConstructor()) {
11182         if (!Constructor->isUsed(false))
11183           DefineImplicitCopyConstructor(Loc, Constructor);
11184       } else if (Constructor->isMoveConstructor()) {
11185         if (!Constructor->isUsed(false))
11186           DefineImplicitMoveConstructor(Loc, Constructor);
11187       }
11188     } else if (Constructor->getInheritedConstructor()) {
11189       if (!Constructor->isUsed(false))
11190         DefineInheritingConstructor(Loc, Constructor);
11191     }
11192 
11193     MarkVTableUsed(Loc, Constructor->getParent());
11194   } else if (CXXDestructorDecl *Destructor =
11195                  dyn_cast<CXXDestructorDecl>(Func)) {
11196     if (Destructor->isDefaulted() && !Destructor->isDeleted() &&
11197         !Destructor->isUsed(false))
11198       DefineImplicitDestructor(Loc, Destructor);
11199     if (Destructor->isVirtual())
11200       MarkVTableUsed(Loc, Destructor->getParent());
11201   } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
11202     if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted() &&
11203         MethodDecl->isOverloadedOperator() &&
11204         MethodDecl->getOverloadedOperator() == OO_Equal) {
11205       if (!MethodDecl->isUsed(false)) {
11206         if (MethodDecl->isCopyAssignmentOperator())
11207           DefineImplicitCopyAssignment(Loc, MethodDecl);
11208         else
11209           DefineImplicitMoveAssignment(Loc, MethodDecl);
11210       }
11211     } else if (isa<CXXConversionDecl>(MethodDecl) &&
11212                MethodDecl->getParent()->isLambda()) {
11213       CXXConversionDecl *Conversion = cast<CXXConversionDecl>(MethodDecl);
11214       if (Conversion->isLambdaToBlockPointerConversion())
11215         DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
11216       else
11217         DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
11218     } else if (MethodDecl->isVirtual())
11219       MarkVTableUsed(Loc, MethodDecl->getParent());
11220   }
11221 
11222   // Recursive functions should be marked when used from another function.
11223   // FIXME: Is this really right?
11224   if (CurContext == Func) return;
11225 
11226   // Resolve the exception specification for any function which is
11227   // used: CodeGen will need it.
11228   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
11229   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
11230     ResolveExceptionSpec(Loc, FPT);
11231 
11232   // Implicit instantiation of function templates and member functions of
11233   // class templates.
11234   if (Func->isImplicitlyInstantiable()) {
11235     bool AlreadyInstantiated = false;
11236     SourceLocation PointOfInstantiation = Loc;
11237     if (FunctionTemplateSpecializationInfo *SpecInfo
11238                               = Func->getTemplateSpecializationInfo()) {
11239       if (SpecInfo->getPointOfInstantiation().isInvalid())
11240         SpecInfo->setPointOfInstantiation(Loc);
11241       else if (SpecInfo->getTemplateSpecializationKind()
11242                  == TSK_ImplicitInstantiation) {
11243         AlreadyInstantiated = true;
11244         PointOfInstantiation = SpecInfo->getPointOfInstantiation();
11245       }
11246     } else if (MemberSpecializationInfo *MSInfo
11247                                 = Func->getMemberSpecializationInfo()) {
11248       if (MSInfo->getPointOfInstantiation().isInvalid())
11249         MSInfo->setPointOfInstantiation(Loc);
11250       else if (MSInfo->getTemplateSpecializationKind()
11251                  == TSK_ImplicitInstantiation) {
11252         AlreadyInstantiated = true;
11253         PointOfInstantiation = MSInfo->getPointOfInstantiation();
11254       }
11255     }
11256 
11257     if (!AlreadyInstantiated || Func->isConstexpr()) {
11258       if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
11259           cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
11260           ActiveTemplateInstantiations.size())
11261         PendingLocalImplicitInstantiations.push_back(
11262             std::make_pair(Func, PointOfInstantiation));
11263       else if (Func->isConstexpr())
11264         // Do not defer instantiations of constexpr functions, to avoid the
11265         // expression evaluator needing to call back into Sema if it sees a
11266         // call to such a function.
11267         InstantiateFunctionDefinition(PointOfInstantiation, Func);
11268       else {
11269         PendingInstantiations.push_back(std::make_pair(Func,
11270                                                        PointOfInstantiation));
11271         // Notify the consumer that a function was implicitly instantiated.
11272         Consumer.HandleCXXImplicitFunctionInstantiation(Func);
11273       }
11274     }
11275   } else {
11276     // Walk redefinitions, as some of them may be instantiable.
11277     for (FunctionDecl::redecl_iterator i(Func->redecls_begin()),
11278          e(Func->redecls_end()); i != e; ++i) {
11279       if (!i->isUsed(false) && i->isImplicitlyInstantiable())
11280         MarkFunctionReferenced(Loc, *i);
11281     }
11282   }
11283 
11284   // Keep track of used but undefined functions.
11285   if (!Func->isDefined()) {
11286     if (mightHaveNonExternalLinkage(Func))
11287       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
11288     else if (Func->getMostRecentDecl()->isInlined() &&
11289              (LangOpts.CPlusPlus || !LangOpts.GNUInline) &&
11290              !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
11291       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
11292   }
11293 
11294   // Normally the most current decl is marked used while processing the use and
11295   // any subsequent decls are marked used by decl merging. This fails with
11296   // template instantiation since marking can happen at the end of the file
11297   // and, because of the two phase lookup, this function is called with at
11298   // decl in the middle of a decl chain. We loop to maintain the invariant
11299   // that once a decl is used, all decls after it are also used.
11300   for (FunctionDecl *F = Func->getMostRecentDecl();; F = F->getPreviousDecl()) {
11301     F->markUsed(Context);
11302     if (F == Func)
11303       break;
11304   }
11305 }
11306 
11307 static void
11308 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
11309                                    VarDecl *var, DeclContext *DC) {
11310   DeclContext *VarDC = var->getDeclContext();
11311 
11312   //  If the parameter still belongs to the translation unit, then
11313   //  we're actually just using one parameter in the declaration of
11314   //  the next.
11315   if (isa<ParmVarDecl>(var) &&
11316       isa<TranslationUnitDecl>(VarDC))
11317     return;
11318 
11319   // For C code, don't diagnose about capture if we're not actually in code
11320   // right now; it's impossible to write a non-constant expression outside of
11321   // function context, so we'll get other (more useful) diagnostics later.
11322   //
11323   // For C++, things get a bit more nasty... it would be nice to suppress this
11324   // diagnostic for certain cases like using a local variable in an array bound
11325   // for a member of a local class, but the correct predicate is not obvious.
11326   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
11327     return;
11328 
11329   if (isa<CXXMethodDecl>(VarDC) &&
11330       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
11331     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda)
11332       << var->getIdentifier();
11333   } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) {
11334     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
11335       << var->getIdentifier() << fn->getDeclName();
11336   } else if (isa<BlockDecl>(VarDC)) {
11337     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block)
11338       << var->getIdentifier();
11339   } else {
11340     // FIXME: Is there any other context where a local variable can be
11341     // declared?
11342     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context)
11343       << var->getIdentifier();
11344   }
11345 
11346   S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
11347     << var->getIdentifier();
11348 
11349   // FIXME: Add additional diagnostic info about class etc. which prevents
11350   // capture.
11351 }
11352 
11353 
11354 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
11355                                       bool &SubCapturesAreNested,
11356                                       QualType &CaptureType,
11357                                       QualType &DeclRefType) {
11358    // Check whether we've already captured it.
11359   if (CSI->CaptureMap.count(Var)) {
11360     // If we found a capture, any subcaptures are nested.
11361     SubCapturesAreNested = true;
11362 
11363     // Retrieve the capture type for this variable.
11364     CaptureType = CSI->getCapture(Var).getCaptureType();
11365 
11366     // Compute the type of an expression that refers to this variable.
11367     DeclRefType = CaptureType.getNonReferenceType();
11368 
11369     const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var);
11370     if (Cap.isCopyCapture() &&
11371         !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable))
11372       DeclRefType.addConst();
11373     return true;
11374   }
11375   return false;
11376 }
11377 
11378 // Only block literals, captured statements, and lambda expressions can
11379 // capture; other scopes don't work.
11380 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
11381                                  SourceLocation Loc,
11382                                  const bool Diagnose, Sema &S) {
11383   if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
11384     return getLambdaAwareParentOfDeclContext(DC);
11385   else {
11386     if (Diagnose)
11387        diagnoseUncapturableValueReference(S, Loc, Var, DC);
11388   }
11389   return 0;
11390 }
11391 
11392 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
11393 // certain types of variables (unnamed, variably modified types etc.)
11394 // so check for eligibility.
11395 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
11396                                  SourceLocation Loc,
11397                                  const bool Diagnose, Sema &S) {
11398 
11399   bool IsBlock = isa<BlockScopeInfo>(CSI);
11400   bool IsLambda = isa<LambdaScopeInfo>(CSI);
11401 
11402   // Lambdas are not allowed to capture unnamed variables
11403   // (e.g. anonymous unions).
11404   // FIXME: The C++11 rule don't actually state this explicitly, but I'm
11405   // assuming that's the intent.
11406   if (IsLambda && !Var->getDeclName()) {
11407     if (Diagnose) {
11408       S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
11409       S.Diag(Var->getLocation(), diag::note_declared_at);
11410     }
11411     return false;
11412   }
11413 
11414   // Prohibit variably-modified types; they're difficult to deal with.
11415   if (Var->getType()->isVariablyModifiedType()) {
11416     if (Diagnose) {
11417       if (IsBlock)
11418         S.Diag(Loc, diag::err_ref_vm_type);
11419       else
11420         S.Diag(Loc, diag::err_lambda_capture_vm_type) << Var->getDeclName();
11421       S.Diag(Var->getLocation(), diag::note_previous_decl)
11422         << Var->getDeclName();
11423     }
11424     return false;
11425   }
11426   // Prohibit structs with flexible array members too.
11427   // We cannot capture what is in the tail end of the struct.
11428   if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
11429     if (VTTy->getDecl()->hasFlexibleArrayMember()) {
11430       if (Diagnose) {
11431         if (IsBlock)
11432           S.Diag(Loc, diag::err_ref_flexarray_type);
11433         else
11434           S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
11435             << Var->getDeclName();
11436         S.Diag(Var->getLocation(), diag::note_previous_decl)
11437           << Var->getDeclName();
11438       }
11439       return false;
11440     }
11441   }
11442   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
11443   // Lambdas and captured statements are not allowed to capture __block
11444   // variables; they don't support the expected semantics.
11445   if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
11446     if (Diagnose) {
11447       S.Diag(Loc, diag::err_capture_block_variable)
11448         << Var->getDeclName() << !IsLambda;
11449       S.Diag(Var->getLocation(), diag::note_previous_decl)
11450         << Var->getDeclName();
11451     }
11452     return false;
11453   }
11454 
11455   return true;
11456 }
11457 
11458 // Returns true if the capture by block was successful.
11459 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
11460                                  SourceLocation Loc,
11461                                  const bool BuildAndDiagnose,
11462                                  QualType &CaptureType,
11463                                  QualType &DeclRefType,
11464                                  const bool Nested,
11465                                  Sema &S) {
11466   Expr *CopyExpr = 0;
11467   bool ByRef = false;
11468 
11469   // Blocks are not allowed to capture arrays.
11470   if (CaptureType->isArrayType()) {
11471     if (BuildAndDiagnose) {
11472       S.Diag(Loc, diag::err_ref_array_type);
11473       S.Diag(Var->getLocation(), diag::note_previous_decl)
11474       << Var->getDeclName();
11475     }
11476     return false;
11477   }
11478 
11479   // Forbid the block-capture of autoreleasing variables.
11480   if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
11481     if (BuildAndDiagnose) {
11482       S.Diag(Loc, diag::err_arc_autoreleasing_capture)
11483         << /*block*/ 0;
11484       S.Diag(Var->getLocation(), diag::note_previous_decl)
11485         << Var->getDeclName();
11486     }
11487     return false;
11488   }
11489   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
11490   if (HasBlocksAttr || CaptureType->isReferenceType()) {
11491     // Block capture by reference does not change the capture or
11492     // declaration reference types.
11493     ByRef = true;
11494   } else {
11495     // Block capture by copy introduces 'const'.
11496     CaptureType = CaptureType.getNonReferenceType().withConst();
11497     DeclRefType = CaptureType;
11498 
11499     if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) {
11500       if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
11501         // The capture logic needs the destructor, so make sure we mark it.
11502         // Usually this is unnecessary because most local variables have
11503         // their destructors marked at declaration time, but parameters are
11504         // an exception because it's technically only the call site that
11505         // actually requires the destructor.
11506         if (isa<ParmVarDecl>(Var))
11507           S.FinalizeVarWithDestructor(Var, Record);
11508 
11509         // Enter a new evaluation context to insulate the copy
11510         // full-expression.
11511         EnterExpressionEvaluationContext scope(S, S.PotentiallyEvaluated);
11512 
11513         // According to the blocks spec, the capture of a variable from
11514         // the stack requires a const copy constructor.  This is not true
11515         // of the copy/move done to move a __block variable to the heap.
11516         Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested,
11517                                                   DeclRefType.withConst(),
11518                                                   VK_LValue, Loc);
11519 
11520         ExprResult Result
11521           = S.PerformCopyInitialization(
11522               InitializedEntity::InitializeBlock(Var->getLocation(),
11523                                                   CaptureType, false),
11524               Loc, S.Owned(DeclRef));
11525 
11526         // Build a full-expression copy expression if initialization
11527         // succeeded and used a non-trivial constructor.  Recover from
11528         // errors by pretending that the copy isn't necessary.
11529         if (!Result.isInvalid() &&
11530             !cast<CXXConstructExpr>(Result.get())->getConstructor()
11531                 ->isTrivial()) {
11532           Result = S.MaybeCreateExprWithCleanups(Result);
11533           CopyExpr = Result.take();
11534         }
11535       }
11536     }
11537   }
11538 
11539   // Actually capture the variable.
11540   if (BuildAndDiagnose)
11541     BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
11542                     SourceLocation(), CaptureType, CopyExpr);
11543 
11544   return true;
11545 
11546 }
11547 
11548 
11549 /// \brief Capture the given variable in the captured region.
11550 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
11551                                     VarDecl *Var,
11552                                     SourceLocation Loc,
11553                                     const bool BuildAndDiagnose,
11554                                     QualType &CaptureType,
11555                                     QualType &DeclRefType,
11556                                     const bool RefersToEnclosingLocal,
11557                                     Sema &S) {
11558 
11559   // By default, capture variables by reference.
11560   bool ByRef = true;
11561   // Using an LValue reference type is consistent with Lambdas (see below).
11562   CaptureType = S.Context.getLValueReferenceType(DeclRefType);
11563   Expr *CopyExpr = 0;
11564   if (BuildAndDiagnose) {
11565     // The current implementation assumes that all variables are captured
11566     // by references. Since there is no capture by copy, no expression evaluation
11567     // will be needed.
11568     //
11569     RecordDecl *RD = RSI->TheRecordDecl;
11570 
11571     FieldDecl *Field
11572       = FieldDecl::Create(S.Context, RD, Loc, Loc, 0, CaptureType,
11573                           S.Context.getTrivialTypeSourceInfo(CaptureType, Loc),
11574                           0, false, ICIS_NoInit);
11575     Field->setImplicit(true);
11576     Field->setAccess(AS_private);
11577     RD->addDecl(Field);
11578 
11579     CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToEnclosingLocal,
11580                                             DeclRefType, VK_LValue, Loc);
11581     Var->setReferenced(true);
11582     Var->markUsed(S.Context);
11583   }
11584 
11585   // Actually capture the variable.
11586   if (BuildAndDiagnose)
11587     RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToEnclosingLocal, Loc,
11588                     SourceLocation(), CaptureType, CopyExpr);
11589 
11590 
11591   return true;
11592 }
11593 
11594 /// \brief Create a field within the lambda class for the variable
11595 ///  being captured.  Handle Array captures.
11596 static ExprResult addAsFieldToClosureType(Sema &S,
11597                                  LambdaScopeInfo *LSI,
11598                                   VarDecl *Var, QualType FieldType,
11599                                   QualType DeclRefType,
11600                                   SourceLocation Loc,
11601                                   bool RefersToEnclosingLocal) {
11602   CXXRecordDecl *Lambda = LSI->Lambda;
11603 
11604   // Build the non-static data member.
11605   FieldDecl *Field
11606     = FieldDecl::Create(S.Context, Lambda, Loc, Loc, 0, FieldType,
11607                         S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
11608                         0, false, ICIS_NoInit);
11609   Field->setImplicit(true);
11610   Field->setAccess(AS_private);
11611   Lambda->addDecl(Field);
11612 
11613   // C++11 [expr.prim.lambda]p21:
11614   //   When the lambda-expression is evaluated, the entities that
11615   //   are captured by copy are used to direct-initialize each
11616   //   corresponding non-static data member of the resulting closure
11617   //   object. (For array members, the array elements are
11618   //   direct-initialized in increasing subscript order.) These
11619   //   initializations are performed in the (unspecified) order in
11620   //   which the non-static data members are declared.
11621 
11622   // Introduce a new evaluation context for the initialization, so
11623   // that temporaries introduced as part of the capture are retained
11624   // to be re-"exported" from the lambda expression itself.
11625   EnterExpressionEvaluationContext scope(S, Sema::PotentiallyEvaluated);
11626 
11627   // C++ [expr.prim.labda]p12:
11628   //   An entity captured by a lambda-expression is odr-used (3.2) in
11629   //   the scope containing the lambda-expression.
11630   Expr *Ref = new (S.Context) DeclRefExpr(Var, RefersToEnclosingLocal,
11631                                           DeclRefType, VK_LValue, Loc);
11632   Var->setReferenced(true);
11633   Var->markUsed(S.Context);
11634 
11635   // When the field has array type, create index variables for each
11636   // dimension of the array. We use these index variables to subscript
11637   // the source array, and other clients (e.g., CodeGen) will perform
11638   // the necessary iteration with these index variables.
11639   SmallVector<VarDecl *, 4> IndexVariables;
11640   QualType BaseType = FieldType;
11641   QualType SizeType = S.Context.getSizeType();
11642   LSI->ArrayIndexStarts.push_back(LSI->ArrayIndexVars.size());
11643   while (const ConstantArrayType *Array
11644                         = S.Context.getAsConstantArrayType(BaseType)) {
11645     // Create the iteration variable for this array index.
11646     IdentifierInfo *IterationVarName = 0;
11647     {
11648       SmallString<8> Str;
11649       llvm::raw_svector_ostream OS(Str);
11650       OS << "__i" << IndexVariables.size();
11651       IterationVarName = &S.Context.Idents.get(OS.str());
11652     }
11653     VarDecl *IterationVar
11654       = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
11655                         IterationVarName, SizeType,
11656                         S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
11657                         SC_None);
11658     IndexVariables.push_back(IterationVar);
11659     LSI->ArrayIndexVars.push_back(IterationVar);
11660 
11661     // Create a reference to the iteration variable.
11662     ExprResult IterationVarRef
11663       = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
11664     assert(!IterationVarRef.isInvalid() &&
11665            "Reference to invented variable cannot fail!");
11666     IterationVarRef = S.DefaultLvalueConversion(IterationVarRef.take());
11667     assert(!IterationVarRef.isInvalid() &&
11668            "Conversion of invented variable cannot fail!");
11669 
11670     // Subscript the array with this iteration variable.
11671     ExprResult Subscript = S.CreateBuiltinArraySubscriptExpr(
11672                              Ref, Loc, IterationVarRef.take(), Loc);
11673     if (Subscript.isInvalid()) {
11674       S.CleanupVarDeclMarking();
11675       S.DiscardCleanupsInEvaluationContext();
11676       return ExprError();
11677     }
11678 
11679     Ref = Subscript.take();
11680     BaseType = Array->getElementType();
11681   }
11682 
11683   // Construct the entity that we will be initializing. For an array, this
11684   // will be first element in the array, which may require several levels
11685   // of array-subscript entities.
11686   SmallVector<InitializedEntity, 4> Entities;
11687   Entities.reserve(1 + IndexVariables.size());
11688   Entities.push_back(
11689     InitializedEntity::InitializeLambdaCapture(Var, Field, Loc));
11690   for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
11691     Entities.push_back(InitializedEntity::InitializeElement(S.Context,
11692                                                             0,
11693                                                             Entities.back()));
11694 
11695   InitializationKind InitKind
11696     = InitializationKind::CreateDirect(Loc, Loc, Loc);
11697   InitializationSequence Init(S, Entities.back(), InitKind, Ref);
11698   ExprResult Result(true);
11699   if (!Init.Diagnose(S, Entities.back(), InitKind, Ref))
11700     Result = Init.Perform(S, Entities.back(), InitKind, Ref);
11701 
11702   // If this initialization requires any cleanups (e.g., due to a
11703   // default argument to a copy constructor), note that for the
11704   // lambda.
11705   if (S.ExprNeedsCleanups)
11706     LSI->ExprNeedsCleanups = true;
11707 
11708   // Exit the expression evaluation context used for the capture.
11709   S.CleanupVarDeclMarking();
11710   S.DiscardCleanupsInEvaluationContext();
11711   return Result;
11712 }
11713 
11714 
11715 
11716 /// \brief Capture the given variable in the lambda.
11717 static bool captureInLambda(LambdaScopeInfo *LSI,
11718                             VarDecl *Var,
11719                             SourceLocation Loc,
11720                             const bool BuildAndDiagnose,
11721                             QualType &CaptureType,
11722                             QualType &DeclRefType,
11723                             const bool RefersToEnclosingLocal,
11724                             const Sema::TryCaptureKind Kind,
11725                             SourceLocation EllipsisLoc,
11726                             const bool IsTopScope,
11727                             Sema &S) {
11728 
11729   // Determine whether we are capturing by reference or by value.
11730   bool ByRef = false;
11731   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
11732     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
11733   } else {
11734     ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
11735   }
11736 
11737   // Compute the type of the field that will capture this variable.
11738   if (ByRef) {
11739     // C++11 [expr.prim.lambda]p15:
11740     //   An entity is captured by reference if it is implicitly or
11741     //   explicitly captured but not captured by copy. It is
11742     //   unspecified whether additional unnamed non-static data
11743     //   members are declared in the closure type for entities
11744     //   captured by reference.
11745     //
11746     // FIXME: It is not clear whether we want to build an lvalue reference
11747     // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
11748     // to do the former, while EDG does the latter. Core issue 1249 will
11749     // clarify, but for now we follow GCC because it's a more permissive and
11750     // easily defensible position.
11751     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
11752   } else {
11753     // C++11 [expr.prim.lambda]p14:
11754     //   For each entity captured by copy, an unnamed non-static
11755     //   data member is declared in the closure type. The
11756     //   declaration order of these members is unspecified. The type
11757     //   of such a data member is the type of the corresponding
11758     //   captured entity if the entity is not a reference to an
11759     //   object, or the referenced type otherwise. [Note: If the
11760     //   captured entity is a reference to a function, the
11761     //   corresponding data member is also a reference to a
11762     //   function. - end note ]
11763     if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
11764       if (!RefType->getPointeeType()->isFunctionType())
11765         CaptureType = RefType->getPointeeType();
11766     }
11767 
11768     // Forbid the lambda copy-capture of autoreleasing variables.
11769     if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
11770       if (BuildAndDiagnose) {
11771         S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
11772         S.Diag(Var->getLocation(), diag::note_previous_decl)
11773           << Var->getDeclName();
11774       }
11775       return false;
11776     }
11777 
11778     if (S.RequireNonAbstractType(Loc, CaptureType,
11779                                  diag::err_capture_of_abstract_type))
11780       return false;
11781   }
11782 
11783   // Capture this variable in the lambda.
11784   Expr *CopyExpr = 0;
11785   if (BuildAndDiagnose) {
11786     ExprResult Result = addAsFieldToClosureType(S, LSI, Var,
11787                                         CaptureType, DeclRefType, Loc,
11788                                         RefersToEnclosingLocal);
11789     if (!Result.isInvalid())
11790       CopyExpr = Result.take();
11791   }
11792 
11793   // Compute the type of a reference to this captured variable.
11794   if (ByRef)
11795     DeclRefType = CaptureType.getNonReferenceType();
11796   else {
11797     // C++ [expr.prim.lambda]p5:
11798     //   The closure type for a lambda-expression has a public inline
11799     //   function call operator [...]. This function call operator is
11800     //   declared const (9.3.1) if and only if the lambda-expression’s
11801     //   parameter-declaration-clause is not followed by mutable.
11802     DeclRefType = CaptureType.getNonReferenceType();
11803     if (!LSI->Mutable && !CaptureType->isReferenceType())
11804       DeclRefType.addConst();
11805   }
11806 
11807   // Add the capture.
11808   if (BuildAndDiagnose)
11809     LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToEnclosingLocal,
11810                     Loc, EllipsisLoc, CaptureType, CopyExpr);
11811 
11812   return true;
11813 }
11814 
11815 
11816 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation ExprLoc,
11817                               TryCaptureKind Kind, SourceLocation EllipsisLoc,
11818                               bool BuildAndDiagnose,
11819                               QualType &CaptureType,
11820                               QualType &DeclRefType,
11821 						                const unsigned *const FunctionScopeIndexToStopAt) {
11822   bool Nested = false;
11823 
11824   DeclContext *DC = CurContext;
11825   const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
11826       ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
11827   // We need to sync up the Declaration Context with the
11828   // FunctionScopeIndexToStopAt
11829   if (FunctionScopeIndexToStopAt) {
11830     unsigned FSIndex = FunctionScopes.size() - 1;
11831     while (FSIndex != MaxFunctionScopesIndex) {
11832       DC = getLambdaAwareParentOfDeclContext(DC);
11833       --FSIndex;
11834     }
11835   }
11836 
11837 
11838   // If the variable is declared in the current context (and is not an
11839   // init-capture), there is no need to capture it.
11840   if (!Var->isInitCapture() && Var->getDeclContext() == DC) return true;
11841   if (!Var->hasLocalStorage()) return true;
11842 
11843   // Walk up the stack to determine whether we can capture the variable,
11844   // performing the "simple" checks that don't depend on type. We stop when
11845   // we've either hit the declared scope of the variable or find an existing
11846   // capture of that variable.  We start from the innermost capturing-entity
11847   // (the DC) and ensure that all intervening capturing-entities
11848   // (blocks/lambdas etc.) between the innermost capturer and the variable`s
11849   // declcontext can either capture the variable or have already captured
11850   // the variable.
11851   CaptureType = Var->getType();
11852   DeclRefType = CaptureType.getNonReferenceType();
11853   bool Explicit = (Kind != TryCapture_Implicit);
11854   unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
11855   do {
11856     // Only block literals, captured statements, and lambda expressions can
11857     // capture; other scopes don't work.
11858     DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
11859                                                               ExprLoc,
11860                                                               BuildAndDiagnose,
11861                                                               *this);
11862     if (!ParentDC) return true;
11863 
11864     FunctionScopeInfo  *FSI = FunctionScopes[FunctionScopesIndex];
11865     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
11866 
11867 
11868     // Check whether we've already captured it.
11869     if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
11870                                              DeclRefType))
11871       break;
11872     // If we are instantiating a generic lambda call operator body,
11873     // we do not want to capture new variables.  What was captured
11874     // during either a lambdas transformation or initial parsing
11875     // should be used.
11876     if (isGenericLambdaCallOperatorSpecialization(DC)) {
11877       if (BuildAndDiagnose) {
11878         LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
11879         if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
11880           Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
11881           Diag(Var->getLocation(), diag::note_previous_decl)
11882              << Var->getDeclName();
11883           Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl);
11884         } else
11885           diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
11886       }
11887       return true;
11888     }
11889     // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
11890     // certain types of variables (unnamed, variably modified types etc.)
11891     // so check for eligibility.
11892     if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this))
11893        return true;
11894 
11895     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
11896       // No capture-default, and this is not an explicit capture
11897       // so cannot capture this variable.
11898       if (BuildAndDiagnose) {
11899         Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
11900         Diag(Var->getLocation(), diag::note_previous_decl)
11901           << Var->getDeclName();
11902         Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
11903              diag::note_lambda_decl);
11904         // FIXME: If we error out because an outer lambda can not implicitly
11905         // capture a variable that an inner lambda explicitly captures, we
11906         // should have the inner lambda do the explicit capture - because
11907         // it makes for cleaner diagnostics later.  This would purely be done
11908         // so that the diagnostic does not misleadingly claim that a variable
11909         // can not be captured by a lambda implicitly even though it is captured
11910         // explicitly.  Suggestion:
11911         //  - create const bool VariableCaptureWasInitiallyExplicit = Explicit
11912         //    at the function head
11913         //  - cache the StartingDeclContext - this must be a lambda
11914         //  - captureInLambda in the innermost lambda the variable.
11915       }
11916       return true;
11917     }
11918 
11919     FunctionScopesIndex--;
11920     DC = ParentDC;
11921     Explicit = false;
11922   } while (!Var->getDeclContext()->Equals(DC));
11923 
11924   // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
11925   // computing the type of the capture at each step, checking type-specific
11926   // requirements, and adding captures if requested.
11927   // If the variable had already been captured previously, we start capturing
11928   // at the lambda nested within that one.
11929   for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
11930        ++I) {
11931     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
11932 
11933     if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
11934       if (!captureInBlock(BSI, Var, ExprLoc,
11935                           BuildAndDiagnose, CaptureType,
11936                           DeclRefType, Nested, *this))
11937         return true;
11938       Nested = true;
11939     } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
11940       if (!captureInCapturedRegion(RSI, Var, ExprLoc,
11941                                    BuildAndDiagnose, CaptureType,
11942                                    DeclRefType, Nested, *this))
11943         return true;
11944       Nested = true;
11945     } else {
11946       LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
11947       if (!captureInLambda(LSI, Var, ExprLoc,
11948                            BuildAndDiagnose, CaptureType,
11949                            DeclRefType, Nested, Kind, EllipsisLoc,
11950                             /*IsTopScope*/I == N - 1, *this))
11951         return true;
11952       Nested = true;
11953     }
11954   }
11955   return false;
11956 }
11957 
11958 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
11959                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {
11960   QualType CaptureType;
11961   QualType DeclRefType;
11962   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
11963                             /*BuildAndDiagnose=*/true, CaptureType,
11964                             DeclRefType, 0);
11965 }
11966 
11967 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
11968   QualType CaptureType;
11969   QualType DeclRefType;
11970 
11971   // Determine whether we can capture this variable.
11972   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
11973                          /*BuildAndDiagnose=*/false, CaptureType,
11974                          DeclRefType, 0))
11975     return QualType();
11976 
11977   return DeclRefType;
11978 }
11979 
11980 
11981 
11982 // If either the type of the variable or the initializer is dependent,
11983 // return false. Otherwise, determine whether the variable is a constant
11984 // expression. Use this if you need to know if a variable that might or
11985 // might not be dependent is truly a constant expression.
11986 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var,
11987     ASTContext &Context) {
11988 
11989   if (Var->getType()->isDependentType())
11990     return false;
11991   const VarDecl *DefVD = 0;
11992   Var->getAnyInitializer(DefVD);
11993   if (!DefVD)
11994     return false;
11995   EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
11996   Expr *Init = cast<Expr>(Eval->Value);
11997   if (Init->isValueDependent())
11998     return false;
11999   return IsVariableAConstantExpression(Var, Context);
12000 }
12001 
12002 
12003 void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
12004   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
12005   // an object that satisfies the requirements for appearing in a
12006   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
12007   // is immediately applied."  This function handles the lvalue-to-rvalue
12008   // conversion part.
12009   MaybeODRUseExprs.erase(E->IgnoreParens());
12010 
12011   // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers
12012   // to a variable that is a constant expression, and if so, identify it as
12013   // a reference to a variable that does not involve an odr-use of that
12014   // variable.
12015   if (LambdaScopeInfo *LSI = getCurLambda()) {
12016     Expr *SansParensExpr = E->IgnoreParens();
12017     VarDecl *Var = 0;
12018     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr))
12019       Var = dyn_cast<VarDecl>(DRE->getFoundDecl());
12020     else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr))
12021       Var = dyn_cast<VarDecl>(ME->getMemberDecl());
12022 
12023     if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context))
12024       LSI->markVariableExprAsNonODRUsed(SansParensExpr);
12025   }
12026 }
12027 
12028 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
12029   if (!Res.isUsable())
12030     return Res;
12031 
12032   // If a constant-expression is a reference to a variable where we delay
12033   // deciding whether it is an odr-use, just assume we will apply the
12034   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
12035   // (a non-type template argument), we have special handling anyway.
12036   UpdateMarkingForLValueToRValue(Res.get());
12037   return Res;
12038 }
12039 
12040 void Sema::CleanupVarDeclMarking() {
12041   for (llvm::SmallPtrSetIterator<Expr*> i = MaybeODRUseExprs.begin(),
12042                                         e = MaybeODRUseExprs.end();
12043        i != e; ++i) {
12044     VarDecl *Var;
12045     SourceLocation Loc;
12046     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(*i)) {
12047       Var = cast<VarDecl>(DRE->getDecl());
12048       Loc = DRE->getLocation();
12049     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(*i)) {
12050       Var = cast<VarDecl>(ME->getMemberDecl());
12051       Loc = ME->getMemberLoc();
12052     } else {
12053       llvm_unreachable("Unexpcted expression");
12054     }
12055 
12056     MarkVarDeclODRUsed(Var, Loc, *this, /*MaxFunctionScopeIndex Pointer*/ 0);
12057   }
12058 
12059   MaybeODRUseExprs.clear();
12060 }
12061 
12062 
12063 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
12064                                     VarDecl *Var, Expr *E) {
12065   assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) &&
12066          "Invalid Expr argument to DoMarkVarDeclReferenced");
12067   Var->setReferenced();
12068 
12069   // If the context is not PotentiallyEvaluated and not Unevaluated
12070   // (i.e PotentiallyEvaluatedIfUsed) do not bother to consider variables
12071   // in this context for odr-use unless we are within a lambda.
12072   // If we don't know whether the context is potentially evaluated or not
12073   // (for e.g., if we're in a generic lambda), we want to add a potential
12074   // capture and eventually analyze for odr-use.
12075   // We should also be able to analyze certain constructs in a non-generic
12076   // lambda setting for potential odr-use and capture violation:
12077   // template<class T> void foo(T t) {
12078   //    auto L = [](int i) { return t; };
12079   // }
12080   //
12081   if (!IsPotentiallyEvaluatedContext(SemaRef)) {
12082 
12083     if (SemaRef.isUnevaluatedContext()) return;
12084 
12085     const bool refersToEnclosingScope =
12086       (SemaRef.CurContext != Var->getDeclContext() &&
12087            Var->getDeclContext()->isFunctionOrMethod());
12088     if (!refersToEnclosingScope) return;
12089 
12090     if (LambdaScopeInfo *const LSI = SemaRef.getCurLambda()) {
12091       // If a variable could potentially be odr-used, defer marking it so
12092       // until we finish analyzing the full expression for any lvalue-to-rvalue
12093       // or discarded value conversions that would obviate odr-use.
12094       // Add it to the list of potential captures that will be analyzed
12095       // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
12096       // unless the variable is a reference that was initialized by a constant
12097       // expression (this will never need to be captured or odr-used).
12098       const bool IsConstantExpr = IsVariableNonDependentAndAConstantExpression(
12099           Var, SemaRef.Context);
12100       assert(E && "Capture variable should be used in an expression.");
12101       if (!IsConstantExpr || !Var->getType()->isReferenceType())
12102         LSI->addPotentialCapture(E->IgnoreParens());
12103     }
12104     return;
12105   }
12106 
12107   VarTemplateSpecializationDecl *VarSpec =
12108       dyn_cast<VarTemplateSpecializationDecl>(Var);
12109   assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
12110          "Can't instantiate a partial template specialization.");
12111 
12112   // Implicit instantiation of static data members, static data member
12113   // templates of class templates, and variable template specializations.
12114   // Delay instantiations of variable templates, except for those
12115   // that could be used in a constant expression.
12116   TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
12117   if (isTemplateInstantiation(TSK)) {
12118     bool TryInstantiating = TSK == TSK_ImplicitInstantiation;
12119 
12120     if (TryInstantiating && !isa<VarTemplateSpecializationDecl>(Var)) {
12121       if (Var->getPointOfInstantiation().isInvalid()) {
12122         // This is a modification of an existing AST node. Notify listeners.
12123         if (ASTMutationListener *L = SemaRef.getASTMutationListener())
12124           L->StaticDataMemberInstantiated(Var);
12125       } else if (!Var->isUsableInConstantExpressions(SemaRef.Context))
12126         // Don't bother trying to instantiate it again, unless we might need
12127         // its initializer before we get to the end of the TU.
12128         TryInstantiating = false;
12129     }
12130 
12131     if (Var->getPointOfInstantiation().isInvalid())
12132       Var->setTemplateSpecializationKind(TSK, Loc);
12133 
12134     if (TryInstantiating) {
12135       SourceLocation PointOfInstantiation = Var->getPointOfInstantiation();
12136       bool InstantiationDependent = false;
12137       bool IsNonDependent =
12138           VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
12139                         VarSpec->getTemplateArgsInfo(), InstantiationDependent)
12140                   : true;
12141 
12142       // Do not instantiate specializations that are still type-dependent.
12143       if (IsNonDependent) {
12144         if (Var->isUsableInConstantExpressions(SemaRef.Context)) {
12145           // Do not defer instantiations of variables which could be used in a
12146           // constant expression.
12147           SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
12148         } else {
12149           SemaRef.PendingInstantiations
12150               .push_back(std::make_pair(Var, PointOfInstantiation));
12151         }
12152       }
12153     }
12154   }
12155   // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies
12156   // the requirements for appearing in a constant expression (5.19) and, if
12157   // it is an object, the lvalue-to-rvalue conversion (4.1)
12158   // is immediately applied."  We check the first part here, and
12159   // Sema::UpdateMarkingForLValueToRValue deals with the second part.
12160   // Note that we use the C++11 definition everywhere because nothing in
12161   // C++03 depends on whether we get the C++03 version correct. The second
12162   // part does not apply to references, since they are not objects.
12163   if (E && IsVariableAConstantExpression(Var, SemaRef.Context)) {
12164     // A reference initialized by a constant expression can never be
12165     // odr-used, so simply ignore it.
12166     // But a non-reference might get odr-used if it doesn't undergo
12167     // an lvalue-to-rvalue or is discarded, so track it.
12168     if (!Var->getType()->isReferenceType())
12169       SemaRef.MaybeODRUseExprs.insert(E);
12170   }
12171   else
12172     MarkVarDeclODRUsed(Var, Loc, SemaRef, /*MaxFunctionScopeIndex ptr*/0);
12173 }
12174 
12175 /// \brief Mark a variable referenced, and check whether it is odr-used
12176 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
12177 /// used directly for normal expressions referring to VarDecl.
12178 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
12179   DoMarkVarDeclReferenced(*this, Loc, Var, 0);
12180 }
12181 
12182 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
12183                                Decl *D, Expr *E, bool OdrUse) {
12184   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
12185     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
12186     return;
12187   }
12188 
12189   SemaRef.MarkAnyDeclReferenced(Loc, D, OdrUse);
12190 
12191   // If this is a call to a method via a cast, also mark the method in the
12192   // derived class used in case codegen can devirtualize the call.
12193   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
12194   if (!ME)
12195     return;
12196   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
12197   if (!MD)
12198     return;
12199   const Expr *Base = ME->getBase();
12200   const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
12201   if (!MostDerivedClassDecl)
12202     return;
12203   CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl);
12204   if (!DM || DM->isPure())
12205     return;
12206   SemaRef.MarkAnyDeclReferenced(Loc, DM, OdrUse);
12207 }
12208 
12209 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
12210 void Sema::MarkDeclRefReferenced(DeclRefExpr *E) {
12211   // TODO: update this with DR# once a defect report is filed.
12212   // C++11 defect. The address of a pure member should not be an ODR use, even
12213   // if it's a qualified reference.
12214   bool OdrUse = true;
12215   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
12216     if (Method->isVirtual())
12217       OdrUse = false;
12218   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
12219 }
12220 
12221 /// \brief Perform reference-marking and odr-use handling for a MemberExpr.
12222 void Sema::MarkMemberReferenced(MemberExpr *E) {
12223   // C++11 [basic.def.odr]p2:
12224   //   A non-overloaded function whose name appears as a potentially-evaluated
12225   //   expression or a member of a set of candidate functions, if selected by
12226   //   overload resolution when referred to from a potentially-evaluated
12227   //   expression, is odr-used, unless it is a pure virtual function and its
12228   //   name is not explicitly qualified.
12229   bool OdrUse = true;
12230   if (!E->hasQualifier()) {
12231     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
12232       if (Method->isPure())
12233         OdrUse = false;
12234   }
12235   SourceLocation Loc = E->getMemberLoc().isValid() ?
12236                             E->getMemberLoc() : E->getLocStart();
12237   MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, OdrUse);
12238 }
12239 
12240 /// \brief Perform marking for a reference to an arbitrary declaration.  It
12241 /// marks the declaration referenced, and performs odr-use checking for functions
12242 /// and variables. This method should not be used when building an normal
12243 /// expression which refers to a variable.
12244 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool OdrUse) {
12245   if (OdrUse) {
12246     if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
12247       MarkVariableReferenced(Loc, VD);
12248       return;
12249     }
12250     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
12251       MarkFunctionReferenced(Loc, FD);
12252       return;
12253     }
12254   }
12255   D->setReferenced();
12256 }
12257 
12258 namespace {
12259   // Mark all of the declarations referenced
12260   // FIXME: Not fully implemented yet! We need to have a better understanding
12261   // of when we're entering
12262   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
12263     Sema &S;
12264     SourceLocation Loc;
12265 
12266   public:
12267     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
12268 
12269     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
12270 
12271     bool TraverseTemplateArgument(const TemplateArgument &Arg);
12272     bool TraverseRecordType(RecordType *T);
12273   };
12274 }
12275 
12276 bool MarkReferencedDecls::TraverseTemplateArgument(
12277   const TemplateArgument &Arg) {
12278   if (Arg.getKind() == TemplateArgument::Declaration) {
12279     if (Decl *D = Arg.getAsDecl())
12280       S.MarkAnyDeclReferenced(Loc, D, true);
12281   }
12282 
12283   return Inherited::TraverseTemplateArgument(Arg);
12284 }
12285 
12286 bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
12287   if (ClassTemplateSpecializationDecl *Spec
12288                   = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
12289     const TemplateArgumentList &Args = Spec->getTemplateArgs();
12290     return TraverseTemplateArguments(Args.data(), Args.size());
12291   }
12292 
12293   return true;
12294 }
12295 
12296 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
12297   MarkReferencedDecls Marker(*this, Loc);
12298   Marker.TraverseType(Context.getCanonicalType(T));
12299 }
12300 
12301 namespace {
12302   /// \brief Helper class that marks all of the declarations referenced by
12303   /// potentially-evaluated subexpressions as "referenced".
12304   class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
12305     Sema &S;
12306     bool SkipLocalVariables;
12307 
12308   public:
12309     typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
12310 
12311     EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
12312       : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
12313 
12314     void VisitDeclRefExpr(DeclRefExpr *E) {
12315       // If we were asked not to visit local variables, don't.
12316       if (SkipLocalVariables) {
12317         if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
12318           if (VD->hasLocalStorage())
12319             return;
12320       }
12321 
12322       S.MarkDeclRefReferenced(E);
12323     }
12324 
12325     void VisitMemberExpr(MemberExpr *E) {
12326       S.MarkMemberReferenced(E);
12327       Inherited::VisitMemberExpr(E);
12328     }
12329 
12330     void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
12331       S.MarkFunctionReferenced(E->getLocStart(),
12332             const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
12333       Visit(E->getSubExpr());
12334     }
12335 
12336     void VisitCXXNewExpr(CXXNewExpr *E) {
12337       if (E->getOperatorNew())
12338         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
12339       if (E->getOperatorDelete())
12340         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
12341       Inherited::VisitCXXNewExpr(E);
12342     }
12343 
12344     void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
12345       if (E->getOperatorDelete())
12346         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
12347       QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
12348       if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
12349         CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
12350         S.MarkFunctionReferenced(E->getLocStart(),
12351                                     S.LookupDestructor(Record));
12352       }
12353 
12354       Inherited::VisitCXXDeleteExpr(E);
12355     }
12356 
12357     void VisitCXXConstructExpr(CXXConstructExpr *E) {
12358       S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
12359       Inherited::VisitCXXConstructExpr(E);
12360     }
12361 
12362     void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
12363       Visit(E->getExpr());
12364     }
12365 
12366     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
12367       Inherited::VisitImplicitCastExpr(E);
12368 
12369       if (E->getCastKind() == CK_LValueToRValue)
12370         S.UpdateMarkingForLValueToRValue(E->getSubExpr());
12371     }
12372   };
12373 }
12374 
12375 /// \brief Mark any declarations that appear within this expression or any
12376 /// potentially-evaluated subexpressions as "referenced".
12377 ///
12378 /// \param SkipLocalVariables If true, don't mark local variables as
12379 /// 'referenced'.
12380 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
12381                                             bool SkipLocalVariables) {
12382   EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
12383 }
12384 
12385 /// \brief Emit a diagnostic that describes an effect on the run-time behavior
12386 /// of the program being compiled.
12387 ///
12388 /// This routine emits the given diagnostic when the code currently being
12389 /// type-checked is "potentially evaluated", meaning that there is a
12390 /// possibility that the code will actually be executable. Code in sizeof()
12391 /// expressions, code used only during overload resolution, etc., are not
12392 /// potentially evaluated. This routine will suppress such diagnostics or,
12393 /// in the absolutely nutty case of potentially potentially evaluated
12394 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
12395 /// later.
12396 ///
12397 /// This routine should be used for all diagnostics that describe the run-time
12398 /// behavior of a program, such as passing a non-POD value through an ellipsis.
12399 /// Failure to do so will likely result in spurious diagnostics or failures
12400 /// during overload resolution or within sizeof/alignof/typeof/typeid.
12401 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
12402                                const PartialDiagnostic &PD) {
12403   switch (ExprEvalContexts.back().Context) {
12404   case Unevaluated:
12405   case UnevaluatedAbstract:
12406     // The argument will never be evaluated, so don't complain.
12407     break;
12408 
12409   case ConstantEvaluated:
12410     // Relevant diagnostics should be produced by constant evaluation.
12411     break;
12412 
12413   case PotentiallyEvaluated:
12414   case PotentiallyEvaluatedIfUsed:
12415     if (Statement && getCurFunctionOrMethodDecl()) {
12416       FunctionScopes.back()->PossiblyUnreachableDiags.
12417         push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
12418     }
12419     else
12420       Diag(Loc, PD);
12421 
12422     return true;
12423   }
12424 
12425   return false;
12426 }
12427 
12428 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
12429                                CallExpr *CE, FunctionDecl *FD) {
12430   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
12431     return false;
12432 
12433   // If we're inside a decltype's expression, don't check for a valid return
12434   // type or construct temporaries until we know whether this is the last call.
12435   if (ExprEvalContexts.back().IsDecltype) {
12436     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
12437     return false;
12438   }
12439 
12440   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
12441     FunctionDecl *FD;
12442     CallExpr *CE;
12443 
12444   public:
12445     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
12446       : FD(FD), CE(CE) { }
12447 
12448     virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
12449       if (!FD) {
12450         S.Diag(Loc, diag::err_call_incomplete_return)
12451           << T << CE->getSourceRange();
12452         return;
12453       }
12454 
12455       S.Diag(Loc, diag::err_call_function_incomplete_return)
12456         << CE->getSourceRange() << FD->getDeclName() << T;
12457       S.Diag(FD->getLocation(),
12458              diag::note_function_with_incomplete_return_type_declared_here)
12459         << FD->getDeclName();
12460     }
12461   } Diagnoser(FD, CE);
12462 
12463   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
12464     return true;
12465 
12466   return false;
12467 }
12468 
12469 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
12470 // will prevent this condition from triggering, which is what we want.
12471 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
12472   SourceLocation Loc;
12473 
12474   unsigned diagnostic = diag::warn_condition_is_assignment;
12475   bool IsOrAssign = false;
12476 
12477   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
12478     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
12479       return;
12480 
12481     IsOrAssign = Op->getOpcode() == BO_OrAssign;
12482 
12483     // Greylist some idioms by putting them into a warning subcategory.
12484     if (ObjCMessageExpr *ME
12485           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
12486       Selector Sel = ME->getSelector();
12487 
12488       // self = [<foo> init...]
12489       if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
12490         diagnostic = diag::warn_condition_is_idiomatic_assignment;
12491 
12492       // <foo> = [<bar> nextObject]
12493       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
12494         diagnostic = diag::warn_condition_is_idiomatic_assignment;
12495     }
12496 
12497     Loc = Op->getOperatorLoc();
12498   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
12499     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
12500       return;
12501 
12502     IsOrAssign = Op->getOperator() == OO_PipeEqual;
12503     Loc = Op->getOperatorLoc();
12504   } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
12505     return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
12506   else {
12507     // Not an assignment.
12508     return;
12509   }
12510 
12511   Diag(Loc, diagnostic) << E->getSourceRange();
12512 
12513   SourceLocation Open = E->getLocStart();
12514   SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
12515   Diag(Loc, diag::note_condition_assign_silence)
12516         << FixItHint::CreateInsertion(Open, "(")
12517         << FixItHint::CreateInsertion(Close, ")");
12518 
12519   if (IsOrAssign)
12520     Diag(Loc, diag::note_condition_or_assign_to_comparison)
12521       << FixItHint::CreateReplacement(Loc, "!=");
12522   else
12523     Diag(Loc, diag::note_condition_assign_to_comparison)
12524       << FixItHint::CreateReplacement(Loc, "==");
12525 }
12526 
12527 /// \brief Redundant parentheses over an equality comparison can indicate
12528 /// that the user intended an assignment used as condition.
12529 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
12530   // Don't warn if the parens came from a macro.
12531   SourceLocation parenLoc = ParenE->getLocStart();
12532   if (parenLoc.isInvalid() || parenLoc.isMacroID())
12533     return;
12534   // Don't warn for dependent expressions.
12535   if (ParenE->isTypeDependent())
12536     return;
12537 
12538   Expr *E = ParenE->IgnoreParens();
12539 
12540   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
12541     if (opE->getOpcode() == BO_EQ &&
12542         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
12543                                                            == Expr::MLV_Valid) {
12544       SourceLocation Loc = opE->getOperatorLoc();
12545 
12546       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
12547       SourceRange ParenERange = ParenE->getSourceRange();
12548       Diag(Loc, diag::note_equality_comparison_silence)
12549         << FixItHint::CreateRemoval(ParenERange.getBegin())
12550         << FixItHint::CreateRemoval(ParenERange.getEnd());
12551       Diag(Loc, diag::note_equality_comparison_to_assign)
12552         << FixItHint::CreateReplacement(Loc, "=");
12553     }
12554 }
12555 
12556 ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
12557   DiagnoseAssignmentAsCondition(E);
12558   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
12559     DiagnoseEqualityWithExtraParens(parenE);
12560 
12561   ExprResult result = CheckPlaceholderExpr(E);
12562   if (result.isInvalid()) return ExprError();
12563   E = result.take();
12564 
12565   if (!E->isTypeDependent()) {
12566     if (getLangOpts().CPlusPlus)
12567       return CheckCXXBooleanCondition(E); // C++ 6.4p4
12568 
12569     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
12570     if (ERes.isInvalid())
12571       return ExprError();
12572     E = ERes.take();
12573 
12574     QualType T = E->getType();
12575     if (!T->isScalarType()) { // C99 6.8.4.1p1
12576       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
12577         << T << E->getSourceRange();
12578       return ExprError();
12579     }
12580   }
12581 
12582   return Owned(E);
12583 }
12584 
12585 ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
12586                                        Expr *SubExpr) {
12587   if (!SubExpr)
12588     return ExprError();
12589 
12590   return CheckBooleanCondition(SubExpr, Loc);
12591 }
12592 
12593 namespace {
12594   /// A visitor for rebuilding a call to an __unknown_any expression
12595   /// to have an appropriate type.
12596   struct RebuildUnknownAnyFunction
12597     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
12598 
12599     Sema &S;
12600 
12601     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
12602 
12603     ExprResult VisitStmt(Stmt *S) {
12604       llvm_unreachable("unexpected statement!");
12605     }
12606 
12607     ExprResult VisitExpr(Expr *E) {
12608       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
12609         << E->getSourceRange();
12610       return ExprError();
12611     }
12612 
12613     /// Rebuild an expression which simply semantically wraps another
12614     /// expression which it shares the type and value kind of.
12615     template <class T> ExprResult rebuildSugarExpr(T *E) {
12616       ExprResult SubResult = Visit(E->getSubExpr());
12617       if (SubResult.isInvalid()) return ExprError();
12618 
12619       Expr *SubExpr = SubResult.take();
12620       E->setSubExpr(SubExpr);
12621       E->setType(SubExpr->getType());
12622       E->setValueKind(SubExpr->getValueKind());
12623       assert(E->getObjectKind() == OK_Ordinary);
12624       return E;
12625     }
12626 
12627     ExprResult VisitParenExpr(ParenExpr *E) {
12628       return rebuildSugarExpr(E);
12629     }
12630 
12631     ExprResult VisitUnaryExtension(UnaryOperator *E) {
12632       return rebuildSugarExpr(E);
12633     }
12634 
12635     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
12636       ExprResult SubResult = Visit(E->getSubExpr());
12637       if (SubResult.isInvalid()) return ExprError();
12638 
12639       Expr *SubExpr = SubResult.take();
12640       E->setSubExpr(SubExpr);
12641       E->setType(S.Context.getPointerType(SubExpr->getType()));
12642       assert(E->getValueKind() == VK_RValue);
12643       assert(E->getObjectKind() == OK_Ordinary);
12644       return E;
12645     }
12646 
12647     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
12648       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
12649 
12650       E->setType(VD->getType());
12651 
12652       assert(E->getValueKind() == VK_RValue);
12653       if (S.getLangOpts().CPlusPlus &&
12654           !(isa<CXXMethodDecl>(VD) &&
12655             cast<CXXMethodDecl>(VD)->isInstance()))
12656         E->setValueKind(VK_LValue);
12657 
12658       return E;
12659     }
12660 
12661     ExprResult VisitMemberExpr(MemberExpr *E) {
12662       return resolveDecl(E, E->getMemberDecl());
12663     }
12664 
12665     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
12666       return resolveDecl(E, E->getDecl());
12667     }
12668   };
12669 }
12670 
12671 /// Given a function expression of unknown-any type, try to rebuild it
12672 /// to have a function type.
12673 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
12674   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
12675   if (Result.isInvalid()) return ExprError();
12676   return S.DefaultFunctionArrayConversion(Result.take());
12677 }
12678 
12679 namespace {
12680   /// A visitor for rebuilding an expression of type __unknown_anytype
12681   /// into one which resolves the type directly on the referring
12682   /// expression.  Strict preservation of the original source
12683   /// structure is not a goal.
12684   struct RebuildUnknownAnyExpr
12685     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
12686 
12687     Sema &S;
12688 
12689     /// The current destination type.
12690     QualType DestType;
12691 
12692     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
12693       : S(S), DestType(CastType) {}
12694 
12695     ExprResult VisitStmt(Stmt *S) {
12696       llvm_unreachable("unexpected statement!");
12697     }
12698 
12699     ExprResult VisitExpr(Expr *E) {
12700       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
12701         << E->getSourceRange();
12702       return ExprError();
12703     }
12704 
12705     ExprResult VisitCallExpr(CallExpr *E);
12706     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
12707 
12708     /// Rebuild an expression which simply semantically wraps another
12709     /// expression which it shares the type and value kind of.
12710     template <class T> ExprResult rebuildSugarExpr(T *E) {
12711       ExprResult SubResult = Visit(E->getSubExpr());
12712       if (SubResult.isInvalid()) return ExprError();
12713       Expr *SubExpr = SubResult.take();
12714       E->setSubExpr(SubExpr);
12715       E->setType(SubExpr->getType());
12716       E->setValueKind(SubExpr->getValueKind());
12717       assert(E->getObjectKind() == OK_Ordinary);
12718       return E;
12719     }
12720 
12721     ExprResult VisitParenExpr(ParenExpr *E) {
12722       return rebuildSugarExpr(E);
12723     }
12724 
12725     ExprResult VisitUnaryExtension(UnaryOperator *E) {
12726       return rebuildSugarExpr(E);
12727     }
12728 
12729     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
12730       const PointerType *Ptr = DestType->getAs<PointerType>();
12731       if (!Ptr) {
12732         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
12733           << E->getSourceRange();
12734         return ExprError();
12735       }
12736       assert(E->getValueKind() == VK_RValue);
12737       assert(E->getObjectKind() == OK_Ordinary);
12738       E->setType(DestType);
12739 
12740       // Build the sub-expression as if it were an object of the pointee type.
12741       DestType = Ptr->getPointeeType();
12742       ExprResult SubResult = Visit(E->getSubExpr());
12743       if (SubResult.isInvalid()) return ExprError();
12744       E->setSubExpr(SubResult.take());
12745       return E;
12746     }
12747 
12748     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
12749 
12750     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
12751 
12752     ExprResult VisitMemberExpr(MemberExpr *E) {
12753       return resolveDecl(E, E->getMemberDecl());
12754     }
12755 
12756     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
12757       return resolveDecl(E, E->getDecl());
12758     }
12759   };
12760 }
12761 
12762 /// Rebuilds a call expression which yielded __unknown_anytype.
12763 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
12764   Expr *CalleeExpr = E->getCallee();
12765 
12766   enum FnKind {
12767     FK_MemberFunction,
12768     FK_FunctionPointer,
12769     FK_BlockPointer
12770   };
12771 
12772   FnKind Kind;
12773   QualType CalleeType = CalleeExpr->getType();
12774   if (CalleeType == S.Context.BoundMemberTy) {
12775     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
12776     Kind = FK_MemberFunction;
12777     CalleeType = Expr::findBoundMemberType(CalleeExpr);
12778   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
12779     CalleeType = Ptr->getPointeeType();
12780     Kind = FK_FunctionPointer;
12781   } else {
12782     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
12783     Kind = FK_BlockPointer;
12784   }
12785   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
12786 
12787   // Verify that this is a legal result type of a function.
12788   if (DestType->isArrayType() || DestType->isFunctionType()) {
12789     unsigned diagID = diag::err_func_returning_array_function;
12790     if (Kind == FK_BlockPointer)
12791       diagID = diag::err_block_returning_array_function;
12792 
12793     S.Diag(E->getExprLoc(), diagID)
12794       << DestType->isFunctionType() << DestType;
12795     return ExprError();
12796   }
12797 
12798   // Otherwise, go ahead and set DestType as the call's result.
12799   E->setType(DestType.getNonLValueExprType(S.Context));
12800   E->setValueKind(Expr::getValueKindForType(DestType));
12801   assert(E->getObjectKind() == OK_Ordinary);
12802 
12803   // Rebuild the function type, replacing the result type with DestType.
12804   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
12805   if (Proto) {
12806     // __unknown_anytype(...) is a special case used by the debugger when
12807     // it has no idea what a function's signature is.
12808     //
12809     // We want to build this call essentially under the K&R
12810     // unprototyped rules, but making a FunctionNoProtoType in C++
12811     // would foul up all sorts of assumptions.  However, we cannot
12812     // simply pass all arguments as variadic arguments, nor can we
12813     // portably just call the function under a non-variadic type; see
12814     // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
12815     // However, it turns out that in practice it is generally safe to
12816     // call a function declared as "A foo(B,C,D);" under the prototype
12817     // "A foo(B,C,D,...);".  The only known exception is with the
12818     // Windows ABI, where any variadic function is implicitly cdecl
12819     // regardless of its normal CC.  Therefore we change the parameter
12820     // types to match the types of the arguments.
12821     //
12822     // This is a hack, but it is far superior to moving the
12823     // corresponding target-specific code from IR-gen to Sema/AST.
12824 
12825     ArrayRef<QualType> ParamTypes = Proto->getArgTypes();
12826     SmallVector<QualType, 8> ArgTypes;
12827     if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
12828       ArgTypes.reserve(E->getNumArgs());
12829       for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
12830         Expr *Arg = E->getArg(i);
12831         QualType ArgType = Arg->getType();
12832         if (E->isLValue()) {
12833           ArgType = S.Context.getLValueReferenceType(ArgType);
12834         } else if (E->isXValue()) {
12835           ArgType = S.Context.getRValueReferenceType(ArgType);
12836         }
12837         ArgTypes.push_back(ArgType);
12838       }
12839       ParamTypes = ArgTypes;
12840     }
12841     DestType = S.Context.getFunctionType(DestType, ParamTypes,
12842                                          Proto->getExtProtoInfo());
12843   } else {
12844     DestType = S.Context.getFunctionNoProtoType(DestType,
12845                                                 FnType->getExtInfo());
12846   }
12847 
12848   // Rebuild the appropriate pointer-to-function type.
12849   switch (Kind) {
12850   case FK_MemberFunction:
12851     // Nothing to do.
12852     break;
12853 
12854   case FK_FunctionPointer:
12855     DestType = S.Context.getPointerType(DestType);
12856     break;
12857 
12858   case FK_BlockPointer:
12859     DestType = S.Context.getBlockPointerType(DestType);
12860     break;
12861   }
12862 
12863   // Finally, we can recurse.
12864   ExprResult CalleeResult = Visit(CalleeExpr);
12865   if (!CalleeResult.isUsable()) return ExprError();
12866   E->setCallee(CalleeResult.take());
12867 
12868   // Bind a temporary if necessary.
12869   return S.MaybeBindToTemporary(E);
12870 }
12871 
12872 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
12873   // Verify that this is a legal result type of a call.
12874   if (DestType->isArrayType() || DestType->isFunctionType()) {
12875     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
12876       << DestType->isFunctionType() << DestType;
12877     return ExprError();
12878   }
12879 
12880   // Rewrite the method result type if available.
12881   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
12882     assert(Method->getResultType() == S.Context.UnknownAnyTy);
12883     Method->setResultType(DestType);
12884   }
12885 
12886   // Change the type of the message.
12887   E->setType(DestType.getNonReferenceType());
12888   E->setValueKind(Expr::getValueKindForType(DestType));
12889 
12890   return S.MaybeBindToTemporary(E);
12891 }
12892 
12893 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
12894   // The only case we should ever see here is a function-to-pointer decay.
12895   if (E->getCastKind() == CK_FunctionToPointerDecay) {
12896     assert(E->getValueKind() == VK_RValue);
12897     assert(E->getObjectKind() == OK_Ordinary);
12898 
12899     E->setType(DestType);
12900 
12901     // Rebuild the sub-expression as the pointee (function) type.
12902     DestType = DestType->castAs<PointerType>()->getPointeeType();
12903 
12904     ExprResult Result = Visit(E->getSubExpr());
12905     if (!Result.isUsable()) return ExprError();
12906 
12907     E->setSubExpr(Result.take());
12908     return S.Owned(E);
12909   } else if (E->getCastKind() == CK_LValueToRValue) {
12910     assert(E->getValueKind() == VK_RValue);
12911     assert(E->getObjectKind() == OK_Ordinary);
12912 
12913     assert(isa<BlockPointerType>(E->getType()));
12914 
12915     E->setType(DestType);
12916 
12917     // The sub-expression has to be a lvalue reference, so rebuild it as such.
12918     DestType = S.Context.getLValueReferenceType(DestType);
12919 
12920     ExprResult Result = Visit(E->getSubExpr());
12921     if (!Result.isUsable()) return ExprError();
12922 
12923     E->setSubExpr(Result.take());
12924     return S.Owned(E);
12925   } else {
12926     llvm_unreachable("Unhandled cast type!");
12927   }
12928 }
12929 
12930 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
12931   ExprValueKind ValueKind = VK_LValue;
12932   QualType Type = DestType;
12933 
12934   // We know how to make this work for certain kinds of decls:
12935 
12936   //  - functions
12937   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
12938     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
12939       DestType = Ptr->getPointeeType();
12940       ExprResult Result = resolveDecl(E, VD);
12941       if (Result.isInvalid()) return ExprError();
12942       return S.ImpCastExprToType(Result.take(), Type,
12943                                  CK_FunctionToPointerDecay, VK_RValue);
12944     }
12945 
12946     if (!Type->isFunctionType()) {
12947       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
12948         << VD << E->getSourceRange();
12949       return ExprError();
12950     }
12951 
12952     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
12953       if (MD->isInstance()) {
12954         ValueKind = VK_RValue;
12955         Type = S.Context.BoundMemberTy;
12956       }
12957 
12958     // Function references aren't l-values in C.
12959     if (!S.getLangOpts().CPlusPlus)
12960       ValueKind = VK_RValue;
12961 
12962   //  - variables
12963   } else if (isa<VarDecl>(VD)) {
12964     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
12965       Type = RefTy->getPointeeType();
12966     } else if (Type->isFunctionType()) {
12967       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
12968         << VD << E->getSourceRange();
12969       return ExprError();
12970     }
12971 
12972   //  - nothing else
12973   } else {
12974     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
12975       << VD << E->getSourceRange();
12976     return ExprError();
12977   }
12978 
12979   // Modifying the declaration like this is friendly to IR-gen but
12980   // also really dangerous.
12981   VD->setType(DestType);
12982   E->setType(Type);
12983   E->setValueKind(ValueKind);
12984   return S.Owned(E);
12985 }
12986 
12987 /// Check a cast of an unknown-any type.  We intentionally only
12988 /// trigger this for C-style casts.
12989 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
12990                                      Expr *CastExpr, CastKind &CastKind,
12991                                      ExprValueKind &VK, CXXCastPath &Path) {
12992   // Rewrite the casted expression from scratch.
12993   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
12994   if (!result.isUsable()) return ExprError();
12995 
12996   CastExpr = result.take();
12997   VK = CastExpr->getValueKind();
12998   CastKind = CK_NoOp;
12999 
13000   return CastExpr;
13001 }
13002 
13003 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
13004   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
13005 }
13006 
13007 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
13008                                     Expr *arg, QualType &paramType) {
13009   // If the syntactic form of the argument is not an explicit cast of
13010   // any sort, just do default argument promotion.
13011   ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
13012   if (!castArg) {
13013     ExprResult result = DefaultArgumentPromotion(arg);
13014     if (result.isInvalid()) return ExprError();
13015     paramType = result.get()->getType();
13016     return result;
13017   }
13018 
13019   // Otherwise, use the type that was written in the explicit cast.
13020   assert(!arg->hasPlaceholderType());
13021   paramType = castArg->getTypeAsWritten();
13022 
13023   // Copy-initialize a parameter of that type.
13024   InitializedEntity entity =
13025     InitializedEntity::InitializeParameter(Context, paramType,
13026                                            /*consumed*/ false);
13027   return PerformCopyInitialization(entity, callLoc, Owned(arg));
13028 }
13029 
13030 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
13031   Expr *orig = E;
13032   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
13033   while (true) {
13034     E = E->IgnoreParenImpCasts();
13035     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
13036       E = call->getCallee();
13037       diagID = diag::err_uncasted_call_of_unknown_any;
13038     } else {
13039       break;
13040     }
13041   }
13042 
13043   SourceLocation loc;
13044   NamedDecl *d;
13045   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
13046     loc = ref->getLocation();
13047     d = ref->getDecl();
13048   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
13049     loc = mem->getMemberLoc();
13050     d = mem->getMemberDecl();
13051   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
13052     diagID = diag::err_uncasted_call_of_unknown_any;
13053     loc = msg->getSelectorStartLoc();
13054     d = msg->getMethodDecl();
13055     if (!d) {
13056       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
13057         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
13058         << orig->getSourceRange();
13059       return ExprError();
13060     }
13061   } else {
13062     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
13063       << E->getSourceRange();
13064     return ExprError();
13065   }
13066 
13067   S.Diag(loc, diagID) << d << orig->getSourceRange();
13068 
13069   // Never recoverable.
13070   return ExprError();
13071 }
13072 
13073 /// Check for operands with placeholder types and complain if found.
13074 /// Returns true if there was an error and no recovery was possible.
13075 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
13076   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
13077   if (!placeholderType) return Owned(E);
13078 
13079   switch (placeholderType->getKind()) {
13080 
13081   // Overloaded expressions.
13082   case BuiltinType::Overload: {
13083     // Try to resolve a single function template specialization.
13084     // This is obligatory.
13085     ExprResult result = Owned(E);
13086     if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) {
13087       return result;
13088 
13089     // If that failed, try to recover with a call.
13090     } else {
13091       tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable),
13092                            /*complain*/ true);
13093       return result;
13094     }
13095   }
13096 
13097   // Bound member functions.
13098   case BuiltinType::BoundMember: {
13099     ExprResult result = Owned(E);
13100     tryToRecoverWithCall(result, PDiag(diag::err_bound_member_function),
13101                          /*complain*/ true);
13102     return result;
13103   }
13104 
13105   // ARC unbridged casts.
13106   case BuiltinType::ARCUnbridgedCast: {
13107     Expr *realCast = stripARCUnbridgedCast(E);
13108     diagnoseARCUnbridgedCast(realCast);
13109     return Owned(realCast);
13110   }
13111 
13112   // Expressions of unknown type.
13113   case BuiltinType::UnknownAny:
13114     return diagnoseUnknownAnyExpr(*this, E);
13115 
13116   // Pseudo-objects.
13117   case BuiltinType::PseudoObject:
13118     return checkPseudoObjectRValue(E);
13119 
13120   case BuiltinType::BuiltinFn:
13121     Diag(E->getLocStart(), diag::err_builtin_fn_use);
13122     return ExprError();
13123 
13124   // Everything else should be impossible.
13125 #define BUILTIN_TYPE(Id, SingletonId) \
13126   case BuiltinType::Id:
13127 #define PLACEHOLDER_TYPE(Id, SingletonId)
13128 #include "clang/AST/BuiltinTypes.def"
13129     break;
13130   }
13131 
13132   llvm_unreachable("invalid placeholder type!");
13133 }
13134 
13135 bool Sema::CheckCaseExpression(Expr *E) {
13136   if (E->isTypeDependent())
13137     return true;
13138   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
13139     return E->getType()->isIntegralOrEnumerationType();
13140   return false;
13141 }
13142 
13143 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
13144 ExprResult
13145 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
13146   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
13147          "Unknown Objective-C Boolean value!");
13148   QualType BoolT = Context.ObjCBuiltinBoolTy;
13149   if (!Context.getBOOLDecl()) {
13150     LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
13151                         Sema::LookupOrdinaryName);
13152     if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
13153       NamedDecl *ND = Result.getFoundDecl();
13154       if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
13155         Context.setBOOLDecl(TD);
13156     }
13157   }
13158   if (Context.getBOOLDecl())
13159     BoolT = Context.getBOOLType();
13160   return Owned(new (Context) ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes,
13161                                         BoolT, OpLoc));
13162 }
13163