1 //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements semantic analysis for expressions.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/Sema/SemaInternal.h"
15 #include "TreeTransform.h"
16 #include "clang/AST/ASTConsumer.h"
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/ASTMutationListener.h"
19 #include "clang/AST/CXXInheritance.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/DeclTemplate.h"
22 #include "clang/AST/EvaluatedExprVisitor.h"
23 #include "clang/AST/Expr.h"
24 #include "clang/AST/ExprCXX.h"
25 #include "clang/AST/ExprObjC.h"
26 #include "clang/AST/RecursiveASTVisitor.h"
27 #include "clang/AST/TypeLoc.h"
28 #include "clang/Basic/PartialDiagnostic.h"
29 #include "clang/Basic/SourceManager.h"
30 #include "clang/Basic/TargetInfo.h"
31 #include "clang/Lex/LiteralSupport.h"
32 #include "clang/Lex/Preprocessor.h"
33 #include "clang/Sema/AnalysisBasedWarnings.h"
34 #include "clang/Sema/DeclSpec.h"
35 #include "clang/Sema/DelayedDiagnostic.h"
36 #include "clang/Sema/Designator.h"
37 #include "clang/Sema/Initialization.h"
38 #include "clang/Sema/Lookup.h"
39 #include "clang/Sema/ParsedTemplate.h"
40 #include "clang/Sema/Scope.h"
41 #include "clang/Sema/ScopeInfo.h"
42 #include "clang/Sema/SemaFixItUtils.h"
43 #include "clang/Sema/Template.h"
44 using namespace clang;
45 using namespace sema;
46 
47 /// \brief Determine whether the use of this declaration is valid, without
48 /// emitting diagnostics.
49 bool Sema::CanUseDecl(NamedDecl *D) {
50   // See if this is an auto-typed variable whose initializer we are parsing.
51   if (ParsingInitForAutoVars.count(D))
52     return false;
53 
54   // See if this is a deleted function.
55   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
56     if (FD->isDeleted())
57       return false;
58 
59     // If the function has a deduced return type, and we can't deduce it,
60     // then we can't use it either.
61     if (getLangOpts().CPlusPlus1y && FD->getResultType()->isUndeducedType() &&
62         DeduceReturnType(FD, SourceLocation(), /*Diagnose*/false))
63       return false;
64   }
65 
66   // See if this function is unavailable.
67   if (D->getAvailability() == AR_Unavailable &&
68       cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
69     return false;
70 
71   return true;
72 }
73 
74 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
75   // Warn if this is used but marked unused.
76   if (D->hasAttr<UnusedAttr>()) {
77     const Decl *DC = cast<Decl>(S.getCurObjCLexicalContext());
78     if (!DC->hasAttr<UnusedAttr>())
79       S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
80   }
81 }
82 
83 static AvailabilityResult DiagnoseAvailabilityOfDecl(Sema &S,
84                               NamedDecl *D, SourceLocation Loc,
85                               const ObjCInterfaceDecl *UnknownObjCClass) {
86   // See if this declaration is unavailable or deprecated.
87   std::string Message;
88   AvailabilityResult Result = D->getAvailability(&Message);
89   if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D))
90     if (Result == AR_Available) {
91       const DeclContext *DC = ECD->getDeclContext();
92       if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC))
93         Result = TheEnumDecl->getAvailability(&Message);
94     }
95 
96   const ObjCPropertyDecl *ObjCPDecl = 0;
97   if (Result == AR_Deprecated || Result == AR_Unavailable) {
98     if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
99       if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) {
100         AvailabilityResult PDeclResult = PD->getAvailability(0);
101         if (PDeclResult == Result)
102           ObjCPDecl = PD;
103       }
104     }
105   }
106 
107   switch (Result) {
108     case AR_Available:
109     case AR_NotYetIntroduced:
110       break;
111 
112     case AR_Deprecated:
113       S.EmitDeprecationWarning(D, Message, Loc, UnknownObjCClass, ObjCPDecl);
114       break;
115 
116     case AR_Unavailable:
117       if (S.getCurContextAvailability() != AR_Unavailable) {
118         if (Message.empty()) {
119           if (!UnknownObjCClass) {
120             S.Diag(Loc, diag::err_unavailable) << D->getDeclName();
121             if (ObjCPDecl)
122               S.Diag(ObjCPDecl->getLocation(), diag::note_property_attribute)
123                 << ObjCPDecl->getDeclName() << 1;
124           }
125           else
126             S.Diag(Loc, diag::warn_unavailable_fwdclass_message)
127               << D->getDeclName();
128         }
129         else
130           S.Diag(Loc, diag::err_unavailable_message)
131             << D->getDeclName() << Message;
132         S.Diag(D->getLocation(), diag::note_unavailable_here)
133                   << isa<FunctionDecl>(D) << false;
134         if (ObjCPDecl)
135           S.Diag(ObjCPDecl->getLocation(), diag::note_property_attribute)
136           << ObjCPDecl->getDeclName() << 1;
137       }
138       break;
139     }
140     return Result;
141 }
142 
143 /// \brief Emit a note explaining that this function is deleted.
144 void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
145   assert(Decl->isDeleted());
146 
147   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
148 
149   if (Method && Method->isDeleted() && Method->isDefaulted()) {
150     // If the method was explicitly defaulted, point at that declaration.
151     if (!Method->isImplicit())
152       Diag(Decl->getLocation(), diag::note_implicitly_deleted);
153 
154     // Try to diagnose why this special member function was implicitly
155     // deleted. This might fail, if that reason no longer applies.
156     CXXSpecialMember CSM = getSpecialMember(Method);
157     if (CSM != CXXInvalid)
158       ShouldDeleteSpecialMember(Method, CSM, /*Diagnose=*/true);
159 
160     return;
161   }
162 
163   if (CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Decl)) {
164     if (CXXConstructorDecl *BaseCD =
165             const_cast<CXXConstructorDecl*>(CD->getInheritedConstructor())) {
166       Diag(Decl->getLocation(), diag::note_inherited_deleted_here);
167       if (BaseCD->isDeleted()) {
168         NoteDeletedFunction(BaseCD);
169       } else {
170         // FIXME: An explanation of why exactly it can't be inherited
171         // would be nice.
172         Diag(BaseCD->getLocation(), diag::note_cannot_inherit);
173       }
174       return;
175     }
176   }
177 
178   Diag(Decl->getLocation(), diag::note_unavailable_here)
179     << 1 << true;
180 }
181 
182 /// \brief Determine whether a FunctionDecl was ever declared with an
183 /// explicit storage class.
184 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
185   for (FunctionDecl::redecl_iterator I = D->redecls_begin(),
186                                      E = D->redecls_end();
187        I != E; ++I) {
188     if (I->getStorageClass() != SC_None)
189       return true;
190   }
191   return false;
192 }
193 
194 /// \brief Check whether we're in an extern inline function and referring to a
195 /// variable or function with internal linkage (C11 6.7.4p3).
196 ///
197 /// This is only a warning because we used to silently accept this code, but
198 /// in many cases it will not behave correctly. This is not enabled in C++ mode
199 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
200 /// and so while there may still be user mistakes, most of the time we can't
201 /// prove that there are errors.
202 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
203                                                       const NamedDecl *D,
204                                                       SourceLocation Loc) {
205   // This is disabled under C++; there are too many ways for this to fire in
206   // contexts where the warning is a false positive, or where it is technically
207   // correct but benign.
208   if (S.getLangOpts().CPlusPlus)
209     return;
210 
211   // Check if this is an inlined function or method.
212   FunctionDecl *Current = S.getCurFunctionDecl();
213   if (!Current)
214     return;
215   if (!Current->isInlined())
216     return;
217   if (!Current->isExternallyVisible())
218     return;
219 
220   // Check if the decl has internal linkage.
221   if (D->getFormalLinkage() != InternalLinkage)
222     return;
223 
224   // Downgrade from ExtWarn to Extension if
225   //  (1) the supposedly external inline function is in the main file,
226   //      and probably won't be included anywhere else.
227   //  (2) the thing we're referencing is a pure function.
228   //  (3) the thing we're referencing is another inline function.
229   // This last can give us false negatives, but it's better than warning on
230   // wrappers for simple C library functions.
231   const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
232   bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
233   if (!DowngradeWarning && UsedFn)
234     DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
235 
236   S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline
237                                : diag::warn_internal_in_extern_inline)
238     << /*IsVar=*/!UsedFn << D;
239 
240   S.MaybeSuggestAddingStaticToDecl(Current);
241 
242   S.Diag(D->getCanonicalDecl()->getLocation(),
243          diag::note_internal_decl_declared_here)
244     << D;
245 }
246 
247 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
248   const FunctionDecl *First = Cur->getFirstDecl();
249 
250   // Suggest "static" on the function, if possible.
251   if (!hasAnyExplicitStorageClass(First)) {
252     SourceLocation DeclBegin = First->getSourceRange().getBegin();
253     Diag(DeclBegin, diag::note_convert_inline_to_static)
254       << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
255   }
256 }
257 
258 /// \brief Determine whether the use of this declaration is valid, and
259 /// emit any corresponding diagnostics.
260 ///
261 /// This routine diagnoses various problems with referencing
262 /// declarations that can occur when using a declaration. For example,
263 /// it might warn if a deprecated or unavailable declaration is being
264 /// used, or produce an error (and return true) if a C++0x deleted
265 /// function is being used.
266 ///
267 /// \returns true if there was an error (this declaration cannot be
268 /// referenced), false otherwise.
269 ///
270 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
271                              const ObjCInterfaceDecl *UnknownObjCClass) {
272   if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
273     // If there were any diagnostics suppressed by template argument deduction,
274     // emit them now.
275     SuppressedDiagnosticsMap::iterator
276       Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
277     if (Pos != SuppressedDiagnostics.end()) {
278       SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second;
279       for (unsigned I = 0, N = Suppressed.size(); I != N; ++I)
280         Diag(Suppressed[I].first, Suppressed[I].second);
281 
282       // Clear out the list of suppressed diagnostics, so that we don't emit
283       // them again for this specialization. However, we don't obsolete this
284       // entry from the table, because we want to avoid ever emitting these
285       // diagnostics again.
286       Suppressed.clear();
287     }
288   }
289 
290   // See if this is an auto-typed variable whose initializer we are parsing.
291   if (ParsingInitForAutoVars.count(D)) {
292     Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
293       << D->getDeclName();
294     return true;
295   }
296 
297   // See if this is a deleted function.
298   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
299     if (FD->isDeleted()) {
300       Diag(Loc, diag::err_deleted_function_use);
301       NoteDeletedFunction(FD);
302       return true;
303     }
304 
305     // If the function has a deduced return type, and we can't deduce it,
306     // then we can't use it either.
307     if (getLangOpts().CPlusPlus1y && FD->getResultType()->isUndeducedType() &&
308         DeduceReturnType(FD, Loc))
309       return true;
310   }
311   DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass);
312 
313   DiagnoseUnusedOfDecl(*this, D, Loc);
314 
315   diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
316 
317   return false;
318 }
319 
320 /// \brief Retrieve the message suffix that should be added to a
321 /// diagnostic complaining about the given function being deleted or
322 /// unavailable.
323 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
324   std::string Message;
325   if (FD->getAvailability(&Message))
326     return ": " + Message;
327 
328   return std::string();
329 }
330 
331 /// DiagnoseSentinelCalls - This routine checks whether a call or
332 /// message-send is to a declaration with the sentinel attribute, and
333 /// if so, it checks that the requirements of the sentinel are
334 /// satisfied.
335 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
336                                  ArrayRef<Expr *> Args) {
337   const SentinelAttr *attr = D->getAttr<SentinelAttr>();
338   if (!attr)
339     return;
340 
341   // The number of formal parameters of the declaration.
342   unsigned numFormalParams;
343 
344   // The kind of declaration.  This is also an index into a %select in
345   // the diagnostic.
346   enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
347 
348   if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
349     numFormalParams = MD->param_size();
350     calleeType = CT_Method;
351   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
352     numFormalParams = FD->param_size();
353     calleeType = CT_Function;
354   } else if (isa<VarDecl>(D)) {
355     QualType type = cast<ValueDecl>(D)->getType();
356     const FunctionType *fn = 0;
357     if (const PointerType *ptr = type->getAs<PointerType>()) {
358       fn = ptr->getPointeeType()->getAs<FunctionType>();
359       if (!fn) return;
360       calleeType = CT_Function;
361     } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
362       fn = ptr->getPointeeType()->castAs<FunctionType>();
363       calleeType = CT_Block;
364     } else {
365       return;
366     }
367 
368     if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
369       numFormalParams = proto->getNumArgs();
370     } else {
371       numFormalParams = 0;
372     }
373   } else {
374     return;
375   }
376 
377   // "nullPos" is the number of formal parameters at the end which
378   // effectively count as part of the variadic arguments.  This is
379   // useful if you would prefer to not have *any* formal parameters,
380   // but the language forces you to have at least one.
381   unsigned nullPos = attr->getNullPos();
382   assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
383   numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
384 
385   // The number of arguments which should follow the sentinel.
386   unsigned numArgsAfterSentinel = attr->getSentinel();
387 
388   // If there aren't enough arguments for all the formal parameters,
389   // the sentinel, and the args after the sentinel, complain.
390   if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
391     Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
392     Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
393     return;
394   }
395 
396   // Otherwise, find the sentinel expression.
397   Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
398   if (!sentinelExpr) return;
399   if (sentinelExpr->isValueDependent()) return;
400   if (Context.isSentinelNullExpr(sentinelExpr)) return;
401 
402   // Pick a reasonable string to insert.  Optimistically use 'nil' or
403   // 'NULL' if those are actually defined in the context.  Only use
404   // 'nil' for ObjC methods, where it's much more likely that the
405   // variadic arguments form a list of object pointers.
406   SourceLocation MissingNilLoc
407     = PP.getLocForEndOfToken(sentinelExpr->getLocEnd());
408   std::string NullValue;
409   if (calleeType == CT_Method &&
410       PP.getIdentifierInfo("nil")->hasMacroDefinition())
411     NullValue = "nil";
412   else if (PP.getIdentifierInfo("NULL")->hasMacroDefinition())
413     NullValue = "NULL";
414   else
415     NullValue = "(void*) 0";
416 
417   if (MissingNilLoc.isInvalid())
418     Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
419   else
420     Diag(MissingNilLoc, diag::warn_missing_sentinel)
421       << int(calleeType)
422       << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
423   Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
424 }
425 
426 SourceRange Sema::getExprRange(Expr *E) const {
427   return E ? E->getSourceRange() : SourceRange();
428 }
429 
430 //===----------------------------------------------------------------------===//
431 //  Standard Promotions and Conversions
432 //===----------------------------------------------------------------------===//
433 
434 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
435 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) {
436   // Handle any placeholder expressions which made it here.
437   if (E->getType()->isPlaceholderType()) {
438     ExprResult result = CheckPlaceholderExpr(E);
439     if (result.isInvalid()) return ExprError();
440     E = result.take();
441   }
442 
443   QualType Ty = E->getType();
444   assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
445 
446   if (Ty->isFunctionType())
447     E = ImpCastExprToType(E, Context.getPointerType(Ty),
448                           CK_FunctionToPointerDecay).take();
449   else if (Ty->isArrayType()) {
450     // In C90 mode, arrays only promote to pointers if the array expression is
451     // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
452     // type 'array of type' is converted to an expression that has type 'pointer
453     // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
454     // that has type 'array of type' ...".  The relevant change is "an lvalue"
455     // (C90) to "an expression" (C99).
456     //
457     // C++ 4.2p1:
458     // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
459     // T" can be converted to an rvalue of type "pointer to T".
460     //
461     if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
462       E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
463                             CK_ArrayToPointerDecay).take();
464   }
465   return Owned(E);
466 }
467 
468 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
469   // Check to see if we are dereferencing a null pointer.  If so,
470   // and if not volatile-qualified, this is undefined behavior that the
471   // optimizer will delete, so warn about it.  People sometimes try to use this
472   // to get a deterministic trap and are surprised by clang's behavior.  This
473   // only handles the pattern "*null", which is a very syntactic check.
474   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
475     if (UO->getOpcode() == UO_Deref &&
476         UO->getSubExpr()->IgnoreParenCasts()->
477           isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
478         !UO->getType().isVolatileQualified()) {
479     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
480                           S.PDiag(diag::warn_indirection_through_null)
481                             << UO->getSubExpr()->getSourceRange());
482     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
483                         S.PDiag(diag::note_indirection_through_null));
484   }
485 }
486 
487 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
488                                     SourceLocation AssignLoc,
489                                     const Expr* RHS) {
490   const ObjCIvarDecl *IV = OIRE->getDecl();
491   if (!IV)
492     return;
493 
494   DeclarationName MemberName = IV->getDeclName();
495   IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
496   if (!Member || !Member->isStr("isa"))
497     return;
498 
499   const Expr *Base = OIRE->getBase();
500   QualType BaseType = Base->getType();
501   if (OIRE->isArrow())
502     BaseType = BaseType->getPointeeType();
503   if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
504     if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
505       ObjCInterfaceDecl *ClassDeclared = 0;
506       ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
507       if (!ClassDeclared->getSuperClass()
508           && (*ClassDeclared->ivar_begin()) == IV) {
509         if (RHS) {
510           NamedDecl *ObjectSetClass =
511             S.LookupSingleName(S.TUScope,
512                                &S.Context.Idents.get("object_setClass"),
513                                SourceLocation(), S.LookupOrdinaryName);
514           if (ObjectSetClass) {
515             SourceLocation RHSLocEnd = S.PP.getLocForEndOfToken(RHS->getLocEnd());
516             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) <<
517             FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") <<
518             FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(),
519                                                      AssignLoc), ",") <<
520             FixItHint::CreateInsertion(RHSLocEnd, ")");
521           }
522           else
523             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
524         } else {
525           NamedDecl *ObjectGetClass =
526             S.LookupSingleName(S.TUScope,
527                                &S.Context.Idents.get("object_getClass"),
528                                SourceLocation(), S.LookupOrdinaryName);
529           if (ObjectGetClass)
530             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) <<
531             FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") <<
532             FixItHint::CreateReplacement(
533                                          SourceRange(OIRE->getOpLoc(),
534                                                      OIRE->getLocEnd()), ")");
535           else
536             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
537         }
538         S.Diag(IV->getLocation(), diag::note_ivar_decl);
539       }
540     }
541 }
542 
543 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
544   // Handle any placeholder expressions which made it here.
545   if (E->getType()->isPlaceholderType()) {
546     ExprResult result = CheckPlaceholderExpr(E);
547     if (result.isInvalid()) return ExprError();
548     E = result.take();
549   }
550 
551   // C++ [conv.lval]p1:
552   //   A glvalue of a non-function, non-array type T can be
553   //   converted to a prvalue.
554   if (!E->isGLValue()) return Owned(E);
555 
556   QualType T = E->getType();
557   assert(!T.isNull() && "r-value conversion on typeless expression?");
558 
559   // We don't want to throw lvalue-to-rvalue casts on top of
560   // expressions of certain types in C++.
561   if (getLangOpts().CPlusPlus &&
562       (E->getType() == Context.OverloadTy ||
563        T->isDependentType() ||
564        T->isRecordType()))
565     return Owned(E);
566 
567   // The C standard is actually really unclear on this point, and
568   // DR106 tells us what the result should be but not why.  It's
569   // generally best to say that void types just doesn't undergo
570   // lvalue-to-rvalue at all.  Note that expressions of unqualified
571   // 'void' type are never l-values, but qualified void can be.
572   if (T->isVoidType())
573     return Owned(E);
574 
575   // OpenCL usually rejects direct accesses to values of 'half' type.
576   if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16 &&
577       T->isHalfType()) {
578     Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
579       << 0 << T;
580     return ExprError();
581   }
582 
583   CheckForNullPointerDereference(*this, E);
584   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
585     NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
586                                      &Context.Idents.get("object_getClass"),
587                                      SourceLocation(), LookupOrdinaryName);
588     if (ObjectGetClass)
589       Diag(E->getExprLoc(), diag::warn_objc_isa_use) <<
590         FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") <<
591         FixItHint::CreateReplacement(
592                     SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
593     else
594       Diag(E->getExprLoc(), diag::warn_objc_isa_use);
595   }
596   else if (const ObjCIvarRefExpr *OIRE =
597             dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
598     DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/0);
599 
600   // C++ [conv.lval]p1:
601   //   [...] If T is a non-class type, the type of the prvalue is the
602   //   cv-unqualified version of T. Otherwise, the type of the
603   //   rvalue is T.
604   //
605   // C99 6.3.2.1p2:
606   //   If the lvalue has qualified type, the value has the unqualified
607   //   version of the type of the lvalue; otherwise, the value has the
608   //   type of the lvalue.
609   if (T.hasQualifiers())
610     T = T.getUnqualifiedType();
611 
612   UpdateMarkingForLValueToRValue(E);
613 
614   // Loading a __weak object implicitly retains the value, so we need a cleanup to
615   // balance that.
616   if (getLangOpts().ObjCAutoRefCount &&
617       E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
618     ExprNeedsCleanups = true;
619 
620   ExprResult Res = Owned(ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
621                                                   E, 0, VK_RValue));
622 
623   // C11 6.3.2.1p2:
624   //   ... if the lvalue has atomic type, the value has the non-atomic version
625   //   of the type of the lvalue ...
626   if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
627     T = Atomic->getValueType().getUnqualifiedType();
628     Res = Owned(ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic,
629                                          Res.get(), 0, VK_RValue));
630   }
631 
632   return Res;
633 }
634 
635 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) {
636   ExprResult Res = DefaultFunctionArrayConversion(E);
637   if (Res.isInvalid())
638     return ExprError();
639   Res = DefaultLvalueConversion(Res.take());
640   if (Res.isInvalid())
641     return ExprError();
642   return Res;
643 }
644 
645 
646 /// UsualUnaryConversions - Performs various conversions that are common to most
647 /// operators (C99 6.3). The conversions of array and function types are
648 /// sometimes suppressed. For example, the array->pointer conversion doesn't
649 /// apply if the array is an argument to the sizeof or address (&) operators.
650 /// In these instances, this routine should *not* be called.
651 ExprResult Sema::UsualUnaryConversions(Expr *E) {
652   // First, convert to an r-value.
653   ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
654   if (Res.isInvalid())
655     return ExprError();
656   E = Res.take();
657 
658   QualType Ty = E->getType();
659   assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
660 
661   // Half FP have to be promoted to float unless it is natively supported
662   if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
663     return ImpCastExprToType(Res.take(), Context.FloatTy, CK_FloatingCast);
664 
665   // Try to perform integral promotions if the object has a theoretically
666   // promotable type.
667   if (Ty->isIntegralOrUnscopedEnumerationType()) {
668     // C99 6.3.1.1p2:
669     //
670     //   The following may be used in an expression wherever an int or
671     //   unsigned int may be used:
672     //     - an object or expression with an integer type whose integer
673     //       conversion rank is less than or equal to the rank of int
674     //       and unsigned int.
675     //     - A bit-field of type _Bool, int, signed int, or unsigned int.
676     //
677     //   If an int can represent all values of the original type, the
678     //   value is converted to an int; otherwise, it is converted to an
679     //   unsigned int. These are called the integer promotions. All
680     //   other types are unchanged by the integer promotions.
681 
682     QualType PTy = Context.isPromotableBitField(E);
683     if (!PTy.isNull()) {
684       E = ImpCastExprToType(E, PTy, CK_IntegralCast).take();
685       return Owned(E);
686     }
687     if (Ty->isPromotableIntegerType()) {
688       QualType PT = Context.getPromotedIntegerType(Ty);
689       E = ImpCastExprToType(E, PT, CK_IntegralCast).take();
690       return Owned(E);
691     }
692   }
693   return Owned(E);
694 }
695 
696 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
697 /// do not have a prototype. Arguments that have type float or __fp16
698 /// are promoted to double. All other argument types are converted by
699 /// UsualUnaryConversions().
700 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
701   QualType Ty = E->getType();
702   assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
703 
704   ExprResult Res = UsualUnaryConversions(E);
705   if (Res.isInvalid())
706     return ExprError();
707   E = Res.take();
708 
709   // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to
710   // double.
711   const BuiltinType *BTy = Ty->getAs<BuiltinType>();
712   if (BTy && (BTy->getKind() == BuiltinType::Half ||
713               BTy->getKind() == BuiltinType::Float))
714     E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).take();
715 
716   // C++ performs lvalue-to-rvalue conversion as a default argument
717   // promotion, even on class types, but note:
718   //   C++11 [conv.lval]p2:
719   //     When an lvalue-to-rvalue conversion occurs in an unevaluated
720   //     operand or a subexpression thereof the value contained in the
721   //     referenced object is not accessed. Otherwise, if the glvalue
722   //     has a class type, the conversion copy-initializes a temporary
723   //     of type T from the glvalue and the result of the conversion
724   //     is a prvalue for the temporary.
725   // FIXME: add some way to gate this entire thing for correctness in
726   // potentially potentially evaluated contexts.
727   if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
728     ExprResult Temp = PerformCopyInitialization(
729                        InitializedEntity::InitializeTemporary(E->getType()),
730                                                 E->getExprLoc(),
731                                                 Owned(E));
732     if (Temp.isInvalid())
733       return ExprError();
734     E = Temp.get();
735   }
736 
737   return Owned(E);
738 }
739 
740 /// Determine the degree of POD-ness for an expression.
741 /// Incomplete types are considered POD, since this check can be performed
742 /// when we're in an unevaluated context.
743 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
744   if (Ty->isIncompleteType()) {
745     // C++11 [expr.call]p7:
746     //   After these conversions, if the argument does not have arithmetic,
747     //   enumeration, pointer, pointer to member, or class type, the program
748     //   is ill-formed.
749     //
750     // Since we've already performed array-to-pointer and function-to-pointer
751     // decay, the only such type in C++ is cv void. This also handles
752     // initializer lists as variadic arguments.
753     if (Ty->isVoidType())
754       return VAK_Invalid;
755 
756     if (Ty->isObjCObjectType())
757       return VAK_Invalid;
758     return VAK_Valid;
759   }
760 
761   if (Ty.isCXX98PODType(Context))
762     return VAK_Valid;
763 
764   // C++11 [expr.call]p7:
765   //   Passing a potentially-evaluated argument of class type (Clause 9)
766   //   having a non-trivial copy constructor, a non-trivial move constructor,
767   //   or a non-trivial destructor, with no corresponding parameter,
768   //   is conditionally-supported with implementation-defined semantics.
769   if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
770     if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
771       if (!Record->hasNonTrivialCopyConstructor() &&
772           !Record->hasNonTrivialMoveConstructor() &&
773           !Record->hasNonTrivialDestructor())
774         return VAK_ValidInCXX11;
775 
776   if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
777     return VAK_Valid;
778 
779   if (Ty->isObjCObjectType())
780     return VAK_Invalid;
781 
782   // FIXME: In C++11, these cases are conditionally-supported, meaning we're
783   // permitted to reject them. We should consider doing so.
784   return VAK_Undefined;
785 }
786 
787 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
788   // Don't allow one to pass an Objective-C interface to a vararg.
789   const QualType &Ty = E->getType();
790   VarArgKind VAK = isValidVarArgType(Ty);
791 
792   // Complain about passing non-POD types through varargs.
793   switch (VAK) {
794   case VAK_Valid:
795     break;
796 
797   case VAK_ValidInCXX11:
798     DiagRuntimeBehavior(
799         E->getLocStart(), 0,
800         PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
801           << E->getType() << CT);
802     break;
803 
804   case VAK_Undefined:
805     DiagRuntimeBehavior(
806         E->getLocStart(), 0,
807         PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
808           << getLangOpts().CPlusPlus11 << Ty << CT);
809     break;
810 
811   case VAK_Invalid:
812     if (Ty->isObjCObjectType())
813       DiagRuntimeBehavior(
814           E->getLocStart(), 0,
815           PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
816             << Ty << CT);
817     else
818       Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg)
819         << isa<InitListExpr>(E) << Ty << CT;
820     break;
821   }
822 }
823 
824 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
825 /// will create a trap if the resulting type is not a POD type.
826 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
827                                                   FunctionDecl *FDecl) {
828   if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
829     // Strip the unbridged-cast placeholder expression off, if applicable.
830     if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
831         (CT == VariadicMethod ||
832          (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
833       E = stripARCUnbridgedCast(E);
834 
835     // Otherwise, do normal placeholder checking.
836     } else {
837       ExprResult ExprRes = CheckPlaceholderExpr(E);
838       if (ExprRes.isInvalid())
839         return ExprError();
840       E = ExprRes.take();
841     }
842   }
843 
844   ExprResult ExprRes = DefaultArgumentPromotion(E);
845   if (ExprRes.isInvalid())
846     return ExprError();
847   E = ExprRes.take();
848 
849   // Diagnostics regarding non-POD argument types are
850   // emitted along with format string checking in Sema::CheckFunctionCall().
851   if (isValidVarArgType(E->getType()) == VAK_Undefined) {
852     // Turn this into a trap.
853     CXXScopeSpec SS;
854     SourceLocation TemplateKWLoc;
855     UnqualifiedId Name;
856     Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
857                        E->getLocStart());
858     ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
859                                           Name, true, false);
860     if (TrapFn.isInvalid())
861       return ExprError();
862 
863     ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(),
864                                     E->getLocStart(), None,
865                                     E->getLocEnd());
866     if (Call.isInvalid())
867       return ExprError();
868 
869     ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
870                                   Call.get(), E);
871     if (Comma.isInvalid())
872       return ExprError();
873     return Comma.get();
874   }
875 
876   if (!getLangOpts().CPlusPlus &&
877       RequireCompleteType(E->getExprLoc(), E->getType(),
878                           diag::err_call_incomplete_argument))
879     return ExprError();
880 
881   return Owned(E);
882 }
883 
884 /// \brief Converts an integer to complex float type.  Helper function of
885 /// UsualArithmeticConversions()
886 ///
887 /// \return false if the integer expression is an integer type and is
888 /// successfully converted to the complex type.
889 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
890                                                   ExprResult &ComplexExpr,
891                                                   QualType IntTy,
892                                                   QualType ComplexTy,
893                                                   bool SkipCast) {
894   if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
895   if (SkipCast) return false;
896   if (IntTy->isIntegerType()) {
897     QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
898     IntExpr = S.ImpCastExprToType(IntExpr.take(), fpTy, CK_IntegralToFloating);
899     IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
900                                   CK_FloatingRealToComplex);
901   } else {
902     assert(IntTy->isComplexIntegerType());
903     IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
904                                   CK_IntegralComplexToFloatingComplex);
905   }
906   return false;
907 }
908 
909 /// \brief Takes two complex float types and converts them to the same type.
910 /// Helper function of UsualArithmeticConversions()
911 static QualType
912 handleComplexFloatToComplexFloatConverstion(Sema &S, ExprResult &LHS,
913                                             ExprResult &RHS, QualType LHSType,
914                                             QualType RHSType,
915                                             bool IsCompAssign) {
916   int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
917 
918   if (order < 0) {
919     // _Complex float -> _Complex double
920     if (!IsCompAssign)
921       LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingComplexCast);
922     return RHSType;
923   }
924   if (order > 0)
925     // _Complex float -> _Complex double
926     RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingComplexCast);
927   return LHSType;
928 }
929 
930 /// \brief Converts otherExpr to complex float and promotes complexExpr if
931 /// necessary.  Helper function of UsualArithmeticConversions()
932 static QualType handleOtherComplexFloatConversion(Sema &S,
933                                                   ExprResult &ComplexExpr,
934                                                   ExprResult &OtherExpr,
935                                                   QualType ComplexTy,
936                                                   QualType OtherTy,
937                                                   bool ConvertComplexExpr,
938                                                   bool ConvertOtherExpr) {
939   int order = S.Context.getFloatingTypeOrder(ComplexTy, OtherTy);
940 
941   // If just the complexExpr is complex, the otherExpr needs to be converted,
942   // and the complexExpr might need to be promoted.
943   if (order > 0) { // complexExpr is wider
944     // float -> _Complex double
945     if (ConvertOtherExpr) {
946       QualType fp = cast<ComplexType>(ComplexTy)->getElementType();
947       OtherExpr = S.ImpCastExprToType(OtherExpr.take(), fp, CK_FloatingCast);
948       OtherExpr = S.ImpCastExprToType(OtherExpr.take(), ComplexTy,
949                                       CK_FloatingRealToComplex);
950     }
951     return ComplexTy;
952   }
953 
954   // otherTy is at least as wide.  Find its corresponding complex type.
955   QualType result = (order == 0 ? ComplexTy :
956                                   S.Context.getComplexType(OtherTy));
957 
958   // double -> _Complex double
959   if (ConvertOtherExpr)
960     OtherExpr = S.ImpCastExprToType(OtherExpr.take(), result,
961                                     CK_FloatingRealToComplex);
962 
963   // _Complex float -> _Complex double
964   if (ConvertComplexExpr && order < 0)
965     ComplexExpr = S.ImpCastExprToType(ComplexExpr.take(), result,
966                                       CK_FloatingComplexCast);
967 
968   return result;
969 }
970 
971 /// \brief Handle arithmetic conversion with complex types.  Helper function of
972 /// UsualArithmeticConversions()
973 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
974                                              ExprResult &RHS, QualType LHSType,
975                                              QualType RHSType,
976                                              bool IsCompAssign) {
977   // if we have an integer operand, the result is the complex type.
978   if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
979                                              /*skipCast*/false))
980     return LHSType;
981   if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
982                                              /*skipCast*/IsCompAssign))
983     return RHSType;
984 
985   // This handles complex/complex, complex/float, or float/complex.
986   // When both operands are complex, the shorter operand is converted to the
987   // type of the longer, and that is the type of the result. This corresponds
988   // to what is done when combining two real floating-point operands.
989   // The fun begins when size promotion occur across type domains.
990   // From H&S 6.3.4: When one operand is complex and the other is a real
991   // floating-point type, the less precise type is converted, within it's
992   // real or complex domain, to the precision of the other type. For example,
993   // when combining a "long double" with a "double _Complex", the
994   // "double _Complex" is promoted to "long double _Complex".
995 
996   bool LHSComplexFloat = LHSType->isComplexType();
997   bool RHSComplexFloat = RHSType->isComplexType();
998 
999   // If both are complex, just cast to the more precise type.
1000   if (LHSComplexFloat && RHSComplexFloat)
1001     return handleComplexFloatToComplexFloatConverstion(S, LHS, RHS,
1002                                                        LHSType, RHSType,
1003                                                        IsCompAssign);
1004 
1005   // If only one operand is complex, promote it if necessary and convert the
1006   // other operand to complex.
1007   if (LHSComplexFloat)
1008     return handleOtherComplexFloatConversion(
1009         S, LHS, RHS, LHSType, RHSType, /*convertComplexExpr*/!IsCompAssign,
1010         /*convertOtherExpr*/ true);
1011 
1012   assert(RHSComplexFloat);
1013   return handleOtherComplexFloatConversion(
1014       S, RHS, LHS, RHSType, LHSType, /*convertComplexExpr*/true,
1015       /*convertOtherExpr*/ !IsCompAssign);
1016 }
1017 
1018 /// \brief Hande arithmetic conversion from integer to float.  Helper function
1019 /// of UsualArithmeticConversions()
1020 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1021                                            ExprResult &IntExpr,
1022                                            QualType FloatTy, QualType IntTy,
1023                                            bool ConvertFloat, bool ConvertInt) {
1024   if (IntTy->isIntegerType()) {
1025     if (ConvertInt)
1026       // Convert intExpr to the lhs floating point type.
1027       IntExpr = S.ImpCastExprToType(IntExpr.take(), FloatTy,
1028                                     CK_IntegralToFloating);
1029     return FloatTy;
1030   }
1031 
1032   // Convert both sides to the appropriate complex float.
1033   assert(IntTy->isComplexIntegerType());
1034   QualType result = S.Context.getComplexType(FloatTy);
1035 
1036   // _Complex int -> _Complex float
1037   if (ConvertInt)
1038     IntExpr = S.ImpCastExprToType(IntExpr.take(), result,
1039                                   CK_IntegralComplexToFloatingComplex);
1040 
1041   // float -> _Complex float
1042   if (ConvertFloat)
1043     FloatExpr = S.ImpCastExprToType(FloatExpr.take(), result,
1044                                     CK_FloatingRealToComplex);
1045 
1046   return result;
1047 }
1048 
1049 /// \brief Handle arithmethic conversion with floating point types.  Helper
1050 /// function of UsualArithmeticConversions()
1051 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1052                                       ExprResult &RHS, QualType LHSType,
1053                                       QualType RHSType, bool IsCompAssign) {
1054   bool LHSFloat = LHSType->isRealFloatingType();
1055   bool RHSFloat = RHSType->isRealFloatingType();
1056 
1057   // If we have two real floating types, convert the smaller operand
1058   // to the bigger result.
1059   if (LHSFloat && RHSFloat) {
1060     int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1061     if (order > 0) {
1062       RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingCast);
1063       return LHSType;
1064     }
1065 
1066     assert(order < 0 && "illegal float comparison");
1067     if (!IsCompAssign)
1068       LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingCast);
1069     return RHSType;
1070   }
1071 
1072   if (LHSFloat)
1073     return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1074                                       /*convertFloat=*/!IsCompAssign,
1075                                       /*convertInt=*/ true);
1076   assert(RHSFloat);
1077   return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1078                                     /*convertInt=*/ true,
1079                                     /*convertFloat=*/!IsCompAssign);
1080 }
1081 
1082 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1083 
1084 namespace {
1085 /// These helper callbacks are placed in an anonymous namespace to
1086 /// permit their use as function template parameters.
1087 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1088   return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1089 }
1090 
1091 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1092   return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1093                              CK_IntegralComplexCast);
1094 }
1095 }
1096 
1097 /// \brief Handle integer arithmetic conversions.  Helper function of
1098 /// UsualArithmeticConversions()
1099 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1100 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1101                                         ExprResult &RHS, QualType LHSType,
1102                                         QualType RHSType, bool IsCompAssign) {
1103   // The rules for this case are in C99 6.3.1.8
1104   int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1105   bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1106   bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1107   if (LHSSigned == RHSSigned) {
1108     // Same signedness; use the higher-ranked type
1109     if (order >= 0) {
1110       RHS = (*doRHSCast)(S, RHS.take(), LHSType);
1111       return LHSType;
1112     } else if (!IsCompAssign)
1113       LHS = (*doLHSCast)(S, LHS.take(), RHSType);
1114     return RHSType;
1115   } else if (order != (LHSSigned ? 1 : -1)) {
1116     // The unsigned type has greater than or equal rank to the
1117     // signed type, so use the unsigned type
1118     if (RHSSigned) {
1119       RHS = (*doRHSCast)(S, RHS.take(), LHSType);
1120       return LHSType;
1121     } else if (!IsCompAssign)
1122       LHS = (*doLHSCast)(S, LHS.take(), RHSType);
1123     return RHSType;
1124   } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1125     // The two types are different widths; if we are here, that
1126     // means the signed type is larger than the unsigned type, so
1127     // use the signed type.
1128     if (LHSSigned) {
1129       RHS = (*doRHSCast)(S, RHS.take(), LHSType);
1130       return LHSType;
1131     } else if (!IsCompAssign)
1132       LHS = (*doLHSCast)(S, LHS.take(), RHSType);
1133     return RHSType;
1134   } else {
1135     // The signed type is higher-ranked than the unsigned type,
1136     // but isn't actually any bigger (like unsigned int and long
1137     // on most 32-bit systems).  Use the unsigned type corresponding
1138     // to the signed type.
1139     QualType result =
1140       S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1141     RHS = (*doRHSCast)(S, RHS.take(), result);
1142     if (!IsCompAssign)
1143       LHS = (*doLHSCast)(S, LHS.take(), result);
1144     return result;
1145   }
1146 }
1147 
1148 /// \brief Handle conversions with GCC complex int extension.  Helper function
1149 /// of UsualArithmeticConversions()
1150 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1151                                            ExprResult &RHS, QualType LHSType,
1152                                            QualType RHSType,
1153                                            bool IsCompAssign) {
1154   const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1155   const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1156 
1157   if (LHSComplexInt && RHSComplexInt) {
1158     QualType LHSEltType = LHSComplexInt->getElementType();
1159     QualType RHSEltType = RHSComplexInt->getElementType();
1160     QualType ScalarType =
1161       handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1162         (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1163 
1164     return S.Context.getComplexType(ScalarType);
1165   }
1166 
1167   if (LHSComplexInt) {
1168     QualType LHSEltType = LHSComplexInt->getElementType();
1169     QualType ScalarType =
1170       handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1171         (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1172     QualType ComplexType = S.Context.getComplexType(ScalarType);
1173     RHS = S.ImpCastExprToType(RHS.take(), ComplexType,
1174                               CK_IntegralRealToComplex);
1175 
1176     return ComplexType;
1177   }
1178 
1179   assert(RHSComplexInt);
1180 
1181   QualType RHSEltType = RHSComplexInt->getElementType();
1182   QualType ScalarType =
1183     handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1184       (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1185   QualType ComplexType = S.Context.getComplexType(ScalarType);
1186 
1187   if (!IsCompAssign)
1188     LHS = S.ImpCastExprToType(LHS.take(), ComplexType,
1189                               CK_IntegralRealToComplex);
1190   return ComplexType;
1191 }
1192 
1193 /// UsualArithmeticConversions - Performs various conversions that are common to
1194 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1195 /// routine returns the first non-arithmetic type found. The client is
1196 /// responsible for emitting appropriate error diagnostics.
1197 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1198                                           bool IsCompAssign) {
1199   if (!IsCompAssign) {
1200     LHS = UsualUnaryConversions(LHS.take());
1201     if (LHS.isInvalid())
1202       return QualType();
1203   }
1204 
1205   RHS = UsualUnaryConversions(RHS.take());
1206   if (RHS.isInvalid())
1207     return QualType();
1208 
1209   // For conversion purposes, we ignore any qualifiers.
1210   // For example, "const float" and "float" are equivalent.
1211   QualType LHSType =
1212     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1213   QualType RHSType =
1214     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1215 
1216   // For conversion purposes, we ignore any atomic qualifier on the LHS.
1217   if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1218     LHSType = AtomicLHS->getValueType();
1219 
1220   // If both types are identical, no conversion is needed.
1221   if (LHSType == RHSType)
1222     return LHSType;
1223 
1224   // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1225   // The caller can deal with this (e.g. pointer + int).
1226   if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1227     return QualType();
1228 
1229   // Apply unary and bitfield promotions to the LHS's type.
1230   QualType LHSUnpromotedType = LHSType;
1231   if (LHSType->isPromotableIntegerType())
1232     LHSType = Context.getPromotedIntegerType(LHSType);
1233   QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1234   if (!LHSBitfieldPromoteTy.isNull())
1235     LHSType = LHSBitfieldPromoteTy;
1236   if (LHSType != LHSUnpromotedType && !IsCompAssign)
1237     LHS = ImpCastExprToType(LHS.take(), LHSType, CK_IntegralCast);
1238 
1239   // If both types are identical, no conversion is needed.
1240   if (LHSType == RHSType)
1241     return LHSType;
1242 
1243   // At this point, we have two different arithmetic types.
1244 
1245   // Handle complex types first (C99 6.3.1.8p1).
1246   if (LHSType->isComplexType() || RHSType->isComplexType())
1247     return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1248                                         IsCompAssign);
1249 
1250   // Now handle "real" floating types (i.e. float, double, long double).
1251   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1252     return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1253                                  IsCompAssign);
1254 
1255   // Handle GCC complex int extension.
1256   if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1257     return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1258                                       IsCompAssign);
1259 
1260   // Finally, we have two differing integer types.
1261   return handleIntegerConversion<doIntegralCast, doIntegralCast>
1262            (*this, LHS, RHS, LHSType, RHSType, IsCompAssign);
1263 }
1264 
1265 
1266 //===----------------------------------------------------------------------===//
1267 //  Semantic Analysis for various Expression Types
1268 //===----------------------------------------------------------------------===//
1269 
1270 
1271 ExprResult
1272 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1273                                 SourceLocation DefaultLoc,
1274                                 SourceLocation RParenLoc,
1275                                 Expr *ControllingExpr,
1276                                 ArrayRef<ParsedType> ArgTypes,
1277                                 ArrayRef<Expr *> ArgExprs) {
1278   unsigned NumAssocs = ArgTypes.size();
1279   assert(NumAssocs == ArgExprs.size());
1280 
1281   TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1282   for (unsigned i = 0; i < NumAssocs; ++i) {
1283     if (ArgTypes[i])
1284       (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1285     else
1286       Types[i] = 0;
1287   }
1288 
1289   ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1290                                              ControllingExpr,
1291                                              llvm::makeArrayRef(Types, NumAssocs),
1292                                              ArgExprs);
1293   delete [] Types;
1294   return ER;
1295 }
1296 
1297 ExprResult
1298 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1299                                  SourceLocation DefaultLoc,
1300                                  SourceLocation RParenLoc,
1301                                  Expr *ControllingExpr,
1302                                  ArrayRef<TypeSourceInfo *> Types,
1303                                  ArrayRef<Expr *> Exprs) {
1304   unsigned NumAssocs = Types.size();
1305   assert(NumAssocs == Exprs.size());
1306   if (ControllingExpr->getType()->isPlaceholderType()) {
1307     ExprResult result = CheckPlaceholderExpr(ControllingExpr);
1308     if (result.isInvalid()) return ExprError();
1309     ControllingExpr = result.take();
1310   }
1311 
1312   bool TypeErrorFound = false,
1313        IsResultDependent = ControllingExpr->isTypeDependent(),
1314        ContainsUnexpandedParameterPack
1315          = ControllingExpr->containsUnexpandedParameterPack();
1316 
1317   for (unsigned i = 0; i < NumAssocs; ++i) {
1318     if (Exprs[i]->containsUnexpandedParameterPack())
1319       ContainsUnexpandedParameterPack = true;
1320 
1321     if (Types[i]) {
1322       if (Types[i]->getType()->containsUnexpandedParameterPack())
1323         ContainsUnexpandedParameterPack = true;
1324 
1325       if (Types[i]->getType()->isDependentType()) {
1326         IsResultDependent = true;
1327       } else {
1328         // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1329         // complete object type other than a variably modified type."
1330         unsigned D = 0;
1331         if (Types[i]->getType()->isIncompleteType())
1332           D = diag::err_assoc_type_incomplete;
1333         else if (!Types[i]->getType()->isObjectType())
1334           D = diag::err_assoc_type_nonobject;
1335         else if (Types[i]->getType()->isVariablyModifiedType())
1336           D = diag::err_assoc_type_variably_modified;
1337 
1338         if (D != 0) {
1339           Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1340             << Types[i]->getTypeLoc().getSourceRange()
1341             << Types[i]->getType();
1342           TypeErrorFound = true;
1343         }
1344 
1345         // C11 6.5.1.1p2 "No two generic associations in the same generic
1346         // selection shall specify compatible types."
1347         for (unsigned j = i+1; j < NumAssocs; ++j)
1348           if (Types[j] && !Types[j]->getType()->isDependentType() &&
1349               Context.typesAreCompatible(Types[i]->getType(),
1350                                          Types[j]->getType())) {
1351             Diag(Types[j]->getTypeLoc().getBeginLoc(),
1352                  diag::err_assoc_compatible_types)
1353               << Types[j]->getTypeLoc().getSourceRange()
1354               << Types[j]->getType()
1355               << Types[i]->getType();
1356             Diag(Types[i]->getTypeLoc().getBeginLoc(),
1357                  diag::note_compat_assoc)
1358               << Types[i]->getTypeLoc().getSourceRange()
1359               << Types[i]->getType();
1360             TypeErrorFound = true;
1361           }
1362       }
1363     }
1364   }
1365   if (TypeErrorFound)
1366     return ExprError();
1367 
1368   // If we determined that the generic selection is result-dependent, don't
1369   // try to compute the result expression.
1370   if (IsResultDependent)
1371     return Owned(new (Context) GenericSelectionExpr(
1372                    Context, KeyLoc, ControllingExpr,
1373                    Types, Exprs,
1374                    DefaultLoc, RParenLoc, ContainsUnexpandedParameterPack));
1375 
1376   SmallVector<unsigned, 1> CompatIndices;
1377   unsigned DefaultIndex = -1U;
1378   for (unsigned i = 0; i < NumAssocs; ++i) {
1379     if (!Types[i])
1380       DefaultIndex = i;
1381     else if (Context.typesAreCompatible(ControllingExpr->getType(),
1382                                         Types[i]->getType()))
1383       CompatIndices.push_back(i);
1384   }
1385 
1386   // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1387   // type compatible with at most one of the types named in its generic
1388   // association list."
1389   if (CompatIndices.size() > 1) {
1390     // We strip parens here because the controlling expression is typically
1391     // parenthesized in macro definitions.
1392     ControllingExpr = ControllingExpr->IgnoreParens();
1393     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1394       << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1395       << (unsigned) CompatIndices.size();
1396     for (SmallVectorImpl<unsigned>::iterator I = CompatIndices.begin(),
1397          E = CompatIndices.end(); I != E; ++I) {
1398       Diag(Types[*I]->getTypeLoc().getBeginLoc(),
1399            diag::note_compat_assoc)
1400         << Types[*I]->getTypeLoc().getSourceRange()
1401         << Types[*I]->getType();
1402     }
1403     return ExprError();
1404   }
1405 
1406   // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1407   // its controlling expression shall have type compatible with exactly one of
1408   // the types named in its generic association list."
1409   if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1410     // We strip parens here because the controlling expression is typically
1411     // parenthesized in macro definitions.
1412     ControllingExpr = ControllingExpr->IgnoreParens();
1413     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1414       << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1415     return ExprError();
1416   }
1417 
1418   // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1419   // type name that is compatible with the type of the controlling expression,
1420   // then the result expression of the generic selection is the expression
1421   // in that generic association. Otherwise, the result expression of the
1422   // generic selection is the expression in the default generic association."
1423   unsigned ResultIndex =
1424     CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1425 
1426   return Owned(new (Context) GenericSelectionExpr(
1427                  Context, KeyLoc, ControllingExpr,
1428                  Types, Exprs,
1429                  DefaultLoc, RParenLoc, ContainsUnexpandedParameterPack,
1430                  ResultIndex));
1431 }
1432 
1433 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1434 /// location of the token and the offset of the ud-suffix within it.
1435 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1436                                      unsigned Offset) {
1437   return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1438                                         S.getLangOpts());
1439 }
1440 
1441 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1442 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1443 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1444                                                  IdentifierInfo *UDSuffix,
1445                                                  SourceLocation UDSuffixLoc,
1446                                                  ArrayRef<Expr*> Args,
1447                                                  SourceLocation LitEndLoc) {
1448   assert(Args.size() <= 2 && "too many arguments for literal operator");
1449 
1450   QualType ArgTy[2];
1451   for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1452     ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1453     if (ArgTy[ArgIdx]->isArrayType())
1454       ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1455   }
1456 
1457   DeclarationName OpName =
1458     S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1459   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1460   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1461 
1462   LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1463   if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1464                               /*AllowRaw*/false, /*AllowTemplate*/false,
1465                               /*AllowStringTemplate*/false) == Sema::LOLR_Error)
1466     return ExprError();
1467 
1468   return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1469 }
1470 
1471 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1472 /// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
1473 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1474 /// multiple tokens.  However, the common case is that StringToks points to one
1475 /// string.
1476 ///
1477 ExprResult
1478 Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks,
1479                          Scope *UDLScope) {
1480   assert(NumStringToks && "Must have at least one string!");
1481 
1482   StringLiteralParser Literal(StringToks, NumStringToks, PP);
1483   if (Literal.hadError)
1484     return ExprError();
1485 
1486   SmallVector<SourceLocation, 4> StringTokLocs;
1487   for (unsigned i = 0; i != NumStringToks; ++i)
1488     StringTokLocs.push_back(StringToks[i].getLocation());
1489 
1490   QualType CharTy = Context.CharTy;
1491   StringLiteral::StringKind Kind = StringLiteral::Ascii;
1492   if (Literal.isWide()) {
1493     CharTy = Context.getWideCharType();
1494     Kind = StringLiteral::Wide;
1495   } else if (Literal.isUTF8()) {
1496     Kind = StringLiteral::UTF8;
1497   } else if (Literal.isUTF16()) {
1498     CharTy = Context.Char16Ty;
1499     Kind = StringLiteral::UTF16;
1500   } else if (Literal.isUTF32()) {
1501     CharTy = Context.Char32Ty;
1502     Kind = StringLiteral::UTF32;
1503   } else if (Literal.isPascal()) {
1504     CharTy = Context.UnsignedCharTy;
1505   }
1506 
1507   QualType CharTyConst = CharTy;
1508   // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
1509   if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
1510     CharTyConst.addConst();
1511 
1512   // Get an array type for the string, according to C99 6.4.5.  This includes
1513   // the nul terminator character as well as the string length for pascal
1514   // strings.
1515   QualType StrTy = Context.getConstantArrayType(CharTyConst,
1516                                  llvm::APInt(32, Literal.GetNumStringChars()+1),
1517                                  ArrayType::Normal, 0);
1518 
1519   // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1520   StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1521                                              Kind, Literal.Pascal, StrTy,
1522                                              &StringTokLocs[0],
1523                                              StringTokLocs.size());
1524   if (Literal.getUDSuffix().empty())
1525     return Owned(Lit);
1526 
1527   // We're building a user-defined literal.
1528   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1529   SourceLocation UDSuffixLoc =
1530     getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1531                    Literal.getUDSuffixOffset());
1532 
1533   // Make sure we're allowed user-defined literals here.
1534   if (!UDLScope)
1535     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1536 
1537   // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1538   //   operator "" X (str, len)
1539   QualType SizeType = Context.getSizeType();
1540 
1541   DeclarationName OpName =
1542     Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1543   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1544   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1545 
1546   QualType ArgTy[] = {
1547     Context.getArrayDecayedType(StrTy), SizeType
1548   };
1549 
1550   LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1551   switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1552                                 /*AllowRaw*/false, /*AllowTemplate*/false,
1553                                 /*AllowStringTemplate*/true)) {
1554 
1555   case LOLR_Cooked: {
1556     llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1557     IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1558                                                     StringTokLocs[0]);
1559     Expr *Args[] = { Lit, LenArg };
1560 
1561     return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1562   }
1563 
1564   case LOLR_StringTemplate: {
1565     TemplateArgumentListInfo ExplicitArgs;
1566 
1567     unsigned CharBits = Context.getIntWidth(CharTy);
1568     bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1569     llvm::APSInt Value(CharBits, CharIsUnsigned);
1570 
1571     TemplateArgument TypeArg(CharTy);
1572     TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1573     ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1574 
1575     for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1576       Value = Lit->getCodeUnit(I);
1577       TemplateArgument Arg(Context, Value, CharTy);
1578       TemplateArgumentLocInfo ArgInfo;
1579       ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1580     }
1581     return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1582                                     &ExplicitArgs);
1583   }
1584   case LOLR_Raw:
1585   case LOLR_Template:
1586     llvm_unreachable("unexpected literal operator lookup result");
1587   case LOLR_Error:
1588     return ExprError();
1589   }
1590   llvm_unreachable("unexpected literal operator lookup result");
1591 }
1592 
1593 ExprResult
1594 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1595                        SourceLocation Loc,
1596                        const CXXScopeSpec *SS) {
1597   DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1598   return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1599 }
1600 
1601 /// BuildDeclRefExpr - Build an expression that references a
1602 /// declaration that does not require a closure capture.
1603 ExprResult
1604 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1605                        const DeclarationNameInfo &NameInfo,
1606                        const CXXScopeSpec *SS, NamedDecl *FoundD,
1607                        const TemplateArgumentListInfo *TemplateArgs) {
1608   if (getLangOpts().CUDA)
1609     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
1610       if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) {
1611         CUDAFunctionTarget CallerTarget = IdentifyCUDATarget(Caller),
1612                            CalleeTarget = IdentifyCUDATarget(Callee);
1613         if (CheckCUDATarget(CallerTarget, CalleeTarget)) {
1614           Diag(NameInfo.getLoc(), diag::err_ref_bad_target)
1615             << CalleeTarget << D->getIdentifier() << CallerTarget;
1616           Diag(D->getLocation(), diag::note_previous_decl)
1617             << D->getIdentifier();
1618           return ExprError();
1619         }
1620       }
1621 
1622   bool refersToEnclosingScope =
1623     (CurContext != D->getDeclContext() &&
1624      D->getDeclContext()->isFunctionOrMethod()) ||
1625     (isa<VarDecl>(D) &&
1626      cast<VarDecl>(D)->isInitCapture());
1627 
1628   DeclRefExpr *E;
1629   if (isa<VarTemplateSpecializationDecl>(D)) {
1630     VarTemplateSpecializationDecl *VarSpec =
1631         cast<VarTemplateSpecializationDecl>(D);
1632 
1633     E = DeclRefExpr::Create(
1634         Context,
1635         SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(),
1636         VarSpec->getTemplateKeywordLoc(), D, refersToEnclosingScope,
1637         NameInfo.getLoc(), Ty, VK, FoundD, TemplateArgs);
1638   } else {
1639     assert(!TemplateArgs && "No template arguments for non-variable"
1640                             " template specialization referrences");
1641     E = DeclRefExpr::Create(
1642         Context,
1643         SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(),
1644         SourceLocation(), D, refersToEnclosingScope, NameInfo, Ty, VK, FoundD);
1645   }
1646 
1647   MarkDeclRefReferenced(E);
1648 
1649   if (getLangOpts().ObjCARCWeak && isa<VarDecl>(D) &&
1650       Ty.getObjCLifetime() == Qualifiers::OCL_Weak) {
1651     DiagnosticsEngine::Level Level =
1652       Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
1653                                E->getLocStart());
1654     if (Level != DiagnosticsEngine::Ignored)
1655       recordUseOfEvaluatedWeak(E);
1656   }
1657 
1658   // Just in case we're building an illegal pointer-to-member.
1659   FieldDecl *FD = dyn_cast<FieldDecl>(D);
1660   if (FD && FD->isBitField())
1661     E->setObjectKind(OK_BitField);
1662 
1663   return Owned(E);
1664 }
1665 
1666 /// Decomposes the given name into a DeclarationNameInfo, its location, and
1667 /// possibly a list of template arguments.
1668 ///
1669 /// If this produces template arguments, it is permitted to call
1670 /// DecomposeTemplateName.
1671 ///
1672 /// This actually loses a lot of source location information for
1673 /// non-standard name kinds; we should consider preserving that in
1674 /// some way.
1675 void
1676 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1677                              TemplateArgumentListInfo &Buffer,
1678                              DeclarationNameInfo &NameInfo,
1679                              const TemplateArgumentListInfo *&TemplateArgs) {
1680   if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1681     Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1682     Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1683 
1684     ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
1685                                        Id.TemplateId->NumArgs);
1686     translateTemplateArguments(TemplateArgsPtr, Buffer);
1687 
1688     TemplateName TName = Id.TemplateId->Template.get();
1689     SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1690     NameInfo = Context.getNameForTemplate(TName, TNameLoc);
1691     TemplateArgs = &Buffer;
1692   } else {
1693     NameInfo = GetNameFromUnqualifiedId(Id);
1694     TemplateArgs = 0;
1695   }
1696 }
1697 
1698 /// Diagnose an empty lookup.
1699 ///
1700 /// \return false if new lookup candidates were found
1701 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1702                                CorrectionCandidateCallback &CCC,
1703                                TemplateArgumentListInfo *ExplicitTemplateArgs,
1704                                ArrayRef<Expr *> Args) {
1705   DeclarationName Name = R.getLookupName();
1706 
1707   unsigned diagnostic = diag::err_undeclared_var_use;
1708   unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
1709   if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1710       Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
1711       Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
1712     diagnostic = diag::err_undeclared_use;
1713     diagnostic_suggest = diag::err_undeclared_use_suggest;
1714   }
1715 
1716   // If the original lookup was an unqualified lookup, fake an
1717   // unqualified lookup.  This is useful when (for example) the
1718   // original lookup would not have found something because it was a
1719   // dependent name.
1720   DeclContext *DC = (SS.isEmpty() && !CallsUndergoingInstantiation.empty())
1721     ? CurContext : 0;
1722   while (DC) {
1723     if (isa<CXXRecordDecl>(DC)) {
1724       LookupQualifiedName(R, DC);
1725 
1726       if (!R.empty()) {
1727         // Don't give errors about ambiguities in this lookup.
1728         R.suppressDiagnostics();
1729 
1730         // During a default argument instantiation the CurContext points
1731         // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1732         // function parameter list, hence add an explicit check.
1733         bool isDefaultArgument = !ActiveTemplateInstantiations.empty() &&
1734                               ActiveTemplateInstantiations.back().Kind ==
1735             ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
1736         CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1737         bool isInstance = CurMethod &&
1738                           CurMethod->isInstance() &&
1739                           DC == CurMethod->getParent() && !isDefaultArgument;
1740 
1741 
1742         // Give a code modification hint to insert 'this->'.
1743         // TODO: fixit for inserting 'Base<T>::' in the other cases.
1744         // Actually quite difficult!
1745         if (getLangOpts().MicrosoftMode)
1746           diagnostic = diag::warn_found_via_dependent_bases_lookup;
1747         if (isInstance) {
1748           Diag(R.getNameLoc(), diagnostic) << Name
1749             << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1750           UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1751               CallsUndergoingInstantiation.back()->getCallee());
1752 
1753           CXXMethodDecl *DepMethod;
1754           if (CurMethod->isDependentContext())
1755             DepMethod = CurMethod;
1756           else if (CurMethod->getTemplatedKind() ==
1757               FunctionDecl::TK_FunctionTemplateSpecialization)
1758             DepMethod = cast<CXXMethodDecl>(CurMethod->getPrimaryTemplate()->
1759                 getInstantiatedFromMemberTemplate()->getTemplatedDecl());
1760           else
1761             DepMethod = cast<CXXMethodDecl>(
1762                 CurMethod->getInstantiatedFromMemberFunction());
1763           assert(DepMethod && "No template pattern found");
1764 
1765           QualType DepThisType = DepMethod->getThisType(Context);
1766           CheckCXXThisCapture(R.getNameLoc());
1767           CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1768                                      R.getNameLoc(), DepThisType, false);
1769           TemplateArgumentListInfo TList;
1770           if (ULE->hasExplicitTemplateArgs())
1771             ULE->copyTemplateArgumentsInto(TList);
1772 
1773           CXXScopeSpec SS;
1774           SS.Adopt(ULE->getQualifierLoc());
1775           CXXDependentScopeMemberExpr *DepExpr =
1776               CXXDependentScopeMemberExpr::Create(
1777                   Context, DepThis, DepThisType, true, SourceLocation(),
1778                   SS.getWithLocInContext(Context),
1779                   ULE->getTemplateKeywordLoc(), 0,
1780                   R.getLookupNameInfo(),
1781                   ULE->hasExplicitTemplateArgs() ? &TList : 0);
1782           CallsUndergoingInstantiation.back()->setCallee(DepExpr);
1783         } else {
1784           Diag(R.getNameLoc(), diagnostic) << Name;
1785         }
1786 
1787         // Do we really want to note all of these?
1788         for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1789           Diag((*I)->getLocation(), diag::note_dependent_var_use);
1790 
1791         // Return true if we are inside a default argument instantiation
1792         // and the found name refers to an instance member function, otherwise
1793         // the function calling DiagnoseEmptyLookup will try to create an
1794         // implicit member call and this is wrong for default argument.
1795         if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1796           Diag(R.getNameLoc(), diag::err_member_call_without_object);
1797           return true;
1798         }
1799 
1800         // Tell the callee to try to recover.
1801         return false;
1802       }
1803 
1804       R.clear();
1805     }
1806 
1807     // In Microsoft mode, if we are performing lookup from within a friend
1808     // function definition declared at class scope then we must set
1809     // DC to the lexical parent to be able to search into the parent
1810     // class.
1811     if (getLangOpts().MicrosoftMode && isa<FunctionDecl>(DC) &&
1812         cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1813         DC->getLexicalParent()->isRecord())
1814       DC = DC->getLexicalParent();
1815     else
1816       DC = DC->getParent();
1817   }
1818 
1819   // We didn't find anything, so try to correct for a typo.
1820   TypoCorrection Corrected;
1821   if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
1822                                     S, &SS, CCC))) {
1823     std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1824     bool DroppedSpecifier =
1825         Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
1826     R.setLookupName(Corrected.getCorrection());
1827 
1828     bool AcceptableWithRecovery = false;
1829     bool AcceptableWithoutRecovery = false;
1830     NamedDecl *ND = Corrected.getCorrectionDecl();
1831     if (ND) {
1832       if (Corrected.isOverloaded()) {
1833         OverloadCandidateSet OCS(R.getNameLoc());
1834         OverloadCandidateSet::iterator Best;
1835         for (TypoCorrection::decl_iterator CD = Corrected.begin(),
1836                                         CDEnd = Corrected.end();
1837              CD != CDEnd; ++CD) {
1838           if (FunctionTemplateDecl *FTD =
1839                    dyn_cast<FunctionTemplateDecl>(*CD))
1840             AddTemplateOverloadCandidate(
1841                 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
1842                 Args, OCS);
1843           else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
1844             if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1845               AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
1846                                    Args, OCS);
1847         }
1848         switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1849         case OR_Success:
1850           ND = Best->Function;
1851           Corrected.setCorrectionDecl(ND);
1852           break;
1853         default:
1854           // FIXME: Arbitrarily pick the first declaration for the note.
1855           Corrected.setCorrectionDecl(ND);
1856           break;
1857         }
1858       }
1859       R.addDecl(ND);
1860 
1861       AcceptableWithRecovery =
1862           isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND);
1863       // FIXME: If we ended up with a typo for a type name or
1864       // Objective-C class name, we're in trouble because the parser
1865       // is in the wrong place to recover. Suggest the typo
1866       // correction, but don't make it a fix-it since we're not going
1867       // to recover well anyway.
1868       AcceptableWithoutRecovery =
1869           isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
1870     } else {
1871       // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
1872       // because we aren't able to recover.
1873       AcceptableWithoutRecovery = true;
1874     }
1875 
1876     if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
1877       unsigned NoteID = (Corrected.getCorrectionDecl() &&
1878                          isa<ImplicitParamDecl>(Corrected.getCorrectionDecl()))
1879                             ? diag::note_implicit_param_decl
1880                             : diag::note_previous_decl;
1881       if (SS.isEmpty())
1882         diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
1883                      PDiag(NoteID), AcceptableWithRecovery);
1884       else
1885         diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
1886                                   << Name << computeDeclContext(SS, false)
1887                                   << DroppedSpecifier << SS.getRange(),
1888                      PDiag(NoteID), AcceptableWithRecovery);
1889 
1890       // Tell the callee whether to try to recover.
1891       return !AcceptableWithRecovery;
1892     }
1893   }
1894   R.clear();
1895 
1896   // Emit a special diagnostic for failed member lookups.
1897   // FIXME: computing the declaration context might fail here (?)
1898   if (!SS.isEmpty()) {
1899     Diag(R.getNameLoc(), diag::err_no_member)
1900       << Name << computeDeclContext(SS, false)
1901       << SS.getRange();
1902     return true;
1903   }
1904 
1905   // Give up, we can't recover.
1906   Diag(R.getNameLoc(), diagnostic) << Name;
1907   return true;
1908 }
1909 
1910 ExprResult Sema::ActOnIdExpression(Scope *S,
1911                                    CXXScopeSpec &SS,
1912                                    SourceLocation TemplateKWLoc,
1913                                    UnqualifiedId &Id,
1914                                    bool HasTrailingLParen,
1915                                    bool IsAddressOfOperand,
1916                                    CorrectionCandidateCallback *CCC,
1917                                    bool IsInlineAsmIdentifier) {
1918   assert(!(IsAddressOfOperand && HasTrailingLParen) &&
1919          "cannot be direct & operand and have a trailing lparen");
1920   if (SS.isInvalid())
1921     return ExprError();
1922 
1923   TemplateArgumentListInfo TemplateArgsBuffer;
1924 
1925   // Decompose the UnqualifiedId into the following data.
1926   DeclarationNameInfo NameInfo;
1927   const TemplateArgumentListInfo *TemplateArgs;
1928   DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
1929 
1930   DeclarationName Name = NameInfo.getName();
1931   IdentifierInfo *II = Name.getAsIdentifierInfo();
1932   SourceLocation NameLoc = NameInfo.getLoc();
1933 
1934   // C++ [temp.dep.expr]p3:
1935   //   An id-expression is type-dependent if it contains:
1936   //     -- an identifier that was declared with a dependent type,
1937   //        (note: handled after lookup)
1938   //     -- a template-id that is dependent,
1939   //        (note: handled in BuildTemplateIdExpr)
1940   //     -- a conversion-function-id that specifies a dependent type,
1941   //     -- a nested-name-specifier that contains a class-name that
1942   //        names a dependent type.
1943   // Determine whether this is a member of an unknown specialization;
1944   // we need to handle these differently.
1945   bool DependentID = false;
1946   if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1947       Name.getCXXNameType()->isDependentType()) {
1948     DependentID = true;
1949   } else if (SS.isSet()) {
1950     if (DeclContext *DC = computeDeclContext(SS, false)) {
1951       if (RequireCompleteDeclContext(SS, DC))
1952         return ExprError();
1953     } else {
1954       DependentID = true;
1955     }
1956   }
1957 
1958   if (DependentID)
1959     return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1960                                       IsAddressOfOperand, TemplateArgs);
1961 
1962   // Perform the required lookup.
1963   LookupResult R(*this, NameInfo,
1964                  (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
1965                   ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
1966   if (TemplateArgs) {
1967     // Lookup the template name again to correctly establish the context in
1968     // which it was found. This is really unfortunate as we already did the
1969     // lookup to determine that it was a template name in the first place. If
1970     // this becomes a performance hit, we can work harder to preserve those
1971     // results until we get here but it's likely not worth it.
1972     bool MemberOfUnknownSpecialization;
1973     LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1974                        MemberOfUnknownSpecialization);
1975 
1976     if (MemberOfUnknownSpecialization ||
1977         (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
1978       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1979                                         IsAddressOfOperand, TemplateArgs);
1980   } else {
1981     bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
1982     LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
1983 
1984     // If the result might be in a dependent base class, this is a dependent
1985     // id-expression.
1986     if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
1987       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1988                                         IsAddressOfOperand, TemplateArgs);
1989 
1990     // If this reference is in an Objective-C method, then we need to do
1991     // some special Objective-C lookup, too.
1992     if (IvarLookupFollowUp) {
1993       ExprResult E(LookupInObjCMethod(R, S, II, true));
1994       if (E.isInvalid())
1995         return ExprError();
1996 
1997       if (Expr *Ex = E.takeAs<Expr>())
1998         return Owned(Ex);
1999     }
2000   }
2001 
2002   if (R.isAmbiguous())
2003     return ExprError();
2004 
2005   // Determine whether this name might be a candidate for
2006   // argument-dependent lookup.
2007   bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2008 
2009   if (R.empty() && !ADL) {
2010 
2011     // Otherwise, this could be an implicitly declared function reference (legal
2012     // in C90, extension in C99, forbidden in C++).
2013     if (HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2014       NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2015       if (D) R.addDecl(D);
2016     }
2017 
2018     // If this name wasn't predeclared and if this is not a function
2019     // call, diagnose the problem.
2020     if (R.empty()) {
2021       // In Microsoft mode, if we are inside a template class member function
2022       // whose parent class has dependent base classes, and we can't resolve
2023       // an identifier, then assume the identifier is a member of a dependent
2024       // base class.  The goal is to postpone name lookup to instantiation time
2025       // to be able to search into the type dependent base classes.
2026       // FIXME: If we want 100% compatibility with MSVC, we will have delay all
2027       // unqualified name lookup.  Any name lookup during template parsing means
2028       // clang might find something that MSVC doesn't.  For now, we only handle
2029       // the common case of members of a dependent base class.
2030       if (getLangOpts().MicrosoftMode) {
2031         CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext);
2032         if (MD && MD->isInstance() && MD->getParent()->hasAnyDependentBases()) {
2033           assert(SS.isEmpty() && "qualifiers should be already handled");
2034           QualType ThisType = MD->getThisType(Context);
2035           // Since the 'this' expression is synthesized, we don't need to
2036           // perform the double-lookup check.
2037           NamedDecl *FirstQualifierInScope = 0;
2038           return Owned(CXXDependentScopeMemberExpr::Create(
2039               Context, /*This=*/0, ThisType, /*IsArrow=*/true,
2040               /*Op=*/SourceLocation(), SS.getWithLocInContext(Context),
2041               TemplateKWLoc, FirstQualifierInScope, NameInfo, TemplateArgs));
2042         }
2043       }
2044 
2045       // Don't diagnose an empty lookup for inline assmebly.
2046       if (IsInlineAsmIdentifier)
2047         return ExprError();
2048 
2049       CorrectionCandidateCallback DefaultValidator;
2050       if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator))
2051         return ExprError();
2052 
2053       assert(!R.empty() &&
2054              "DiagnoseEmptyLookup returned false but added no results");
2055 
2056       // If we found an Objective-C instance variable, let
2057       // LookupInObjCMethod build the appropriate expression to
2058       // reference the ivar.
2059       if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2060         R.clear();
2061         ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2062         // In a hopelessly buggy code, Objective-C instance variable
2063         // lookup fails and no expression will be built to reference it.
2064         if (!E.isInvalid() && !E.get())
2065           return ExprError();
2066         return E;
2067       }
2068     }
2069   }
2070 
2071   // This is guaranteed from this point on.
2072   assert(!R.empty() || ADL);
2073 
2074   // Check whether this might be a C++ implicit instance member access.
2075   // C++ [class.mfct.non-static]p3:
2076   //   When an id-expression that is not part of a class member access
2077   //   syntax and not used to form a pointer to member is used in the
2078   //   body of a non-static member function of class X, if name lookup
2079   //   resolves the name in the id-expression to a non-static non-type
2080   //   member of some class C, the id-expression is transformed into a
2081   //   class member access expression using (*this) as the
2082   //   postfix-expression to the left of the . operator.
2083   //
2084   // But we don't actually need to do this for '&' operands if R
2085   // resolved to a function or overloaded function set, because the
2086   // expression is ill-formed if it actually works out to be a
2087   // non-static member function:
2088   //
2089   // C++ [expr.ref]p4:
2090   //   Otherwise, if E1.E2 refers to a non-static member function. . .
2091   //   [t]he expression can be used only as the left-hand operand of a
2092   //   member function call.
2093   //
2094   // There are other safeguards against such uses, but it's important
2095   // to get this right here so that we don't end up making a
2096   // spuriously dependent expression if we're inside a dependent
2097   // instance method.
2098   if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2099     bool MightBeImplicitMember;
2100     if (!IsAddressOfOperand)
2101       MightBeImplicitMember = true;
2102     else if (!SS.isEmpty())
2103       MightBeImplicitMember = false;
2104     else if (R.isOverloadedResult())
2105       MightBeImplicitMember = false;
2106     else if (R.isUnresolvableResult())
2107       MightBeImplicitMember = true;
2108     else
2109       MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2110                               isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2111                               isa<MSPropertyDecl>(R.getFoundDecl());
2112 
2113     if (MightBeImplicitMember)
2114       return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2115                                              R, TemplateArgs);
2116   }
2117 
2118   if (TemplateArgs || TemplateKWLoc.isValid()) {
2119 
2120     // In C++1y, if this is a variable template id, then check it
2121     // in BuildTemplateIdExpr().
2122     // The single lookup result must be a variable template declaration.
2123     if (Id.getKind() == UnqualifiedId::IK_TemplateId && Id.TemplateId &&
2124         Id.TemplateId->Kind == TNK_Var_template) {
2125       assert(R.getAsSingle<VarTemplateDecl>() &&
2126              "There should only be one declaration found.");
2127     }
2128 
2129     return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2130   }
2131 
2132   return BuildDeclarationNameExpr(SS, R, ADL);
2133 }
2134 
2135 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2136 /// declaration name, generally during template instantiation.
2137 /// There's a large number of things which don't need to be done along
2138 /// this path.
2139 ExprResult
2140 Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
2141                                         const DeclarationNameInfo &NameInfo,
2142                                         bool IsAddressOfOperand) {
2143   DeclContext *DC = computeDeclContext(SS, false);
2144   if (!DC)
2145     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2146                                      NameInfo, /*TemplateArgs=*/0);
2147 
2148   if (RequireCompleteDeclContext(SS, DC))
2149     return ExprError();
2150 
2151   LookupResult R(*this, NameInfo, LookupOrdinaryName);
2152   LookupQualifiedName(R, DC);
2153 
2154   if (R.isAmbiguous())
2155     return ExprError();
2156 
2157   if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2158     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2159                                      NameInfo, /*TemplateArgs=*/0);
2160 
2161   if (R.empty()) {
2162     Diag(NameInfo.getLoc(), diag::err_no_member)
2163       << NameInfo.getName() << DC << SS.getRange();
2164     return ExprError();
2165   }
2166 
2167   // Defend against this resolving to an implicit member access. We usually
2168   // won't get here if this might be a legitimate a class member (we end up in
2169   // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2170   // a pointer-to-member or in an unevaluated context in C++11.
2171   if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2172     return BuildPossibleImplicitMemberExpr(SS,
2173                                            /*TemplateKWLoc=*/SourceLocation(),
2174                                            R, /*TemplateArgs=*/0);
2175 
2176   return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2177 }
2178 
2179 /// LookupInObjCMethod - The parser has read a name in, and Sema has
2180 /// detected that we're currently inside an ObjC method.  Perform some
2181 /// additional lookup.
2182 ///
2183 /// Ideally, most of this would be done by lookup, but there's
2184 /// actually quite a lot of extra work involved.
2185 ///
2186 /// Returns a null sentinel to indicate trivial success.
2187 ExprResult
2188 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2189                          IdentifierInfo *II, bool AllowBuiltinCreation) {
2190   SourceLocation Loc = Lookup.getNameLoc();
2191   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2192 
2193   // Check for error condition which is already reported.
2194   if (!CurMethod)
2195     return ExprError();
2196 
2197   // There are two cases to handle here.  1) scoped lookup could have failed,
2198   // in which case we should look for an ivar.  2) scoped lookup could have
2199   // found a decl, but that decl is outside the current instance method (i.e.
2200   // a global variable).  In these two cases, we do a lookup for an ivar with
2201   // this name, if the lookup sucedes, we replace it our current decl.
2202 
2203   // If we're in a class method, we don't normally want to look for
2204   // ivars.  But if we don't find anything else, and there's an
2205   // ivar, that's an error.
2206   bool IsClassMethod = CurMethod->isClassMethod();
2207 
2208   bool LookForIvars;
2209   if (Lookup.empty())
2210     LookForIvars = true;
2211   else if (IsClassMethod)
2212     LookForIvars = false;
2213   else
2214     LookForIvars = (Lookup.isSingleResult() &&
2215                     Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2216   ObjCInterfaceDecl *IFace = 0;
2217   if (LookForIvars) {
2218     IFace = CurMethod->getClassInterface();
2219     ObjCInterfaceDecl *ClassDeclared;
2220     ObjCIvarDecl *IV = 0;
2221     if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2222       // Diagnose using an ivar in a class method.
2223       if (IsClassMethod)
2224         return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
2225                          << IV->getDeclName());
2226 
2227       // If we're referencing an invalid decl, just return this as a silent
2228       // error node.  The error diagnostic was already emitted on the decl.
2229       if (IV->isInvalidDecl())
2230         return ExprError();
2231 
2232       // Check if referencing a field with __attribute__((deprecated)).
2233       if (DiagnoseUseOfDecl(IV, Loc))
2234         return ExprError();
2235 
2236       // Diagnose the use of an ivar outside of the declaring class.
2237       if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2238           !declaresSameEntity(ClassDeclared, IFace) &&
2239           !getLangOpts().DebuggerSupport)
2240         Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
2241 
2242       // FIXME: This should use a new expr for a direct reference, don't
2243       // turn this into Self->ivar, just return a BareIVarExpr or something.
2244       IdentifierInfo &II = Context.Idents.get("self");
2245       UnqualifiedId SelfName;
2246       SelfName.setIdentifier(&II, SourceLocation());
2247       SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
2248       CXXScopeSpec SelfScopeSpec;
2249       SourceLocation TemplateKWLoc;
2250       ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
2251                                               SelfName, false, false);
2252       if (SelfExpr.isInvalid())
2253         return ExprError();
2254 
2255       SelfExpr = DefaultLvalueConversion(SelfExpr.take());
2256       if (SelfExpr.isInvalid())
2257         return ExprError();
2258 
2259       MarkAnyDeclReferenced(Loc, IV, true);
2260 
2261       ObjCMethodFamily MF = CurMethod->getMethodFamily();
2262       if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2263           !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2264         Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2265 
2266       ObjCIvarRefExpr *Result = new (Context) ObjCIvarRefExpr(IV, IV->getType(),
2267                                                               Loc, IV->getLocation(),
2268                                                               SelfExpr.take(),
2269                                                               true, true);
2270 
2271       if (getLangOpts().ObjCAutoRefCount) {
2272         if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2273           DiagnosticsEngine::Level Level =
2274             Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, Loc);
2275           if (Level != DiagnosticsEngine::Ignored)
2276             recordUseOfEvaluatedWeak(Result);
2277         }
2278         if (CurContext->isClosure())
2279           Diag(Loc, diag::warn_implicitly_retains_self)
2280             << FixItHint::CreateInsertion(Loc, "self->");
2281       }
2282 
2283       return Owned(Result);
2284     }
2285   } else if (CurMethod->isInstanceMethod()) {
2286     // We should warn if a local variable hides an ivar.
2287     if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2288       ObjCInterfaceDecl *ClassDeclared;
2289       if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2290         if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2291             declaresSameEntity(IFace, ClassDeclared))
2292           Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2293       }
2294     }
2295   } else if (Lookup.isSingleResult() &&
2296              Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2297     // If accessing a stand-alone ivar in a class method, this is an error.
2298     if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
2299       return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
2300                        << IV->getDeclName());
2301   }
2302 
2303   if (Lookup.empty() && II && AllowBuiltinCreation) {
2304     // FIXME. Consolidate this with similar code in LookupName.
2305     if (unsigned BuiltinID = II->getBuiltinID()) {
2306       if (!(getLangOpts().CPlusPlus &&
2307             Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2308         NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2309                                            S, Lookup.isForRedeclaration(),
2310                                            Lookup.getNameLoc());
2311         if (D) Lookup.addDecl(D);
2312       }
2313     }
2314   }
2315   // Sentinel value saying that we didn't do anything special.
2316   return Owned((Expr*) 0);
2317 }
2318 
2319 /// \brief Cast a base object to a member's actual type.
2320 ///
2321 /// Logically this happens in three phases:
2322 ///
2323 /// * First we cast from the base type to the naming class.
2324 ///   The naming class is the class into which we were looking
2325 ///   when we found the member;  it's the qualifier type if a
2326 ///   qualifier was provided, and otherwise it's the base type.
2327 ///
2328 /// * Next we cast from the naming class to the declaring class.
2329 ///   If the member we found was brought into a class's scope by
2330 ///   a using declaration, this is that class;  otherwise it's
2331 ///   the class declaring the member.
2332 ///
2333 /// * Finally we cast from the declaring class to the "true"
2334 ///   declaring class of the member.  This conversion does not
2335 ///   obey access control.
2336 ExprResult
2337 Sema::PerformObjectMemberConversion(Expr *From,
2338                                     NestedNameSpecifier *Qualifier,
2339                                     NamedDecl *FoundDecl,
2340                                     NamedDecl *Member) {
2341   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2342   if (!RD)
2343     return Owned(From);
2344 
2345   QualType DestRecordType;
2346   QualType DestType;
2347   QualType FromRecordType;
2348   QualType FromType = From->getType();
2349   bool PointerConversions = false;
2350   if (isa<FieldDecl>(Member)) {
2351     DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2352 
2353     if (FromType->getAs<PointerType>()) {
2354       DestType = Context.getPointerType(DestRecordType);
2355       FromRecordType = FromType->getPointeeType();
2356       PointerConversions = true;
2357     } else {
2358       DestType = DestRecordType;
2359       FromRecordType = FromType;
2360     }
2361   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2362     if (Method->isStatic())
2363       return Owned(From);
2364 
2365     DestType = Method->getThisType(Context);
2366     DestRecordType = DestType->getPointeeType();
2367 
2368     if (FromType->getAs<PointerType>()) {
2369       FromRecordType = FromType->getPointeeType();
2370       PointerConversions = true;
2371     } else {
2372       FromRecordType = FromType;
2373       DestType = DestRecordType;
2374     }
2375   } else {
2376     // No conversion necessary.
2377     return Owned(From);
2378   }
2379 
2380   if (DestType->isDependentType() || FromType->isDependentType())
2381     return Owned(From);
2382 
2383   // If the unqualified types are the same, no conversion is necessary.
2384   if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2385     return Owned(From);
2386 
2387   SourceRange FromRange = From->getSourceRange();
2388   SourceLocation FromLoc = FromRange.getBegin();
2389 
2390   ExprValueKind VK = From->getValueKind();
2391 
2392   // C++ [class.member.lookup]p8:
2393   //   [...] Ambiguities can often be resolved by qualifying a name with its
2394   //   class name.
2395   //
2396   // If the member was a qualified name and the qualified referred to a
2397   // specific base subobject type, we'll cast to that intermediate type
2398   // first and then to the object in which the member is declared. That allows
2399   // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2400   //
2401   //   class Base { public: int x; };
2402   //   class Derived1 : public Base { };
2403   //   class Derived2 : public Base { };
2404   //   class VeryDerived : public Derived1, public Derived2 { void f(); };
2405   //
2406   //   void VeryDerived::f() {
2407   //     x = 17; // error: ambiguous base subobjects
2408   //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
2409   //   }
2410   if (Qualifier && Qualifier->getAsType()) {
2411     QualType QType = QualType(Qualifier->getAsType(), 0);
2412     assert(QType->isRecordType() && "lookup done with non-record type");
2413 
2414     QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2415 
2416     // In C++98, the qualifier type doesn't actually have to be a base
2417     // type of the object type, in which case we just ignore it.
2418     // Otherwise build the appropriate casts.
2419     if (IsDerivedFrom(FromRecordType, QRecordType)) {
2420       CXXCastPath BasePath;
2421       if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2422                                        FromLoc, FromRange, &BasePath))
2423         return ExprError();
2424 
2425       if (PointerConversions)
2426         QType = Context.getPointerType(QType);
2427       From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2428                                VK, &BasePath).take();
2429 
2430       FromType = QType;
2431       FromRecordType = QRecordType;
2432 
2433       // If the qualifier type was the same as the destination type,
2434       // we're done.
2435       if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2436         return Owned(From);
2437     }
2438   }
2439 
2440   bool IgnoreAccess = false;
2441 
2442   // If we actually found the member through a using declaration, cast
2443   // down to the using declaration's type.
2444   //
2445   // Pointer equality is fine here because only one declaration of a
2446   // class ever has member declarations.
2447   if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2448     assert(isa<UsingShadowDecl>(FoundDecl));
2449     QualType URecordType = Context.getTypeDeclType(
2450                            cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2451 
2452     // We only need to do this if the naming-class to declaring-class
2453     // conversion is non-trivial.
2454     if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2455       assert(IsDerivedFrom(FromRecordType, URecordType));
2456       CXXCastPath BasePath;
2457       if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2458                                        FromLoc, FromRange, &BasePath))
2459         return ExprError();
2460 
2461       QualType UType = URecordType;
2462       if (PointerConversions)
2463         UType = Context.getPointerType(UType);
2464       From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2465                                VK, &BasePath).take();
2466       FromType = UType;
2467       FromRecordType = URecordType;
2468     }
2469 
2470     // We don't do access control for the conversion from the
2471     // declaring class to the true declaring class.
2472     IgnoreAccess = true;
2473   }
2474 
2475   CXXCastPath BasePath;
2476   if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2477                                    FromLoc, FromRange, &BasePath,
2478                                    IgnoreAccess))
2479     return ExprError();
2480 
2481   return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2482                            VK, &BasePath);
2483 }
2484 
2485 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2486                                       const LookupResult &R,
2487                                       bool HasTrailingLParen) {
2488   // Only when used directly as the postfix-expression of a call.
2489   if (!HasTrailingLParen)
2490     return false;
2491 
2492   // Never if a scope specifier was provided.
2493   if (SS.isSet())
2494     return false;
2495 
2496   // Only in C++ or ObjC++.
2497   if (!getLangOpts().CPlusPlus)
2498     return false;
2499 
2500   // Turn off ADL when we find certain kinds of declarations during
2501   // normal lookup:
2502   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2503     NamedDecl *D = *I;
2504 
2505     // C++0x [basic.lookup.argdep]p3:
2506     //     -- a declaration of a class member
2507     // Since using decls preserve this property, we check this on the
2508     // original decl.
2509     if (D->isCXXClassMember())
2510       return false;
2511 
2512     // C++0x [basic.lookup.argdep]p3:
2513     //     -- a block-scope function declaration that is not a
2514     //        using-declaration
2515     // NOTE: we also trigger this for function templates (in fact, we
2516     // don't check the decl type at all, since all other decl types
2517     // turn off ADL anyway).
2518     if (isa<UsingShadowDecl>(D))
2519       D = cast<UsingShadowDecl>(D)->getTargetDecl();
2520     else if (D->getLexicalDeclContext()->isFunctionOrMethod())
2521       return false;
2522 
2523     // C++0x [basic.lookup.argdep]p3:
2524     //     -- a declaration that is neither a function or a function
2525     //        template
2526     // And also for builtin functions.
2527     if (isa<FunctionDecl>(D)) {
2528       FunctionDecl *FDecl = cast<FunctionDecl>(D);
2529 
2530       // But also builtin functions.
2531       if (FDecl->getBuiltinID() && FDecl->isImplicit())
2532         return false;
2533     } else if (!isa<FunctionTemplateDecl>(D))
2534       return false;
2535   }
2536 
2537   return true;
2538 }
2539 
2540 
2541 /// Diagnoses obvious problems with the use of the given declaration
2542 /// as an expression.  This is only actually called for lookups that
2543 /// were not overloaded, and it doesn't promise that the declaration
2544 /// will in fact be used.
2545 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2546   if (isa<TypedefNameDecl>(D)) {
2547     S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2548     return true;
2549   }
2550 
2551   if (isa<ObjCInterfaceDecl>(D)) {
2552     S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2553     return true;
2554   }
2555 
2556   if (isa<NamespaceDecl>(D)) {
2557     S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2558     return true;
2559   }
2560 
2561   return false;
2562 }
2563 
2564 ExprResult
2565 Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2566                                LookupResult &R,
2567                                bool NeedsADL) {
2568   // If this is a single, fully-resolved result and we don't need ADL,
2569   // just build an ordinary singleton decl ref.
2570   if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
2571     return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
2572                                     R.getRepresentativeDecl());
2573 
2574   // We only need to check the declaration if there's exactly one
2575   // result, because in the overloaded case the results can only be
2576   // functions and function templates.
2577   if (R.isSingleResult() &&
2578       CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
2579     return ExprError();
2580 
2581   // Otherwise, just build an unresolved lookup expression.  Suppress
2582   // any lookup-related diagnostics; we'll hash these out later, when
2583   // we've picked a target.
2584   R.suppressDiagnostics();
2585 
2586   UnresolvedLookupExpr *ULE
2587     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2588                                    SS.getWithLocInContext(Context),
2589                                    R.getLookupNameInfo(),
2590                                    NeedsADL, R.isOverloadedResult(),
2591                                    R.begin(), R.end());
2592 
2593   return Owned(ULE);
2594 }
2595 
2596 /// \brief Complete semantic analysis for a reference to the given declaration.
2597 ExprResult Sema::BuildDeclarationNameExpr(
2598     const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
2599     NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs) {
2600   assert(D && "Cannot refer to a NULL declaration");
2601   assert(!isa<FunctionTemplateDecl>(D) &&
2602          "Cannot refer unambiguously to a function template");
2603 
2604   SourceLocation Loc = NameInfo.getLoc();
2605   if (CheckDeclInExpr(*this, Loc, D))
2606     return ExprError();
2607 
2608   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2609     // Specifically diagnose references to class templates that are missing
2610     // a template argument list.
2611     Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0)
2612                                            << Template << SS.getRange();
2613     Diag(Template->getLocation(), diag::note_template_decl_here);
2614     return ExprError();
2615   }
2616 
2617   // Make sure that we're referring to a value.
2618   ValueDecl *VD = dyn_cast<ValueDecl>(D);
2619   if (!VD) {
2620     Diag(Loc, diag::err_ref_non_value)
2621       << D << SS.getRange();
2622     Diag(D->getLocation(), diag::note_declared_at);
2623     return ExprError();
2624   }
2625 
2626   // Check whether this declaration can be used. Note that we suppress
2627   // this check when we're going to perform argument-dependent lookup
2628   // on this function name, because this might not be the function
2629   // that overload resolution actually selects.
2630   if (DiagnoseUseOfDecl(VD, Loc))
2631     return ExprError();
2632 
2633   // Only create DeclRefExpr's for valid Decl's.
2634   if (VD->isInvalidDecl())
2635     return ExprError();
2636 
2637   // Handle members of anonymous structs and unions.  If we got here,
2638   // and the reference is to a class member indirect field, then this
2639   // must be the subject of a pointer-to-member expression.
2640   if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2641     if (!indirectField->isCXXClassMember())
2642       return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2643                                                       indirectField);
2644 
2645   {
2646     QualType type = VD->getType();
2647     ExprValueKind valueKind = VK_RValue;
2648 
2649     switch (D->getKind()) {
2650     // Ignore all the non-ValueDecl kinds.
2651 #define ABSTRACT_DECL(kind)
2652 #define VALUE(type, base)
2653 #define DECL(type, base) \
2654     case Decl::type:
2655 #include "clang/AST/DeclNodes.inc"
2656       llvm_unreachable("invalid value decl kind");
2657 
2658     // These shouldn't make it here.
2659     case Decl::ObjCAtDefsField:
2660     case Decl::ObjCIvar:
2661       llvm_unreachable("forming non-member reference to ivar?");
2662 
2663     // Enum constants are always r-values and never references.
2664     // Unresolved using declarations are dependent.
2665     case Decl::EnumConstant:
2666     case Decl::UnresolvedUsingValue:
2667       valueKind = VK_RValue;
2668       break;
2669 
2670     // Fields and indirect fields that got here must be for
2671     // pointer-to-member expressions; we just call them l-values for
2672     // internal consistency, because this subexpression doesn't really
2673     // exist in the high-level semantics.
2674     case Decl::Field:
2675     case Decl::IndirectField:
2676       assert(getLangOpts().CPlusPlus &&
2677              "building reference to field in C?");
2678 
2679       // These can't have reference type in well-formed programs, but
2680       // for internal consistency we do this anyway.
2681       type = type.getNonReferenceType();
2682       valueKind = VK_LValue;
2683       break;
2684 
2685     // Non-type template parameters are either l-values or r-values
2686     // depending on the type.
2687     case Decl::NonTypeTemplateParm: {
2688       if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2689         type = reftype->getPointeeType();
2690         valueKind = VK_LValue; // even if the parameter is an r-value reference
2691         break;
2692       }
2693 
2694       // For non-references, we need to strip qualifiers just in case
2695       // the template parameter was declared as 'const int' or whatever.
2696       valueKind = VK_RValue;
2697       type = type.getUnqualifiedType();
2698       break;
2699     }
2700 
2701     case Decl::Var:
2702     case Decl::VarTemplateSpecialization:
2703     case Decl::VarTemplatePartialSpecialization:
2704       // In C, "extern void blah;" is valid and is an r-value.
2705       if (!getLangOpts().CPlusPlus &&
2706           !type.hasQualifiers() &&
2707           type->isVoidType()) {
2708         valueKind = VK_RValue;
2709         break;
2710       }
2711       // fallthrough
2712 
2713     case Decl::ImplicitParam:
2714     case Decl::ParmVar: {
2715       // These are always l-values.
2716       valueKind = VK_LValue;
2717       type = type.getNonReferenceType();
2718 
2719       // FIXME: Does the addition of const really only apply in
2720       // potentially-evaluated contexts? Since the variable isn't actually
2721       // captured in an unevaluated context, it seems that the answer is no.
2722       if (!isUnevaluatedContext()) {
2723         QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
2724         if (!CapturedType.isNull())
2725           type = CapturedType;
2726       }
2727 
2728       break;
2729     }
2730 
2731     case Decl::Function: {
2732       if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
2733         if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
2734           type = Context.BuiltinFnTy;
2735           valueKind = VK_RValue;
2736           break;
2737         }
2738       }
2739 
2740       const FunctionType *fty = type->castAs<FunctionType>();
2741 
2742       // If we're referring to a function with an __unknown_anytype
2743       // result type, make the entire expression __unknown_anytype.
2744       if (fty->getResultType() == Context.UnknownAnyTy) {
2745         type = Context.UnknownAnyTy;
2746         valueKind = VK_RValue;
2747         break;
2748       }
2749 
2750       // Functions are l-values in C++.
2751       if (getLangOpts().CPlusPlus) {
2752         valueKind = VK_LValue;
2753         break;
2754       }
2755 
2756       // C99 DR 316 says that, if a function type comes from a
2757       // function definition (without a prototype), that type is only
2758       // used for checking compatibility. Therefore, when referencing
2759       // the function, we pretend that we don't have the full function
2760       // type.
2761       if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2762           isa<FunctionProtoType>(fty))
2763         type = Context.getFunctionNoProtoType(fty->getResultType(),
2764                                               fty->getExtInfo());
2765 
2766       // Functions are r-values in C.
2767       valueKind = VK_RValue;
2768       break;
2769     }
2770 
2771     case Decl::MSProperty:
2772       valueKind = VK_LValue;
2773       break;
2774 
2775     case Decl::CXXMethod:
2776       // If we're referring to a method with an __unknown_anytype
2777       // result type, make the entire expression __unknown_anytype.
2778       // This should only be possible with a type written directly.
2779       if (const FunctionProtoType *proto
2780             = dyn_cast<FunctionProtoType>(VD->getType()))
2781         if (proto->getResultType() == Context.UnknownAnyTy) {
2782           type = Context.UnknownAnyTy;
2783           valueKind = VK_RValue;
2784           break;
2785         }
2786 
2787       // C++ methods are l-values if static, r-values if non-static.
2788       if (cast<CXXMethodDecl>(VD)->isStatic()) {
2789         valueKind = VK_LValue;
2790         break;
2791       }
2792       // fallthrough
2793 
2794     case Decl::CXXConversion:
2795     case Decl::CXXDestructor:
2796     case Decl::CXXConstructor:
2797       valueKind = VK_RValue;
2798       break;
2799     }
2800 
2801     return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
2802                             TemplateArgs);
2803   }
2804 }
2805 
2806 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
2807                                      PredefinedExpr::IdentType IT) {
2808   // Pick the current block, lambda, captured statement or function.
2809   Decl *currentDecl = 0;
2810   if (const BlockScopeInfo *BSI = getCurBlock())
2811     currentDecl = BSI->TheDecl;
2812   else if (const LambdaScopeInfo *LSI = getCurLambda())
2813     currentDecl = LSI->CallOperator;
2814   else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
2815     currentDecl = CSI->TheCapturedDecl;
2816   else
2817     currentDecl = getCurFunctionOrMethodDecl();
2818 
2819   if (!currentDecl) {
2820     Diag(Loc, diag::ext_predef_outside_function);
2821     currentDecl = Context.getTranslationUnitDecl();
2822   }
2823 
2824   QualType ResTy;
2825   if (cast<DeclContext>(currentDecl)->isDependentContext())
2826     ResTy = Context.DependentTy;
2827   else {
2828     // Pre-defined identifiers are of type char[x], where x is the length of
2829     // the string.
2830     unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
2831 
2832     llvm::APInt LengthI(32, Length + 1);
2833     if (IT == PredefinedExpr::LFunction)
2834       ResTy = Context.WideCharTy.withConst();
2835     else
2836       ResTy = Context.CharTy.withConst();
2837     ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2838   }
2839 
2840   return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
2841 }
2842 
2843 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
2844   PredefinedExpr::IdentType IT;
2845 
2846   switch (Kind) {
2847   default: llvm_unreachable("Unknown simple primary expr!");
2848   case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2849   case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
2850   case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break;
2851   case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
2852   }
2853 
2854   return BuildPredefinedExpr(Loc, IT);
2855 }
2856 
2857 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
2858   SmallString<16> CharBuffer;
2859   bool Invalid = false;
2860   StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
2861   if (Invalid)
2862     return ExprError();
2863 
2864   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
2865                             PP, Tok.getKind());
2866   if (Literal.hadError())
2867     return ExprError();
2868 
2869   QualType Ty;
2870   if (Literal.isWide())
2871     Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
2872   else if (Literal.isUTF16())
2873     Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
2874   else if (Literal.isUTF32())
2875     Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
2876   else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
2877     Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
2878   else
2879     Ty = Context.CharTy;  // 'x' -> char in C++
2880 
2881   CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
2882   if (Literal.isWide())
2883     Kind = CharacterLiteral::Wide;
2884   else if (Literal.isUTF16())
2885     Kind = CharacterLiteral::UTF16;
2886   else if (Literal.isUTF32())
2887     Kind = CharacterLiteral::UTF32;
2888 
2889   Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
2890                                              Tok.getLocation());
2891 
2892   if (Literal.getUDSuffix().empty())
2893     return Owned(Lit);
2894 
2895   // We're building a user-defined literal.
2896   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2897   SourceLocation UDSuffixLoc =
2898     getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
2899 
2900   // Make sure we're allowed user-defined literals here.
2901   if (!UDLScope)
2902     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
2903 
2904   // C++11 [lex.ext]p6: The literal L is treated as a call of the form
2905   //   operator "" X (ch)
2906   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
2907                                         Lit, Tok.getLocation());
2908 }
2909 
2910 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
2911   unsigned IntSize = Context.getTargetInfo().getIntWidth();
2912   return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
2913                                       Context.IntTy, Loc));
2914 }
2915 
2916 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
2917                                   QualType Ty, SourceLocation Loc) {
2918   const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
2919 
2920   using llvm::APFloat;
2921   APFloat Val(Format);
2922 
2923   APFloat::opStatus result = Literal.GetFloatValue(Val);
2924 
2925   // Overflow is always an error, but underflow is only an error if
2926   // we underflowed to zero (APFloat reports denormals as underflow).
2927   if ((result & APFloat::opOverflow) ||
2928       ((result & APFloat::opUnderflow) && Val.isZero())) {
2929     unsigned diagnostic;
2930     SmallString<20> buffer;
2931     if (result & APFloat::opOverflow) {
2932       diagnostic = diag::warn_float_overflow;
2933       APFloat::getLargest(Format).toString(buffer);
2934     } else {
2935       diagnostic = diag::warn_float_underflow;
2936       APFloat::getSmallest(Format).toString(buffer);
2937     }
2938 
2939     S.Diag(Loc, diagnostic)
2940       << Ty
2941       << StringRef(buffer.data(), buffer.size());
2942   }
2943 
2944   bool isExact = (result == APFloat::opOK);
2945   return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
2946 }
2947 
2948 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
2949   // Fast path for a single digit (which is quite common).  A single digit
2950   // cannot have a trigraph, escaped newline, radix prefix, or suffix.
2951   if (Tok.getLength() == 1) {
2952     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
2953     return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
2954   }
2955 
2956   SmallString<128> SpellingBuffer;
2957   // NumericLiteralParser wants to overread by one character.  Add padding to
2958   // the buffer in case the token is copied to the buffer.  If getSpelling()
2959   // returns a StringRef to the memory buffer, it should have a null char at
2960   // the EOF, so it is also safe.
2961   SpellingBuffer.resize(Tok.getLength() + 1);
2962 
2963   // Get the spelling of the token, which eliminates trigraphs, etc.
2964   bool Invalid = false;
2965   StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
2966   if (Invalid)
2967     return ExprError();
2968 
2969   NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
2970   if (Literal.hadError)
2971     return ExprError();
2972 
2973   if (Literal.hasUDSuffix()) {
2974     // We're building a user-defined literal.
2975     IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2976     SourceLocation UDSuffixLoc =
2977       getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
2978 
2979     // Make sure we're allowed user-defined literals here.
2980     if (!UDLScope)
2981       return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
2982 
2983     QualType CookedTy;
2984     if (Literal.isFloatingLiteral()) {
2985       // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
2986       // long double, the literal is treated as a call of the form
2987       //   operator "" X (f L)
2988       CookedTy = Context.LongDoubleTy;
2989     } else {
2990       // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
2991       // unsigned long long, the literal is treated as a call of the form
2992       //   operator "" X (n ULL)
2993       CookedTy = Context.UnsignedLongLongTy;
2994     }
2995 
2996     DeclarationName OpName =
2997       Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
2998     DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
2999     OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3000 
3001     SourceLocation TokLoc = Tok.getLocation();
3002 
3003     // Perform literal operator lookup to determine if we're building a raw
3004     // literal or a cooked one.
3005     LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3006     switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3007                                   /*AllowRaw*/true, /*AllowTemplate*/true,
3008                                   /*AllowStringTemplate*/false)) {
3009     case LOLR_Error:
3010       return ExprError();
3011 
3012     case LOLR_Cooked: {
3013       Expr *Lit;
3014       if (Literal.isFloatingLiteral()) {
3015         Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3016       } else {
3017         llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3018         if (Literal.GetIntegerValue(ResultVal))
3019           Diag(Tok.getLocation(), diag::err_integer_too_large);
3020         Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3021                                      Tok.getLocation());
3022       }
3023       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3024     }
3025 
3026     case LOLR_Raw: {
3027       // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3028       // literal is treated as a call of the form
3029       //   operator "" X ("n")
3030       unsigned Length = Literal.getUDSuffixOffset();
3031       QualType StrTy = Context.getConstantArrayType(
3032           Context.CharTy.withConst(), llvm::APInt(32, Length + 1),
3033           ArrayType::Normal, 0);
3034       Expr *Lit = StringLiteral::Create(
3035           Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3036           /*Pascal*/false, StrTy, &TokLoc, 1);
3037       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3038     }
3039 
3040     case LOLR_Template: {
3041       // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3042       // template), L is treated as a call fo the form
3043       //   operator "" X <'c1', 'c2', ... 'ck'>()
3044       // where n is the source character sequence c1 c2 ... ck.
3045       TemplateArgumentListInfo ExplicitArgs;
3046       unsigned CharBits = Context.getIntWidth(Context.CharTy);
3047       bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3048       llvm::APSInt Value(CharBits, CharIsUnsigned);
3049       for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3050         Value = TokSpelling[I];
3051         TemplateArgument Arg(Context, Value, Context.CharTy);
3052         TemplateArgumentLocInfo ArgInfo;
3053         ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3054       }
3055       return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3056                                       &ExplicitArgs);
3057     }
3058     case LOLR_StringTemplate:
3059       llvm_unreachable("unexpected literal operator lookup result");
3060     }
3061   }
3062 
3063   Expr *Res;
3064 
3065   if (Literal.isFloatingLiteral()) {
3066     QualType Ty;
3067     if (Literal.isFloat)
3068       Ty = Context.FloatTy;
3069     else if (!Literal.isLong)
3070       Ty = Context.DoubleTy;
3071     else
3072       Ty = Context.LongDoubleTy;
3073 
3074     Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3075 
3076     if (Ty == Context.DoubleTy) {
3077       if (getLangOpts().SinglePrecisionConstants) {
3078         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
3079       } else if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
3080         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3081         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
3082       }
3083     }
3084   } else if (!Literal.isIntegerLiteral()) {
3085     return ExprError();
3086   } else {
3087     QualType Ty;
3088 
3089     // 'long long' is a C99 or C++11 feature.
3090     if (!getLangOpts().C99 && Literal.isLongLong) {
3091       if (getLangOpts().CPlusPlus)
3092         Diag(Tok.getLocation(),
3093              getLangOpts().CPlusPlus11 ?
3094              diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3095       else
3096         Diag(Tok.getLocation(), diag::ext_c99_longlong);
3097     }
3098 
3099     // Get the value in the widest-possible width.
3100     unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3101     // The microsoft literal suffix extensions support 128-bit literals, which
3102     // may be wider than [u]intmax_t.
3103     // FIXME: Actually, they don't. We seem to have accidentally invented the
3104     //        i128 suffix.
3105     if (Literal.isMicrosoftInteger && MaxWidth < 128 &&
3106         PP.getTargetInfo().hasInt128Type())
3107       MaxWidth = 128;
3108     llvm::APInt ResultVal(MaxWidth, 0);
3109 
3110     if (Literal.GetIntegerValue(ResultVal)) {
3111       // If this value didn't fit into uintmax_t, error and force to ull.
3112       Diag(Tok.getLocation(), diag::err_integer_too_large);
3113       Ty = Context.UnsignedLongLongTy;
3114       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3115              "long long is not intmax_t?");
3116     } else {
3117       // If this value fits into a ULL, try to figure out what else it fits into
3118       // according to the rules of C99 6.4.4.1p5.
3119 
3120       // Octal, Hexadecimal, and integers with a U suffix are allowed to
3121       // be an unsigned int.
3122       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3123 
3124       // Check from smallest to largest, picking the smallest type we can.
3125       unsigned Width = 0;
3126       if (!Literal.isLong && !Literal.isLongLong) {
3127         // Are int/unsigned possibilities?
3128         unsigned IntSize = Context.getTargetInfo().getIntWidth();
3129 
3130         // Does it fit in a unsigned int?
3131         if (ResultVal.isIntN(IntSize)) {
3132           // Does it fit in a signed int?
3133           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3134             Ty = Context.IntTy;
3135           else if (AllowUnsigned)
3136             Ty = Context.UnsignedIntTy;
3137           Width = IntSize;
3138         }
3139       }
3140 
3141       // Are long/unsigned long possibilities?
3142       if (Ty.isNull() && !Literal.isLongLong) {
3143         unsigned LongSize = Context.getTargetInfo().getLongWidth();
3144 
3145         // Does it fit in a unsigned long?
3146         if (ResultVal.isIntN(LongSize)) {
3147           // Does it fit in a signed long?
3148           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3149             Ty = Context.LongTy;
3150           else if (AllowUnsigned)
3151             Ty = Context.UnsignedLongTy;
3152           Width = LongSize;
3153         }
3154       }
3155 
3156       // Check long long if needed.
3157       if (Ty.isNull()) {
3158         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3159 
3160         // Does it fit in a unsigned long long?
3161         if (ResultVal.isIntN(LongLongSize)) {
3162           // Does it fit in a signed long long?
3163           // To be compatible with MSVC, hex integer literals ending with the
3164           // LL or i64 suffix are always signed in Microsoft mode.
3165           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3166               (getLangOpts().MicrosoftExt && Literal.isLongLong)))
3167             Ty = Context.LongLongTy;
3168           else if (AllowUnsigned)
3169             Ty = Context.UnsignedLongLongTy;
3170           Width = LongLongSize;
3171         }
3172       }
3173 
3174       // If it doesn't fit in unsigned long long, and we're using Microsoft
3175       // extensions, then its a 128-bit integer literal.
3176       if (Ty.isNull() && Literal.isMicrosoftInteger &&
3177           PP.getTargetInfo().hasInt128Type()) {
3178         if (Literal.isUnsigned)
3179           Ty = Context.UnsignedInt128Ty;
3180         else
3181           Ty = Context.Int128Ty;
3182         Width = 128;
3183       }
3184 
3185       // If we still couldn't decide a type, we probably have something that
3186       // does not fit in a signed long long, but has no U suffix.
3187       if (Ty.isNull()) {
3188         Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
3189         Ty = Context.UnsignedLongLongTy;
3190         Width = Context.getTargetInfo().getLongLongWidth();
3191       }
3192 
3193       if (ResultVal.getBitWidth() != Width)
3194         ResultVal = ResultVal.trunc(Width);
3195     }
3196     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3197   }
3198 
3199   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3200   if (Literal.isImaginary)
3201     Res = new (Context) ImaginaryLiteral(Res,
3202                                         Context.getComplexType(Res->getType()));
3203 
3204   return Owned(Res);
3205 }
3206 
3207 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
3208   assert((E != 0) && "ActOnParenExpr() missing expr");
3209   return Owned(new (Context) ParenExpr(L, R, E));
3210 }
3211 
3212 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3213                                          SourceLocation Loc,
3214                                          SourceRange ArgRange) {
3215   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3216   // scalar or vector data type argument..."
3217   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3218   // type (C99 6.2.5p18) or void.
3219   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3220     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3221       << T << ArgRange;
3222     return true;
3223   }
3224 
3225   assert((T->isVoidType() || !T->isIncompleteType()) &&
3226          "Scalar types should always be complete");
3227   return false;
3228 }
3229 
3230 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3231                                            SourceLocation Loc,
3232                                            SourceRange ArgRange,
3233                                            UnaryExprOrTypeTrait TraitKind) {
3234   // Invalid types must be hard errors for SFINAE in C++.
3235   if (S.LangOpts.CPlusPlus)
3236     return true;
3237 
3238   // C99 6.5.3.4p1:
3239   if (T->isFunctionType() &&
3240       (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) {
3241     // sizeof(function)/alignof(function) is allowed as an extension.
3242     S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3243       << TraitKind << ArgRange;
3244     return false;
3245   }
3246 
3247   // Allow sizeof(void)/alignof(void) as an extension.
3248   if (T->isVoidType()) {
3249     S.Diag(Loc, diag::ext_sizeof_alignof_void_type) << TraitKind << ArgRange;
3250     return false;
3251   }
3252 
3253   return true;
3254 }
3255 
3256 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
3257                                              SourceLocation Loc,
3258                                              SourceRange ArgRange,
3259                                              UnaryExprOrTypeTrait TraitKind) {
3260   // Reject sizeof(interface) and sizeof(interface<proto>) if the
3261   // runtime doesn't allow it.
3262   if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
3263     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3264       << T << (TraitKind == UETT_SizeOf)
3265       << ArgRange;
3266     return true;
3267   }
3268 
3269   return false;
3270 }
3271 
3272 /// \brief Check whether E is a pointer from a decayed array type (the decayed
3273 /// pointer type is equal to T) and emit a warning if it is.
3274 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
3275                                      Expr *E) {
3276   // Don't warn if the operation changed the type.
3277   if (T != E->getType())
3278     return;
3279 
3280   // Now look for array decays.
3281   ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
3282   if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
3283     return;
3284 
3285   S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
3286                                              << ICE->getType()
3287                                              << ICE->getSubExpr()->getType();
3288 }
3289 
3290 /// \brief Check the constrains on expression operands to unary type expression
3291 /// and type traits.
3292 ///
3293 /// Completes any types necessary and validates the constraints on the operand
3294 /// expression. The logic mostly mirrors the type-based overload, but may modify
3295 /// the expression as it completes the type for that expression through template
3296 /// instantiation, etc.
3297 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
3298                                             UnaryExprOrTypeTrait ExprKind) {
3299   QualType ExprTy = E->getType();
3300   assert(!ExprTy->isReferenceType());
3301 
3302   if (ExprKind == UETT_VecStep)
3303     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
3304                                         E->getSourceRange());
3305 
3306   // Whitelist some types as extensions
3307   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
3308                                       E->getSourceRange(), ExprKind))
3309     return false;
3310 
3311   if (RequireCompleteExprType(E,
3312                               diag::err_sizeof_alignof_incomplete_type,
3313                               ExprKind, E->getSourceRange()))
3314     return true;
3315 
3316   // Completing the expression's type may have changed it.
3317   ExprTy = E->getType();
3318   assert(!ExprTy->isReferenceType());
3319 
3320   if (ExprTy->isFunctionType()) {
3321     Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
3322       << ExprKind << E->getSourceRange();
3323     return true;
3324   }
3325 
3326   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
3327                                        E->getSourceRange(), ExprKind))
3328     return true;
3329 
3330   if (ExprKind == UETT_SizeOf) {
3331     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
3332       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
3333         QualType OType = PVD->getOriginalType();
3334         QualType Type = PVD->getType();
3335         if (Type->isPointerType() && OType->isArrayType()) {
3336           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
3337             << Type << OType;
3338           Diag(PVD->getLocation(), diag::note_declared_at);
3339         }
3340       }
3341     }
3342 
3343     // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
3344     // decays into a pointer and returns an unintended result. This is most
3345     // likely a typo for "sizeof(array) op x".
3346     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
3347       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3348                                BO->getLHS());
3349       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3350                                BO->getRHS());
3351     }
3352   }
3353 
3354   return false;
3355 }
3356 
3357 /// \brief Check the constraints on operands to unary expression and type
3358 /// traits.
3359 ///
3360 /// This will complete any types necessary, and validate the various constraints
3361 /// on those operands.
3362 ///
3363 /// The UsualUnaryConversions() function is *not* called by this routine.
3364 /// C99 6.3.2.1p[2-4] all state:
3365 ///   Except when it is the operand of the sizeof operator ...
3366 ///
3367 /// C++ [expr.sizeof]p4
3368 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3369 ///   standard conversions are not applied to the operand of sizeof.
3370 ///
3371 /// This policy is followed for all of the unary trait expressions.
3372 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
3373                                             SourceLocation OpLoc,
3374                                             SourceRange ExprRange,
3375                                             UnaryExprOrTypeTrait ExprKind) {
3376   if (ExprType->isDependentType())
3377     return false;
3378 
3379   // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
3380   //   the result is the size of the referenced type."
3381   // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
3382   //   result shall be the alignment of the referenced type."
3383   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3384     ExprType = Ref->getPointeeType();
3385 
3386   if (ExprKind == UETT_VecStep)
3387     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
3388 
3389   // Whitelist some types as extensions
3390   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
3391                                       ExprKind))
3392     return false;
3393 
3394   if (RequireCompleteType(OpLoc, ExprType,
3395                           diag::err_sizeof_alignof_incomplete_type,
3396                           ExprKind, ExprRange))
3397     return true;
3398 
3399   if (ExprType->isFunctionType()) {
3400     Diag(OpLoc, diag::err_sizeof_alignof_function_type)
3401       << ExprKind << ExprRange;
3402     return true;
3403   }
3404 
3405   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
3406                                        ExprKind))
3407     return true;
3408 
3409   return false;
3410 }
3411 
3412 static bool CheckAlignOfExpr(Sema &S, Expr *E) {
3413   E = E->IgnoreParens();
3414 
3415   // Cannot know anything else if the expression is dependent.
3416   if (E->isTypeDependent())
3417     return false;
3418 
3419   if (E->getObjectKind() == OK_BitField) {
3420     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield)
3421        << 1 << E->getSourceRange();
3422     return true;
3423   }
3424 
3425   ValueDecl *D = 0;
3426   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3427     D = DRE->getDecl();
3428   } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3429     D = ME->getMemberDecl();
3430   }
3431 
3432   // If it's a field, require the containing struct to have a
3433   // complete definition so that we can compute the layout.
3434   //
3435   // This requires a very particular set of circumstances.  For a
3436   // field to be contained within an incomplete type, we must in the
3437   // process of parsing that type.  To have an expression refer to a
3438   // field, it must be an id-expression or a member-expression, but
3439   // the latter are always ill-formed when the base type is
3440   // incomplete, including only being partially complete.  An
3441   // id-expression can never refer to a field in C because fields
3442   // are not in the ordinary namespace.  In C++, an id-expression
3443   // can implicitly be a member access, but only if there's an
3444   // implicit 'this' value, and all such contexts are subject to
3445   // delayed parsing --- except for trailing return types in C++11.
3446   // And if an id-expression referring to a field occurs in a
3447   // context that lacks a 'this' value, it's ill-formed --- except,
3448   // agian, in C++11, where such references are allowed in an
3449   // unevaluated context.  So C++11 introduces some new complexity.
3450   //
3451   // For the record, since __alignof__ on expressions is a GCC
3452   // extension, GCC seems to permit this but always gives the
3453   // nonsensical answer 0.
3454   //
3455   // We don't really need the layout here --- we could instead just
3456   // directly check for all the appropriate alignment-lowing
3457   // attributes --- but that would require duplicating a lot of
3458   // logic that just isn't worth duplicating for such a marginal
3459   // use-case.
3460   if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
3461     // Fast path this check, since we at least know the record has a
3462     // definition if we can find a member of it.
3463     if (!FD->getParent()->isCompleteDefinition()) {
3464       S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
3465         << E->getSourceRange();
3466       return true;
3467     }
3468 
3469     // Otherwise, if it's a field, and the field doesn't have
3470     // reference type, then it must have a complete type (or be a
3471     // flexible array member, which we explicitly want to
3472     // white-list anyway), which makes the following checks trivial.
3473     if (!FD->getType()->isReferenceType())
3474       return false;
3475   }
3476 
3477   return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
3478 }
3479 
3480 bool Sema::CheckVecStepExpr(Expr *E) {
3481   E = E->IgnoreParens();
3482 
3483   // Cannot know anything else if the expression is dependent.
3484   if (E->isTypeDependent())
3485     return false;
3486 
3487   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
3488 }
3489 
3490 /// \brief Build a sizeof or alignof expression given a type operand.
3491 ExprResult
3492 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3493                                      SourceLocation OpLoc,
3494                                      UnaryExprOrTypeTrait ExprKind,
3495                                      SourceRange R) {
3496   if (!TInfo)
3497     return ExprError();
3498 
3499   QualType T = TInfo->getType();
3500 
3501   if (!T->isDependentType() &&
3502       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
3503     return ExprError();
3504 
3505   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
3506   return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo,
3507                                                       Context.getSizeType(),
3508                                                       OpLoc, R.getEnd()));
3509 }
3510 
3511 /// \brief Build a sizeof or alignof expression given an expression
3512 /// operand.
3513 ExprResult
3514 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
3515                                      UnaryExprOrTypeTrait ExprKind) {
3516   ExprResult PE = CheckPlaceholderExpr(E);
3517   if (PE.isInvalid())
3518     return ExprError();
3519 
3520   E = PE.get();
3521 
3522   // Verify that the operand is valid.
3523   bool isInvalid = false;
3524   if (E->isTypeDependent()) {
3525     // Delay type-checking for type-dependent expressions.
3526   } else if (ExprKind == UETT_AlignOf) {
3527     isInvalid = CheckAlignOfExpr(*this, E);
3528   } else if (ExprKind == UETT_VecStep) {
3529     isInvalid = CheckVecStepExpr(E);
3530   } else if (E->refersToBitField()) {  // C99 6.5.3.4p1.
3531     Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0;
3532     isInvalid = true;
3533   } else {
3534     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
3535   }
3536 
3537   if (isInvalid)
3538     return ExprError();
3539 
3540   if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
3541     PE = TransformToPotentiallyEvaluated(E);
3542     if (PE.isInvalid()) return ExprError();
3543     E = PE.take();
3544   }
3545 
3546   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
3547   return Owned(new (Context) UnaryExprOrTypeTraitExpr(
3548       ExprKind, E, Context.getSizeType(), OpLoc,
3549       E->getSourceRange().getEnd()));
3550 }
3551 
3552 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
3553 /// expr and the same for @c alignof and @c __alignof
3554 /// Note that the ArgRange is invalid if isType is false.
3555 ExprResult
3556 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
3557                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
3558                                     void *TyOrEx, const SourceRange &ArgRange) {
3559   // If error parsing type, ignore.
3560   if (TyOrEx == 0) return ExprError();
3561 
3562   if (IsType) {
3563     TypeSourceInfo *TInfo;
3564     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
3565     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
3566   }
3567 
3568   Expr *ArgEx = (Expr *)TyOrEx;
3569   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
3570   return Result;
3571 }
3572 
3573 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
3574                                      bool IsReal) {
3575   if (V.get()->isTypeDependent())
3576     return S.Context.DependentTy;
3577 
3578   // _Real and _Imag are only l-values for normal l-values.
3579   if (V.get()->getObjectKind() != OK_Ordinary) {
3580     V = S.DefaultLvalueConversion(V.take());
3581     if (V.isInvalid())
3582       return QualType();
3583   }
3584 
3585   // These operators return the element type of a complex type.
3586   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
3587     return CT->getElementType();
3588 
3589   // Otherwise they pass through real integer and floating point types here.
3590   if (V.get()->getType()->isArithmeticType())
3591     return V.get()->getType();
3592 
3593   // Test for placeholders.
3594   ExprResult PR = S.CheckPlaceholderExpr(V.get());
3595   if (PR.isInvalid()) return QualType();
3596   if (PR.get() != V.get()) {
3597     V = PR;
3598     return CheckRealImagOperand(S, V, Loc, IsReal);
3599   }
3600 
3601   // Reject anything else.
3602   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
3603     << (IsReal ? "__real" : "__imag");
3604   return QualType();
3605 }
3606 
3607 
3608 
3609 ExprResult
3610 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
3611                           tok::TokenKind Kind, Expr *Input) {
3612   UnaryOperatorKind Opc;
3613   switch (Kind) {
3614   default: llvm_unreachable("Unknown unary op!");
3615   case tok::plusplus:   Opc = UO_PostInc; break;
3616   case tok::minusminus: Opc = UO_PostDec; break;
3617   }
3618 
3619   // Since this might is a postfix expression, get rid of ParenListExprs.
3620   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
3621   if (Result.isInvalid()) return ExprError();
3622   Input = Result.take();
3623 
3624   return BuildUnaryOp(S, OpLoc, Opc, Input);
3625 }
3626 
3627 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal.
3628 ///
3629 /// \return true on error
3630 static bool checkArithmeticOnObjCPointer(Sema &S,
3631                                          SourceLocation opLoc,
3632                                          Expr *op) {
3633   assert(op->getType()->isObjCObjectPointerType());
3634   if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic())
3635     return false;
3636 
3637   S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
3638     << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
3639     << op->getSourceRange();
3640   return true;
3641 }
3642 
3643 ExprResult
3644 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
3645                               Expr *idx, SourceLocation rbLoc) {
3646   // Since this might be a postfix expression, get rid of ParenListExprs.
3647   if (isa<ParenListExpr>(base)) {
3648     ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
3649     if (result.isInvalid()) return ExprError();
3650     base = result.take();
3651   }
3652 
3653   // Handle any non-overload placeholder types in the base and index
3654   // expressions.  We can't handle overloads here because the other
3655   // operand might be an overloadable type, in which case the overload
3656   // resolution for the operator overload should get the first crack
3657   // at the overload.
3658   if (base->getType()->isNonOverloadPlaceholderType()) {
3659     ExprResult result = CheckPlaceholderExpr(base);
3660     if (result.isInvalid()) return ExprError();
3661     base = result.take();
3662   }
3663   if (idx->getType()->isNonOverloadPlaceholderType()) {
3664     ExprResult result = CheckPlaceholderExpr(idx);
3665     if (result.isInvalid()) return ExprError();
3666     idx = result.take();
3667   }
3668 
3669   // Build an unanalyzed expression if either operand is type-dependent.
3670   if (getLangOpts().CPlusPlus &&
3671       (base->isTypeDependent() || idx->isTypeDependent())) {
3672     return Owned(new (Context) ArraySubscriptExpr(base, idx,
3673                                                   Context.DependentTy,
3674                                                   VK_LValue, OK_Ordinary,
3675                                                   rbLoc));
3676   }
3677 
3678   // Use C++ overloaded-operator rules if either operand has record
3679   // type.  The spec says to do this if either type is *overloadable*,
3680   // but enum types can't declare subscript operators or conversion
3681   // operators, so there's nothing interesting for overload resolution
3682   // to do if there aren't any record types involved.
3683   //
3684   // ObjC pointers have their own subscripting logic that is not tied
3685   // to overload resolution and so should not take this path.
3686   if (getLangOpts().CPlusPlus &&
3687       (base->getType()->isRecordType() ||
3688        (!base->getType()->isObjCObjectPointerType() &&
3689         idx->getType()->isRecordType()))) {
3690     return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
3691   }
3692 
3693   return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
3694 }
3695 
3696 ExprResult
3697 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
3698                                       Expr *Idx, SourceLocation RLoc) {
3699   Expr *LHSExp = Base;
3700   Expr *RHSExp = Idx;
3701 
3702   // Perform default conversions.
3703   if (!LHSExp->getType()->getAs<VectorType>()) {
3704     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
3705     if (Result.isInvalid())
3706       return ExprError();
3707     LHSExp = Result.take();
3708   }
3709   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
3710   if (Result.isInvalid())
3711     return ExprError();
3712   RHSExp = Result.take();
3713 
3714   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
3715   ExprValueKind VK = VK_LValue;
3716   ExprObjectKind OK = OK_Ordinary;
3717 
3718   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
3719   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
3720   // in the subscript position. As a result, we need to derive the array base
3721   // and index from the expression types.
3722   Expr *BaseExpr, *IndexExpr;
3723   QualType ResultType;
3724   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3725     BaseExpr = LHSExp;
3726     IndexExpr = RHSExp;
3727     ResultType = Context.DependentTy;
3728   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
3729     BaseExpr = LHSExp;
3730     IndexExpr = RHSExp;
3731     ResultType = PTy->getPointeeType();
3732   } else if (const ObjCObjectPointerType *PTy =
3733                LHSTy->getAs<ObjCObjectPointerType>()) {
3734     BaseExpr = LHSExp;
3735     IndexExpr = RHSExp;
3736 
3737     // Use custom logic if this should be the pseudo-object subscript
3738     // expression.
3739     if (!LangOpts.ObjCRuntime.isSubscriptPointerArithmetic())
3740       return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, 0, 0);
3741 
3742     ResultType = PTy->getPointeeType();
3743     if (!LangOpts.ObjCRuntime.allowsPointerArithmetic()) {
3744       Diag(LLoc, diag::err_subscript_nonfragile_interface)
3745         << ResultType << BaseExpr->getSourceRange();
3746       return ExprError();
3747     }
3748   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
3749      // Handle the uncommon case of "123[Ptr]".
3750     BaseExpr = RHSExp;
3751     IndexExpr = LHSExp;
3752     ResultType = PTy->getPointeeType();
3753   } else if (const ObjCObjectPointerType *PTy =
3754                RHSTy->getAs<ObjCObjectPointerType>()) {
3755      // Handle the uncommon case of "123[Ptr]".
3756     BaseExpr = RHSExp;
3757     IndexExpr = LHSExp;
3758     ResultType = PTy->getPointeeType();
3759     if (!LangOpts.ObjCRuntime.allowsPointerArithmetic()) {
3760       Diag(LLoc, diag::err_subscript_nonfragile_interface)
3761         << ResultType << BaseExpr->getSourceRange();
3762       return ExprError();
3763     }
3764   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
3765     BaseExpr = LHSExp;    // vectors: V[123]
3766     IndexExpr = RHSExp;
3767     VK = LHSExp->getValueKind();
3768     if (VK != VK_RValue)
3769       OK = OK_VectorComponent;
3770 
3771     // FIXME: need to deal with const...
3772     ResultType = VTy->getElementType();
3773   } else if (LHSTy->isArrayType()) {
3774     // If we see an array that wasn't promoted by
3775     // DefaultFunctionArrayLvalueConversion, it must be an array that
3776     // wasn't promoted because of the C90 rule that doesn't
3777     // allow promoting non-lvalue arrays.  Warn, then
3778     // force the promotion here.
3779     Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3780         LHSExp->getSourceRange();
3781     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
3782                                CK_ArrayToPointerDecay).take();
3783     LHSTy = LHSExp->getType();
3784 
3785     BaseExpr = LHSExp;
3786     IndexExpr = RHSExp;
3787     ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
3788   } else if (RHSTy->isArrayType()) {
3789     // Same as previous, except for 123[f().a] case
3790     Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3791         RHSExp->getSourceRange();
3792     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
3793                                CK_ArrayToPointerDecay).take();
3794     RHSTy = RHSExp->getType();
3795 
3796     BaseExpr = RHSExp;
3797     IndexExpr = LHSExp;
3798     ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
3799   } else {
3800     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3801        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
3802   }
3803   // C99 6.5.2.1p1
3804   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
3805     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3806                      << IndexExpr->getSourceRange());
3807 
3808   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
3809        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3810          && !IndexExpr->isTypeDependent())
3811     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3812 
3813   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
3814   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3815   // type. Note that Functions are not objects, and that (in C99 parlance)
3816   // incomplete types are not object types.
3817   if (ResultType->isFunctionType()) {
3818     Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3819       << ResultType << BaseExpr->getSourceRange();
3820     return ExprError();
3821   }
3822 
3823   if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
3824     // GNU extension: subscripting on pointer to void
3825     Diag(LLoc, diag::ext_gnu_subscript_void_type)
3826       << BaseExpr->getSourceRange();
3827 
3828     // C forbids expressions of unqualified void type from being l-values.
3829     // See IsCForbiddenLValueType.
3830     if (!ResultType.hasQualifiers()) VK = VK_RValue;
3831   } else if (!ResultType->isDependentType() &&
3832       RequireCompleteType(LLoc, ResultType,
3833                           diag::err_subscript_incomplete_type, BaseExpr))
3834     return ExprError();
3835 
3836   assert(VK == VK_RValue || LangOpts.CPlusPlus ||
3837          !ResultType.isCForbiddenLValueType());
3838 
3839   return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
3840                                                 ResultType, VK, OK, RLoc));
3841 }
3842 
3843 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
3844                                         FunctionDecl *FD,
3845                                         ParmVarDecl *Param) {
3846   if (Param->hasUnparsedDefaultArg()) {
3847     Diag(CallLoc,
3848          diag::err_use_of_default_argument_to_function_declared_later) <<
3849       FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
3850     Diag(UnparsedDefaultArgLocs[Param],
3851          diag::note_default_argument_declared_here);
3852     return ExprError();
3853   }
3854 
3855   if (Param->hasUninstantiatedDefaultArg()) {
3856     Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
3857 
3858     EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated,
3859                                                  Param);
3860 
3861     // Instantiate the expression.
3862     MultiLevelTemplateArgumentList MutiLevelArgList
3863       = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
3864 
3865     InstantiatingTemplate Inst(*this, CallLoc, Param,
3866                                MutiLevelArgList.getInnermost());
3867     if (Inst.isInvalid())
3868       return ExprError();
3869 
3870     ExprResult Result;
3871     {
3872       // C++ [dcl.fct.default]p5:
3873       //   The names in the [default argument] expression are bound, and
3874       //   the semantic constraints are checked, at the point where the
3875       //   default argument expression appears.
3876       ContextRAII SavedContext(*this, FD);
3877       LocalInstantiationScope Local(*this);
3878       Result = SubstExpr(UninstExpr, MutiLevelArgList);
3879     }
3880     if (Result.isInvalid())
3881       return ExprError();
3882 
3883     // Check the expression as an initializer for the parameter.
3884     InitializedEntity Entity
3885       = InitializedEntity::InitializeParameter(Context, Param);
3886     InitializationKind Kind
3887       = InitializationKind::CreateCopy(Param->getLocation(),
3888              /*FIXME:EqualLoc*/UninstExpr->getLocStart());
3889     Expr *ResultE = Result.takeAs<Expr>();
3890 
3891     InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
3892     Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
3893     if (Result.isInvalid())
3894       return ExprError();
3895 
3896     Expr *Arg = Result.takeAs<Expr>();
3897     CheckCompletedExpr(Arg, Param->getOuterLocStart());
3898     // Build the default argument expression.
3899     return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param, Arg));
3900   }
3901 
3902   // If the default expression creates temporaries, we need to
3903   // push them to the current stack of expression temporaries so they'll
3904   // be properly destroyed.
3905   // FIXME: We should really be rebuilding the default argument with new
3906   // bound temporaries; see the comment in PR5810.
3907   // We don't need to do that with block decls, though, because
3908   // blocks in default argument expression can never capture anything.
3909   if (isa<ExprWithCleanups>(Param->getInit())) {
3910     // Set the "needs cleanups" bit regardless of whether there are
3911     // any explicit objects.
3912     ExprNeedsCleanups = true;
3913 
3914     // Append all the objects to the cleanup list.  Right now, this
3915     // should always be a no-op, because blocks in default argument
3916     // expressions should never be able to capture anything.
3917     assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() &&
3918            "default argument expression has capturing blocks?");
3919   }
3920 
3921   // We already type-checked the argument, so we know it works.
3922   // Just mark all of the declarations in this potentially-evaluated expression
3923   // as being "referenced".
3924   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
3925                                    /*SkipLocalVariables=*/true);
3926   return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
3927 }
3928 
3929 
3930 Sema::VariadicCallType
3931 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
3932                           Expr *Fn) {
3933   if (Proto && Proto->isVariadic()) {
3934     if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
3935       return VariadicConstructor;
3936     else if (Fn && Fn->getType()->isBlockPointerType())
3937       return VariadicBlock;
3938     else if (FDecl) {
3939       if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3940         if (Method->isInstance())
3941           return VariadicMethod;
3942     } else if (Fn && Fn->getType() == Context.BoundMemberTy)
3943       return VariadicMethod;
3944     return VariadicFunction;
3945   }
3946   return VariadicDoesNotApply;
3947 }
3948 
3949 namespace {
3950 class FunctionCallCCC : public FunctionCallFilterCCC {
3951 public:
3952   FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
3953                   unsigned NumArgs, bool HasExplicitTemplateArgs)
3954       : FunctionCallFilterCCC(SemaRef, NumArgs, HasExplicitTemplateArgs),
3955         FunctionName(FuncName) {}
3956 
3957   virtual bool ValidateCandidate(const TypoCorrection &candidate) {
3958     if (!candidate.getCorrectionSpecifier() ||
3959         candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
3960       return false;
3961     }
3962 
3963     return FunctionCallFilterCCC::ValidateCandidate(candidate);
3964   }
3965 
3966 private:
3967   const IdentifierInfo *const FunctionName;
3968 };
3969 }
3970 
3971 static TypoCorrection TryTypoCorrectionForCall(Sema &S,
3972                                                DeclarationNameInfo FuncName,
3973                                                ArrayRef<Expr *> Args) {
3974   FunctionCallCCC CCC(S, FuncName.getName().getAsIdentifierInfo(),
3975                       Args.size(), false);
3976   if (TypoCorrection Corrected =
3977           S.CorrectTypo(FuncName, Sema::LookupOrdinaryName,
3978                         S.getScopeForContext(S.CurContext), NULL, CCC)) {
3979     if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
3980       if (Corrected.isOverloaded()) {
3981         OverloadCandidateSet OCS(FuncName.getLoc());
3982         OverloadCandidateSet::iterator Best;
3983         for (TypoCorrection::decl_iterator CD = Corrected.begin(),
3984                                            CDEnd = Corrected.end();
3985              CD != CDEnd; ++CD) {
3986           if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
3987             S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
3988                                    OCS);
3989         }
3990         switch (OCS.BestViableFunction(S, FuncName.getLoc(), Best)) {
3991         case OR_Success:
3992           ND = Best->Function;
3993           Corrected.setCorrectionDecl(ND);
3994           break;
3995         default:
3996           break;
3997         }
3998       }
3999       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
4000         return Corrected;
4001       }
4002     }
4003   }
4004   return TypoCorrection();
4005 }
4006 
4007 /// ConvertArgumentsForCall - Converts the arguments specified in
4008 /// Args/NumArgs to the parameter types of the function FDecl with
4009 /// function prototype Proto. Call is the call expression itself, and
4010 /// Fn is the function expression. For a C++ member function, this
4011 /// routine does not attempt to convert the object argument. Returns
4012 /// true if the call is ill-formed.
4013 bool
4014 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
4015                               FunctionDecl *FDecl,
4016                               const FunctionProtoType *Proto,
4017                               ArrayRef<Expr *> Args,
4018                               SourceLocation RParenLoc,
4019                               bool IsExecConfig) {
4020   // Bail out early if calling a builtin with custom typechecking.
4021   // We don't need to do this in the
4022   if (FDecl)
4023     if (unsigned ID = FDecl->getBuiltinID())
4024       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
4025         return false;
4026 
4027   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
4028   // assignment, to the types of the corresponding parameter, ...
4029   unsigned NumArgsInProto = Proto->getNumArgs();
4030   bool Invalid = false;
4031   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumArgsInProto;
4032   unsigned FnKind = Fn->getType()->isBlockPointerType()
4033                        ? 1 /* block */
4034                        : (IsExecConfig ? 3 /* kernel function (exec config) */
4035                                        : 0 /* function */);
4036 
4037   // If too few arguments are available (and we don't have default
4038   // arguments for the remaining parameters), don't make the call.
4039   if (Args.size() < NumArgsInProto) {
4040     if (Args.size() < MinArgs) {
4041       MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
4042       TypoCorrection TC;
4043       if (FDecl && (TC = TryTypoCorrectionForCall(
4044                         *this, DeclarationNameInfo(FDecl->getDeclName(),
4045                                                    (ME ? ME->getMemberLoc()
4046                                                        : Fn->getLocStart())),
4047                         Args))) {
4048         unsigned diag_id =
4049             MinArgs == NumArgsInProto && !Proto->isVariadic()
4050                 ? diag::err_typecheck_call_too_few_args_suggest
4051                 : diag::err_typecheck_call_too_few_args_at_least_suggest;
4052         diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
4053                                         << static_cast<unsigned>(Args.size())
4054                                         << Fn->getSourceRange());
4055       } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
4056         Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic()
4057                           ? diag::err_typecheck_call_too_few_args_one
4058                           : diag::err_typecheck_call_too_few_args_at_least_one)
4059           << FnKind
4060           << FDecl->getParamDecl(0) << Fn->getSourceRange();
4061       else
4062         Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic()
4063                           ? diag::err_typecheck_call_too_few_args
4064                           : diag::err_typecheck_call_too_few_args_at_least)
4065           << FnKind
4066           << MinArgs << static_cast<unsigned>(Args.size())
4067           << Fn->getSourceRange();
4068 
4069       // Emit the location of the prototype.
4070       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4071         Diag(FDecl->getLocStart(), diag::note_callee_decl)
4072           << FDecl;
4073 
4074       return true;
4075     }
4076     Call->setNumArgs(Context, NumArgsInProto);
4077   }
4078 
4079   // If too many are passed and not variadic, error on the extras and drop
4080   // them.
4081   if (Args.size() > NumArgsInProto) {
4082     if (!Proto->isVariadic()) {
4083       TypoCorrection TC;
4084       if (FDecl && (TC = TryTypoCorrectionForCall(
4085                         *this, DeclarationNameInfo(FDecl->getDeclName(),
4086                                                    Fn->getLocStart()),
4087                         Args))) {
4088         unsigned diag_id =
4089             MinArgs == NumArgsInProto && !Proto->isVariadic()
4090                 ? diag::err_typecheck_call_too_many_args_suggest
4091                 : diag::err_typecheck_call_too_many_args_at_most_suggest;
4092         diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumArgsInProto
4093                                         << static_cast<unsigned>(Args.size())
4094                                         << Fn->getSourceRange());
4095       } else if (NumArgsInProto == 1 && FDecl &&
4096                  FDecl->getParamDecl(0)->getDeclName())
4097         Diag(Args[NumArgsInProto]->getLocStart(),
4098              MinArgs == NumArgsInProto
4099                ? diag::err_typecheck_call_too_many_args_one
4100                : diag::err_typecheck_call_too_many_args_at_most_one)
4101           << FnKind
4102           << FDecl->getParamDecl(0) << static_cast<unsigned>(Args.size())
4103           << Fn->getSourceRange()
4104           << SourceRange(Args[NumArgsInProto]->getLocStart(),
4105                          Args.back()->getLocEnd());
4106       else
4107         Diag(Args[NumArgsInProto]->getLocStart(),
4108              MinArgs == NumArgsInProto
4109                ? diag::err_typecheck_call_too_many_args
4110                : diag::err_typecheck_call_too_many_args_at_most)
4111           << FnKind
4112           << NumArgsInProto << static_cast<unsigned>(Args.size())
4113           << Fn->getSourceRange()
4114           << SourceRange(Args[NumArgsInProto]->getLocStart(),
4115                          Args.back()->getLocEnd());
4116 
4117       // Emit the location of the prototype.
4118       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4119         Diag(FDecl->getLocStart(), diag::note_callee_decl)
4120           << FDecl;
4121 
4122       // This deletes the extra arguments.
4123       Call->setNumArgs(Context, NumArgsInProto);
4124       return true;
4125     }
4126   }
4127   SmallVector<Expr *, 8> AllArgs;
4128   VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
4129 
4130   Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
4131                                    Proto, 0, Args, AllArgs, CallType);
4132   if (Invalid)
4133     return true;
4134   unsigned TotalNumArgs = AllArgs.size();
4135   for (unsigned i = 0; i < TotalNumArgs; ++i)
4136     Call->setArg(i, AllArgs[i]);
4137 
4138   return false;
4139 }
4140 
4141 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
4142                                   FunctionDecl *FDecl,
4143                                   const FunctionProtoType *Proto,
4144                                   unsigned FirstProtoArg,
4145                                   ArrayRef<Expr *> Args,
4146                                   SmallVectorImpl<Expr *> &AllArgs,
4147                                   VariadicCallType CallType,
4148                                   bool AllowExplicit,
4149                                   bool IsListInitialization) {
4150   unsigned NumArgsInProto = Proto->getNumArgs();
4151   unsigned NumArgsToCheck = Args.size();
4152   bool Invalid = false;
4153   if (Args.size() != NumArgsInProto)
4154     // Use default arguments for missing arguments
4155     NumArgsToCheck = NumArgsInProto;
4156   unsigned ArgIx = 0;
4157   // Continue to check argument types (even if we have too few/many args).
4158   for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
4159     QualType ProtoArgType = Proto->getArgType(i);
4160 
4161     Expr *Arg;
4162     ParmVarDecl *Param;
4163     if (ArgIx < Args.size()) {
4164       Arg = Args[ArgIx++];
4165 
4166       if (RequireCompleteType(Arg->getLocStart(),
4167                               ProtoArgType,
4168                               diag::err_call_incomplete_argument, Arg))
4169         return true;
4170 
4171       // Pass the argument
4172       Param = 0;
4173       if (FDecl && i < FDecl->getNumParams())
4174         Param = FDecl->getParamDecl(i);
4175 
4176       // Strip the unbridged-cast placeholder expression off, if applicable.
4177       bool CFAudited = false;
4178       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
4179           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4180           (!Param || !Param->hasAttr<CFConsumedAttr>()))
4181         Arg = stripARCUnbridgedCast(Arg);
4182       else if (getLangOpts().ObjCAutoRefCount &&
4183                FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4184                (!Param || !Param->hasAttr<CFConsumedAttr>()))
4185         CFAudited = true;
4186 
4187       InitializedEntity Entity = Param ?
4188           InitializedEntity::InitializeParameter(Context, Param, ProtoArgType)
4189         : InitializedEntity::InitializeParameter(Context, ProtoArgType,
4190                                                  Proto->isArgConsumed(i));
4191 
4192       // Remember that parameter belongs to a CF audited API.
4193       if (CFAudited)
4194         Entity.setParameterCFAudited();
4195 
4196       ExprResult ArgE = PerformCopyInitialization(Entity,
4197                                                   SourceLocation(),
4198                                                   Owned(Arg),
4199                                                   IsListInitialization,
4200                                                   AllowExplicit);
4201       if (ArgE.isInvalid())
4202         return true;
4203 
4204       Arg = ArgE.takeAs<Expr>();
4205     } else {
4206       assert(FDecl && "can't use default arguments without a known callee");
4207       Param = FDecl->getParamDecl(i);
4208 
4209       ExprResult ArgExpr =
4210         BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
4211       if (ArgExpr.isInvalid())
4212         return true;
4213 
4214       Arg = ArgExpr.takeAs<Expr>();
4215     }
4216 
4217     // Check for array bounds violations for each argument to the call. This
4218     // check only triggers warnings when the argument isn't a more complex Expr
4219     // with its own checking, such as a BinaryOperator.
4220     CheckArrayAccess(Arg);
4221 
4222     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
4223     CheckStaticArrayArgument(CallLoc, Param, Arg);
4224 
4225     AllArgs.push_back(Arg);
4226   }
4227 
4228   // If this is a variadic call, handle args passed through "...".
4229   if (CallType != VariadicDoesNotApply) {
4230     // Assume that extern "C" functions with variadic arguments that
4231     // return __unknown_anytype aren't *really* variadic.
4232     if (Proto->getResultType() == Context.UnknownAnyTy &&
4233         FDecl && FDecl->isExternC()) {
4234       for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) {
4235         QualType paramType; // ignored
4236         ExprResult arg = checkUnknownAnyArg(CallLoc, Args[i], paramType);
4237         Invalid |= arg.isInvalid();
4238         AllArgs.push_back(arg.take());
4239       }
4240 
4241     // Otherwise do argument promotion, (C99 6.5.2.2p7).
4242     } else {
4243       for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) {
4244         ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType,
4245                                                           FDecl);
4246         Invalid |= Arg.isInvalid();
4247         AllArgs.push_back(Arg.take());
4248       }
4249     }
4250 
4251     // Check for array bounds violations.
4252     for (unsigned i = ArgIx, e = Args.size(); i != e; ++i)
4253       CheckArrayAccess(Args[i]);
4254   }
4255   return Invalid;
4256 }
4257 
4258 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
4259   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
4260   if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
4261     TL = DTL.getOriginalLoc();
4262   if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
4263     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
4264       << ATL.getLocalSourceRange();
4265 }
4266 
4267 /// CheckStaticArrayArgument - If the given argument corresponds to a static
4268 /// array parameter, check that it is non-null, and that if it is formed by
4269 /// array-to-pointer decay, the underlying array is sufficiently large.
4270 ///
4271 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
4272 /// array type derivation, then for each call to the function, the value of the
4273 /// corresponding actual argument shall provide access to the first element of
4274 /// an array with at least as many elements as specified by the size expression.
4275 void
4276 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
4277                                ParmVarDecl *Param,
4278                                const Expr *ArgExpr) {
4279   // Static array parameters are not supported in C++.
4280   if (!Param || getLangOpts().CPlusPlus)
4281     return;
4282 
4283   QualType OrigTy = Param->getOriginalType();
4284 
4285   const ArrayType *AT = Context.getAsArrayType(OrigTy);
4286   if (!AT || AT->getSizeModifier() != ArrayType::Static)
4287     return;
4288 
4289   if (ArgExpr->isNullPointerConstant(Context,
4290                                      Expr::NPC_NeverValueDependent)) {
4291     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
4292     DiagnoseCalleeStaticArrayParam(*this, Param);
4293     return;
4294   }
4295 
4296   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
4297   if (!CAT)
4298     return;
4299 
4300   const ConstantArrayType *ArgCAT =
4301     Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
4302   if (!ArgCAT)
4303     return;
4304 
4305   if (ArgCAT->getSize().ult(CAT->getSize())) {
4306     Diag(CallLoc, diag::warn_static_array_too_small)
4307       << ArgExpr->getSourceRange()
4308       << (unsigned) ArgCAT->getSize().getZExtValue()
4309       << (unsigned) CAT->getSize().getZExtValue();
4310     DiagnoseCalleeStaticArrayParam(*this, Param);
4311   }
4312 }
4313 
4314 /// Given a function expression of unknown-any type, try to rebuild it
4315 /// to have a function type.
4316 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
4317 
4318 /// Is the given type a placeholder that we need to lower out
4319 /// immediately during argument processing?
4320 static bool isPlaceholderToRemoveAsArg(QualType type) {
4321   // Placeholders are never sugared.
4322   const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
4323   if (!placeholder) return false;
4324 
4325   switch (placeholder->getKind()) {
4326   // Ignore all the non-placeholder types.
4327 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
4328 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
4329 #include "clang/AST/BuiltinTypes.def"
4330     return false;
4331 
4332   // We cannot lower out overload sets; they might validly be resolved
4333   // by the call machinery.
4334   case BuiltinType::Overload:
4335     return false;
4336 
4337   // Unbridged casts in ARC can be handled in some call positions and
4338   // should be left in place.
4339   case BuiltinType::ARCUnbridgedCast:
4340     return false;
4341 
4342   // Pseudo-objects should be converted as soon as possible.
4343   case BuiltinType::PseudoObject:
4344     return true;
4345 
4346   // The debugger mode could theoretically but currently does not try
4347   // to resolve unknown-typed arguments based on known parameter types.
4348   case BuiltinType::UnknownAny:
4349     return true;
4350 
4351   // These are always invalid as call arguments and should be reported.
4352   case BuiltinType::BoundMember:
4353   case BuiltinType::BuiltinFn:
4354     return true;
4355   }
4356   llvm_unreachable("bad builtin type kind");
4357 }
4358 
4359 /// Check an argument list for placeholders that we won't try to
4360 /// handle later.
4361 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
4362   // Apply this processing to all the arguments at once instead of
4363   // dying at the first failure.
4364   bool hasInvalid = false;
4365   for (size_t i = 0, e = args.size(); i != e; i++) {
4366     if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
4367       ExprResult result = S.CheckPlaceholderExpr(args[i]);
4368       if (result.isInvalid()) hasInvalid = true;
4369       else args[i] = result.take();
4370     }
4371   }
4372   return hasInvalid;
4373 }
4374 
4375 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
4376 /// This provides the location of the left/right parens and a list of comma
4377 /// locations.
4378 ExprResult
4379 Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
4380                     MultiExprArg ArgExprs, SourceLocation RParenLoc,
4381                     Expr *ExecConfig, bool IsExecConfig) {
4382   // Since this might be a postfix expression, get rid of ParenListExprs.
4383   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
4384   if (Result.isInvalid()) return ExprError();
4385   Fn = Result.take();
4386 
4387   if (checkArgsForPlaceholders(*this, ArgExprs))
4388     return ExprError();
4389 
4390   if (getLangOpts().CPlusPlus) {
4391     // If this is a pseudo-destructor expression, build the call immediately.
4392     if (isa<CXXPseudoDestructorExpr>(Fn)) {
4393       if (!ArgExprs.empty()) {
4394         // Pseudo-destructor calls should not have any arguments.
4395         Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
4396           << FixItHint::CreateRemoval(
4397                                     SourceRange(ArgExprs[0]->getLocStart(),
4398                                                 ArgExprs.back()->getLocEnd()));
4399       }
4400 
4401       return Owned(new (Context) CallExpr(Context, Fn, None,
4402                                           Context.VoidTy, VK_RValue,
4403                                           RParenLoc));
4404     }
4405     if (Fn->getType() == Context.PseudoObjectTy) {
4406       ExprResult result = CheckPlaceholderExpr(Fn);
4407       if (result.isInvalid()) return ExprError();
4408       Fn = result.take();
4409     }
4410 
4411     // Determine whether this is a dependent call inside a C++ template,
4412     // in which case we won't do any semantic analysis now.
4413     // FIXME: Will need to cache the results of name lookup (including ADL) in
4414     // Fn.
4415     bool Dependent = false;
4416     if (Fn->isTypeDependent())
4417       Dependent = true;
4418     else if (Expr::hasAnyTypeDependentArguments(ArgExprs))
4419       Dependent = true;
4420 
4421     if (Dependent) {
4422       if (ExecConfig) {
4423         return Owned(new (Context) CUDAKernelCallExpr(
4424             Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
4425             Context.DependentTy, VK_RValue, RParenLoc));
4426       } else {
4427         return Owned(new (Context) CallExpr(Context, Fn, ArgExprs,
4428                                             Context.DependentTy, VK_RValue,
4429                                             RParenLoc));
4430       }
4431     }
4432 
4433     // Determine whether this is a call to an object (C++ [over.call.object]).
4434     if (Fn->getType()->isRecordType())
4435       return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc,
4436                                                 ArgExprs, RParenLoc));
4437 
4438     if (Fn->getType() == Context.UnknownAnyTy) {
4439       ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
4440       if (result.isInvalid()) return ExprError();
4441       Fn = result.take();
4442     }
4443 
4444     if (Fn->getType() == Context.BoundMemberTy) {
4445       return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs, RParenLoc);
4446     }
4447   }
4448 
4449   // Check for overloaded calls.  This can happen even in C due to extensions.
4450   if (Fn->getType() == Context.OverloadTy) {
4451     OverloadExpr::FindResult find = OverloadExpr::find(Fn);
4452 
4453     // We aren't supposed to apply this logic for if there's an '&' involved.
4454     if (!find.HasFormOfMemberPointer) {
4455       OverloadExpr *ovl = find.Expression;
4456       if (isa<UnresolvedLookupExpr>(ovl)) {
4457         UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
4458         return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, ArgExprs,
4459                                        RParenLoc, ExecConfig);
4460       } else {
4461         return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs,
4462                                          RParenLoc);
4463       }
4464     }
4465   }
4466 
4467   // If we're directly calling a function, get the appropriate declaration.
4468   if (Fn->getType() == Context.UnknownAnyTy) {
4469     ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
4470     if (result.isInvalid()) return ExprError();
4471     Fn = result.take();
4472   }
4473 
4474   Expr *NakedFn = Fn->IgnoreParens();
4475 
4476   NamedDecl *NDecl = 0;
4477   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
4478     if (UnOp->getOpcode() == UO_AddrOf)
4479       NakedFn = UnOp->getSubExpr()->IgnoreParens();
4480 
4481   if (isa<DeclRefExpr>(NakedFn))
4482     NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
4483   else if (isa<MemberExpr>(NakedFn))
4484     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
4485 
4486   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
4487                                ExecConfig, IsExecConfig);
4488 }
4489 
4490 ExprResult
4491 Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
4492                               MultiExprArg ExecConfig, SourceLocation GGGLoc) {
4493   FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
4494   if (!ConfigDecl)
4495     return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
4496                           << "cudaConfigureCall");
4497   QualType ConfigQTy = ConfigDecl->getType();
4498 
4499   DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
4500       ConfigDecl, false, ConfigQTy, VK_LValue, LLLLoc);
4501   MarkFunctionReferenced(LLLLoc, ConfigDecl);
4502 
4503   return ActOnCallExpr(S, ConfigDR, LLLLoc, ExecConfig, GGGLoc, 0,
4504                        /*IsExecConfig=*/true);
4505 }
4506 
4507 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
4508 ///
4509 /// __builtin_astype( value, dst type )
4510 ///
4511 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
4512                                  SourceLocation BuiltinLoc,
4513                                  SourceLocation RParenLoc) {
4514   ExprValueKind VK = VK_RValue;
4515   ExprObjectKind OK = OK_Ordinary;
4516   QualType DstTy = GetTypeFromParser(ParsedDestTy);
4517   QualType SrcTy = E->getType();
4518   if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
4519     return ExprError(Diag(BuiltinLoc,
4520                           diag::err_invalid_astype_of_different_size)
4521                      << DstTy
4522                      << SrcTy
4523                      << E->getSourceRange());
4524   return Owned(new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc,
4525                RParenLoc));
4526 }
4527 
4528 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
4529 /// provided arguments.
4530 ///
4531 /// __builtin_convertvector( value, dst type )
4532 ///
4533 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
4534                                         SourceLocation BuiltinLoc,
4535                                         SourceLocation RParenLoc) {
4536   TypeSourceInfo *TInfo;
4537   GetTypeFromParser(ParsedDestTy, &TInfo);
4538   return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
4539 }
4540 
4541 /// BuildResolvedCallExpr - Build a call to a resolved expression,
4542 /// i.e. an expression not of \p OverloadTy.  The expression should
4543 /// unary-convert to an expression of function-pointer or
4544 /// block-pointer type.
4545 ///
4546 /// \param NDecl the declaration being called, if available
4547 ExprResult
4548 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
4549                             SourceLocation LParenLoc,
4550                             ArrayRef<Expr *> Args,
4551                             SourceLocation RParenLoc,
4552                             Expr *Config, bool IsExecConfig) {
4553   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
4554   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
4555 
4556   // Promote the function operand.
4557   // We special-case function promotion here because we only allow promoting
4558   // builtin functions to function pointers in the callee of a call.
4559   ExprResult Result;
4560   if (BuiltinID &&
4561       Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
4562     Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()),
4563                                CK_BuiltinFnToFnPtr).take();
4564   } else {
4565     Result = UsualUnaryConversions(Fn);
4566   }
4567   if (Result.isInvalid())
4568     return ExprError();
4569   Fn = Result.take();
4570 
4571   // Make the call expr early, before semantic checks.  This guarantees cleanup
4572   // of arguments and function on error.
4573   CallExpr *TheCall;
4574   if (Config)
4575     TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
4576                                                cast<CallExpr>(Config), Args,
4577                                                Context.BoolTy, VK_RValue,
4578                                                RParenLoc);
4579   else
4580     TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy,
4581                                      VK_RValue, RParenLoc);
4582 
4583   // Bail out early if calling a builtin with custom typechecking.
4584   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
4585     return CheckBuiltinFunctionCall(BuiltinID, TheCall);
4586 
4587  retry:
4588   const FunctionType *FuncT;
4589   if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
4590     // C99 6.5.2.2p1 - "The expression that denotes the called function shall
4591     // have type pointer to function".
4592     FuncT = PT->getPointeeType()->getAs<FunctionType>();
4593     if (FuncT == 0)
4594       return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4595                          << Fn->getType() << Fn->getSourceRange());
4596   } else if (const BlockPointerType *BPT =
4597                Fn->getType()->getAs<BlockPointerType>()) {
4598     FuncT = BPT->getPointeeType()->castAs<FunctionType>();
4599   } else {
4600     // Handle calls to expressions of unknown-any type.
4601     if (Fn->getType() == Context.UnknownAnyTy) {
4602       ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
4603       if (rewrite.isInvalid()) return ExprError();
4604       Fn = rewrite.take();
4605       TheCall->setCallee(Fn);
4606       goto retry;
4607     }
4608 
4609     return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4610       << Fn->getType() << Fn->getSourceRange());
4611   }
4612 
4613   if (getLangOpts().CUDA) {
4614     if (Config) {
4615       // CUDA: Kernel calls must be to global functions
4616       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
4617         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
4618             << FDecl->getName() << Fn->getSourceRange());
4619 
4620       // CUDA: Kernel function must have 'void' return type
4621       if (!FuncT->getResultType()->isVoidType())
4622         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
4623             << Fn->getType() << Fn->getSourceRange());
4624     } else {
4625       // CUDA: Calls to global functions must be configured
4626       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
4627         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
4628             << FDecl->getName() << Fn->getSourceRange());
4629     }
4630   }
4631 
4632   // Check for a valid return type
4633   if (CheckCallReturnType(FuncT->getResultType(),
4634                           Fn->getLocStart(), TheCall,
4635                           FDecl))
4636     return ExprError();
4637 
4638   // We know the result type of the call, set it.
4639   TheCall->setType(FuncT->getCallResultType(Context));
4640   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
4641 
4642   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
4643   if (Proto) {
4644     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
4645                                 IsExecConfig))
4646       return ExprError();
4647   } else {
4648     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
4649 
4650     if (FDecl) {
4651       // Check if we have too few/too many template arguments, based
4652       // on our knowledge of the function definition.
4653       const FunctionDecl *Def = 0;
4654       if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
4655         Proto = Def->getType()->getAs<FunctionProtoType>();
4656        if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
4657           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
4658           << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
4659       }
4660 
4661       // If the function we're calling isn't a function prototype, but we have
4662       // a function prototype from a prior declaratiom, use that prototype.
4663       if (!FDecl->hasPrototype())
4664         Proto = FDecl->getType()->getAs<FunctionProtoType>();
4665     }
4666 
4667     // Promote the arguments (C99 6.5.2.2p6).
4668     for (unsigned i = 0, e = Args.size(); i != e; i++) {
4669       Expr *Arg = Args[i];
4670 
4671       if (Proto && i < Proto->getNumArgs()) {
4672         InitializedEntity Entity
4673           = InitializedEntity::InitializeParameter(Context,
4674                                                    Proto->getArgType(i),
4675                                                    Proto->isArgConsumed(i));
4676         ExprResult ArgE = PerformCopyInitialization(Entity,
4677                                                     SourceLocation(),
4678                                                     Owned(Arg));
4679         if (ArgE.isInvalid())
4680           return true;
4681 
4682         Arg = ArgE.takeAs<Expr>();
4683 
4684       } else {
4685         ExprResult ArgE = DefaultArgumentPromotion(Arg);
4686 
4687         if (ArgE.isInvalid())
4688           return true;
4689 
4690         Arg = ArgE.takeAs<Expr>();
4691       }
4692 
4693       if (RequireCompleteType(Arg->getLocStart(),
4694                               Arg->getType(),
4695                               diag::err_call_incomplete_argument, Arg))
4696         return ExprError();
4697 
4698       TheCall->setArg(i, Arg);
4699     }
4700   }
4701 
4702   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4703     if (!Method->isStatic())
4704       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
4705         << Fn->getSourceRange());
4706 
4707   // Check for sentinels
4708   if (NDecl)
4709     DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
4710 
4711   // Do special checking on direct calls to functions.
4712   if (FDecl) {
4713     if (CheckFunctionCall(FDecl, TheCall, Proto))
4714       return ExprError();
4715 
4716     if (BuiltinID)
4717       return CheckBuiltinFunctionCall(BuiltinID, TheCall);
4718   } else if (NDecl) {
4719     if (CheckPointerCall(NDecl, TheCall, Proto))
4720       return ExprError();
4721   } else {
4722     if (CheckOtherCall(TheCall, Proto))
4723       return ExprError();
4724   }
4725 
4726   return MaybeBindToTemporary(TheCall);
4727 }
4728 
4729 ExprResult
4730 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
4731                            SourceLocation RParenLoc, Expr *InitExpr) {
4732   assert(Ty && "ActOnCompoundLiteral(): missing type");
4733   // FIXME: put back this assert when initializers are worked out.
4734   //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
4735 
4736   TypeSourceInfo *TInfo;
4737   QualType literalType = GetTypeFromParser(Ty, &TInfo);
4738   if (!TInfo)
4739     TInfo = Context.getTrivialTypeSourceInfo(literalType);
4740 
4741   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
4742 }
4743 
4744 ExprResult
4745 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
4746                                SourceLocation RParenLoc, Expr *LiteralExpr) {
4747   QualType literalType = TInfo->getType();
4748 
4749   if (literalType->isArrayType()) {
4750     if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
4751           diag::err_illegal_decl_array_incomplete_type,
4752           SourceRange(LParenLoc,
4753                       LiteralExpr->getSourceRange().getEnd())))
4754       return ExprError();
4755     if (literalType->isVariableArrayType())
4756       return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
4757         << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
4758   } else if (!literalType->isDependentType() &&
4759              RequireCompleteType(LParenLoc, literalType,
4760                diag::err_typecheck_decl_incomplete_type,
4761                SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
4762     return ExprError();
4763 
4764   InitializedEntity Entity
4765     = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
4766   InitializationKind Kind
4767     = InitializationKind::CreateCStyleCast(LParenLoc,
4768                                            SourceRange(LParenLoc, RParenLoc),
4769                                            /*InitList=*/true);
4770   InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
4771   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
4772                                       &literalType);
4773   if (Result.isInvalid())
4774     return ExprError();
4775   LiteralExpr = Result.get();
4776 
4777   bool isFileScope = getCurFunctionOrMethodDecl() == 0;
4778   if (isFileScope &&
4779       !LiteralExpr->isTypeDependent() &&
4780       !LiteralExpr->isValueDependent() &&
4781       !literalType->isDependentType()) { // 6.5.2.5p3
4782     if (CheckForConstantInitializer(LiteralExpr, literalType))
4783       return ExprError();
4784   }
4785 
4786   // In C, compound literals are l-values for some reason.
4787   ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue;
4788 
4789   return MaybeBindToTemporary(
4790            new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
4791                                              VK, LiteralExpr, isFileScope));
4792 }
4793 
4794 ExprResult
4795 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
4796                     SourceLocation RBraceLoc) {
4797   // Immediately handle non-overload placeholders.  Overloads can be
4798   // resolved contextually, but everything else here can't.
4799   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
4800     if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
4801       ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
4802 
4803       // Ignore failures; dropping the entire initializer list because
4804       // of one failure would be terrible for indexing/etc.
4805       if (result.isInvalid()) continue;
4806 
4807       InitArgList[I] = result.take();
4808     }
4809   }
4810 
4811   // Semantic analysis for initializers is done by ActOnDeclarator() and
4812   // CheckInitializer() - it requires knowledge of the object being intialized.
4813 
4814   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
4815                                                RBraceLoc);
4816   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
4817   return Owned(E);
4818 }
4819 
4820 /// Do an explicit extend of the given block pointer if we're in ARC.
4821 static void maybeExtendBlockObject(Sema &S, ExprResult &E) {
4822   assert(E.get()->getType()->isBlockPointerType());
4823   assert(E.get()->isRValue());
4824 
4825   // Only do this in an r-value context.
4826   if (!S.getLangOpts().ObjCAutoRefCount) return;
4827 
4828   E = ImplicitCastExpr::Create(S.Context, E.get()->getType(),
4829                                CK_ARCExtendBlockObject, E.get(),
4830                                /*base path*/ 0, VK_RValue);
4831   S.ExprNeedsCleanups = true;
4832 }
4833 
4834 /// Prepare a conversion of the given expression to an ObjC object
4835 /// pointer type.
4836 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
4837   QualType type = E.get()->getType();
4838   if (type->isObjCObjectPointerType()) {
4839     return CK_BitCast;
4840   } else if (type->isBlockPointerType()) {
4841     maybeExtendBlockObject(*this, E);
4842     return CK_BlockPointerToObjCPointerCast;
4843   } else {
4844     assert(type->isPointerType());
4845     return CK_CPointerToObjCPointerCast;
4846   }
4847 }
4848 
4849 /// Prepares for a scalar cast, performing all the necessary stages
4850 /// except the final cast and returning the kind required.
4851 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
4852   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
4853   // Also, callers should have filtered out the invalid cases with
4854   // pointers.  Everything else should be possible.
4855 
4856   QualType SrcTy = Src.get()->getType();
4857   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
4858     return CK_NoOp;
4859 
4860   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
4861   case Type::STK_MemberPointer:
4862     llvm_unreachable("member pointer type in C");
4863 
4864   case Type::STK_CPointer:
4865   case Type::STK_BlockPointer:
4866   case Type::STK_ObjCObjectPointer:
4867     switch (DestTy->getScalarTypeKind()) {
4868     case Type::STK_CPointer:
4869       return CK_BitCast;
4870     case Type::STK_BlockPointer:
4871       return (SrcKind == Type::STK_BlockPointer
4872                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
4873     case Type::STK_ObjCObjectPointer:
4874       if (SrcKind == Type::STK_ObjCObjectPointer)
4875         return CK_BitCast;
4876       if (SrcKind == Type::STK_CPointer)
4877         return CK_CPointerToObjCPointerCast;
4878       maybeExtendBlockObject(*this, Src);
4879       return CK_BlockPointerToObjCPointerCast;
4880     case Type::STK_Bool:
4881       return CK_PointerToBoolean;
4882     case Type::STK_Integral:
4883       return CK_PointerToIntegral;
4884     case Type::STK_Floating:
4885     case Type::STK_FloatingComplex:
4886     case Type::STK_IntegralComplex:
4887     case Type::STK_MemberPointer:
4888       llvm_unreachable("illegal cast from pointer");
4889     }
4890     llvm_unreachable("Should have returned before this");
4891 
4892   case Type::STK_Bool: // casting from bool is like casting from an integer
4893   case Type::STK_Integral:
4894     switch (DestTy->getScalarTypeKind()) {
4895     case Type::STK_CPointer:
4896     case Type::STK_ObjCObjectPointer:
4897     case Type::STK_BlockPointer:
4898       if (Src.get()->isNullPointerConstant(Context,
4899                                            Expr::NPC_ValueDependentIsNull))
4900         return CK_NullToPointer;
4901       return CK_IntegralToPointer;
4902     case Type::STK_Bool:
4903       return CK_IntegralToBoolean;
4904     case Type::STK_Integral:
4905       return CK_IntegralCast;
4906     case Type::STK_Floating:
4907       return CK_IntegralToFloating;
4908     case Type::STK_IntegralComplex:
4909       Src = ImpCastExprToType(Src.take(),
4910                               DestTy->castAs<ComplexType>()->getElementType(),
4911                               CK_IntegralCast);
4912       return CK_IntegralRealToComplex;
4913     case Type::STK_FloatingComplex:
4914       Src = ImpCastExprToType(Src.take(),
4915                               DestTy->castAs<ComplexType>()->getElementType(),
4916                               CK_IntegralToFloating);
4917       return CK_FloatingRealToComplex;
4918     case Type::STK_MemberPointer:
4919       llvm_unreachable("member pointer type in C");
4920     }
4921     llvm_unreachable("Should have returned before this");
4922 
4923   case Type::STK_Floating:
4924     switch (DestTy->getScalarTypeKind()) {
4925     case Type::STK_Floating:
4926       return CK_FloatingCast;
4927     case Type::STK_Bool:
4928       return CK_FloatingToBoolean;
4929     case Type::STK_Integral:
4930       return CK_FloatingToIntegral;
4931     case Type::STK_FloatingComplex:
4932       Src = ImpCastExprToType(Src.take(),
4933                               DestTy->castAs<ComplexType>()->getElementType(),
4934                               CK_FloatingCast);
4935       return CK_FloatingRealToComplex;
4936     case Type::STK_IntegralComplex:
4937       Src = ImpCastExprToType(Src.take(),
4938                               DestTy->castAs<ComplexType>()->getElementType(),
4939                               CK_FloatingToIntegral);
4940       return CK_IntegralRealToComplex;
4941     case Type::STK_CPointer:
4942     case Type::STK_ObjCObjectPointer:
4943     case Type::STK_BlockPointer:
4944       llvm_unreachable("valid float->pointer cast?");
4945     case Type::STK_MemberPointer:
4946       llvm_unreachable("member pointer type in C");
4947     }
4948     llvm_unreachable("Should have returned before this");
4949 
4950   case Type::STK_FloatingComplex:
4951     switch (DestTy->getScalarTypeKind()) {
4952     case Type::STK_FloatingComplex:
4953       return CK_FloatingComplexCast;
4954     case Type::STK_IntegralComplex:
4955       return CK_FloatingComplexToIntegralComplex;
4956     case Type::STK_Floating: {
4957       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
4958       if (Context.hasSameType(ET, DestTy))
4959         return CK_FloatingComplexToReal;
4960       Src = ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal);
4961       return CK_FloatingCast;
4962     }
4963     case Type::STK_Bool:
4964       return CK_FloatingComplexToBoolean;
4965     case Type::STK_Integral:
4966       Src = ImpCastExprToType(Src.take(),
4967                               SrcTy->castAs<ComplexType>()->getElementType(),
4968                               CK_FloatingComplexToReal);
4969       return CK_FloatingToIntegral;
4970     case Type::STK_CPointer:
4971     case Type::STK_ObjCObjectPointer:
4972     case Type::STK_BlockPointer:
4973       llvm_unreachable("valid complex float->pointer cast?");
4974     case Type::STK_MemberPointer:
4975       llvm_unreachable("member pointer type in C");
4976     }
4977     llvm_unreachable("Should have returned before this");
4978 
4979   case Type::STK_IntegralComplex:
4980     switch (DestTy->getScalarTypeKind()) {
4981     case Type::STK_FloatingComplex:
4982       return CK_IntegralComplexToFloatingComplex;
4983     case Type::STK_IntegralComplex:
4984       return CK_IntegralComplexCast;
4985     case Type::STK_Integral: {
4986       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
4987       if (Context.hasSameType(ET, DestTy))
4988         return CK_IntegralComplexToReal;
4989       Src = ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal);
4990       return CK_IntegralCast;
4991     }
4992     case Type::STK_Bool:
4993       return CK_IntegralComplexToBoolean;
4994     case Type::STK_Floating:
4995       Src = ImpCastExprToType(Src.take(),
4996                               SrcTy->castAs<ComplexType>()->getElementType(),
4997                               CK_IntegralComplexToReal);
4998       return CK_IntegralToFloating;
4999     case Type::STK_CPointer:
5000     case Type::STK_ObjCObjectPointer:
5001     case Type::STK_BlockPointer:
5002       llvm_unreachable("valid complex int->pointer cast?");
5003     case Type::STK_MemberPointer:
5004       llvm_unreachable("member pointer type in C");
5005     }
5006     llvm_unreachable("Should have returned before this");
5007   }
5008 
5009   llvm_unreachable("Unhandled scalar cast");
5010 }
5011 
5012 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
5013                            CastKind &Kind) {
5014   assert(VectorTy->isVectorType() && "Not a vector type!");
5015 
5016   if (Ty->isVectorType() || Ty->isIntegerType()) {
5017     if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
5018       return Diag(R.getBegin(),
5019                   Ty->isVectorType() ?
5020                   diag::err_invalid_conversion_between_vectors :
5021                   diag::err_invalid_conversion_between_vector_and_integer)
5022         << VectorTy << Ty << R;
5023   } else
5024     return Diag(R.getBegin(),
5025                 diag::err_invalid_conversion_between_vector_and_scalar)
5026       << VectorTy << Ty << R;
5027 
5028   Kind = CK_BitCast;
5029   return false;
5030 }
5031 
5032 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
5033                                     Expr *CastExpr, CastKind &Kind) {
5034   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
5035 
5036   QualType SrcTy = CastExpr->getType();
5037 
5038   // If SrcTy is a VectorType, the total size must match to explicitly cast to
5039   // an ExtVectorType.
5040   // In OpenCL, casts between vectors of different types are not allowed.
5041   // (See OpenCL 6.2).
5042   if (SrcTy->isVectorType()) {
5043     if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)
5044         || (getLangOpts().OpenCL &&
5045             (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
5046       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
5047         << DestTy << SrcTy << R;
5048       return ExprError();
5049     }
5050     Kind = CK_BitCast;
5051     return Owned(CastExpr);
5052   }
5053 
5054   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
5055   // conversion will take place first from scalar to elt type, and then
5056   // splat from elt type to vector.
5057   if (SrcTy->isPointerType())
5058     return Diag(R.getBegin(),
5059                 diag::err_invalid_conversion_between_vector_and_scalar)
5060       << DestTy << SrcTy << R;
5061 
5062   QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
5063   ExprResult CastExprRes = Owned(CastExpr);
5064   CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy);
5065   if (CastExprRes.isInvalid())
5066     return ExprError();
5067   CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take();
5068 
5069   Kind = CK_VectorSplat;
5070   return Owned(CastExpr);
5071 }
5072 
5073 ExprResult
5074 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
5075                     Declarator &D, ParsedType &Ty,
5076                     SourceLocation RParenLoc, Expr *CastExpr) {
5077   assert(!D.isInvalidType() && (CastExpr != 0) &&
5078          "ActOnCastExpr(): missing type or expr");
5079 
5080   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
5081   if (D.isInvalidType())
5082     return ExprError();
5083 
5084   if (getLangOpts().CPlusPlus) {
5085     // Check that there are no default arguments (C++ only).
5086     CheckExtraCXXDefaultArguments(D);
5087   }
5088 
5089   checkUnusedDeclAttributes(D);
5090 
5091   QualType castType = castTInfo->getType();
5092   Ty = CreateParsedType(castType, castTInfo);
5093 
5094   bool isVectorLiteral = false;
5095 
5096   // Check for an altivec or OpenCL literal,
5097   // i.e. all the elements are integer constants.
5098   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
5099   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
5100   if ((getLangOpts().AltiVec || getLangOpts().OpenCL)
5101        && castType->isVectorType() && (PE || PLE)) {
5102     if (PLE && PLE->getNumExprs() == 0) {
5103       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
5104       return ExprError();
5105     }
5106     if (PE || PLE->getNumExprs() == 1) {
5107       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
5108       if (!E->getType()->isVectorType())
5109         isVectorLiteral = true;
5110     }
5111     else
5112       isVectorLiteral = true;
5113   }
5114 
5115   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
5116   // then handle it as such.
5117   if (isVectorLiteral)
5118     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
5119 
5120   // If the Expr being casted is a ParenListExpr, handle it specially.
5121   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
5122   // sequence of BinOp comma operators.
5123   if (isa<ParenListExpr>(CastExpr)) {
5124     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
5125     if (Result.isInvalid()) return ExprError();
5126     CastExpr = Result.take();
5127   }
5128 
5129   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
5130 }
5131 
5132 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
5133                                     SourceLocation RParenLoc, Expr *E,
5134                                     TypeSourceInfo *TInfo) {
5135   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
5136          "Expected paren or paren list expression");
5137 
5138   Expr **exprs;
5139   unsigned numExprs;
5140   Expr *subExpr;
5141   SourceLocation LiteralLParenLoc, LiteralRParenLoc;
5142   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
5143     LiteralLParenLoc = PE->getLParenLoc();
5144     LiteralRParenLoc = PE->getRParenLoc();
5145     exprs = PE->getExprs();
5146     numExprs = PE->getNumExprs();
5147   } else { // isa<ParenExpr> by assertion at function entrance
5148     LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
5149     LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
5150     subExpr = cast<ParenExpr>(E)->getSubExpr();
5151     exprs = &subExpr;
5152     numExprs = 1;
5153   }
5154 
5155   QualType Ty = TInfo->getType();
5156   assert(Ty->isVectorType() && "Expected vector type");
5157 
5158   SmallVector<Expr *, 8> initExprs;
5159   const VectorType *VTy = Ty->getAs<VectorType>();
5160   unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
5161 
5162   // '(...)' form of vector initialization in AltiVec: the number of
5163   // initializers must be one or must match the size of the vector.
5164   // If a single value is specified in the initializer then it will be
5165   // replicated to all the components of the vector
5166   if (VTy->getVectorKind() == VectorType::AltiVecVector) {
5167     // The number of initializers must be one or must match the size of the
5168     // vector. If a single value is specified in the initializer then it will
5169     // be replicated to all the components of the vector
5170     if (numExprs == 1) {
5171       QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
5172       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
5173       if (Literal.isInvalid())
5174         return ExprError();
5175       Literal = ImpCastExprToType(Literal.take(), ElemTy,
5176                                   PrepareScalarCast(Literal, ElemTy));
5177       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
5178     }
5179     else if (numExprs < numElems) {
5180       Diag(E->getExprLoc(),
5181            diag::err_incorrect_number_of_vector_initializers);
5182       return ExprError();
5183     }
5184     else
5185       initExprs.append(exprs, exprs + numExprs);
5186   }
5187   else {
5188     // For OpenCL, when the number of initializers is a single value,
5189     // it will be replicated to all components of the vector.
5190     if (getLangOpts().OpenCL &&
5191         VTy->getVectorKind() == VectorType::GenericVector &&
5192         numExprs == 1) {
5193         QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
5194         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
5195         if (Literal.isInvalid())
5196           return ExprError();
5197         Literal = ImpCastExprToType(Literal.take(), ElemTy,
5198                                     PrepareScalarCast(Literal, ElemTy));
5199         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
5200     }
5201 
5202     initExprs.append(exprs, exprs + numExprs);
5203   }
5204   // FIXME: This means that pretty-printing the final AST will produce curly
5205   // braces instead of the original commas.
5206   InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
5207                                                    initExprs, LiteralRParenLoc);
5208   initE->setType(Ty);
5209   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
5210 }
5211 
5212 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
5213 /// the ParenListExpr into a sequence of comma binary operators.
5214 ExprResult
5215 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
5216   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
5217   if (!E)
5218     return Owned(OrigExpr);
5219 
5220   ExprResult Result(E->getExpr(0));
5221 
5222   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
5223     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
5224                         E->getExpr(i));
5225 
5226   if (Result.isInvalid()) return ExprError();
5227 
5228   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
5229 }
5230 
5231 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
5232                                     SourceLocation R,
5233                                     MultiExprArg Val) {
5234   Expr *expr = new (Context) ParenListExpr(Context, L, Val, R);
5235   return Owned(expr);
5236 }
5237 
5238 /// \brief Emit a specialized diagnostic when one expression is a null pointer
5239 /// constant and the other is not a pointer.  Returns true if a diagnostic is
5240 /// emitted.
5241 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
5242                                       SourceLocation QuestionLoc) {
5243   Expr *NullExpr = LHSExpr;
5244   Expr *NonPointerExpr = RHSExpr;
5245   Expr::NullPointerConstantKind NullKind =
5246       NullExpr->isNullPointerConstant(Context,
5247                                       Expr::NPC_ValueDependentIsNotNull);
5248 
5249   if (NullKind == Expr::NPCK_NotNull) {
5250     NullExpr = RHSExpr;
5251     NonPointerExpr = LHSExpr;
5252     NullKind =
5253         NullExpr->isNullPointerConstant(Context,
5254                                         Expr::NPC_ValueDependentIsNotNull);
5255   }
5256 
5257   if (NullKind == Expr::NPCK_NotNull)
5258     return false;
5259 
5260   if (NullKind == Expr::NPCK_ZeroExpression)
5261     return false;
5262 
5263   if (NullKind == Expr::NPCK_ZeroLiteral) {
5264     // In this case, check to make sure that we got here from a "NULL"
5265     // string in the source code.
5266     NullExpr = NullExpr->IgnoreParenImpCasts();
5267     SourceLocation loc = NullExpr->getExprLoc();
5268     if (!findMacroSpelling(loc, "NULL"))
5269       return false;
5270   }
5271 
5272   int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
5273   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
5274       << NonPointerExpr->getType() << DiagType
5275       << NonPointerExpr->getSourceRange();
5276   return true;
5277 }
5278 
5279 /// \brief Return false if the condition expression is valid, true otherwise.
5280 static bool checkCondition(Sema &S, Expr *Cond) {
5281   QualType CondTy = Cond->getType();
5282 
5283   // C99 6.5.15p2
5284   if (CondTy->isScalarType()) return false;
5285 
5286   // OpenCL v1.1 s6.3.i says the condition is allowed to be a vector or scalar.
5287   if (S.getLangOpts().OpenCL && CondTy->isVectorType())
5288     return false;
5289 
5290   // Emit the proper error message.
5291   S.Diag(Cond->getLocStart(), S.getLangOpts().OpenCL ?
5292                               diag::err_typecheck_cond_expect_scalar :
5293                               diag::err_typecheck_cond_expect_scalar_or_vector)
5294     << CondTy;
5295   return true;
5296 }
5297 
5298 /// \brief Return false if the two expressions can be converted to a vector,
5299 /// true otherwise
5300 static bool checkConditionalConvertScalarsToVectors(Sema &S, ExprResult &LHS,
5301                                                     ExprResult &RHS,
5302                                                     QualType CondTy) {
5303   // Both operands should be of scalar type.
5304   if (!LHS.get()->getType()->isScalarType()) {
5305     S.Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
5306       << CondTy;
5307     return true;
5308   }
5309   if (!RHS.get()->getType()->isScalarType()) {
5310     S.Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
5311       << CondTy;
5312     return true;
5313   }
5314 
5315   // Implicity convert these scalars to the type of the condition.
5316   LHS = S.ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast);
5317   RHS = S.ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast);
5318   return false;
5319 }
5320 
5321 /// \brief Handle when one or both operands are void type.
5322 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
5323                                          ExprResult &RHS) {
5324     Expr *LHSExpr = LHS.get();
5325     Expr *RHSExpr = RHS.get();
5326 
5327     if (!LHSExpr->getType()->isVoidType())
5328       S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
5329         << RHSExpr->getSourceRange();
5330     if (!RHSExpr->getType()->isVoidType())
5331       S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
5332         << LHSExpr->getSourceRange();
5333     LHS = S.ImpCastExprToType(LHS.take(), S.Context.VoidTy, CK_ToVoid);
5334     RHS = S.ImpCastExprToType(RHS.take(), S.Context.VoidTy, CK_ToVoid);
5335     return S.Context.VoidTy;
5336 }
5337 
5338 /// \brief Return false if the NullExpr can be promoted to PointerTy,
5339 /// true otherwise.
5340 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
5341                                         QualType PointerTy) {
5342   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
5343       !NullExpr.get()->isNullPointerConstant(S.Context,
5344                                             Expr::NPC_ValueDependentIsNull))
5345     return true;
5346 
5347   NullExpr = S.ImpCastExprToType(NullExpr.take(), PointerTy, CK_NullToPointer);
5348   return false;
5349 }
5350 
5351 /// \brief Checks compatibility between two pointers and return the resulting
5352 /// type.
5353 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
5354                                                      ExprResult &RHS,
5355                                                      SourceLocation Loc) {
5356   QualType LHSTy = LHS.get()->getType();
5357   QualType RHSTy = RHS.get()->getType();
5358 
5359   if (S.Context.hasSameType(LHSTy, RHSTy)) {
5360     // Two identical pointers types are always compatible.
5361     return LHSTy;
5362   }
5363 
5364   QualType lhptee, rhptee;
5365 
5366   // Get the pointee types.
5367   bool IsBlockPointer = false;
5368   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
5369     lhptee = LHSBTy->getPointeeType();
5370     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
5371     IsBlockPointer = true;
5372   } else {
5373     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
5374     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
5375   }
5376 
5377   // C99 6.5.15p6: If both operands are pointers to compatible types or to
5378   // differently qualified versions of compatible types, the result type is
5379   // a pointer to an appropriately qualified version of the composite
5380   // type.
5381 
5382   // Only CVR-qualifiers exist in the standard, and the differently-qualified
5383   // clause doesn't make sense for our extensions. E.g. address space 2 should
5384   // be incompatible with address space 3: they may live on different devices or
5385   // anything.
5386   Qualifiers lhQual = lhptee.getQualifiers();
5387   Qualifiers rhQual = rhptee.getQualifiers();
5388 
5389   unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
5390   lhQual.removeCVRQualifiers();
5391   rhQual.removeCVRQualifiers();
5392 
5393   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
5394   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
5395 
5396   QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
5397 
5398   if (CompositeTy.isNull()) {
5399     S.Diag(Loc, diag::warn_typecheck_cond_incompatible_pointers)
5400       << LHSTy << RHSTy << LHS.get()->getSourceRange()
5401       << RHS.get()->getSourceRange();
5402     // In this situation, we assume void* type. No especially good
5403     // reason, but this is what gcc does, and we do have to pick
5404     // to get a consistent AST.
5405     QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy);
5406     LHS = S.ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
5407     RHS = S.ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
5408     return incompatTy;
5409   }
5410 
5411   // The pointer types are compatible.
5412   QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual);
5413   if (IsBlockPointer)
5414     ResultTy = S.Context.getBlockPointerType(ResultTy);
5415   else
5416     ResultTy = S.Context.getPointerType(ResultTy);
5417 
5418   LHS = S.ImpCastExprToType(LHS.take(), ResultTy, CK_BitCast);
5419   RHS = S.ImpCastExprToType(RHS.take(), ResultTy, CK_BitCast);
5420   return ResultTy;
5421 }
5422 
5423 /// \brief Return the resulting type when the operands are both block pointers.
5424 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
5425                                                           ExprResult &LHS,
5426                                                           ExprResult &RHS,
5427                                                           SourceLocation Loc) {
5428   QualType LHSTy = LHS.get()->getType();
5429   QualType RHSTy = RHS.get()->getType();
5430 
5431   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
5432     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
5433       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
5434       LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
5435       RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
5436       return destType;
5437     }
5438     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
5439       << LHSTy << RHSTy << LHS.get()->getSourceRange()
5440       << RHS.get()->getSourceRange();
5441     return QualType();
5442   }
5443 
5444   // We have 2 block pointer types.
5445   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
5446 }
5447 
5448 /// \brief Return the resulting type when the operands are both pointers.
5449 static QualType
5450 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
5451                                             ExprResult &RHS,
5452                                             SourceLocation Loc) {
5453   // get the pointer types
5454   QualType LHSTy = LHS.get()->getType();
5455   QualType RHSTy = RHS.get()->getType();
5456 
5457   // get the "pointed to" types
5458   QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5459   QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
5460 
5461   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
5462   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
5463     // Figure out necessary qualifiers (C99 6.5.15p6)
5464     QualType destPointee
5465       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
5466     QualType destType = S.Context.getPointerType(destPointee);
5467     // Add qualifiers if necessary.
5468     LHS = S.ImpCastExprToType(LHS.take(), destType, CK_NoOp);
5469     // Promote to void*.
5470     RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
5471     return destType;
5472   }
5473   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
5474     QualType destPointee
5475       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
5476     QualType destType = S.Context.getPointerType(destPointee);
5477     // Add qualifiers if necessary.
5478     RHS = S.ImpCastExprToType(RHS.take(), destType, CK_NoOp);
5479     // Promote to void*.
5480     LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
5481     return destType;
5482   }
5483 
5484   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
5485 }
5486 
5487 /// \brief Return false if the first expression is not an integer and the second
5488 /// expression is not a pointer, true otherwise.
5489 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
5490                                         Expr* PointerExpr, SourceLocation Loc,
5491                                         bool IsIntFirstExpr) {
5492   if (!PointerExpr->getType()->isPointerType() ||
5493       !Int.get()->getType()->isIntegerType())
5494     return false;
5495 
5496   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
5497   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
5498 
5499   S.Diag(Loc, diag::warn_typecheck_cond_pointer_integer_mismatch)
5500     << Expr1->getType() << Expr2->getType()
5501     << Expr1->getSourceRange() << Expr2->getSourceRange();
5502   Int = S.ImpCastExprToType(Int.take(), PointerExpr->getType(),
5503                             CK_IntegralToPointer);
5504   return true;
5505 }
5506 
5507 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
5508 /// In that case, LHS = cond.
5509 /// C99 6.5.15
5510 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
5511                                         ExprResult &RHS, ExprValueKind &VK,
5512                                         ExprObjectKind &OK,
5513                                         SourceLocation QuestionLoc) {
5514 
5515   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
5516   if (!LHSResult.isUsable()) return QualType();
5517   LHS = LHSResult;
5518 
5519   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
5520   if (!RHSResult.isUsable()) return QualType();
5521   RHS = RHSResult;
5522 
5523   // C++ is sufficiently different to merit its own checker.
5524   if (getLangOpts().CPlusPlus)
5525     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
5526 
5527   VK = VK_RValue;
5528   OK = OK_Ordinary;
5529 
5530   // First, check the condition.
5531   Cond = UsualUnaryConversions(Cond.take());
5532   if (Cond.isInvalid())
5533     return QualType();
5534   if (checkCondition(*this, Cond.get()))
5535     return QualType();
5536 
5537   // Now check the two expressions.
5538   if (LHS.get()->getType()->isVectorType() ||
5539       RHS.get()->getType()->isVectorType())
5540     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
5541 
5542   UsualArithmeticConversions(LHS, RHS);
5543   if (LHS.isInvalid() || RHS.isInvalid())
5544     return QualType();
5545 
5546   QualType CondTy = Cond.get()->getType();
5547   QualType LHSTy = LHS.get()->getType();
5548   QualType RHSTy = RHS.get()->getType();
5549 
5550   // If the condition is a vector, and both operands are scalar,
5551   // attempt to implicity convert them to the vector type to act like the
5552   // built in select. (OpenCL v1.1 s6.3.i)
5553   if (getLangOpts().OpenCL && CondTy->isVectorType())
5554     if (checkConditionalConvertScalarsToVectors(*this, LHS, RHS, CondTy))
5555       return QualType();
5556 
5557   // If both operands have arithmetic type, do the usual arithmetic conversions
5558   // to find a common type: C99 6.5.15p3,5.
5559   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType())
5560     return LHS.get()->getType();
5561 
5562   // If both operands are the same structure or union type, the result is that
5563   // type.
5564   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
5565     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
5566       if (LHSRT->getDecl() == RHSRT->getDecl())
5567         // "If both the operands have structure or union type, the result has
5568         // that type."  This implies that CV qualifiers are dropped.
5569         return LHSTy.getUnqualifiedType();
5570     // FIXME: Type of conditional expression must be complete in C mode.
5571   }
5572 
5573   // C99 6.5.15p5: "If both operands have void type, the result has void type."
5574   // The following || allows only one side to be void (a GCC-ism).
5575   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
5576     return checkConditionalVoidType(*this, LHS, RHS);
5577   }
5578 
5579   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
5580   // the type of the other operand."
5581   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
5582   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
5583 
5584   // All objective-c pointer type analysis is done here.
5585   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
5586                                                         QuestionLoc);
5587   if (LHS.isInvalid() || RHS.isInvalid())
5588     return QualType();
5589   if (!compositeType.isNull())
5590     return compositeType;
5591 
5592 
5593   // Handle block pointer types.
5594   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
5595     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
5596                                                      QuestionLoc);
5597 
5598   // Check constraints for C object pointers types (C99 6.5.15p3,6).
5599   if (LHSTy->isPointerType() && RHSTy->isPointerType())
5600     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
5601                                                        QuestionLoc);
5602 
5603   // GCC compatibility: soften pointer/integer mismatch.  Note that
5604   // null pointers have been filtered out by this point.
5605   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
5606       /*isIntFirstExpr=*/true))
5607     return RHSTy;
5608   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
5609       /*isIntFirstExpr=*/false))
5610     return LHSTy;
5611 
5612   // Emit a better diagnostic if one of the expressions is a null pointer
5613   // constant and the other is not a pointer type. In this case, the user most
5614   // likely forgot to take the address of the other expression.
5615   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
5616     return QualType();
5617 
5618   // Otherwise, the operands are not compatible.
5619   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
5620     << LHSTy << RHSTy << LHS.get()->getSourceRange()
5621     << RHS.get()->getSourceRange();
5622   return QualType();
5623 }
5624 
5625 /// FindCompositeObjCPointerType - Helper method to find composite type of
5626 /// two objective-c pointer types of the two input expressions.
5627 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
5628                                             SourceLocation QuestionLoc) {
5629   QualType LHSTy = LHS.get()->getType();
5630   QualType RHSTy = RHS.get()->getType();
5631 
5632   // Handle things like Class and struct objc_class*.  Here we case the result
5633   // to the pseudo-builtin, because that will be implicitly cast back to the
5634   // redefinition type if an attempt is made to access its fields.
5635   if (LHSTy->isObjCClassType() &&
5636       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
5637     RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
5638     return LHSTy;
5639   }
5640   if (RHSTy->isObjCClassType() &&
5641       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
5642     LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
5643     return RHSTy;
5644   }
5645   // And the same for struct objc_object* / id
5646   if (LHSTy->isObjCIdType() &&
5647       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
5648     RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
5649     return LHSTy;
5650   }
5651   if (RHSTy->isObjCIdType() &&
5652       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
5653     LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
5654     return RHSTy;
5655   }
5656   // And the same for struct objc_selector* / SEL
5657   if (Context.isObjCSelType(LHSTy) &&
5658       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
5659     RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
5660     return LHSTy;
5661   }
5662   if (Context.isObjCSelType(RHSTy) &&
5663       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
5664     LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
5665     return RHSTy;
5666   }
5667   // Check constraints for Objective-C object pointers types.
5668   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
5669 
5670     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5671       // Two identical object pointer types are always compatible.
5672       return LHSTy;
5673     }
5674     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
5675     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
5676     QualType compositeType = LHSTy;
5677 
5678     // If both operands are interfaces and either operand can be
5679     // assigned to the other, use that type as the composite
5680     // type. This allows
5681     //   xxx ? (A*) a : (B*) b
5682     // where B is a subclass of A.
5683     //
5684     // Additionally, as for assignment, if either type is 'id'
5685     // allow silent coercion. Finally, if the types are
5686     // incompatible then make sure to use 'id' as the composite
5687     // type so the result is acceptable for sending messages to.
5688 
5689     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
5690     // It could return the composite type.
5691     if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
5692       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
5693     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
5694       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
5695     } else if ((LHSTy->isObjCQualifiedIdType() ||
5696                 RHSTy->isObjCQualifiedIdType()) &&
5697                Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
5698       // Need to handle "id<xx>" explicitly.
5699       // GCC allows qualified id and any Objective-C type to devolve to
5700       // id. Currently localizing to here until clear this should be
5701       // part of ObjCQualifiedIdTypesAreCompatible.
5702       compositeType = Context.getObjCIdType();
5703     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
5704       compositeType = Context.getObjCIdType();
5705     } else if (!(compositeType =
5706                  Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
5707       ;
5708     else {
5709       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
5710       << LHSTy << RHSTy
5711       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5712       QualType incompatTy = Context.getObjCIdType();
5713       LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
5714       RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
5715       return incompatTy;
5716     }
5717     // The object pointer types are compatible.
5718     LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast);
5719     RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast);
5720     return compositeType;
5721   }
5722   // Check Objective-C object pointer types and 'void *'
5723   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
5724     if (getLangOpts().ObjCAutoRefCount) {
5725       // ARC forbids the implicit conversion of object pointers to 'void *',
5726       // so these types are not compatible.
5727       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
5728           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5729       LHS = RHS = true;
5730       return QualType();
5731     }
5732     QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5733     QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5734     QualType destPointee
5735     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
5736     QualType destType = Context.getPointerType(destPointee);
5737     // Add qualifiers if necessary.
5738     LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
5739     // Promote to void*.
5740     RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
5741     return destType;
5742   }
5743   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
5744     if (getLangOpts().ObjCAutoRefCount) {
5745       // ARC forbids the implicit conversion of object pointers to 'void *',
5746       // so these types are not compatible.
5747       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
5748           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5749       LHS = RHS = true;
5750       return QualType();
5751     }
5752     QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5753     QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
5754     QualType destPointee
5755     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
5756     QualType destType = Context.getPointerType(destPointee);
5757     // Add qualifiers if necessary.
5758     RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
5759     // Promote to void*.
5760     LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
5761     return destType;
5762   }
5763   return QualType();
5764 }
5765 
5766 /// SuggestParentheses - Emit a note with a fixit hint that wraps
5767 /// ParenRange in parentheses.
5768 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
5769                                const PartialDiagnostic &Note,
5770                                SourceRange ParenRange) {
5771   SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
5772   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
5773       EndLoc.isValid()) {
5774     Self.Diag(Loc, Note)
5775       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
5776       << FixItHint::CreateInsertion(EndLoc, ")");
5777   } else {
5778     // We can't display the parentheses, so just show the bare note.
5779     Self.Diag(Loc, Note) << ParenRange;
5780   }
5781 }
5782 
5783 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
5784   return Opc >= BO_Mul && Opc <= BO_Shr;
5785 }
5786 
5787 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
5788 /// expression, either using a built-in or overloaded operator,
5789 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
5790 /// expression.
5791 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
5792                                    Expr **RHSExprs) {
5793   // Don't strip parenthesis: we should not warn if E is in parenthesis.
5794   E = E->IgnoreImpCasts();
5795   E = E->IgnoreConversionOperator();
5796   E = E->IgnoreImpCasts();
5797 
5798   // Built-in binary operator.
5799   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
5800     if (IsArithmeticOp(OP->getOpcode())) {
5801       *Opcode = OP->getOpcode();
5802       *RHSExprs = OP->getRHS();
5803       return true;
5804     }
5805   }
5806 
5807   // Overloaded operator.
5808   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
5809     if (Call->getNumArgs() != 2)
5810       return false;
5811 
5812     // Make sure this is really a binary operator that is safe to pass into
5813     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
5814     OverloadedOperatorKind OO = Call->getOperator();
5815     if (OO < OO_Plus || OO > OO_Arrow ||
5816         OO == OO_PlusPlus || OO == OO_MinusMinus)
5817       return false;
5818 
5819     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
5820     if (IsArithmeticOp(OpKind)) {
5821       *Opcode = OpKind;
5822       *RHSExprs = Call->getArg(1);
5823       return true;
5824     }
5825   }
5826 
5827   return false;
5828 }
5829 
5830 static bool IsLogicOp(BinaryOperatorKind Opc) {
5831   return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
5832 }
5833 
5834 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
5835 /// or is a logical expression such as (x==y) which has int type, but is
5836 /// commonly interpreted as boolean.
5837 static bool ExprLooksBoolean(Expr *E) {
5838   E = E->IgnoreParenImpCasts();
5839 
5840   if (E->getType()->isBooleanType())
5841     return true;
5842   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
5843     return IsLogicOp(OP->getOpcode());
5844   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
5845     return OP->getOpcode() == UO_LNot;
5846 
5847   return false;
5848 }
5849 
5850 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
5851 /// and binary operator are mixed in a way that suggests the programmer assumed
5852 /// the conditional operator has higher precedence, for example:
5853 /// "int x = a + someBinaryCondition ? 1 : 2".
5854 static void DiagnoseConditionalPrecedence(Sema &Self,
5855                                           SourceLocation OpLoc,
5856                                           Expr *Condition,
5857                                           Expr *LHSExpr,
5858                                           Expr *RHSExpr) {
5859   BinaryOperatorKind CondOpcode;
5860   Expr *CondRHS;
5861 
5862   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
5863     return;
5864   if (!ExprLooksBoolean(CondRHS))
5865     return;
5866 
5867   // The condition is an arithmetic binary expression, with a right-
5868   // hand side that looks boolean, so warn.
5869 
5870   Self.Diag(OpLoc, diag::warn_precedence_conditional)
5871       << Condition->getSourceRange()
5872       << BinaryOperator::getOpcodeStr(CondOpcode);
5873 
5874   SuggestParentheses(Self, OpLoc,
5875     Self.PDiag(diag::note_precedence_silence)
5876       << BinaryOperator::getOpcodeStr(CondOpcode),
5877     SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
5878 
5879   SuggestParentheses(Self, OpLoc,
5880     Self.PDiag(diag::note_precedence_conditional_first),
5881     SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
5882 }
5883 
5884 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
5885 /// in the case of a the GNU conditional expr extension.
5886 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
5887                                     SourceLocation ColonLoc,
5888                                     Expr *CondExpr, Expr *LHSExpr,
5889                                     Expr *RHSExpr) {
5890   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
5891   // was the condition.
5892   OpaqueValueExpr *opaqueValue = 0;
5893   Expr *commonExpr = 0;
5894   if (LHSExpr == 0) {
5895     commonExpr = CondExpr;
5896     // Lower out placeholder types first.  This is important so that we don't
5897     // try to capture a placeholder. This happens in few cases in C++; such
5898     // as Objective-C++'s dictionary subscripting syntax.
5899     if (commonExpr->hasPlaceholderType()) {
5900       ExprResult result = CheckPlaceholderExpr(commonExpr);
5901       if (!result.isUsable()) return ExprError();
5902       commonExpr = result.take();
5903     }
5904     // We usually want to apply unary conversions *before* saving, except
5905     // in the special case of a C++ l-value conditional.
5906     if (!(getLangOpts().CPlusPlus
5907           && !commonExpr->isTypeDependent()
5908           && commonExpr->getValueKind() == RHSExpr->getValueKind()
5909           && commonExpr->isGLValue()
5910           && commonExpr->isOrdinaryOrBitFieldObject()
5911           && RHSExpr->isOrdinaryOrBitFieldObject()
5912           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
5913       ExprResult commonRes = UsualUnaryConversions(commonExpr);
5914       if (commonRes.isInvalid())
5915         return ExprError();
5916       commonExpr = commonRes.take();
5917     }
5918 
5919     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
5920                                                 commonExpr->getType(),
5921                                                 commonExpr->getValueKind(),
5922                                                 commonExpr->getObjectKind(),
5923                                                 commonExpr);
5924     LHSExpr = CondExpr = opaqueValue;
5925   }
5926 
5927   ExprValueKind VK = VK_RValue;
5928   ExprObjectKind OK = OK_Ordinary;
5929   ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
5930   QualType result = CheckConditionalOperands(Cond, LHS, RHS,
5931                                              VK, OK, QuestionLoc);
5932   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
5933       RHS.isInvalid())
5934     return ExprError();
5935 
5936   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
5937                                 RHS.get());
5938 
5939   if (!commonExpr)
5940     return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc,
5941                                                    LHS.take(), ColonLoc,
5942                                                    RHS.take(), result, VK, OK));
5943 
5944   return Owned(new (Context)
5945     BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(),
5946                               RHS.take(), QuestionLoc, ColonLoc, result, VK,
5947                               OK));
5948 }
5949 
5950 // checkPointerTypesForAssignment - This is a very tricky routine (despite
5951 // being closely modeled after the C99 spec:-). The odd characteristic of this
5952 // routine is it effectively iqnores the qualifiers on the top level pointee.
5953 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
5954 // FIXME: add a couple examples in this comment.
5955 static Sema::AssignConvertType
5956 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
5957   assert(LHSType.isCanonical() && "LHS not canonicalized!");
5958   assert(RHSType.isCanonical() && "RHS not canonicalized!");
5959 
5960   // get the "pointed to" type (ignoring qualifiers at the top level)
5961   const Type *lhptee, *rhptee;
5962   Qualifiers lhq, rhq;
5963   llvm::tie(lhptee, lhq) = cast<PointerType>(LHSType)->getPointeeType().split();
5964   llvm::tie(rhptee, rhq) = cast<PointerType>(RHSType)->getPointeeType().split();
5965 
5966   Sema::AssignConvertType ConvTy = Sema::Compatible;
5967 
5968   // C99 6.5.16.1p1: This following citation is common to constraints
5969   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
5970   // qualifiers of the type *pointed to* by the right;
5971   Qualifiers lq;
5972 
5973   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
5974   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
5975       lhq.compatiblyIncludesObjCLifetime(rhq)) {
5976     // Ignore lifetime for further calculation.
5977     lhq.removeObjCLifetime();
5978     rhq.removeObjCLifetime();
5979   }
5980 
5981   if (!lhq.compatiblyIncludes(rhq)) {
5982     // Treat address-space mismatches as fatal.  TODO: address subspaces
5983     if (lhq.getAddressSpace() != rhq.getAddressSpace())
5984       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5985 
5986     // It's okay to add or remove GC or lifetime qualifiers when converting to
5987     // and from void*.
5988     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
5989                         .compatiblyIncludes(
5990                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
5991              && (lhptee->isVoidType() || rhptee->isVoidType()))
5992       ; // keep old
5993 
5994     // Treat lifetime mismatches as fatal.
5995     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
5996       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5997 
5998     // For GCC compatibility, other qualifier mismatches are treated
5999     // as still compatible in C.
6000     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
6001   }
6002 
6003   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
6004   // incomplete type and the other is a pointer to a qualified or unqualified
6005   // version of void...
6006   if (lhptee->isVoidType()) {
6007     if (rhptee->isIncompleteOrObjectType())
6008       return ConvTy;
6009 
6010     // As an extension, we allow cast to/from void* to function pointer.
6011     assert(rhptee->isFunctionType());
6012     return Sema::FunctionVoidPointer;
6013   }
6014 
6015   if (rhptee->isVoidType()) {
6016     if (lhptee->isIncompleteOrObjectType())
6017       return ConvTy;
6018 
6019     // As an extension, we allow cast to/from void* to function pointer.
6020     assert(lhptee->isFunctionType());
6021     return Sema::FunctionVoidPointer;
6022   }
6023 
6024   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
6025   // unqualified versions of compatible types, ...
6026   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
6027   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
6028     // Check if the pointee types are compatible ignoring the sign.
6029     // We explicitly check for char so that we catch "char" vs
6030     // "unsigned char" on systems where "char" is unsigned.
6031     if (lhptee->isCharType())
6032       ltrans = S.Context.UnsignedCharTy;
6033     else if (lhptee->hasSignedIntegerRepresentation())
6034       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
6035 
6036     if (rhptee->isCharType())
6037       rtrans = S.Context.UnsignedCharTy;
6038     else if (rhptee->hasSignedIntegerRepresentation())
6039       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
6040 
6041     if (ltrans == rtrans) {
6042       // Types are compatible ignoring the sign. Qualifier incompatibility
6043       // takes priority over sign incompatibility because the sign
6044       // warning can be disabled.
6045       if (ConvTy != Sema::Compatible)
6046         return ConvTy;
6047 
6048       return Sema::IncompatiblePointerSign;
6049     }
6050 
6051     // If we are a multi-level pointer, it's possible that our issue is simply
6052     // one of qualification - e.g. char ** -> const char ** is not allowed. If
6053     // the eventual target type is the same and the pointers have the same
6054     // level of indirection, this must be the issue.
6055     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
6056       do {
6057         lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
6058         rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
6059       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
6060 
6061       if (lhptee == rhptee)
6062         return Sema::IncompatibleNestedPointerQualifiers;
6063     }
6064 
6065     // General pointer incompatibility takes priority over qualifiers.
6066     return Sema::IncompatiblePointer;
6067   }
6068   if (!S.getLangOpts().CPlusPlus &&
6069       S.IsNoReturnConversion(ltrans, rtrans, ltrans))
6070     return Sema::IncompatiblePointer;
6071   return ConvTy;
6072 }
6073 
6074 /// checkBlockPointerTypesForAssignment - This routine determines whether two
6075 /// block pointer types are compatible or whether a block and normal pointer
6076 /// are compatible. It is more restrict than comparing two function pointer
6077 // types.
6078 static Sema::AssignConvertType
6079 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
6080                                     QualType RHSType) {
6081   assert(LHSType.isCanonical() && "LHS not canonicalized!");
6082   assert(RHSType.isCanonical() && "RHS not canonicalized!");
6083 
6084   QualType lhptee, rhptee;
6085 
6086   // get the "pointed to" type (ignoring qualifiers at the top level)
6087   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
6088   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
6089 
6090   // In C++, the types have to match exactly.
6091   if (S.getLangOpts().CPlusPlus)
6092     return Sema::IncompatibleBlockPointer;
6093 
6094   Sema::AssignConvertType ConvTy = Sema::Compatible;
6095 
6096   // For blocks we enforce that qualifiers are identical.
6097   if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
6098     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
6099 
6100   if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
6101     return Sema::IncompatibleBlockPointer;
6102 
6103   return ConvTy;
6104 }
6105 
6106 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
6107 /// for assignment compatibility.
6108 static Sema::AssignConvertType
6109 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
6110                                    QualType RHSType) {
6111   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
6112   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
6113 
6114   if (LHSType->isObjCBuiltinType()) {
6115     // Class is not compatible with ObjC object pointers.
6116     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
6117         !RHSType->isObjCQualifiedClassType())
6118       return Sema::IncompatiblePointer;
6119     return Sema::Compatible;
6120   }
6121   if (RHSType->isObjCBuiltinType()) {
6122     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
6123         !LHSType->isObjCQualifiedClassType())
6124       return Sema::IncompatiblePointer;
6125     return Sema::Compatible;
6126   }
6127   QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
6128   QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
6129 
6130   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
6131       // make an exception for id<P>
6132       !LHSType->isObjCQualifiedIdType())
6133     return Sema::CompatiblePointerDiscardsQualifiers;
6134 
6135   if (S.Context.typesAreCompatible(LHSType, RHSType))
6136     return Sema::Compatible;
6137   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
6138     return Sema::IncompatibleObjCQualifiedId;
6139   return Sema::IncompatiblePointer;
6140 }
6141 
6142 Sema::AssignConvertType
6143 Sema::CheckAssignmentConstraints(SourceLocation Loc,
6144                                  QualType LHSType, QualType RHSType) {
6145   // Fake up an opaque expression.  We don't actually care about what
6146   // cast operations are required, so if CheckAssignmentConstraints
6147   // adds casts to this they'll be wasted, but fortunately that doesn't
6148   // usually happen on valid code.
6149   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
6150   ExprResult RHSPtr = &RHSExpr;
6151   CastKind K = CK_Invalid;
6152 
6153   return CheckAssignmentConstraints(LHSType, RHSPtr, K);
6154 }
6155 
6156 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
6157 /// has code to accommodate several GCC extensions when type checking
6158 /// pointers. Here are some objectionable examples that GCC considers warnings:
6159 ///
6160 ///  int a, *pint;
6161 ///  short *pshort;
6162 ///  struct foo *pfoo;
6163 ///
6164 ///  pint = pshort; // warning: assignment from incompatible pointer type
6165 ///  a = pint; // warning: assignment makes integer from pointer without a cast
6166 ///  pint = a; // warning: assignment makes pointer from integer without a cast
6167 ///  pint = pfoo; // warning: assignment from incompatible pointer type
6168 ///
6169 /// As a result, the code for dealing with pointers is more complex than the
6170 /// C99 spec dictates.
6171 ///
6172 /// Sets 'Kind' for any result kind except Incompatible.
6173 Sema::AssignConvertType
6174 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
6175                                  CastKind &Kind) {
6176   QualType RHSType = RHS.get()->getType();
6177   QualType OrigLHSType = LHSType;
6178 
6179   // Get canonical types.  We're not formatting these types, just comparing
6180   // them.
6181   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
6182   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
6183 
6184   // Common case: no conversion required.
6185   if (LHSType == RHSType) {
6186     Kind = CK_NoOp;
6187     return Compatible;
6188   }
6189 
6190   // If we have an atomic type, try a non-atomic assignment, then just add an
6191   // atomic qualification step.
6192   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
6193     Sema::AssignConvertType result =
6194       CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
6195     if (result != Compatible)
6196       return result;
6197     if (Kind != CK_NoOp)
6198       RHS = ImpCastExprToType(RHS.take(), AtomicTy->getValueType(), Kind);
6199     Kind = CK_NonAtomicToAtomic;
6200     return Compatible;
6201   }
6202 
6203   // If the left-hand side is a reference type, then we are in a
6204   // (rare!) case where we've allowed the use of references in C,
6205   // e.g., as a parameter type in a built-in function. In this case,
6206   // just make sure that the type referenced is compatible with the
6207   // right-hand side type. The caller is responsible for adjusting
6208   // LHSType so that the resulting expression does not have reference
6209   // type.
6210   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
6211     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
6212       Kind = CK_LValueBitCast;
6213       return Compatible;
6214     }
6215     return Incompatible;
6216   }
6217 
6218   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
6219   // to the same ExtVector type.
6220   if (LHSType->isExtVectorType()) {
6221     if (RHSType->isExtVectorType())
6222       return Incompatible;
6223     if (RHSType->isArithmeticType()) {
6224       // CK_VectorSplat does T -> vector T, so first cast to the
6225       // element type.
6226       QualType elType = cast<ExtVectorType>(LHSType)->getElementType();
6227       if (elType != RHSType) {
6228         Kind = PrepareScalarCast(RHS, elType);
6229         RHS = ImpCastExprToType(RHS.take(), elType, Kind);
6230       }
6231       Kind = CK_VectorSplat;
6232       return Compatible;
6233     }
6234   }
6235 
6236   // Conversions to or from vector type.
6237   if (LHSType->isVectorType() || RHSType->isVectorType()) {
6238     if (LHSType->isVectorType() && RHSType->isVectorType()) {
6239       // Allow assignments of an AltiVec vector type to an equivalent GCC
6240       // vector type and vice versa
6241       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
6242         Kind = CK_BitCast;
6243         return Compatible;
6244       }
6245 
6246       // If we are allowing lax vector conversions, and LHS and RHS are both
6247       // vectors, the total size only needs to be the same. This is a bitcast;
6248       // no bits are changed but the result type is different.
6249       if (getLangOpts().LaxVectorConversions &&
6250           (Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType))) {
6251         Kind = CK_BitCast;
6252         return IncompatibleVectors;
6253       }
6254     }
6255     return Incompatible;
6256   }
6257 
6258   // Arithmetic conversions.
6259   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
6260       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
6261     Kind = PrepareScalarCast(RHS, LHSType);
6262     return Compatible;
6263   }
6264 
6265   // Conversions to normal pointers.
6266   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
6267     // U* -> T*
6268     if (isa<PointerType>(RHSType)) {
6269       Kind = CK_BitCast;
6270       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
6271     }
6272 
6273     // int -> T*
6274     if (RHSType->isIntegerType()) {
6275       Kind = CK_IntegralToPointer; // FIXME: null?
6276       return IntToPointer;
6277     }
6278 
6279     // C pointers are not compatible with ObjC object pointers,
6280     // with two exceptions:
6281     if (isa<ObjCObjectPointerType>(RHSType)) {
6282       //  - conversions to void*
6283       if (LHSPointer->getPointeeType()->isVoidType()) {
6284         Kind = CK_BitCast;
6285         return Compatible;
6286       }
6287 
6288       //  - conversions from 'Class' to the redefinition type
6289       if (RHSType->isObjCClassType() &&
6290           Context.hasSameType(LHSType,
6291                               Context.getObjCClassRedefinitionType())) {
6292         Kind = CK_BitCast;
6293         return Compatible;
6294       }
6295 
6296       Kind = CK_BitCast;
6297       return IncompatiblePointer;
6298     }
6299 
6300     // U^ -> void*
6301     if (RHSType->getAs<BlockPointerType>()) {
6302       if (LHSPointer->getPointeeType()->isVoidType()) {
6303         Kind = CK_BitCast;
6304         return Compatible;
6305       }
6306     }
6307 
6308     return Incompatible;
6309   }
6310 
6311   // Conversions to block pointers.
6312   if (isa<BlockPointerType>(LHSType)) {
6313     // U^ -> T^
6314     if (RHSType->isBlockPointerType()) {
6315       Kind = CK_BitCast;
6316       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
6317     }
6318 
6319     // int or null -> T^
6320     if (RHSType->isIntegerType()) {
6321       Kind = CK_IntegralToPointer; // FIXME: null
6322       return IntToBlockPointer;
6323     }
6324 
6325     // id -> T^
6326     if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
6327       Kind = CK_AnyPointerToBlockPointerCast;
6328       return Compatible;
6329     }
6330 
6331     // void* -> T^
6332     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
6333       if (RHSPT->getPointeeType()->isVoidType()) {
6334         Kind = CK_AnyPointerToBlockPointerCast;
6335         return Compatible;
6336       }
6337 
6338     return Incompatible;
6339   }
6340 
6341   // Conversions to Objective-C pointers.
6342   if (isa<ObjCObjectPointerType>(LHSType)) {
6343     // A* -> B*
6344     if (RHSType->isObjCObjectPointerType()) {
6345       Kind = CK_BitCast;
6346       Sema::AssignConvertType result =
6347         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
6348       if (getLangOpts().ObjCAutoRefCount &&
6349           result == Compatible &&
6350           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
6351         result = IncompatibleObjCWeakRef;
6352       return result;
6353     }
6354 
6355     // int or null -> A*
6356     if (RHSType->isIntegerType()) {
6357       Kind = CK_IntegralToPointer; // FIXME: null
6358       return IntToPointer;
6359     }
6360 
6361     // In general, C pointers are not compatible with ObjC object pointers,
6362     // with two exceptions:
6363     if (isa<PointerType>(RHSType)) {
6364       Kind = CK_CPointerToObjCPointerCast;
6365 
6366       //  - conversions from 'void*'
6367       if (RHSType->isVoidPointerType()) {
6368         return Compatible;
6369       }
6370 
6371       //  - conversions to 'Class' from its redefinition type
6372       if (LHSType->isObjCClassType() &&
6373           Context.hasSameType(RHSType,
6374                               Context.getObjCClassRedefinitionType())) {
6375         return Compatible;
6376       }
6377 
6378       return IncompatiblePointer;
6379     }
6380 
6381     // T^ -> A*
6382     if (RHSType->isBlockPointerType()) {
6383       maybeExtendBlockObject(*this, RHS);
6384       Kind = CK_BlockPointerToObjCPointerCast;
6385       return Compatible;
6386     }
6387 
6388     return Incompatible;
6389   }
6390 
6391   // Conversions from pointers that are not covered by the above.
6392   if (isa<PointerType>(RHSType)) {
6393     // T* -> _Bool
6394     if (LHSType == Context.BoolTy) {
6395       Kind = CK_PointerToBoolean;
6396       return Compatible;
6397     }
6398 
6399     // T* -> int
6400     if (LHSType->isIntegerType()) {
6401       Kind = CK_PointerToIntegral;
6402       return PointerToInt;
6403     }
6404 
6405     return Incompatible;
6406   }
6407 
6408   // Conversions from Objective-C pointers that are not covered by the above.
6409   if (isa<ObjCObjectPointerType>(RHSType)) {
6410     // T* -> _Bool
6411     if (LHSType == Context.BoolTy) {
6412       Kind = CK_PointerToBoolean;
6413       return Compatible;
6414     }
6415 
6416     // T* -> int
6417     if (LHSType->isIntegerType()) {
6418       Kind = CK_PointerToIntegral;
6419       return PointerToInt;
6420     }
6421 
6422     return Incompatible;
6423   }
6424 
6425   // struct A -> struct B
6426   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
6427     if (Context.typesAreCompatible(LHSType, RHSType)) {
6428       Kind = CK_NoOp;
6429       return Compatible;
6430     }
6431   }
6432 
6433   return Incompatible;
6434 }
6435 
6436 /// \brief Constructs a transparent union from an expression that is
6437 /// used to initialize the transparent union.
6438 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
6439                                       ExprResult &EResult, QualType UnionType,
6440                                       FieldDecl *Field) {
6441   // Build an initializer list that designates the appropriate member
6442   // of the transparent union.
6443   Expr *E = EResult.take();
6444   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
6445                                                    E, SourceLocation());
6446   Initializer->setType(UnionType);
6447   Initializer->setInitializedFieldInUnion(Field);
6448 
6449   // Build a compound literal constructing a value of the transparent
6450   // union type from this initializer list.
6451   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
6452   EResult = S.Owned(
6453     new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
6454                                 VK_RValue, Initializer, false));
6455 }
6456 
6457 Sema::AssignConvertType
6458 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
6459                                                ExprResult &RHS) {
6460   QualType RHSType = RHS.get()->getType();
6461 
6462   // If the ArgType is a Union type, we want to handle a potential
6463   // transparent_union GCC extension.
6464   const RecordType *UT = ArgType->getAsUnionType();
6465   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
6466     return Incompatible;
6467 
6468   // The field to initialize within the transparent union.
6469   RecordDecl *UD = UT->getDecl();
6470   FieldDecl *InitField = 0;
6471   // It's compatible if the expression matches any of the fields.
6472   for (RecordDecl::field_iterator it = UD->field_begin(),
6473          itend = UD->field_end();
6474        it != itend; ++it) {
6475     if (it->getType()->isPointerType()) {
6476       // If the transparent union contains a pointer type, we allow:
6477       // 1) void pointer
6478       // 2) null pointer constant
6479       if (RHSType->isPointerType())
6480         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
6481           RHS = ImpCastExprToType(RHS.take(), it->getType(), CK_BitCast);
6482           InitField = *it;
6483           break;
6484         }
6485 
6486       if (RHS.get()->isNullPointerConstant(Context,
6487                                            Expr::NPC_ValueDependentIsNull)) {
6488         RHS = ImpCastExprToType(RHS.take(), it->getType(),
6489                                 CK_NullToPointer);
6490         InitField = *it;
6491         break;
6492       }
6493     }
6494 
6495     CastKind Kind = CK_Invalid;
6496     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
6497           == Compatible) {
6498       RHS = ImpCastExprToType(RHS.take(), it->getType(), Kind);
6499       InitField = *it;
6500       break;
6501     }
6502   }
6503 
6504   if (!InitField)
6505     return Incompatible;
6506 
6507   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
6508   return Compatible;
6509 }
6510 
6511 Sema::AssignConvertType
6512 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS,
6513                                        bool Diagnose,
6514                                        bool DiagnoseCFAudited) {
6515   if (getLangOpts().CPlusPlus) {
6516     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
6517       // C++ 5.17p3: If the left operand is not of class type, the
6518       // expression is implicitly converted (C++ 4) to the
6519       // cv-unqualified type of the left operand.
6520       ExprResult Res;
6521       if (Diagnose) {
6522         Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
6523                                         AA_Assigning);
6524       } else {
6525         ImplicitConversionSequence ICS =
6526             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
6527                                   /*SuppressUserConversions=*/false,
6528                                   /*AllowExplicit=*/false,
6529                                   /*InOverloadResolution=*/false,
6530                                   /*CStyle=*/false,
6531                                   /*AllowObjCWritebackConversion=*/false);
6532         if (ICS.isFailure())
6533           return Incompatible;
6534         Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
6535                                         ICS, AA_Assigning);
6536       }
6537       if (Res.isInvalid())
6538         return Incompatible;
6539       Sema::AssignConvertType result = Compatible;
6540       if (getLangOpts().ObjCAutoRefCount &&
6541           !CheckObjCARCUnavailableWeakConversion(LHSType,
6542                                                  RHS.get()->getType()))
6543         result = IncompatibleObjCWeakRef;
6544       RHS = Res;
6545       return result;
6546     }
6547 
6548     // FIXME: Currently, we fall through and treat C++ classes like C
6549     // structures.
6550     // FIXME: We also fall through for atomics; not sure what should
6551     // happen there, though.
6552   }
6553 
6554   // C99 6.5.16.1p1: the left operand is a pointer and the right is
6555   // a null pointer constant.
6556   if ((LHSType->isPointerType() ||
6557        LHSType->isObjCObjectPointerType() ||
6558        LHSType->isBlockPointerType())
6559       && RHS.get()->isNullPointerConstant(Context,
6560                                           Expr::NPC_ValueDependentIsNull)) {
6561     RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
6562     return Compatible;
6563   }
6564 
6565   // This check seems unnatural, however it is necessary to ensure the proper
6566   // conversion of functions/arrays. If the conversion were done for all
6567   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
6568   // expressions that suppress this implicit conversion (&, sizeof).
6569   //
6570   // Suppress this for references: C++ 8.5.3p5.
6571   if (!LHSType->isReferenceType()) {
6572     RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
6573     if (RHS.isInvalid())
6574       return Incompatible;
6575   }
6576 
6577   CastKind Kind = CK_Invalid;
6578   Sema::AssignConvertType result =
6579     CheckAssignmentConstraints(LHSType, RHS, Kind);
6580 
6581   // C99 6.5.16.1p2: The value of the right operand is converted to the
6582   // type of the assignment expression.
6583   // CheckAssignmentConstraints allows the left-hand side to be a reference,
6584   // so that we can use references in built-in functions even in C.
6585   // The getNonReferenceType() call makes sure that the resulting expression
6586   // does not have reference type.
6587   if (result != Incompatible && RHS.get()->getType() != LHSType) {
6588     QualType Ty = LHSType.getNonLValueExprType(Context);
6589     Expr *E = RHS.take();
6590     if (getLangOpts().ObjCAutoRefCount)
6591       CheckObjCARCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
6592                              DiagnoseCFAudited);
6593     RHS = ImpCastExprToType(E, Ty, Kind);
6594   }
6595   return result;
6596 }
6597 
6598 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
6599                                ExprResult &RHS) {
6600   Diag(Loc, diag::err_typecheck_invalid_operands)
6601     << LHS.get()->getType() << RHS.get()->getType()
6602     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6603   return QualType();
6604 }
6605 
6606 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
6607                                    SourceLocation Loc, bool IsCompAssign) {
6608   if (!IsCompAssign) {
6609     LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
6610     if (LHS.isInvalid())
6611       return QualType();
6612   }
6613   RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
6614   if (RHS.isInvalid())
6615     return QualType();
6616 
6617   // For conversion purposes, we ignore any qualifiers.
6618   // For example, "const float" and "float" are equivalent.
6619   QualType LHSType =
6620     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
6621   QualType RHSType =
6622     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
6623 
6624   // If the vector types are identical, return.
6625   if (LHSType == RHSType)
6626     return LHSType;
6627 
6628   // Handle the case of equivalent AltiVec and GCC vector types
6629   if (LHSType->isVectorType() && RHSType->isVectorType() &&
6630       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
6631     if (LHSType->isExtVectorType()) {
6632       RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
6633       return LHSType;
6634     }
6635 
6636     if (!IsCompAssign)
6637       LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
6638     return RHSType;
6639   }
6640 
6641   if (getLangOpts().LaxVectorConversions &&
6642       Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType)) {
6643     // If we are allowing lax vector conversions, and LHS and RHS are both
6644     // vectors, the total size only needs to be the same. This is a
6645     // bitcast; no bits are changed but the result type is different.
6646     // FIXME: Should we really be allowing this?
6647     RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
6648     return LHSType;
6649   }
6650 
6651   // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
6652   // swap back (so that we don't reverse the inputs to a subtract, for instance.
6653   bool swapped = false;
6654   if (RHSType->isExtVectorType() && !IsCompAssign) {
6655     swapped = true;
6656     std::swap(RHS, LHS);
6657     std::swap(RHSType, LHSType);
6658   }
6659 
6660   // Handle the case of an ext vector and scalar.
6661   if (const ExtVectorType *LV = LHSType->getAs<ExtVectorType>()) {
6662     QualType EltTy = LV->getElementType();
6663     if (EltTy->isIntegralType(Context) && RHSType->isIntegralType(Context)) {
6664       int order = Context.getIntegerTypeOrder(EltTy, RHSType);
6665       if (order > 0)
6666         RHS = ImpCastExprToType(RHS.take(), EltTy, CK_IntegralCast);
6667       if (order >= 0) {
6668         RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
6669         if (swapped) std::swap(RHS, LHS);
6670         return LHSType;
6671       }
6672     }
6673     if (EltTy->isRealFloatingType() && RHSType->isScalarType()) {
6674       if (RHSType->isRealFloatingType()) {
6675         int order = Context.getFloatingTypeOrder(EltTy, RHSType);
6676         if (order > 0)
6677           RHS = ImpCastExprToType(RHS.take(), EltTy, CK_FloatingCast);
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 (RHSType->isIntegralType(Context)) {
6685         RHS = ImpCastExprToType(RHS.take(), EltTy, CK_IntegralToFloating);
6686         RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
6687         if (swapped) std::swap(RHS, LHS);
6688         return LHSType;
6689       }
6690     }
6691   }
6692 
6693   // Vectors of different size or scalar and non-ext-vector are errors.
6694   if (swapped) std::swap(RHS, LHS);
6695   Diag(Loc, diag::err_typecheck_vector_not_convertable)
6696     << LHS.get()->getType() << RHS.get()->getType()
6697     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6698   return QualType();
6699 }
6700 
6701 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
6702 // expression.  These are mainly cases where the null pointer is used as an
6703 // integer instead of a pointer.
6704 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
6705                                 SourceLocation Loc, bool IsCompare) {
6706   // The canonical way to check for a GNU null is with isNullPointerConstant,
6707   // but we use a bit of a hack here for speed; this is a relatively
6708   // hot path, and isNullPointerConstant is slow.
6709   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
6710   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
6711 
6712   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
6713 
6714   // Avoid analyzing cases where the result will either be invalid (and
6715   // diagnosed as such) or entirely valid and not something to warn about.
6716   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
6717       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
6718     return;
6719 
6720   // Comparison operations would not make sense with a null pointer no matter
6721   // what the other expression is.
6722   if (!IsCompare) {
6723     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
6724         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
6725         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
6726     return;
6727   }
6728 
6729   // The rest of the operations only make sense with a null pointer
6730   // if the other expression is a pointer.
6731   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
6732       NonNullType->canDecayToPointerType())
6733     return;
6734 
6735   S.Diag(Loc, diag::warn_null_in_comparison_operation)
6736       << LHSNull /* LHS is NULL */ << NonNullType
6737       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6738 }
6739 
6740 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
6741                                            SourceLocation Loc,
6742                                            bool IsCompAssign, bool IsDiv) {
6743   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6744 
6745   if (LHS.get()->getType()->isVectorType() ||
6746       RHS.get()->getType()->isVectorType())
6747     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
6748 
6749   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
6750   if (LHS.isInvalid() || RHS.isInvalid())
6751     return QualType();
6752 
6753 
6754   if (compType.isNull() || !compType->isArithmeticType())
6755     return InvalidOperands(Loc, LHS, RHS);
6756 
6757   // Check for division by zero.
6758   llvm::APSInt RHSValue;
6759   if (IsDiv && !RHS.get()->isValueDependent() &&
6760       RHS.get()->EvaluateAsInt(RHSValue, Context) && RHSValue == 0)
6761     DiagRuntimeBehavior(Loc, RHS.get(),
6762                         PDiag(diag::warn_division_by_zero)
6763                           << RHS.get()->getSourceRange());
6764 
6765   return compType;
6766 }
6767 
6768 QualType Sema::CheckRemainderOperands(
6769   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
6770   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6771 
6772   if (LHS.get()->getType()->isVectorType() ||
6773       RHS.get()->getType()->isVectorType()) {
6774     if (LHS.get()->getType()->hasIntegerRepresentation() &&
6775         RHS.get()->getType()->hasIntegerRepresentation())
6776       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
6777     return InvalidOperands(Loc, LHS, RHS);
6778   }
6779 
6780   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
6781   if (LHS.isInvalid() || RHS.isInvalid())
6782     return QualType();
6783 
6784   if (compType.isNull() || !compType->isIntegerType())
6785     return InvalidOperands(Loc, LHS, RHS);
6786 
6787   // Check for remainder by zero.
6788   llvm::APSInt RHSValue;
6789   if (!RHS.get()->isValueDependent() &&
6790       RHS.get()->EvaluateAsInt(RHSValue, Context) && RHSValue == 0)
6791     DiagRuntimeBehavior(Loc, RHS.get(),
6792                         PDiag(diag::warn_remainder_by_zero)
6793                           << RHS.get()->getSourceRange());
6794 
6795   return compType;
6796 }
6797 
6798 /// \brief Diagnose invalid arithmetic on two void pointers.
6799 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
6800                                                 Expr *LHSExpr, Expr *RHSExpr) {
6801   S.Diag(Loc, S.getLangOpts().CPlusPlus
6802                 ? diag::err_typecheck_pointer_arith_void_type
6803                 : diag::ext_gnu_void_ptr)
6804     << 1 /* two pointers */ << LHSExpr->getSourceRange()
6805                             << RHSExpr->getSourceRange();
6806 }
6807 
6808 /// \brief Diagnose invalid arithmetic on a void pointer.
6809 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
6810                                             Expr *Pointer) {
6811   S.Diag(Loc, S.getLangOpts().CPlusPlus
6812                 ? diag::err_typecheck_pointer_arith_void_type
6813                 : diag::ext_gnu_void_ptr)
6814     << 0 /* one pointer */ << Pointer->getSourceRange();
6815 }
6816 
6817 /// \brief Diagnose invalid arithmetic on two function pointers.
6818 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
6819                                                     Expr *LHS, Expr *RHS) {
6820   assert(LHS->getType()->isAnyPointerType());
6821   assert(RHS->getType()->isAnyPointerType());
6822   S.Diag(Loc, S.getLangOpts().CPlusPlus
6823                 ? diag::err_typecheck_pointer_arith_function_type
6824                 : diag::ext_gnu_ptr_func_arith)
6825     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
6826     // We only show the second type if it differs from the first.
6827     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
6828                                                    RHS->getType())
6829     << RHS->getType()->getPointeeType()
6830     << LHS->getSourceRange() << RHS->getSourceRange();
6831 }
6832 
6833 /// \brief Diagnose invalid arithmetic on a function pointer.
6834 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
6835                                                 Expr *Pointer) {
6836   assert(Pointer->getType()->isAnyPointerType());
6837   S.Diag(Loc, S.getLangOpts().CPlusPlus
6838                 ? diag::err_typecheck_pointer_arith_function_type
6839                 : diag::ext_gnu_ptr_func_arith)
6840     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
6841     << 0 /* one pointer, so only one type */
6842     << Pointer->getSourceRange();
6843 }
6844 
6845 /// \brief Emit error if Operand is incomplete pointer type
6846 ///
6847 /// \returns True if pointer has incomplete type
6848 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
6849                                                  Expr *Operand) {
6850   assert(Operand->getType()->isAnyPointerType() &&
6851          !Operand->getType()->isDependentType());
6852   QualType PointeeTy = Operand->getType()->getPointeeType();
6853   return S.RequireCompleteType(Loc, PointeeTy,
6854                                diag::err_typecheck_arithmetic_incomplete_type,
6855                                PointeeTy, Operand->getSourceRange());
6856 }
6857 
6858 /// \brief Check the validity of an arithmetic pointer operand.
6859 ///
6860 /// If the operand has pointer type, this code will check for pointer types
6861 /// which are invalid in arithmetic operations. These will be diagnosed
6862 /// appropriately, including whether or not the use is supported as an
6863 /// extension.
6864 ///
6865 /// \returns True when the operand is valid to use (even if as an extension).
6866 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
6867                                             Expr *Operand) {
6868   if (!Operand->getType()->isAnyPointerType()) return true;
6869 
6870   QualType PointeeTy = Operand->getType()->getPointeeType();
6871   if (PointeeTy->isVoidType()) {
6872     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
6873     return !S.getLangOpts().CPlusPlus;
6874   }
6875   if (PointeeTy->isFunctionType()) {
6876     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
6877     return !S.getLangOpts().CPlusPlus;
6878   }
6879 
6880   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
6881 
6882   return true;
6883 }
6884 
6885 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
6886 /// operands.
6887 ///
6888 /// This routine will diagnose any invalid arithmetic on pointer operands much
6889 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
6890 /// for emitting a single diagnostic even for operations where both LHS and RHS
6891 /// are (potentially problematic) pointers.
6892 ///
6893 /// \returns True when the operand is valid to use (even if as an extension).
6894 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
6895                                                 Expr *LHSExpr, Expr *RHSExpr) {
6896   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
6897   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
6898   if (!isLHSPointer && !isRHSPointer) return true;
6899 
6900   QualType LHSPointeeTy, RHSPointeeTy;
6901   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
6902   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
6903 
6904   // Check for arithmetic on pointers to incomplete types.
6905   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
6906   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
6907   if (isLHSVoidPtr || isRHSVoidPtr) {
6908     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
6909     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
6910     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
6911 
6912     return !S.getLangOpts().CPlusPlus;
6913   }
6914 
6915   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
6916   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
6917   if (isLHSFuncPtr || isRHSFuncPtr) {
6918     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
6919     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
6920                                                                 RHSExpr);
6921     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
6922 
6923     return !S.getLangOpts().CPlusPlus;
6924   }
6925 
6926   if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
6927     return false;
6928   if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
6929     return false;
6930 
6931   return true;
6932 }
6933 
6934 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
6935 /// literal.
6936 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
6937                                   Expr *LHSExpr, Expr *RHSExpr) {
6938   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
6939   Expr* IndexExpr = RHSExpr;
6940   if (!StrExpr) {
6941     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
6942     IndexExpr = LHSExpr;
6943   }
6944 
6945   bool IsStringPlusInt = StrExpr &&
6946       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
6947   if (!IsStringPlusInt)
6948     return;
6949 
6950   llvm::APSInt index;
6951   if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
6952     unsigned StrLenWithNull = StrExpr->getLength() + 1;
6953     if (index.isNonNegative() &&
6954         index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
6955                               index.isUnsigned()))
6956       return;
6957   }
6958 
6959   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
6960   Self.Diag(OpLoc, diag::warn_string_plus_int)
6961       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
6962 
6963   // Only print a fixit for "str" + int, not for int + "str".
6964   if (IndexExpr == RHSExpr) {
6965     SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd());
6966     Self.Diag(OpLoc, diag::note_string_plus_int_silence)
6967         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
6968         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
6969         << FixItHint::CreateInsertion(EndLoc, "]");
6970   } else
6971     Self.Diag(OpLoc, diag::note_string_plus_int_silence);
6972 }
6973 
6974 /// \brief Emit error when two pointers are incompatible.
6975 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
6976                                            Expr *LHSExpr, Expr *RHSExpr) {
6977   assert(LHSExpr->getType()->isAnyPointerType());
6978   assert(RHSExpr->getType()->isAnyPointerType());
6979   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
6980     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
6981     << RHSExpr->getSourceRange();
6982 }
6983 
6984 QualType Sema::CheckAdditionOperands( // C99 6.5.6
6985     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc,
6986     QualType* CompLHSTy) {
6987   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6988 
6989   if (LHS.get()->getType()->isVectorType() ||
6990       RHS.get()->getType()->isVectorType()) {
6991     QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
6992     if (CompLHSTy) *CompLHSTy = compType;
6993     return compType;
6994   }
6995 
6996   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6997   if (LHS.isInvalid() || RHS.isInvalid())
6998     return QualType();
6999 
7000   // Diagnose "string literal" '+' int.
7001   if (Opc == BO_Add)
7002     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
7003 
7004   // handle the common case first (both operands are arithmetic).
7005   if (!compType.isNull() && compType->isArithmeticType()) {
7006     if (CompLHSTy) *CompLHSTy = compType;
7007     return compType;
7008   }
7009 
7010   // Type-checking.  Ultimately the pointer's going to be in PExp;
7011   // note that we bias towards the LHS being the pointer.
7012   Expr *PExp = LHS.get(), *IExp = RHS.get();
7013 
7014   bool isObjCPointer;
7015   if (PExp->getType()->isPointerType()) {
7016     isObjCPointer = false;
7017   } else if (PExp->getType()->isObjCObjectPointerType()) {
7018     isObjCPointer = true;
7019   } else {
7020     std::swap(PExp, IExp);
7021     if (PExp->getType()->isPointerType()) {
7022       isObjCPointer = false;
7023     } else if (PExp->getType()->isObjCObjectPointerType()) {
7024       isObjCPointer = true;
7025     } else {
7026       return InvalidOperands(Loc, LHS, RHS);
7027     }
7028   }
7029   assert(PExp->getType()->isAnyPointerType());
7030 
7031   if (!IExp->getType()->isIntegerType())
7032     return InvalidOperands(Loc, LHS, RHS);
7033 
7034   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
7035     return QualType();
7036 
7037   if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
7038     return QualType();
7039 
7040   // Check array bounds for pointer arithemtic
7041   CheckArrayAccess(PExp, IExp);
7042 
7043   if (CompLHSTy) {
7044     QualType LHSTy = Context.isPromotableBitField(LHS.get());
7045     if (LHSTy.isNull()) {
7046       LHSTy = LHS.get()->getType();
7047       if (LHSTy->isPromotableIntegerType())
7048         LHSTy = Context.getPromotedIntegerType(LHSTy);
7049     }
7050     *CompLHSTy = LHSTy;
7051   }
7052 
7053   return PExp->getType();
7054 }
7055 
7056 // C99 6.5.6
7057 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
7058                                         SourceLocation Loc,
7059                                         QualType* CompLHSTy) {
7060   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7061 
7062   if (LHS.get()->getType()->isVectorType() ||
7063       RHS.get()->getType()->isVectorType()) {
7064     QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
7065     if (CompLHSTy) *CompLHSTy = compType;
7066     return compType;
7067   }
7068 
7069   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
7070   if (LHS.isInvalid() || RHS.isInvalid())
7071     return QualType();
7072 
7073   // Enforce type constraints: C99 6.5.6p3.
7074 
7075   // Handle the common case first (both operands are arithmetic).
7076   if (!compType.isNull() && compType->isArithmeticType()) {
7077     if (CompLHSTy) *CompLHSTy = compType;
7078     return compType;
7079   }
7080 
7081   // Either ptr - int   or   ptr - ptr.
7082   if (LHS.get()->getType()->isAnyPointerType()) {
7083     QualType lpointee = LHS.get()->getType()->getPointeeType();
7084 
7085     // Diagnose bad cases where we step over interface counts.
7086     if (LHS.get()->getType()->isObjCObjectPointerType() &&
7087         checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
7088       return QualType();
7089 
7090     // The result type of a pointer-int computation is the pointer type.
7091     if (RHS.get()->getType()->isIntegerType()) {
7092       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
7093         return QualType();
7094 
7095       // Check array bounds for pointer arithemtic
7096       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/0,
7097                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
7098 
7099       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
7100       return LHS.get()->getType();
7101     }
7102 
7103     // Handle pointer-pointer subtractions.
7104     if (const PointerType *RHSPTy
7105           = RHS.get()->getType()->getAs<PointerType>()) {
7106       QualType rpointee = RHSPTy->getPointeeType();
7107 
7108       if (getLangOpts().CPlusPlus) {
7109         // Pointee types must be the same: C++ [expr.add]
7110         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
7111           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
7112         }
7113       } else {
7114         // Pointee types must be compatible C99 6.5.6p3
7115         if (!Context.typesAreCompatible(
7116                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
7117                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
7118           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
7119           return QualType();
7120         }
7121       }
7122 
7123       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
7124                                                LHS.get(), RHS.get()))
7125         return QualType();
7126 
7127       // The pointee type may have zero size.  As an extension, a structure or
7128       // union may have zero size or an array may have zero length.  In this
7129       // case subtraction does not make sense.
7130       if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
7131         CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
7132         if (ElementSize.isZero()) {
7133           Diag(Loc,diag::warn_sub_ptr_zero_size_types)
7134             << rpointee.getUnqualifiedType()
7135             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7136         }
7137       }
7138 
7139       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
7140       return Context.getPointerDiffType();
7141     }
7142   }
7143 
7144   return InvalidOperands(Loc, LHS, RHS);
7145 }
7146 
7147 static bool isScopedEnumerationType(QualType T) {
7148   if (const EnumType *ET = dyn_cast<EnumType>(T))
7149     return ET->getDecl()->isScoped();
7150   return false;
7151 }
7152 
7153 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
7154                                    SourceLocation Loc, unsigned Opc,
7155                                    QualType LHSType) {
7156   // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
7157   // so skip remaining warnings as we don't want to modify values within Sema.
7158   if (S.getLangOpts().OpenCL)
7159     return;
7160 
7161   llvm::APSInt Right;
7162   // Check right/shifter operand
7163   if (RHS.get()->isValueDependent() ||
7164       !RHS.get()->isIntegerConstantExpr(Right, S.Context))
7165     return;
7166 
7167   if (Right.isNegative()) {
7168     S.DiagRuntimeBehavior(Loc, RHS.get(),
7169                           S.PDiag(diag::warn_shift_negative)
7170                             << RHS.get()->getSourceRange());
7171     return;
7172   }
7173   llvm::APInt LeftBits(Right.getBitWidth(),
7174                        S.Context.getTypeSize(LHS.get()->getType()));
7175   if (Right.uge(LeftBits)) {
7176     S.DiagRuntimeBehavior(Loc, RHS.get(),
7177                           S.PDiag(diag::warn_shift_gt_typewidth)
7178                             << RHS.get()->getSourceRange());
7179     return;
7180   }
7181   if (Opc != BO_Shl)
7182     return;
7183 
7184   // When left shifting an ICE which is signed, we can check for overflow which
7185   // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
7186   // integers have defined behavior modulo one more than the maximum value
7187   // representable in the result type, so never warn for those.
7188   llvm::APSInt Left;
7189   if (LHS.get()->isValueDependent() ||
7190       !LHS.get()->isIntegerConstantExpr(Left, S.Context) ||
7191       LHSType->hasUnsignedIntegerRepresentation())
7192     return;
7193   llvm::APInt ResultBits =
7194       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
7195   if (LeftBits.uge(ResultBits))
7196     return;
7197   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
7198   Result = Result.shl(Right);
7199 
7200   // Print the bit representation of the signed integer as an unsigned
7201   // hexadecimal number.
7202   SmallString<40> HexResult;
7203   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
7204 
7205   // If we are only missing a sign bit, this is less likely to result in actual
7206   // bugs -- if the result is cast back to an unsigned type, it will have the
7207   // expected value. Thus we place this behind a different warning that can be
7208   // turned off separately if needed.
7209   if (LeftBits == ResultBits - 1) {
7210     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
7211         << HexResult.str() << LHSType
7212         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7213     return;
7214   }
7215 
7216   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
7217     << HexResult.str() << Result.getMinSignedBits() << LHSType
7218     << Left.getBitWidth() << LHS.get()->getSourceRange()
7219     << RHS.get()->getSourceRange();
7220 }
7221 
7222 // C99 6.5.7
7223 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
7224                                   SourceLocation Loc, unsigned Opc,
7225                                   bool IsCompAssign) {
7226   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7227 
7228   // Vector shifts promote their scalar inputs to vector type.
7229   if (LHS.get()->getType()->isVectorType() ||
7230       RHS.get()->getType()->isVectorType())
7231     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
7232 
7233   // Shifts don't perform usual arithmetic conversions, they just do integer
7234   // promotions on each operand. C99 6.5.7p3
7235 
7236   // For the LHS, do usual unary conversions, but then reset them away
7237   // if this is a compound assignment.
7238   ExprResult OldLHS = LHS;
7239   LHS = UsualUnaryConversions(LHS.take());
7240   if (LHS.isInvalid())
7241     return QualType();
7242   QualType LHSType = LHS.get()->getType();
7243   if (IsCompAssign) LHS = OldLHS;
7244 
7245   // The RHS is simpler.
7246   RHS = UsualUnaryConversions(RHS.take());
7247   if (RHS.isInvalid())
7248     return QualType();
7249   QualType RHSType = RHS.get()->getType();
7250 
7251   // C99 6.5.7p2: Each of the operands shall have integer type.
7252   if (!LHSType->hasIntegerRepresentation() ||
7253       !RHSType->hasIntegerRepresentation())
7254     return InvalidOperands(Loc, LHS, RHS);
7255 
7256   // C++0x: Don't allow scoped enums. FIXME: Use something better than
7257   // hasIntegerRepresentation() above instead of this.
7258   if (isScopedEnumerationType(LHSType) ||
7259       isScopedEnumerationType(RHSType)) {
7260     return InvalidOperands(Loc, LHS, RHS);
7261   }
7262   // Sanity-check shift operands
7263   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
7264 
7265   // "The type of the result is that of the promoted left operand."
7266   return LHSType;
7267 }
7268 
7269 static bool IsWithinTemplateSpecialization(Decl *D) {
7270   if (DeclContext *DC = D->getDeclContext()) {
7271     if (isa<ClassTemplateSpecializationDecl>(DC))
7272       return true;
7273     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
7274       return FD->isFunctionTemplateSpecialization();
7275   }
7276   return false;
7277 }
7278 
7279 /// If two different enums are compared, raise a warning.
7280 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS,
7281                                 Expr *RHS) {
7282   QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
7283   QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
7284 
7285   const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
7286   if (!LHSEnumType)
7287     return;
7288   const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
7289   if (!RHSEnumType)
7290     return;
7291 
7292   // Ignore anonymous enums.
7293   if (!LHSEnumType->getDecl()->getIdentifier())
7294     return;
7295   if (!RHSEnumType->getDecl()->getIdentifier())
7296     return;
7297 
7298   if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
7299     return;
7300 
7301   S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
7302       << LHSStrippedType << RHSStrippedType
7303       << LHS->getSourceRange() << RHS->getSourceRange();
7304 }
7305 
7306 /// \brief Diagnose bad pointer comparisons.
7307 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
7308                                               ExprResult &LHS, ExprResult &RHS,
7309                                               bool IsError) {
7310   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
7311                       : diag::ext_typecheck_comparison_of_distinct_pointers)
7312     << LHS.get()->getType() << RHS.get()->getType()
7313     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7314 }
7315 
7316 /// \brief Returns false if the pointers are converted to a composite type,
7317 /// true otherwise.
7318 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
7319                                            ExprResult &LHS, ExprResult &RHS) {
7320   // C++ [expr.rel]p2:
7321   //   [...] Pointer conversions (4.10) and qualification
7322   //   conversions (4.4) are performed on pointer operands (or on
7323   //   a pointer operand and a null pointer constant) to bring
7324   //   them to their composite pointer type. [...]
7325   //
7326   // C++ [expr.eq]p1 uses the same notion for (in)equality
7327   // comparisons of pointers.
7328 
7329   // C++ [expr.eq]p2:
7330   //   In addition, pointers to members can be compared, or a pointer to
7331   //   member and a null pointer constant. Pointer to member conversions
7332   //   (4.11) and qualification conversions (4.4) are performed to bring
7333   //   them to a common type. If one operand is a null pointer constant,
7334   //   the common type is the type of the other operand. Otherwise, the
7335   //   common type is a pointer to member type similar (4.4) to the type
7336   //   of one of the operands, with a cv-qualification signature (4.4)
7337   //   that is the union of the cv-qualification signatures of the operand
7338   //   types.
7339 
7340   QualType LHSType = LHS.get()->getType();
7341   QualType RHSType = RHS.get()->getType();
7342   assert((LHSType->isPointerType() && RHSType->isPointerType()) ||
7343          (LHSType->isMemberPointerType() && RHSType->isMemberPointerType()));
7344 
7345   bool NonStandardCompositeType = false;
7346   bool *BoolPtr = S.isSFINAEContext() ? 0 : &NonStandardCompositeType;
7347   QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr);
7348   if (T.isNull()) {
7349     diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
7350     return true;
7351   }
7352 
7353   if (NonStandardCompositeType)
7354     S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
7355       << LHSType << RHSType << T << LHS.get()->getSourceRange()
7356       << RHS.get()->getSourceRange();
7357 
7358   LHS = S.ImpCastExprToType(LHS.take(), T, CK_BitCast);
7359   RHS = S.ImpCastExprToType(RHS.take(), T, CK_BitCast);
7360   return false;
7361 }
7362 
7363 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
7364                                                     ExprResult &LHS,
7365                                                     ExprResult &RHS,
7366                                                     bool IsError) {
7367   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
7368                       : diag::ext_typecheck_comparison_of_fptr_to_void)
7369     << LHS.get()->getType() << RHS.get()->getType()
7370     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7371 }
7372 
7373 static bool isObjCObjectLiteral(ExprResult &E) {
7374   switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
7375   case Stmt::ObjCArrayLiteralClass:
7376   case Stmt::ObjCDictionaryLiteralClass:
7377   case Stmt::ObjCStringLiteralClass:
7378   case Stmt::ObjCBoxedExprClass:
7379     return true;
7380   default:
7381     // Note that ObjCBoolLiteral is NOT an object literal!
7382     return false;
7383   }
7384 }
7385 
7386 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
7387   const ObjCObjectPointerType *Type =
7388     LHS->getType()->getAs<ObjCObjectPointerType>();
7389 
7390   // If this is not actually an Objective-C object, bail out.
7391   if (!Type)
7392     return false;
7393 
7394   // Get the LHS object's interface type.
7395   QualType InterfaceType = Type->getPointeeType();
7396   if (const ObjCObjectType *iQFaceTy =
7397       InterfaceType->getAsObjCQualifiedInterfaceType())
7398     InterfaceType = iQFaceTy->getBaseType();
7399 
7400   // If the RHS isn't an Objective-C object, bail out.
7401   if (!RHS->getType()->isObjCObjectPointerType())
7402     return false;
7403 
7404   // Try to find the -isEqual: method.
7405   Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
7406   ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
7407                                                       InterfaceType,
7408                                                       /*instance=*/true);
7409   if (!Method) {
7410     if (Type->isObjCIdType()) {
7411       // For 'id', just check the global pool.
7412       Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
7413                                                   /*receiverId=*/true,
7414                                                   /*warn=*/false);
7415     } else {
7416       // Check protocols.
7417       Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
7418                                              /*instance=*/true);
7419     }
7420   }
7421 
7422   if (!Method)
7423     return false;
7424 
7425   QualType T = Method->param_begin()[0]->getType();
7426   if (!T->isObjCObjectPointerType())
7427     return false;
7428 
7429   QualType R = Method->getResultType();
7430   if (!R->isScalarType())
7431     return false;
7432 
7433   return true;
7434 }
7435 
7436 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
7437   FromE = FromE->IgnoreParenImpCasts();
7438   switch (FromE->getStmtClass()) {
7439     default:
7440       break;
7441     case Stmt::ObjCStringLiteralClass:
7442       // "string literal"
7443       return LK_String;
7444     case Stmt::ObjCArrayLiteralClass:
7445       // "array literal"
7446       return LK_Array;
7447     case Stmt::ObjCDictionaryLiteralClass:
7448       // "dictionary literal"
7449       return LK_Dictionary;
7450     case Stmt::BlockExprClass:
7451       return LK_Block;
7452     case Stmt::ObjCBoxedExprClass: {
7453       Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
7454       switch (Inner->getStmtClass()) {
7455         case Stmt::IntegerLiteralClass:
7456         case Stmt::FloatingLiteralClass:
7457         case Stmt::CharacterLiteralClass:
7458         case Stmt::ObjCBoolLiteralExprClass:
7459         case Stmt::CXXBoolLiteralExprClass:
7460           // "numeric literal"
7461           return LK_Numeric;
7462         case Stmt::ImplicitCastExprClass: {
7463           CastKind CK = cast<CastExpr>(Inner)->getCastKind();
7464           // Boolean literals can be represented by implicit casts.
7465           if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
7466             return LK_Numeric;
7467           break;
7468         }
7469         default:
7470           break;
7471       }
7472       return LK_Boxed;
7473     }
7474   }
7475   return LK_None;
7476 }
7477 
7478 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
7479                                           ExprResult &LHS, ExprResult &RHS,
7480                                           BinaryOperator::Opcode Opc){
7481   Expr *Literal;
7482   Expr *Other;
7483   if (isObjCObjectLiteral(LHS)) {
7484     Literal = LHS.get();
7485     Other = RHS.get();
7486   } else {
7487     Literal = RHS.get();
7488     Other = LHS.get();
7489   }
7490 
7491   // Don't warn on comparisons against nil.
7492   Other = Other->IgnoreParenCasts();
7493   if (Other->isNullPointerConstant(S.getASTContext(),
7494                                    Expr::NPC_ValueDependentIsNotNull))
7495     return;
7496 
7497   // This should be kept in sync with warn_objc_literal_comparison.
7498   // LK_String should always be after the other literals, since it has its own
7499   // warning flag.
7500   Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
7501   assert(LiteralKind != Sema::LK_Block);
7502   if (LiteralKind == Sema::LK_None) {
7503     llvm_unreachable("Unknown Objective-C object literal kind");
7504   }
7505 
7506   if (LiteralKind == Sema::LK_String)
7507     S.Diag(Loc, diag::warn_objc_string_literal_comparison)
7508       << Literal->getSourceRange();
7509   else
7510     S.Diag(Loc, diag::warn_objc_literal_comparison)
7511       << LiteralKind << Literal->getSourceRange();
7512 
7513   if (BinaryOperator::isEqualityOp(Opc) &&
7514       hasIsEqualMethod(S, LHS.get(), RHS.get())) {
7515     SourceLocation Start = LHS.get()->getLocStart();
7516     SourceLocation End = S.PP.getLocForEndOfToken(RHS.get()->getLocEnd());
7517     CharSourceRange OpRange =
7518       CharSourceRange::getCharRange(Loc, S.PP.getLocForEndOfToken(Loc));
7519 
7520     S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
7521       << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
7522       << FixItHint::CreateReplacement(OpRange, " isEqual:")
7523       << FixItHint::CreateInsertion(End, "]");
7524   }
7525 }
7526 
7527 static void diagnoseLogicalNotOnLHSofComparison(Sema &S, ExprResult &LHS,
7528                                                 ExprResult &RHS,
7529                                                 SourceLocation Loc,
7530                                                 unsigned OpaqueOpc) {
7531   // This checking requires bools.
7532   if (!S.getLangOpts().Bool) return;
7533 
7534   // Check that left hand side is !something.
7535   UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
7536   if (!UO || UO->getOpcode() != UO_LNot) return;
7537 
7538   // Only check if the right hand side is non-bool arithmetic type.
7539   if (RHS.get()->getType()->isBooleanType()) return;
7540 
7541   // Make sure that the something in !something is not bool.
7542   Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
7543   if (SubExpr->getType()->isBooleanType()) return;
7544 
7545   // Emit warning.
7546   S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_comparison)
7547       << Loc;
7548 
7549   // First note suggest !(x < y)
7550   SourceLocation FirstOpen = SubExpr->getLocStart();
7551   SourceLocation FirstClose = RHS.get()->getLocEnd();
7552   FirstClose = S.getPreprocessor().getLocForEndOfToken(FirstClose);
7553   if (FirstClose.isInvalid())
7554     FirstOpen = SourceLocation();
7555   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
7556       << FixItHint::CreateInsertion(FirstOpen, "(")
7557       << FixItHint::CreateInsertion(FirstClose, ")");
7558 
7559   // Second note suggests (!x) < y
7560   SourceLocation SecondOpen = LHS.get()->getLocStart();
7561   SourceLocation SecondClose = LHS.get()->getLocEnd();
7562   SecondClose = S.getPreprocessor().getLocForEndOfToken(SecondClose);
7563   if (SecondClose.isInvalid())
7564     SecondOpen = SourceLocation();
7565   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
7566       << FixItHint::CreateInsertion(SecondOpen, "(")
7567       << FixItHint::CreateInsertion(SecondClose, ")");
7568 }
7569 
7570 // Get the decl for a simple expression: a reference to a variable,
7571 // an implicit C++ field reference, or an implicit ObjC ivar reference.
7572 static ValueDecl *getCompareDecl(Expr *E) {
7573   if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E))
7574     return DR->getDecl();
7575   if (ObjCIvarRefExpr* Ivar = dyn_cast<ObjCIvarRefExpr>(E)) {
7576     if (Ivar->isFreeIvar())
7577       return Ivar->getDecl();
7578   }
7579   if (MemberExpr* Mem = dyn_cast<MemberExpr>(E)) {
7580     if (Mem->isImplicitAccess())
7581       return Mem->getMemberDecl();
7582   }
7583   return 0;
7584 }
7585 
7586 // C99 6.5.8, C++ [expr.rel]
7587 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
7588                                     SourceLocation Loc, unsigned OpaqueOpc,
7589                                     bool IsRelational) {
7590   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
7591 
7592   BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
7593 
7594   // Handle vector comparisons separately.
7595   if (LHS.get()->getType()->isVectorType() ||
7596       RHS.get()->getType()->isVectorType())
7597     return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
7598 
7599   QualType LHSType = LHS.get()->getType();
7600   QualType RHSType = RHS.get()->getType();
7601 
7602   Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
7603   Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
7604 
7605   checkEnumComparison(*this, Loc, LHS.get(), RHS.get());
7606   diagnoseLogicalNotOnLHSofComparison(*this, LHS, RHS, Loc, OpaqueOpc);
7607 
7608   if (!LHSType->hasFloatingRepresentation() &&
7609       !(LHSType->isBlockPointerType() && IsRelational) &&
7610       !LHS.get()->getLocStart().isMacroID() &&
7611       !RHS.get()->getLocStart().isMacroID()) {
7612     // For non-floating point types, check for self-comparisons of the form
7613     // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
7614     // often indicate logic errors in the program.
7615     //
7616     // NOTE: Don't warn about comparison expressions resulting from macro
7617     // expansion. Also don't warn about comparisons which are only self
7618     // comparisons within a template specialization. The warnings should catch
7619     // obvious cases in the definition of the template anyways. The idea is to
7620     // warn when the typed comparison operator will always evaluate to the same
7621     // result.
7622     ValueDecl *DL = getCompareDecl(LHSStripped);
7623     ValueDecl *DR = getCompareDecl(RHSStripped);
7624     if (DL && DR && DL == DR && !IsWithinTemplateSpecialization(DL)) {
7625       DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
7626                           << 0 // self-
7627                           << (Opc == BO_EQ
7628                               || Opc == BO_LE
7629                               || Opc == BO_GE));
7630     } else if (DL && DR && LHSType->isArrayType() && RHSType->isArrayType() &&
7631                !DL->getType()->isReferenceType() &&
7632                !DR->getType()->isReferenceType()) {
7633         // what is it always going to eval to?
7634         char always_evals_to;
7635         switch(Opc) {
7636         case BO_EQ: // e.g. array1 == array2
7637           always_evals_to = 0; // false
7638           break;
7639         case BO_NE: // e.g. array1 != array2
7640           always_evals_to = 1; // true
7641           break;
7642         default:
7643           // best we can say is 'a constant'
7644           always_evals_to = 2; // e.g. array1 <= array2
7645           break;
7646         }
7647         DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
7648                             << 1 // array
7649                             << always_evals_to);
7650     }
7651 
7652     if (isa<CastExpr>(LHSStripped))
7653       LHSStripped = LHSStripped->IgnoreParenCasts();
7654     if (isa<CastExpr>(RHSStripped))
7655       RHSStripped = RHSStripped->IgnoreParenCasts();
7656 
7657     // Warn about comparisons against a string constant (unless the other
7658     // operand is null), the user probably wants strcmp.
7659     Expr *literalString = 0;
7660     Expr *literalStringStripped = 0;
7661     if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
7662         !RHSStripped->isNullPointerConstant(Context,
7663                                             Expr::NPC_ValueDependentIsNull)) {
7664       literalString = LHS.get();
7665       literalStringStripped = LHSStripped;
7666     } else if ((isa<StringLiteral>(RHSStripped) ||
7667                 isa<ObjCEncodeExpr>(RHSStripped)) &&
7668                !LHSStripped->isNullPointerConstant(Context,
7669                                             Expr::NPC_ValueDependentIsNull)) {
7670       literalString = RHS.get();
7671       literalStringStripped = RHSStripped;
7672     }
7673 
7674     if (literalString) {
7675       DiagRuntimeBehavior(Loc, 0,
7676         PDiag(diag::warn_stringcompare)
7677           << isa<ObjCEncodeExpr>(literalStringStripped)
7678           << literalString->getSourceRange());
7679     }
7680   }
7681 
7682   // C99 6.5.8p3 / C99 6.5.9p4
7683   UsualArithmeticConversions(LHS, RHS);
7684   if (LHS.isInvalid() || RHS.isInvalid())
7685     return QualType();
7686 
7687   LHSType = LHS.get()->getType();
7688   RHSType = RHS.get()->getType();
7689 
7690   // The result of comparisons is 'bool' in C++, 'int' in C.
7691   QualType ResultTy = Context.getLogicalOperationType();
7692 
7693   if (IsRelational) {
7694     if (LHSType->isRealType() && RHSType->isRealType())
7695       return ResultTy;
7696   } else {
7697     // Check for comparisons of floating point operands using != and ==.
7698     if (LHSType->hasFloatingRepresentation())
7699       CheckFloatComparison(Loc, LHS.get(), RHS.get());
7700 
7701     if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
7702       return ResultTy;
7703   }
7704 
7705   bool LHSIsNull = LHS.get()->isNullPointerConstant(Context,
7706                                               Expr::NPC_ValueDependentIsNull);
7707   bool RHSIsNull = RHS.get()->isNullPointerConstant(Context,
7708                                               Expr::NPC_ValueDependentIsNull);
7709 
7710   // All of the following pointer-related warnings are GCC extensions, except
7711   // when handling null pointer constants.
7712   if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2
7713     QualType LCanPointeeTy =
7714       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
7715     QualType RCanPointeeTy =
7716       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
7717 
7718     if (getLangOpts().CPlusPlus) {
7719       if (LCanPointeeTy == RCanPointeeTy)
7720         return ResultTy;
7721       if (!IsRelational &&
7722           (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7723         // Valid unless comparison between non-null pointer and function pointer
7724         // This is a gcc extension compatibility comparison.
7725         // In a SFINAE context, we treat this as a hard error to maintain
7726         // conformance with the C++ standard.
7727         if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
7728             && !LHSIsNull && !RHSIsNull) {
7729           diagnoseFunctionPointerToVoidComparison(
7730               *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
7731 
7732           if (isSFINAEContext())
7733             return QualType();
7734 
7735           RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
7736           return ResultTy;
7737         }
7738       }
7739 
7740       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
7741         return QualType();
7742       else
7743         return ResultTy;
7744     }
7745     // C99 6.5.9p2 and C99 6.5.8p2
7746     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
7747                                    RCanPointeeTy.getUnqualifiedType())) {
7748       // Valid unless a relational comparison of function pointers
7749       if (IsRelational && LCanPointeeTy->isFunctionType()) {
7750         Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
7751           << LHSType << RHSType << LHS.get()->getSourceRange()
7752           << RHS.get()->getSourceRange();
7753       }
7754     } else if (!IsRelational &&
7755                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7756       // Valid unless comparison between non-null pointer and function pointer
7757       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
7758           && !LHSIsNull && !RHSIsNull)
7759         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
7760                                                 /*isError*/false);
7761     } else {
7762       // Invalid
7763       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
7764     }
7765     if (LCanPointeeTy != RCanPointeeTy) {
7766       if (LHSIsNull && !RHSIsNull)
7767         LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
7768       else
7769         RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
7770     }
7771     return ResultTy;
7772   }
7773 
7774   if (getLangOpts().CPlusPlus) {
7775     // Comparison of nullptr_t with itself.
7776     if (LHSType->isNullPtrType() && RHSType->isNullPtrType())
7777       return ResultTy;
7778 
7779     // Comparison of pointers with null pointer constants and equality
7780     // comparisons of member pointers to null pointer constants.
7781     if (RHSIsNull &&
7782         ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) ||
7783          (!IsRelational &&
7784           (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) {
7785       RHS = ImpCastExprToType(RHS.take(), LHSType,
7786                         LHSType->isMemberPointerType()
7787                           ? CK_NullToMemberPointer
7788                           : CK_NullToPointer);
7789       return ResultTy;
7790     }
7791     if (LHSIsNull &&
7792         ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) ||
7793          (!IsRelational &&
7794           (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) {
7795       LHS = ImpCastExprToType(LHS.take(), RHSType,
7796                         RHSType->isMemberPointerType()
7797                           ? CK_NullToMemberPointer
7798                           : CK_NullToPointer);
7799       return ResultTy;
7800     }
7801 
7802     // Comparison of member pointers.
7803     if (!IsRelational &&
7804         LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) {
7805       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
7806         return QualType();
7807       else
7808         return ResultTy;
7809     }
7810 
7811     // Handle scoped enumeration types specifically, since they don't promote
7812     // to integers.
7813     if (LHS.get()->getType()->isEnumeralType() &&
7814         Context.hasSameUnqualifiedType(LHS.get()->getType(),
7815                                        RHS.get()->getType()))
7816       return ResultTy;
7817   }
7818 
7819   // Handle block pointer types.
7820   if (!IsRelational && LHSType->isBlockPointerType() &&
7821       RHSType->isBlockPointerType()) {
7822     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
7823     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
7824 
7825     if (!LHSIsNull && !RHSIsNull &&
7826         !Context.typesAreCompatible(lpointee, rpointee)) {
7827       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
7828         << LHSType << RHSType << LHS.get()->getSourceRange()
7829         << RHS.get()->getSourceRange();
7830     }
7831     RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
7832     return ResultTy;
7833   }
7834 
7835   // Allow block pointers to be compared with null pointer constants.
7836   if (!IsRelational
7837       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
7838           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
7839     if (!LHSIsNull && !RHSIsNull) {
7840       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
7841              ->getPointeeType()->isVoidType())
7842             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
7843                 ->getPointeeType()->isVoidType())))
7844         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
7845           << LHSType << RHSType << LHS.get()->getSourceRange()
7846           << RHS.get()->getSourceRange();
7847     }
7848     if (LHSIsNull && !RHSIsNull)
7849       LHS = ImpCastExprToType(LHS.take(), RHSType,
7850                               RHSType->isPointerType() ? CK_BitCast
7851                                 : CK_AnyPointerToBlockPointerCast);
7852     else
7853       RHS = ImpCastExprToType(RHS.take(), LHSType,
7854                               LHSType->isPointerType() ? CK_BitCast
7855                                 : CK_AnyPointerToBlockPointerCast);
7856     return ResultTy;
7857   }
7858 
7859   if (LHSType->isObjCObjectPointerType() ||
7860       RHSType->isObjCObjectPointerType()) {
7861     const PointerType *LPT = LHSType->getAs<PointerType>();
7862     const PointerType *RPT = RHSType->getAs<PointerType>();
7863     if (LPT || RPT) {
7864       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
7865       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
7866 
7867       if (!LPtrToVoid && !RPtrToVoid &&
7868           !Context.typesAreCompatible(LHSType, RHSType)) {
7869         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
7870                                           /*isError*/false);
7871       }
7872       if (LHSIsNull && !RHSIsNull) {
7873         Expr *E = LHS.take();
7874         if (getLangOpts().ObjCAutoRefCount)
7875           CheckObjCARCConversion(SourceRange(), RHSType, E, CCK_ImplicitConversion);
7876         LHS = ImpCastExprToType(E, RHSType,
7877                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
7878       }
7879       else {
7880         Expr *E = RHS.take();
7881         if (getLangOpts().ObjCAutoRefCount)
7882           CheckObjCARCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion);
7883         RHS = ImpCastExprToType(E, LHSType,
7884                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
7885       }
7886       return ResultTy;
7887     }
7888     if (LHSType->isObjCObjectPointerType() &&
7889         RHSType->isObjCObjectPointerType()) {
7890       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
7891         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
7892                                           /*isError*/false);
7893       if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
7894         diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
7895 
7896       if (LHSIsNull && !RHSIsNull)
7897         LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
7898       else
7899         RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
7900       return ResultTy;
7901     }
7902   }
7903   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
7904       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
7905     unsigned DiagID = 0;
7906     bool isError = false;
7907     if (LangOpts.DebuggerSupport) {
7908       // Under a debugger, allow the comparison of pointers to integers,
7909       // since users tend to want to compare addresses.
7910     } else if ((LHSIsNull && LHSType->isIntegerType()) ||
7911         (RHSIsNull && RHSType->isIntegerType())) {
7912       if (IsRelational && !getLangOpts().CPlusPlus)
7913         DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
7914     } else if (IsRelational && !getLangOpts().CPlusPlus)
7915       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
7916     else if (getLangOpts().CPlusPlus) {
7917       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
7918       isError = true;
7919     } else
7920       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
7921 
7922     if (DiagID) {
7923       Diag(Loc, DiagID)
7924         << LHSType << RHSType << LHS.get()->getSourceRange()
7925         << RHS.get()->getSourceRange();
7926       if (isError)
7927         return QualType();
7928     }
7929 
7930     if (LHSType->isIntegerType())
7931       LHS = ImpCastExprToType(LHS.take(), RHSType,
7932                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
7933     else
7934       RHS = ImpCastExprToType(RHS.take(), LHSType,
7935                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
7936     return ResultTy;
7937   }
7938 
7939   // Handle block pointers.
7940   if (!IsRelational && RHSIsNull
7941       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
7942     RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
7943     return ResultTy;
7944   }
7945   if (!IsRelational && LHSIsNull
7946       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
7947     LHS = ImpCastExprToType(LHS.take(), RHSType, CK_NullToPointer);
7948     return ResultTy;
7949   }
7950 
7951   return InvalidOperands(Loc, LHS, RHS);
7952 }
7953 
7954 
7955 // Return a signed type that is of identical size and number of elements.
7956 // For floating point vectors, return an integer type of identical size
7957 // and number of elements.
7958 QualType Sema::GetSignedVectorType(QualType V) {
7959   const VectorType *VTy = V->getAs<VectorType>();
7960   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
7961   if (TypeSize == Context.getTypeSize(Context.CharTy))
7962     return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
7963   else if (TypeSize == Context.getTypeSize(Context.ShortTy))
7964     return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
7965   else if (TypeSize == Context.getTypeSize(Context.IntTy))
7966     return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
7967   else if (TypeSize == Context.getTypeSize(Context.LongTy))
7968     return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
7969   assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
7970          "Unhandled vector element size in vector compare");
7971   return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
7972 }
7973 
7974 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
7975 /// operates on extended vector types.  Instead of producing an IntTy result,
7976 /// like a scalar comparison, a vector comparison produces a vector of integer
7977 /// types.
7978 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
7979                                           SourceLocation Loc,
7980                                           bool IsRelational) {
7981   // Check to make sure we're operating on vectors of the same type and width,
7982   // Allowing one side to be a scalar of element type.
7983   QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false);
7984   if (vType.isNull())
7985     return vType;
7986 
7987   QualType LHSType = LHS.get()->getType();
7988 
7989   // If AltiVec, the comparison results in a numeric type, i.e.
7990   // bool for C++, int for C
7991   if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
7992     return Context.getLogicalOperationType();
7993 
7994   // For non-floating point types, check for self-comparisons of the form
7995   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
7996   // often indicate logic errors in the program.
7997   if (!LHSType->hasFloatingRepresentation()) {
7998     if (DeclRefExpr* DRL
7999           = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
8000       if (DeclRefExpr* DRR
8001             = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
8002         if (DRL->getDecl() == DRR->getDecl())
8003           DiagRuntimeBehavior(Loc, 0,
8004                               PDiag(diag::warn_comparison_always)
8005                                 << 0 // self-
8006                                 << 2 // "a constant"
8007                               );
8008   }
8009 
8010   // Check for comparisons of floating point operands using != and ==.
8011   if (!IsRelational && LHSType->hasFloatingRepresentation()) {
8012     assert (RHS.get()->getType()->hasFloatingRepresentation());
8013     CheckFloatComparison(Loc, LHS.get(), RHS.get());
8014   }
8015 
8016   // Return a signed type for the vector.
8017   return GetSignedVectorType(LHSType);
8018 }
8019 
8020 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
8021                                           SourceLocation Loc) {
8022   // Ensure that either both operands are of the same vector type, or
8023   // one operand is of a vector type and the other is of its element type.
8024   QualType vType = CheckVectorOperands(LHS, RHS, Loc, false);
8025   if (vType.isNull())
8026     return InvalidOperands(Loc, LHS, RHS);
8027   if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
8028       vType->hasFloatingRepresentation())
8029     return InvalidOperands(Loc, LHS, RHS);
8030 
8031   return GetSignedVectorType(LHS.get()->getType());
8032 }
8033 
8034 inline QualType Sema::CheckBitwiseOperands(
8035   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
8036   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8037 
8038   if (LHS.get()->getType()->isVectorType() ||
8039       RHS.get()->getType()->isVectorType()) {
8040     if (LHS.get()->getType()->hasIntegerRepresentation() &&
8041         RHS.get()->getType()->hasIntegerRepresentation())
8042       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
8043 
8044     return InvalidOperands(Loc, LHS, RHS);
8045   }
8046 
8047   ExprResult LHSResult = Owned(LHS), RHSResult = Owned(RHS);
8048   QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
8049                                                  IsCompAssign);
8050   if (LHSResult.isInvalid() || RHSResult.isInvalid())
8051     return QualType();
8052   LHS = LHSResult.take();
8053   RHS = RHSResult.take();
8054 
8055   if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
8056     return compType;
8057   return InvalidOperands(Loc, LHS, RHS);
8058 }
8059 
8060 inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
8061   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) {
8062 
8063   // Check vector operands differently.
8064   if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
8065     return CheckVectorLogicalOperands(LHS, RHS, Loc);
8066 
8067   // Diagnose cases where the user write a logical and/or but probably meant a
8068   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
8069   // is a constant.
8070   if (LHS.get()->getType()->isIntegerType() &&
8071       !LHS.get()->getType()->isBooleanType() &&
8072       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
8073       // Don't warn in macros or template instantiations.
8074       !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
8075     // If the RHS can be constant folded, and if it constant folds to something
8076     // that isn't 0 or 1 (which indicate a potential logical operation that
8077     // happened to fold to true/false) then warn.
8078     // Parens on the RHS are ignored.
8079     llvm::APSInt Result;
8080     if (RHS.get()->EvaluateAsInt(Result, Context))
8081       if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType()) ||
8082           (Result != 0 && Result != 1)) {
8083         Diag(Loc, diag::warn_logical_instead_of_bitwise)
8084           << RHS.get()->getSourceRange()
8085           << (Opc == BO_LAnd ? "&&" : "||");
8086         // Suggest replacing the logical operator with the bitwise version
8087         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
8088             << (Opc == BO_LAnd ? "&" : "|")
8089             << FixItHint::CreateReplacement(SourceRange(
8090                 Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(),
8091                                                 getLangOpts())),
8092                                             Opc == BO_LAnd ? "&" : "|");
8093         if (Opc == BO_LAnd)
8094           // Suggest replacing "Foo() && kNonZero" with "Foo()"
8095           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
8096               << FixItHint::CreateRemoval(
8097                   SourceRange(
8098                       Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(),
8099                                                  0, getSourceManager(),
8100                                                  getLangOpts()),
8101                       RHS.get()->getLocEnd()));
8102       }
8103   }
8104 
8105   if (!Context.getLangOpts().CPlusPlus) {
8106     // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
8107     // not operate on the built-in scalar and vector float types.
8108     if (Context.getLangOpts().OpenCL &&
8109         Context.getLangOpts().OpenCLVersion < 120) {
8110       if (LHS.get()->getType()->isFloatingType() ||
8111           RHS.get()->getType()->isFloatingType())
8112         return InvalidOperands(Loc, LHS, RHS);
8113     }
8114 
8115     LHS = UsualUnaryConversions(LHS.take());
8116     if (LHS.isInvalid())
8117       return QualType();
8118 
8119     RHS = UsualUnaryConversions(RHS.take());
8120     if (RHS.isInvalid())
8121       return QualType();
8122 
8123     if (!LHS.get()->getType()->isScalarType() ||
8124         !RHS.get()->getType()->isScalarType())
8125       return InvalidOperands(Loc, LHS, RHS);
8126 
8127     return Context.IntTy;
8128   }
8129 
8130   // The following is safe because we only use this method for
8131   // non-overloadable operands.
8132 
8133   // C++ [expr.log.and]p1
8134   // C++ [expr.log.or]p1
8135   // The operands are both contextually converted to type bool.
8136   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
8137   if (LHSRes.isInvalid())
8138     return InvalidOperands(Loc, LHS, RHS);
8139   LHS = LHSRes;
8140 
8141   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
8142   if (RHSRes.isInvalid())
8143     return InvalidOperands(Loc, LHS, RHS);
8144   RHS = RHSRes;
8145 
8146   // C++ [expr.log.and]p2
8147   // C++ [expr.log.or]p2
8148   // The result is a bool.
8149   return Context.BoolTy;
8150 }
8151 
8152 static bool IsReadonlyMessage(Expr *E, Sema &S) {
8153   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
8154   if (!ME) return false;
8155   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
8156   ObjCMessageExpr *Base =
8157     dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts());
8158   if (!Base) return false;
8159   return Base->getMethodDecl() != 0;
8160 }
8161 
8162 /// Is the given expression (which must be 'const') a reference to a
8163 /// variable which was originally non-const, but which has become
8164 /// 'const' due to being captured within a block?
8165 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
8166 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
8167   assert(E->isLValue() && E->getType().isConstQualified());
8168   E = E->IgnoreParens();
8169 
8170   // Must be a reference to a declaration from an enclosing scope.
8171   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
8172   if (!DRE) return NCCK_None;
8173   if (!DRE->refersToEnclosingLocal()) return NCCK_None;
8174 
8175   // The declaration must be a variable which is not declared 'const'.
8176   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
8177   if (!var) return NCCK_None;
8178   if (var->getType().isConstQualified()) return NCCK_None;
8179   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
8180 
8181   // Decide whether the first capture was for a block or a lambda.
8182   DeclContext *DC = S.CurContext, *Prev = 0;
8183   while (DC != var->getDeclContext()) {
8184     Prev = DC;
8185     DC = DC->getParent();
8186   }
8187   // Unless we have an init-capture, we've gone one step too far.
8188   if (!var->isInitCapture())
8189     DC = Prev;
8190   return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
8191 }
8192 
8193 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
8194 /// emit an error and return true.  If so, return false.
8195 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
8196   assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
8197   SourceLocation OrigLoc = Loc;
8198   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
8199                                                               &Loc);
8200   if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
8201     IsLV = Expr::MLV_InvalidMessageExpression;
8202   if (IsLV == Expr::MLV_Valid)
8203     return false;
8204 
8205   unsigned Diag = 0;
8206   bool NeedType = false;
8207   switch (IsLV) { // C99 6.5.16p2
8208   case Expr::MLV_ConstQualified:
8209     Diag = diag::err_typecheck_assign_const;
8210 
8211     // Use a specialized diagnostic when we're assigning to an object
8212     // from an enclosing function or block.
8213     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
8214       if (NCCK == NCCK_Block)
8215         Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
8216       else
8217         Diag = diag::err_lambda_decl_ref_not_modifiable_lvalue;
8218       break;
8219     }
8220 
8221     // In ARC, use some specialized diagnostics for occasions where we
8222     // infer 'const'.  These are always pseudo-strong variables.
8223     if (S.getLangOpts().ObjCAutoRefCount) {
8224       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
8225       if (declRef && isa<VarDecl>(declRef->getDecl())) {
8226         VarDecl *var = cast<VarDecl>(declRef->getDecl());
8227 
8228         // Use the normal diagnostic if it's pseudo-__strong but the
8229         // user actually wrote 'const'.
8230         if (var->isARCPseudoStrong() &&
8231             (!var->getTypeSourceInfo() ||
8232              !var->getTypeSourceInfo()->getType().isConstQualified())) {
8233           // There are two pseudo-strong cases:
8234           //  - self
8235           ObjCMethodDecl *method = S.getCurMethodDecl();
8236           if (method && var == method->getSelfDecl())
8237             Diag = method->isClassMethod()
8238               ? diag::err_typecheck_arc_assign_self_class_method
8239               : diag::err_typecheck_arc_assign_self;
8240 
8241           //  - fast enumeration variables
8242           else
8243             Diag = diag::err_typecheck_arr_assign_enumeration;
8244 
8245           SourceRange Assign;
8246           if (Loc != OrigLoc)
8247             Assign = SourceRange(OrigLoc, OrigLoc);
8248           S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
8249           // We need to preserve the AST regardless, so migration tool
8250           // can do its job.
8251           return false;
8252         }
8253       }
8254     }
8255 
8256     break;
8257   case Expr::MLV_ArrayType:
8258   case Expr::MLV_ArrayTemporary:
8259     Diag = diag::err_typecheck_array_not_modifiable_lvalue;
8260     NeedType = true;
8261     break;
8262   case Expr::MLV_NotObjectType:
8263     Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
8264     NeedType = true;
8265     break;
8266   case Expr::MLV_LValueCast:
8267     Diag = diag::err_typecheck_lvalue_casts_not_supported;
8268     break;
8269   case Expr::MLV_Valid:
8270     llvm_unreachable("did not take early return for MLV_Valid");
8271   case Expr::MLV_InvalidExpression:
8272   case Expr::MLV_MemberFunction:
8273   case Expr::MLV_ClassTemporary:
8274     Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
8275     break;
8276   case Expr::MLV_IncompleteType:
8277   case Expr::MLV_IncompleteVoidType:
8278     return S.RequireCompleteType(Loc, E->getType(),
8279              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
8280   case Expr::MLV_DuplicateVectorComponents:
8281     Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
8282     break;
8283   case Expr::MLV_NoSetterProperty:
8284     llvm_unreachable("readonly properties should be processed differently");
8285   case Expr::MLV_InvalidMessageExpression:
8286     Diag = diag::error_readonly_message_assignment;
8287     break;
8288   case Expr::MLV_SubObjCPropertySetting:
8289     Diag = diag::error_no_subobject_property_setting;
8290     break;
8291   }
8292 
8293   SourceRange Assign;
8294   if (Loc != OrigLoc)
8295     Assign = SourceRange(OrigLoc, OrigLoc);
8296   if (NeedType)
8297     S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
8298   else
8299     S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
8300   return true;
8301 }
8302 
8303 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
8304                                          SourceLocation Loc,
8305                                          Sema &Sema) {
8306   // C / C++ fields
8307   MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
8308   MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
8309   if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) {
8310     if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))
8311       Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
8312   }
8313 
8314   // Objective-C instance variables
8315   ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
8316   ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
8317   if (OL && OR && OL->getDecl() == OR->getDecl()) {
8318     DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
8319     DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
8320     if (RL && RR && RL->getDecl() == RR->getDecl())
8321       Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
8322   }
8323 }
8324 
8325 // C99 6.5.16.1
8326 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
8327                                        SourceLocation Loc,
8328                                        QualType CompoundType) {
8329   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
8330 
8331   // Verify that LHS is a modifiable lvalue, and emit error if not.
8332   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
8333     return QualType();
8334 
8335   QualType LHSType = LHSExpr->getType();
8336   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
8337                                              CompoundType;
8338   AssignConvertType ConvTy;
8339   if (CompoundType.isNull()) {
8340     Expr *RHSCheck = RHS.get();
8341 
8342     CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
8343 
8344     QualType LHSTy(LHSType);
8345     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
8346     if (RHS.isInvalid())
8347       return QualType();
8348     // Special case of NSObject attributes on c-style pointer types.
8349     if (ConvTy == IncompatiblePointer &&
8350         ((Context.isObjCNSObjectType(LHSType) &&
8351           RHSType->isObjCObjectPointerType()) ||
8352          (Context.isObjCNSObjectType(RHSType) &&
8353           LHSType->isObjCObjectPointerType())))
8354       ConvTy = Compatible;
8355 
8356     if (ConvTy == Compatible &&
8357         LHSType->isObjCObjectType())
8358         Diag(Loc, diag::err_objc_object_assignment)
8359           << LHSType;
8360 
8361     // If the RHS is a unary plus or minus, check to see if they = and + are
8362     // right next to each other.  If so, the user may have typo'd "x =+ 4"
8363     // instead of "x += 4".
8364     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
8365       RHSCheck = ICE->getSubExpr();
8366     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
8367       if ((UO->getOpcode() == UO_Plus ||
8368            UO->getOpcode() == UO_Minus) &&
8369           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
8370           // Only if the two operators are exactly adjacent.
8371           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
8372           // And there is a space or other character before the subexpr of the
8373           // unary +/-.  We don't want to warn on "x=-1".
8374           Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
8375           UO->getSubExpr()->getLocStart().isFileID()) {
8376         Diag(Loc, diag::warn_not_compound_assign)
8377           << (UO->getOpcode() == UO_Plus ? "+" : "-")
8378           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
8379       }
8380     }
8381 
8382     if (ConvTy == Compatible) {
8383       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
8384         // Warn about retain cycles where a block captures the LHS, but
8385         // not if the LHS is a simple variable into which the block is
8386         // being stored...unless that variable can be captured by reference!
8387         const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
8388         const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
8389         if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
8390           checkRetainCycles(LHSExpr, RHS.get());
8391 
8392         // It is safe to assign a weak reference into a strong variable.
8393         // Although this code can still have problems:
8394         //   id x = self.weakProp;
8395         //   id y = self.weakProp;
8396         // we do not warn to warn spuriously when 'x' and 'y' are on separate
8397         // paths through the function. This should be revisited if
8398         // -Wrepeated-use-of-weak is made flow-sensitive.
8399         DiagnosticsEngine::Level Level =
8400           Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
8401                                    RHS.get()->getLocStart());
8402         if (Level != DiagnosticsEngine::Ignored)
8403           getCurFunction()->markSafeWeakUse(RHS.get());
8404 
8405       } else if (getLangOpts().ObjCAutoRefCount) {
8406         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
8407       }
8408     }
8409   } else {
8410     // Compound assignment "x += y"
8411     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
8412   }
8413 
8414   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
8415                                RHS.get(), AA_Assigning))
8416     return QualType();
8417 
8418   CheckForNullPointerDereference(*this, LHSExpr);
8419 
8420   // C99 6.5.16p3: The type of an assignment expression is the type of the
8421   // left operand unless the left operand has qualified type, in which case
8422   // it is the unqualified version of the type of the left operand.
8423   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
8424   // is converted to the type of the assignment expression (above).
8425   // C++ 5.17p1: the type of the assignment expression is that of its left
8426   // operand.
8427   return (getLangOpts().CPlusPlus
8428           ? LHSType : LHSType.getUnqualifiedType());
8429 }
8430 
8431 // C99 6.5.17
8432 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
8433                                    SourceLocation Loc) {
8434   LHS = S.CheckPlaceholderExpr(LHS.take());
8435   RHS = S.CheckPlaceholderExpr(RHS.take());
8436   if (LHS.isInvalid() || RHS.isInvalid())
8437     return QualType();
8438 
8439   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
8440   // operands, but not unary promotions.
8441   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
8442 
8443   // So we treat the LHS as a ignored value, and in C++ we allow the
8444   // containing site to determine what should be done with the RHS.
8445   LHS = S.IgnoredValueConversions(LHS.take());
8446   if (LHS.isInvalid())
8447     return QualType();
8448 
8449   S.DiagnoseUnusedExprResult(LHS.get());
8450 
8451   if (!S.getLangOpts().CPlusPlus) {
8452     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take());
8453     if (RHS.isInvalid())
8454       return QualType();
8455     if (!RHS.get()->getType()->isVoidType())
8456       S.RequireCompleteType(Loc, RHS.get()->getType(),
8457                             diag::err_incomplete_type);
8458   }
8459 
8460   return RHS.get()->getType();
8461 }
8462 
8463 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
8464 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
8465 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
8466                                                ExprValueKind &VK,
8467                                                SourceLocation OpLoc,
8468                                                bool IsInc, bool IsPrefix) {
8469   if (Op->isTypeDependent())
8470     return S.Context.DependentTy;
8471 
8472   QualType ResType = Op->getType();
8473   // Atomic types can be used for increment / decrement where the non-atomic
8474   // versions can, so ignore the _Atomic() specifier for the purpose of
8475   // checking.
8476   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
8477     ResType = ResAtomicType->getValueType();
8478 
8479   assert(!ResType.isNull() && "no type for increment/decrement expression");
8480 
8481   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
8482     // Decrement of bool is not allowed.
8483     if (!IsInc) {
8484       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
8485       return QualType();
8486     }
8487     // Increment of bool sets it to true, but is deprecated.
8488     S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
8489   } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
8490     // Error on enum increments and decrements in C++ mode
8491     S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
8492     return QualType();
8493   } else if (ResType->isRealType()) {
8494     // OK!
8495   } else if (ResType->isPointerType()) {
8496     // C99 6.5.2.4p2, 6.5.6p2
8497     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
8498       return QualType();
8499   } else if (ResType->isObjCObjectPointerType()) {
8500     // On modern runtimes, ObjC pointer arithmetic is forbidden.
8501     // Otherwise, we just need a complete type.
8502     if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
8503         checkArithmeticOnObjCPointer(S, OpLoc, Op))
8504       return QualType();
8505   } else if (ResType->isAnyComplexType()) {
8506     // C99 does not support ++/-- on complex types, we allow as an extension.
8507     S.Diag(OpLoc, diag::ext_integer_increment_complex)
8508       << ResType << Op->getSourceRange();
8509   } else if (ResType->isPlaceholderType()) {
8510     ExprResult PR = S.CheckPlaceholderExpr(Op);
8511     if (PR.isInvalid()) return QualType();
8512     return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
8513                                           IsInc, IsPrefix);
8514   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
8515     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
8516   } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
8517             ResType->getAs<VectorType>()->getElementType()->isIntegerType()) {
8518     // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
8519   } else {
8520     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
8521       << ResType << int(IsInc) << Op->getSourceRange();
8522     return QualType();
8523   }
8524   // At this point, we know we have a real, complex or pointer type.
8525   // Now make sure the operand is a modifiable lvalue.
8526   if (CheckForModifiableLvalue(Op, OpLoc, S))
8527     return QualType();
8528   // In C++, a prefix increment is the same type as the operand. Otherwise
8529   // (in C or with postfix), the increment is the unqualified type of the
8530   // operand.
8531   if (IsPrefix && S.getLangOpts().CPlusPlus) {
8532     VK = VK_LValue;
8533     return ResType;
8534   } else {
8535     VK = VK_RValue;
8536     return ResType.getUnqualifiedType();
8537   }
8538 }
8539 
8540 
8541 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
8542 /// This routine allows us to typecheck complex/recursive expressions
8543 /// where the declaration is needed for type checking. We only need to
8544 /// handle cases when the expression references a function designator
8545 /// or is an lvalue. Here are some examples:
8546 ///  - &(x) => x
8547 ///  - &*****f => f for f a function designator.
8548 ///  - &s.xx => s
8549 ///  - &s.zz[1].yy -> s, if zz is an array
8550 ///  - *(x + 1) -> x, if x is an array
8551 ///  - &"123"[2] -> 0
8552 ///  - & __real__ x -> x
8553 static ValueDecl *getPrimaryDecl(Expr *E) {
8554   switch (E->getStmtClass()) {
8555   case Stmt::DeclRefExprClass:
8556     return cast<DeclRefExpr>(E)->getDecl();
8557   case Stmt::MemberExprClass:
8558     // If this is an arrow operator, the address is an offset from
8559     // the base's value, so the object the base refers to is
8560     // irrelevant.
8561     if (cast<MemberExpr>(E)->isArrow())
8562       return 0;
8563     // Otherwise, the expression refers to a part of the base
8564     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
8565   case Stmt::ArraySubscriptExprClass: {
8566     // FIXME: This code shouldn't be necessary!  We should catch the implicit
8567     // promotion of register arrays earlier.
8568     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
8569     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
8570       if (ICE->getSubExpr()->getType()->isArrayType())
8571         return getPrimaryDecl(ICE->getSubExpr());
8572     }
8573     return 0;
8574   }
8575   case Stmt::UnaryOperatorClass: {
8576     UnaryOperator *UO = cast<UnaryOperator>(E);
8577 
8578     switch(UO->getOpcode()) {
8579     case UO_Real:
8580     case UO_Imag:
8581     case UO_Extension:
8582       return getPrimaryDecl(UO->getSubExpr());
8583     default:
8584       return 0;
8585     }
8586   }
8587   case Stmt::ParenExprClass:
8588     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
8589   case Stmt::ImplicitCastExprClass:
8590     // If the result of an implicit cast is an l-value, we care about
8591     // the sub-expression; otherwise, the result here doesn't matter.
8592     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
8593   default:
8594     return 0;
8595   }
8596 }
8597 
8598 namespace {
8599   enum {
8600     AO_Bit_Field = 0,
8601     AO_Vector_Element = 1,
8602     AO_Property_Expansion = 2,
8603     AO_Register_Variable = 3,
8604     AO_No_Error = 4
8605   };
8606 }
8607 /// \brief Diagnose invalid operand for address of operations.
8608 ///
8609 /// \param Type The type of operand which cannot have its address taken.
8610 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
8611                                          Expr *E, unsigned Type) {
8612   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
8613 }
8614 
8615 /// CheckAddressOfOperand - The operand of & must be either a function
8616 /// designator or an lvalue designating an object. If it is an lvalue, the
8617 /// object cannot be declared with storage class register or be a bit field.
8618 /// Note: The usual conversions are *not* applied to the operand of the &
8619 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
8620 /// In C++, the operand might be an overloaded function name, in which case
8621 /// we allow the '&' but retain the overloaded-function type.
8622 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
8623   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
8624     if (PTy->getKind() == BuiltinType::Overload) {
8625       Expr *E = OrigOp.get()->IgnoreParens();
8626       if (!isa<OverloadExpr>(E)) {
8627         assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
8628         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
8629           << OrigOp.get()->getSourceRange();
8630         return QualType();
8631       }
8632 
8633       OverloadExpr *Ovl = cast<OverloadExpr>(E);
8634       if (isa<UnresolvedMemberExpr>(Ovl))
8635         if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
8636           Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
8637             << OrigOp.get()->getSourceRange();
8638           return QualType();
8639         }
8640 
8641       return Context.OverloadTy;
8642     }
8643 
8644     if (PTy->getKind() == BuiltinType::UnknownAny)
8645       return Context.UnknownAnyTy;
8646 
8647     if (PTy->getKind() == BuiltinType::BoundMember) {
8648       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
8649         << OrigOp.get()->getSourceRange();
8650       return QualType();
8651     }
8652 
8653     OrigOp = CheckPlaceholderExpr(OrigOp.take());
8654     if (OrigOp.isInvalid()) return QualType();
8655   }
8656 
8657   if (OrigOp.get()->isTypeDependent())
8658     return Context.DependentTy;
8659 
8660   assert(!OrigOp.get()->getType()->isPlaceholderType());
8661 
8662   // Make sure to ignore parentheses in subsequent checks
8663   Expr *op = OrigOp.get()->IgnoreParens();
8664 
8665   if (getLangOpts().C99) {
8666     // Implement C99-only parts of addressof rules.
8667     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
8668       if (uOp->getOpcode() == UO_Deref)
8669         // Per C99 6.5.3.2, the address of a deref always returns a valid result
8670         // (assuming the deref expression is valid).
8671         return uOp->getSubExpr()->getType();
8672     }
8673     // Technically, there should be a check for array subscript
8674     // expressions here, but the result of one is always an lvalue anyway.
8675   }
8676   ValueDecl *dcl = getPrimaryDecl(op);
8677   Expr::LValueClassification lval = op->ClassifyLValue(Context);
8678   unsigned AddressOfError = AO_No_Error;
8679 
8680   if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
8681     bool sfinae = (bool)isSFINAEContext();
8682     Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
8683                                   : diag::ext_typecheck_addrof_temporary)
8684       << op->getType() << op->getSourceRange();
8685     if (sfinae)
8686       return QualType();
8687     // Materialize the temporary as an lvalue so that we can take its address.
8688     OrigOp = op = new (Context)
8689         MaterializeTemporaryExpr(op->getType(), OrigOp.take(), true, 0);
8690   } else if (isa<ObjCSelectorExpr>(op)) {
8691     return Context.getPointerType(op->getType());
8692   } else if (lval == Expr::LV_MemberFunction) {
8693     // If it's an instance method, make a member pointer.
8694     // The expression must have exactly the form &A::foo.
8695 
8696     // If the underlying expression isn't a decl ref, give up.
8697     if (!isa<DeclRefExpr>(op)) {
8698       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
8699         << OrigOp.get()->getSourceRange();
8700       return QualType();
8701     }
8702     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
8703     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
8704 
8705     // The id-expression was parenthesized.
8706     if (OrigOp.get() != DRE) {
8707       Diag(OpLoc, diag::err_parens_pointer_member_function)
8708         << OrigOp.get()->getSourceRange();
8709 
8710     // The method was named without a qualifier.
8711     } else if (!DRE->getQualifier()) {
8712       if (MD->getParent()->getName().empty())
8713         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
8714           << op->getSourceRange();
8715       else {
8716         SmallString<32> Str;
8717         StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
8718         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
8719           << op->getSourceRange()
8720           << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
8721       }
8722     }
8723 
8724     // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
8725     if (isa<CXXDestructorDecl>(MD))
8726       Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
8727 
8728     return Context.getMemberPointerType(op->getType(),
8729               Context.getTypeDeclType(MD->getParent()).getTypePtr());
8730   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
8731     // C99 6.5.3.2p1
8732     // The operand must be either an l-value or a function designator
8733     if (!op->getType()->isFunctionType()) {
8734       // Use a special diagnostic for loads from property references.
8735       if (isa<PseudoObjectExpr>(op)) {
8736         AddressOfError = AO_Property_Expansion;
8737       } else {
8738         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
8739           << op->getType() << op->getSourceRange();
8740         return QualType();
8741       }
8742     }
8743   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
8744     // The operand cannot be a bit-field
8745     AddressOfError = AO_Bit_Field;
8746   } else if (op->getObjectKind() == OK_VectorComponent) {
8747     // The operand cannot be an element of a vector
8748     AddressOfError = AO_Vector_Element;
8749   } else if (dcl) { // C99 6.5.3.2p1
8750     // We have an lvalue with a decl. Make sure the decl is not declared
8751     // with the register storage-class specifier.
8752     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
8753       // in C++ it is not error to take address of a register
8754       // variable (c++03 7.1.1P3)
8755       if (vd->getStorageClass() == SC_Register &&
8756           !getLangOpts().CPlusPlus) {
8757         AddressOfError = AO_Register_Variable;
8758       }
8759     } else if (isa<FunctionTemplateDecl>(dcl)) {
8760       return Context.OverloadTy;
8761     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
8762       // Okay: we can take the address of a field.
8763       // Could be a pointer to member, though, if there is an explicit
8764       // scope qualifier for the class.
8765       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
8766         DeclContext *Ctx = dcl->getDeclContext();
8767         if (Ctx && Ctx->isRecord()) {
8768           if (dcl->getType()->isReferenceType()) {
8769             Diag(OpLoc,
8770                  diag::err_cannot_form_pointer_to_member_of_reference_type)
8771               << dcl->getDeclName() << dcl->getType();
8772             return QualType();
8773           }
8774 
8775           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
8776             Ctx = Ctx->getParent();
8777           return Context.getMemberPointerType(op->getType(),
8778                 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
8779         }
8780       }
8781     } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl))
8782       llvm_unreachable("Unknown/unexpected decl type");
8783   }
8784 
8785   if (AddressOfError != AO_No_Error) {
8786     diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
8787     return QualType();
8788   }
8789 
8790   if (lval == Expr::LV_IncompleteVoidType) {
8791     // Taking the address of a void variable is technically illegal, but we
8792     // allow it in cases which are otherwise valid.
8793     // Example: "extern void x; void* y = &x;".
8794     Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
8795   }
8796 
8797   // If the operand has type "type", the result has type "pointer to type".
8798   if (op->getType()->isObjCObjectType())
8799     return Context.getObjCObjectPointerType(op->getType());
8800   return Context.getPointerType(op->getType());
8801 }
8802 
8803 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
8804 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
8805                                         SourceLocation OpLoc) {
8806   if (Op->isTypeDependent())
8807     return S.Context.DependentTy;
8808 
8809   ExprResult ConvResult = S.UsualUnaryConversions(Op);
8810   if (ConvResult.isInvalid())
8811     return QualType();
8812   Op = ConvResult.take();
8813   QualType OpTy = Op->getType();
8814   QualType Result;
8815 
8816   if (isa<CXXReinterpretCastExpr>(Op)) {
8817     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
8818     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
8819                                      Op->getSourceRange());
8820   }
8821 
8822   // Note that per both C89 and C99, indirection is always legal, even if OpTy
8823   // is an incomplete type or void.  It would be possible to warn about
8824   // dereferencing a void pointer, but it's completely well-defined, and such a
8825   // warning is unlikely to catch any mistakes.
8826   if (const PointerType *PT = OpTy->getAs<PointerType>())
8827     Result = PT->getPointeeType();
8828   else if (const ObjCObjectPointerType *OPT =
8829              OpTy->getAs<ObjCObjectPointerType>())
8830     Result = OPT->getPointeeType();
8831   else {
8832     ExprResult PR = S.CheckPlaceholderExpr(Op);
8833     if (PR.isInvalid()) return QualType();
8834     if (PR.take() != Op)
8835       return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
8836   }
8837 
8838   if (Result.isNull()) {
8839     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
8840       << OpTy << Op->getSourceRange();
8841     return QualType();
8842   }
8843 
8844   // Dereferences are usually l-values...
8845   VK = VK_LValue;
8846 
8847   // ...except that certain expressions are never l-values in C.
8848   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
8849     VK = VK_RValue;
8850 
8851   return Result;
8852 }
8853 
8854 static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
8855   tok::TokenKind Kind) {
8856   BinaryOperatorKind Opc;
8857   switch (Kind) {
8858   default: llvm_unreachable("Unknown binop!");
8859   case tok::periodstar:           Opc = BO_PtrMemD; break;
8860   case tok::arrowstar:            Opc = BO_PtrMemI; break;
8861   case tok::star:                 Opc = BO_Mul; break;
8862   case tok::slash:                Opc = BO_Div; break;
8863   case tok::percent:              Opc = BO_Rem; break;
8864   case tok::plus:                 Opc = BO_Add; break;
8865   case tok::minus:                Opc = BO_Sub; break;
8866   case tok::lessless:             Opc = BO_Shl; break;
8867   case tok::greatergreater:       Opc = BO_Shr; break;
8868   case tok::lessequal:            Opc = BO_LE; break;
8869   case tok::less:                 Opc = BO_LT; break;
8870   case tok::greaterequal:         Opc = BO_GE; break;
8871   case tok::greater:              Opc = BO_GT; break;
8872   case tok::exclaimequal:         Opc = BO_NE; break;
8873   case tok::equalequal:           Opc = BO_EQ; break;
8874   case tok::amp:                  Opc = BO_And; break;
8875   case tok::caret:                Opc = BO_Xor; break;
8876   case tok::pipe:                 Opc = BO_Or; break;
8877   case tok::ampamp:               Opc = BO_LAnd; break;
8878   case tok::pipepipe:             Opc = BO_LOr; break;
8879   case tok::equal:                Opc = BO_Assign; break;
8880   case tok::starequal:            Opc = BO_MulAssign; break;
8881   case tok::slashequal:           Opc = BO_DivAssign; break;
8882   case tok::percentequal:         Opc = BO_RemAssign; break;
8883   case tok::plusequal:            Opc = BO_AddAssign; break;
8884   case tok::minusequal:           Opc = BO_SubAssign; break;
8885   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
8886   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
8887   case tok::ampequal:             Opc = BO_AndAssign; break;
8888   case tok::caretequal:           Opc = BO_XorAssign; break;
8889   case tok::pipeequal:            Opc = BO_OrAssign; break;
8890   case tok::comma:                Opc = BO_Comma; break;
8891   }
8892   return Opc;
8893 }
8894 
8895 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
8896   tok::TokenKind Kind) {
8897   UnaryOperatorKind Opc;
8898   switch (Kind) {
8899   default: llvm_unreachable("Unknown unary op!");
8900   case tok::plusplus:     Opc = UO_PreInc; break;
8901   case tok::minusminus:   Opc = UO_PreDec; break;
8902   case tok::amp:          Opc = UO_AddrOf; break;
8903   case tok::star:         Opc = UO_Deref; break;
8904   case tok::plus:         Opc = UO_Plus; break;
8905   case tok::minus:        Opc = UO_Minus; break;
8906   case tok::tilde:        Opc = UO_Not; break;
8907   case tok::exclaim:      Opc = UO_LNot; break;
8908   case tok::kw___real:    Opc = UO_Real; break;
8909   case tok::kw___imag:    Opc = UO_Imag; break;
8910   case tok::kw___extension__: Opc = UO_Extension; break;
8911   }
8912   return Opc;
8913 }
8914 
8915 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
8916 /// This warning is only emitted for builtin assignment operations. It is also
8917 /// suppressed in the event of macro expansions.
8918 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
8919                                    SourceLocation OpLoc) {
8920   if (!S.ActiveTemplateInstantiations.empty())
8921     return;
8922   if (OpLoc.isInvalid() || OpLoc.isMacroID())
8923     return;
8924   LHSExpr = LHSExpr->IgnoreParenImpCasts();
8925   RHSExpr = RHSExpr->IgnoreParenImpCasts();
8926   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
8927   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
8928   if (!LHSDeclRef || !RHSDeclRef ||
8929       LHSDeclRef->getLocation().isMacroID() ||
8930       RHSDeclRef->getLocation().isMacroID())
8931     return;
8932   const ValueDecl *LHSDecl =
8933     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
8934   const ValueDecl *RHSDecl =
8935     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
8936   if (LHSDecl != RHSDecl)
8937     return;
8938   if (LHSDecl->getType().isVolatileQualified())
8939     return;
8940   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
8941     if (RefTy->getPointeeType().isVolatileQualified())
8942       return;
8943 
8944   S.Diag(OpLoc, diag::warn_self_assignment)
8945       << LHSDeclRef->getType()
8946       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
8947 }
8948 
8949 /// Check if a bitwise-& is performed on an Objective-C pointer.  This
8950 /// is usually indicative of introspection within the Objective-C pointer.
8951 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
8952                                           SourceLocation OpLoc) {
8953   if (!S.getLangOpts().ObjC1)
8954     return;
8955 
8956   const Expr *ObjCPointerExpr = 0, *OtherExpr = 0;
8957   const Expr *LHS = L.get();
8958   const Expr *RHS = R.get();
8959 
8960   if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
8961     ObjCPointerExpr = LHS;
8962     OtherExpr = RHS;
8963   }
8964   else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
8965     ObjCPointerExpr = RHS;
8966     OtherExpr = LHS;
8967   }
8968 
8969   // This warning is deliberately made very specific to reduce false
8970   // positives with logic that uses '&' for hashing.  This logic mainly
8971   // looks for code trying to introspect into tagged pointers, which
8972   // code should generally never do.
8973   if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
8974     unsigned Diag = diag::warn_objc_pointer_masking;
8975     // Determine if we are introspecting the result of performSelectorXXX.
8976     const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
8977     // Special case messages to -performSelector and friends, which
8978     // can return non-pointer values boxed in a pointer value.
8979     // Some clients may wish to silence warnings in this subcase.
8980     if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
8981       Selector S = ME->getSelector();
8982       StringRef SelArg0 = S.getNameForSlot(0);
8983       if (SelArg0.startswith("performSelector"))
8984         Diag = diag::warn_objc_pointer_masking_performSelector;
8985     }
8986 
8987     S.Diag(OpLoc, Diag)
8988       << ObjCPointerExpr->getSourceRange();
8989   }
8990 }
8991 
8992 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
8993 /// operator @p Opc at location @c TokLoc. This routine only supports
8994 /// built-in operations; ActOnBinOp handles overloaded operators.
8995 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
8996                                     BinaryOperatorKind Opc,
8997                                     Expr *LHSExpr, Expr *RHSExpr) {
8998   if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
8999     // The syntax only allows initializer lists on the RHS of assignment,
9000     // so we don't need to worry about accepting invalid code for
9001     // non-assignment operators.
9002     // C++11 5.17p9:
9003     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
9004     //   of x = {} is x = T().
9005     InitializationKind Kind =
9006         InitializationKind::CreateDirectList(RHSExpr->getLocStart());
9007     InitializedEntity Entity =
9008         InitializedEntity::InitializeTemporary(LHSExpr->getType());
9009     InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
9010     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
9011     if (Init.isInvalid())
9012       return Init;
9013     RHSExpr = Init.take();
9014   }
9015 
9016   ExprResult LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
9017   QualType ResultTy;     // Result type of the binary operator.
9018   // The following two variables are used for compound assignment operators
9019   QualType CompLHSTy;    // Type of LHS after promotions for computation
9020   QualType CompResultTy; // Type of computation result
9021   ExprValueKind VK = VK_RValue;
9022   ExprObjectKind OK = OK_Ordinary;
9023 
9024   switch (Opc) {
9025   case BO_Assign:
9026     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
9027     if (getLangOpts().CPlusPlus &&
9028         LHS.get()->getObjectKind() != OK_ObjCProperty) {
9029       VK = LHS.get()->getValueKind();
9030       OK = LHS.get()->getObjectKind();
9031     }
9032     if (!ResultTy.isNull())
9033       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
9034     break;
9035   case BO_PtrMemD:
9036   case BO_PtrMemI:
9037     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
9038                                             Opc == BO_PtrMemI);
9039     break;
9040   case BO_Mul:
9041   case BO_Div:
9042     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
9043                                            Opc == BO_Div);
9044     break;
9045   case BO_Rem:
9046     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
9047     break;
9048   case BO_Add:
9049     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
9050     break;
9051   case BO_Sub:
9052     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
9053     break;
9054   case BO_Shl:
9055   case BO_Shr:
9056     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
9057     break;
9058   case BO_LE:
9059   case BO_LT:
9060   case BO_GE:
9061   case BO_GT:
9062     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
9063     break;
9064   case BO_EQ:
9065   case BO_NE:
9066     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
9067     break;
9068   case BO_And:
9069     checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
9070   case BO_Xor:
9071   case BO_Or:
9072     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc);
9073     break;
9074   case BO_LAnd:
9075   case BO_LOr:
9076     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
9077     break;
9078   case BO_MulAssign:
9079   case BO_DivAssign:
9080     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
9081                                                Opc == BO_DivAssign);
9082     CompLHSTy = CompResultTy;
9083     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
9084       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
9085     break;
9086   case BO_RemAssign:
9087     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
9088     CompLHSTy = CompResultTy;
9089     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
9090       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
9091     break;
9092   case BO_AddAssign:
9093     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
9094     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
9095       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
9096     break;
9097   case BO_SubAssign:
9098     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
9099     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
9100       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
9101     break;
9102   case BO_ShlAssign:
9103   case BO_ShrAssign:
9104     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
9105     CompLHSTy = CompResultTy;
9106     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
9107       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
9108     break;
9109   case BO_AndAssign:
9110   case BO_XorAssign:
9111   case BO_OrAssign:
9112     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true);
9113     CompLHSTy = CompResultTy;
9114     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
9115       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
9116     break;
9117   case BO_Comma:
9118     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
9119     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
9120       VK = RHS.get()->getValueKind();
9121       OK = RHS.get()->getObjectKind();
9122     }
9123     break;
9124   }
9125   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
9126     return ExprError();
9127 
9128   // Check for array bounds violations for both sides of the BinaryOperator
9129   CheckArrayAccess(LHS.get());
9130   CheckArrayAccess(RHS.get());
9131 
9132   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
9133     NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
9134                                                  &Context.Idents.get("object_setClass"),
9135                                                  SourceLocation(), LookupOrdinaryName);
9136     if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
9137       SourceLocation RHSLocEnd = PP.getLocForEndOfToken(RHS.get()->getLocEnd());
9138       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) <<
9139       FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") <<
9140       FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") <<
9141       FixItHint::CreateInsertion(RHSLocEnd, ")");
9142     }
9143     else
9144       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
9145   }
9146   else if (const ObjCIvarRefExpr *OIRE =
9147            dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
9148     DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
9149 
9150   if (CompResultTy.isNull())
9151     return Owned(new (Context) BinaryOperator(LHS.take(), RHS.take(), Opc,
9152                                               ResultTy, VK, OK, OpLoc,
9153                                               FPFeatures.fp_contract));
9154   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
9155       OK_ObjCProperty) {
9156     VK = VK_LValue;
9157     OK = LHS.get()->getObjectKind();
9158   }
9159   return Owned(new (Context) CompoundAssignOperator(LHS.take(), RHS.take(), Opc,
9160                                                     ResultTy, VK, OK, CompLHSTy,
9161                                                     CompResultTy, OpLoc,
9162                                                     FPFeatures.fp_contract));
9163 }
9164 
9165 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
9166 /// operators are mixed in a way that suggests that the programmer forgot that
9167 /// comparison operators have higher precedence. The most typical example of
9168 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
9169 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
9170                                       SourceLocation OpLoc, Expr *LHSExpr,
9171                                       Expr *RHSExpr) {
9172   BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
9173   BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
9174 
9175   // Check that one of the sides is a comparison operator.
9176   bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
9177   bool isRightComp = RHSBO && RHSBO->isComparisonOp();
9178   if (!isLeftComp && !isRightComp)
9179     return;
9180 
9181   // Bitwise operations are sometimes used as eager logical ops.
9182   // Don't diagnose this.
9183   bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
9184   bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
9185   if ((isLeftComp || isLeftBitwise) && (isRightComp || isRightBitwise))
9186     return;
9187 
9188   SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
9189                                                    OpLoc)
9190                                      : SourceRange(OpLoc, RHSExpr->getLocEnd());
9191   StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
9192   SourceRange ParensRange = isLeftComp ?
9193       SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd())
9194     : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocStart());
9195 
9196   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
9197     << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
9198   SuggestParentheses(Self, OpLoc,
9199     Self.PDiag(diag::note_precedence_silence) << OpStr,
9200     (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
9201   SuggestParentheses(Self, OpLoc,
9202     Self.PDiag(diag::note_precedence_bitwise_first)
9203       << BinaryOperator::getOpcodeStr(Opc),
9204     ParensRange);
9205 }
9206 
9207 /// \brief It accepts a '&' expr that is inside a '|' one.
9208 /// Emit a diagnostic together with a fixit hint that wraps the '&' expression
9209 /// in parentheses.
9210 static void
9211 EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc,
9212                                        BinaryOperator *Bop) {
9213   assert(Bop->getOpcode() == BO_And);
9214   Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or)
9215       << Bop->getSourceRange() << OpLoc;
9216   SuggestParentheses(Self, Bop->getOperatorLoc(),
9217     Self.PDiag(diag::note_precedence_silence)
9218       << Bop->getOpcodeStr(),
9219     Bop->getSourceRange());
9220 }
9221 
9222 /// \brief It accepts a '&&' expr that is inside a '||' one.
9223 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
9224 /// in parentheses.
9225 static void
9226 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
9227                                        BinaryOperator *Bop) {
9228   assert(Bop->getOpcode() == BO_LAnd);
9229   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
9230       << Bop->getSourceRange() << OpLoc;
9231   SuggestParentheses(Self, Bop->getOperatorLoc(),
9232     Self.PDiag(diag::note_precedence_silence)
9233       << Bop->getOpcodeStr(),
9234     Bop->getSourceRange());
9235 }
9236 
9237 /// \brief Returns true if the given expression can be evaluated as a constant
9238 /// 'true'.
9239 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
9240   bool Res;
9241   return !E->isValueDependent() &&
9242          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
9243 }
9244 
9245 /// \brief Returns true if the given expression can be evaluated as a constant
9246 /// 'false'.
9247 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
9248   bool Res;
9249   return !E->isValueDependent() &&
9250          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
9251 }
9252 
9253 /// \brief Look for '&&' in the left hand of a '||' expr.
9254 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
9255                                              Expr *LHSExpr, Expr *RHSExpr) {
9256   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
9257     if (Bop->getOpcode() == BO_LAnd) {
9258       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
9259       if (EvaluatesAsFalse(S, RHSExpr))
9260         return;
9261       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
9262       if (!EvaluatesAsTrue(S, Bop->getLHS()))
9263         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
9264     } else if (Bop->getOpcode() == BO_LOr) {
9265       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
9266         // If it's "a || b && 1 || c" we didn't warn earlier for
9267         // "a || b && 1", but warn now.
9268         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
9269           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
9270       }
9271     }
9272   }
9273 }
9274 
9275 /// \brief Look for '&&' in the right hand of a '||' expr.
9276 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
9277                                              Expr *LHSExpr, Expr *RHSExpr) {
9278   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
9279     if (Bop->getOpcode() == BO_LAnd) {
9280       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
9281       if (EvaluatesAsFalse(S, LHSExpr))
9282         return;
9283       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
9284       if (!EvaluatesAsTrue(S, Bop->getRHS()))
9285         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
9286     }
9287   }
9288 }
9289 
9290 /// \brief Look for '&' in the left or right hand of a '|' expr.
9291 static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc,
9292                                              Expr *OrArg) {
9293   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) {
9294     if (Bop->getOpcode() == BO_And)
9295       return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop);
9296   }
9297 }
9298 
9299 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
9300                                     Expr *SubExpr, StringRef Shift) {
9301   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
9302     if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
9303       StringRef Op = Bop->getOpcodeStr();
9304       S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
9305           << Bop->getSourceRange() << OpLoc << Shift << Op;
9306       SuggestParentheses(S, Bop->getOperatorLoc(),
9307           S.PDiag(diag::note_precedence_silence) << Op,
9308           Bop->getSourceRange());
9309     }
9310   }
9311 }
9312 
9313 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
9314                                  Expr *LHSExpr, Expr *RHSExpr) {
9315   CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
9316   if (!OCE)
9317     return;
9318 
9319   FunctionDecl *FD = OCE->getDirectCallee();
9320   if (!FD || !FD->isOverloadedOperator())
9321     return;
9322 
9323   OverloadedOperatorKind Kind = FD->getOverloadedOperator();
9324   if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
9325     return;
9326 
9327   S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
9328       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
9329       << (Kind == OO_LessLess);
9330   SuggestParentheses(S, OCE->getOperatorLoc(),
9331                      S.PDiag(diag::note_precedence_silence)
9332                          << (Kind == OO_LessLess ? "<<" : ">>"),
9333                      OCE->getSourceRange());
9334   SuggestParentheses(S, OpLoc,
9335                      S.PDiag(diag::note_evaluate_comparison_first),
9336                      SourceRange(OCE->getArg(1)->getLocStart(),
9337                                  RHSExpr->getLocEnd()));
9338 }
9339 
9340 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
9341 /// precedence.
9342 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
9343                                     SourceLocation OpLoc, Expr *LHSExpr,
9344                                     Expr *RHSExpr){
9345   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
9346   if (BinaryOperator::isBitwiseOp(Opc))
9347     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
9348 
9349   // Diagnose "arg1 & arg2 | arg3"
9350   if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) {
9351     DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr);
9352     DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr);
9353   }
9354 
9355   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
9356   // We don't warn for 'assert(a || b && "bad")' since this is safe.
9357   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
9358     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
9359     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
9360   }
9361 
9362   if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
9363       || Opc == BO_Shr) {
9364     StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
9365     DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
9366     DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
9367   }
9368 
9369   // Warn on overloaded shift operators and comparisons, such as:
9370   // cout << 5 == 4;
9371   if (BinaryOperator::isComparisonOp(Opc))
9372     DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
9373 }
9374 
9375 // Binary Operators.  'Tok' is the token for the operator.
9376 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
9377                             tok::TokenKind Kind,
9378                             Expr *LHSExpr, Expr *RHSExpr) {
9379   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
9380   assert((LHSExpr != 0) && "ActOnBinOp(): missing left expression");
9381   assert((RHSExpr != 0) && "ActOnBinOp(): missing right expression");
9382 
9383   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
9384   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
9385 
9386   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
9387 }
9388 
9389 /// Build an overloaded binary operator expression in the given scope.
9390 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
9391                                        BinaryOperatorKind Opc,
9392                                        Expr *LHS, Expr *RHS) {
9393   // Find all of the overloaded operators visible from this
9394   // point. We perform both an operator-name lookup from the local
9395   // scope and an argument-dependent lookup based on the types of
9396   // the arguments.
9397   UnresolvedSet<16> Functions;
9398   OverloadedOperatorKind OverOp
9399     = BinaryOperator::getOverloadedOperator(Opc);
9400   if (Sc && OverOp != OO_None)
9401     S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
9402                                    RHS->getType(), Functions);
9403 
9404   // Build the (potentially-overloaded, potentially-dependent)
9405   // binary operation.
9406   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
9407 }
9408 
9409 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
9410                             BinaryOperatorKind Opc,
9411                             Expr *LHSExpr, Expr *RHSExpr) {
9412   // We want to end up calling one of checkPseudoObjectAssignment
9413   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
9414   // both expressions are overloadable or either is type-dependent),
9415   // or CreateBuiltinBinOp (in any other case).  We also want to get
9416   // any placeholder types out of the way.
9417 
9418   // Handle pseudo-objects in the LHS.
9419   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
9420     // Assignments with a pseudo-object l-value need special analysis.
9421     if (pty->getKind() == BuiltinType::PseudoObject &&
9422         BinaryOperator::isAssignmentOp(Opc))
9423       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
9424 
9425     // Don't resolve overloads if the other type is overloadable.
9426     if (pty->getKind() == BuiltinType::Overload) {
9427       // We can't actually test that if we still have a placeholder,
9428       // though.  Fortunately, none of the exceptions we see in that
9429       // code below are valid when the LHS is an overload set.  Note
9430       // that an overload set can be dependently-typed, but it never
9431       // instantiates to having an overloadable type.
9432       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
9433       if (resolvedRHS.isInvalid()) return ExprError();
9434       RHSExpr = resolvedRHS.take();
9435 
9436       if (RHSExpr->isTypeDependent() ||
9437           RHSExpr->getType()->isOverloadableType())
9438         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9439     }
9440 
9441     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
9442     if (LHS.isInvalid()) return ExprError();
9443     LHSExpr = LHS.take();
9444   }
9445 
9446   // Handle pseudo-objects in the RHS.
9447   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
9448     // An overload in the RHS can potentially be resolved by the type
9449     // being assigned to.
9450     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
9451       if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
9452         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9453 
9454       if (LHSExpr->getType()->isOverloadableType())
9455         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9456 
9457       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
9458     }
9459 
9460     // Don't resolve overloads if the other type is overloadable.
9461     if (pty->getKind() == BuiltinType::Overload &&
9462         LHSExpr->getType()->isOverloadableType())
9463       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9464 
9465     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
9466     if (!resolvedRHS.isUsable()) return ExprError();
9467     RHSExpr = resolvedRHS.take();
9468   }
9469 
9470   if (getLangOpts().CPlusPlus) {
9471     // If either expression is type-dependent, always build an
9472     // overloaded op.
9473     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
9474       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9475 
9476     // Otherwise, build an overloaded op if either expression has an
9477     // overloadable type.
9478     if (LHSExpr->getType()->isOverloadableType() ||
9479         RHSExpr->getType()->isOverloadableType())
9480       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9481   }
9482 
9483   // Build a built-in binary operation.
9484   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
9485 }
9486 
9487 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
9488                                       UnaryOperatorKind Opc,
9489                                       Expr *InputExpr) {
9490   ExprResult Input = Owned(InputExpr);
9491   ExprValueKind VK = VK_RValue;
9492   ExprObjectKind OK = OK_Ordinary;
9493   QualType resultType;
9494   switch (Opc) {
9495   case UO_PreInc:
9496   case UO_PreDec:
9497   case UO_PostInc:
9498   case UO_PostDec:
9499     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc,
9500                                                 Opc == UO_PreInc ||
9501                                                 Opc == UO_PostInc,
9502                                                 Opc == UO_PreInc ||
9503                                                 Opc == UO_PreDec);
9504     break;
9505   case UO_AddrOf:
9506     resultType = CheckAddressOfOperand(Input, OpLoc);
9507     break;
9508   case UO_Deref: {
9509     Input = DefaultFunctionArrayLvalueConversion(Input.take());
9510     if (Input.isInvalid()) return ExprError();
9511     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
9512     break;
9513   }
9514   case UO_Plus:
9515   case UO_Minus:
9516     Input = UsualUnaryConversions(Input.take());
9517     if (Input.isInvalid()) return ExprError();
9518     resultType = Input.get()->getType();
9519     if (resultType->isDependentType())
9520       break;
9521     if (resultType->isArithmeticType() || // C99 6.5.3.3p1
9522         resultType->isVectorType())
9523       break;
9524     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
9525              Opc == UO_Plus &&
9526              resultType->isPointerType())
9527       break;
9528 
9529     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9530       << resultType << Input.get()->getSourceRange());
9531 
9532   case UO_Not: // bitwise complement
9533     Input = UsualUnaryConversions(Input.take());
9534     if (Input.isInvalid())
9535       return ExprError();
9536     resultType = Input.get()->getType();
9537     if (resultType->isDependentType())
9538       break;
9539     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
9540     if (resultType->isComplexType() || resultType->isComplexIntegerType())
9541       // C99 does not support '~' for complex conjugation.
9542       Diag(OpLoc, diag::ext_integer_complement_complex)
9543           << resultType << Input.get()->getSourceRange();
9544     else if (resultType->hasIntegerRepresentation())
9545       break;
9546     else if (resultType->isExtVectorType()) {
9547       if (Context.getLangOpts().OpenCL) {
9548         // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
9549         // on vector float types.
9550         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
9551         if (!T->isIntegerType())
9552           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9553                            << resultType << Input.get()->getSourceRange());
9554       }
9555       break;
9556     } else {
9557       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9558                        << resultType << Input.get()->getSourceRange());
9559     }
9560     break;
9561 
9562   case UO_LNot: // logical negation
9563     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
9564     Input = DefaultFunctionArrayLvalueConversion(Input.take());
9565     if (Input.isInvalid()) return ExprError();
9566     resultType = Input.get()->getType();
9567 
9568     // Though we still have to promote half FP to float...
9569     if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
9570       Input = ImpCastExprToType(Input.take(), Context.FloatTy, CK_FloatingCast).take();
9571       resultType = Context.FloatTy;
9572     }
9573 
9574     if (resultType->isDependentType())
9575       break;
9576     if (resultType->isScalarType()) {
9577       // C99 6.5.3.3p1: ok, fallthrough;
9578       if (Context.getLangOpts().CPlusPlus) {
9579         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
9580         // operand contextually converted to bool.
9581         Input = ImpCastExprToType(Input.take(), Context.BoolTy,
9582                                   ScalarTypeToBooleanCastKind(resultType));
9583       } else if (Context.getLangOpts().OpenCL &&
9584                  Context.getLangOpts().OpenCLVersion < 120) {
9585         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
9586         // operate on scalar float types.
9587         if (!resultType->isIntegerType())
9588           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9589                            << resultType << Input.get()->getSourceRange());
9590       }
9591     } else if (resultType->isExtVectorType()) {
9592       if (Context.getLangOpts().OpenCL &&
9593           Context.getLangOpts().OpenCLVersion < 120) {
9594         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
9595         // operate on vector float types.
9596         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
9597         if (!T->isIntegerType())
9598           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9599                            << resultType << Input.get()->getSourceRange());
9600       }
9601       // Vector logical not returns the signed variant of the operand type.
9602       resultType = GetSignedVectorType(resultType);
9603       break;
9604     } else {
9605       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9606         << resultType << Input.get()->getSourceRange());
9607     }
9608 
9609     // LNot always has type int. C99 6.5.3.3p5.
9610     // In C++, it's bool. C++ 5.3.1p8
9611     resultType = Context.getLogicalOperationType();
9612     break;
9613   case UO_Real:
9614   case UO_Imag:
9615     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
9616     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
9617     // complex l-values to ordinary l-values and all other values to r-values.
9618     if (Input.isInvalid()) return ExprError();
9619     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
9620       if (Input.get()->getValueKind() != VK_RValue &&
9621           Input.get()->getObjectKind() == OK_Ordinary)
9622         VK = Input.get()->getValueKind();
9623     } else if (!getLangOpts().CPlusPlus) {
9624       // In C, a volatile scalar is read by __imag. In C++, it is not.
9625       Input = DefaultLvalueConversion(Input.take());
9626     }
9627     break;
9628   case UO_Extension:
9629     resultType = Input.get()->getType();
9630     VK = Input.get()->getValueKind();
9631     OK = Input.get()->getObjectKind();
9632     break;
9633   }
9634   if (resultType.isNull() || Input.isInvalid())
9635     return ExprError();
9636 
9637   // Check for array bounds violations in the operand of the UnaryOperator,
9638   // except for the '*' and '&' operators that have to be handled specially
9639   // by CheckArrayAccess (as there are special cases like &array[arraysize]
9640   // that are explicitly defined as valid by the standard).
9641   if (Opc != UO_AddrOf && Opc != UO_Deref)
9642     CheckArrayAccess(Input.get());
9643 
9644   return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType,
9645                                            VK, OK, OpLoc));
9646 }
9647 
9648 /// \brief Determine whether the given expression is a qualified member
9649 /// access expression, of a form that could be turned into a pointer to member
9650 /// with the address-of operator.
9651 static bool isQualifiedMemberAccess(Expr *E) {
9652   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
9653     if (!DRE->getQualifier())
9654       return false;
9655 
9656     ValueDecl *VD = DRE->getDecl();
9657     if (!VD->isCXXClassMember())
9658       return false;
9659 
9660     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
9661       return true;
9662     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
9663       return Method->isInstance();
9664 
9665     return false;
9666   }
9667 
9668   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
9669     if (!ULE->getQualifier())
9670       return false;
9671 
9672     for (UnresolvedLookupExpr::decls_iterator D = ULE->decls_begin(),
9673                                            DEnd = ULE->decls_end();
9674          D != DEnd; ++D) {
9675       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*D)) {
9676         if (Method->isInstance())
9677           return true;
9678       } else {
9679         // Overload set does not contain methods.
9680         break;
9681       }
9682     }
9683 
9684     return false;
9685   }
9686 
9687   return false;
9688 }
9689 
9690 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
9691                               UnaryOperatorKind Opc, Expr *Input) {
9692   // First things first: handle placeholders so that the
9693   // overloaded-operator check considers the right type.
9694   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
9695     // Increment and decrement of pseudo-object references.
9696     if (pty->getKind() == BuiltinType::PseudoObject &&
9697         UnaryOperator::isIncrementDecrementOp(Opc))
9698       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
9699 
9700     // extension is always a builtin operator.
9701     if (Opc == UO_Extension)
9702       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
9703 
9704     // & gets special logic for several kinds of placeholder.
9705     // The builtin code knows what to do.
9706     if (Opc == UO_AddrOf &&
9707         (pty->getKind() == BuiltinType::Overload ||
9708          pty->getKind() == BuiltinType::UnknownAny ||
9709          pty->getKind() == BuiltinType::BoundMember))
9710       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
9711 
9712     // Anything else needs to be handled now.
9713     ExprResult Result = CheckPlaceholderExpr(Input);
9714     if (Result.isInvalid()) return ExprError();
9715     Input = Result.take();
9716   }
9717 
9718   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
9719       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
9720       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
9721     // Find all of the overloaded operators visible from this
9722     // point. We perform both an operator-name lookup from the local
9723     // scope and an argument-dependent lookup based on the types of
9724     // the arguments.
9725     UnresolvedSet<16> Functions;
9726     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
9727     if (S && OverOp != OO_None)
9728       LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
9729                                    Functions);
9730 
9731     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
9732   }
9733 
9734   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
9735 }
9736 
9737 // Unary Operators.  'Tok' is the token for the operator.
9738 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
9739                               tok::TokenKind Op, Expr *Input) {
9740   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
9741 }
9742 
9743 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
9744 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
9745                                 LabelDecl *TheDecl) {
9746   TheDecl->markUsed(Context);
9747   // Create the AST node.  The address of a label always has type 'void*'.
9748   return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
9749                                        Context.getPointerType(Context.VoidTy)));
9750 }
9751 
9752 /// Given the last statement in a statement-expression, check whether
9753 /// the result is a producing expression (like a call to an
9754 /// ns_returns_retained function) and, if so, rebuild it to hoist the
9755 /// release out of the full-expression.  Otherwise, return null.
9756 /// Cannot fail.
9757 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
9758   // Should always be wrapped with one of these.
9759   ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
9760   if (!cleanups) return 0;
9761 
9762   ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
9763   if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
9764     return 0;
9765 
9766   // Splice out the cast.  This shouldn't modify any interesting
9767   // features of the statement.
9768   Expr *producer = cast->getSubExpr();
9769   assert(producer->getType() == cast->getType());
9770   assert(producer->getValueKind() == cast->getValueKind());
9771   cleanups->setSubExpr(producer);
9772   return cleanups;
9773 }
9774 
9775 void Sema::ActOnStartStmtExpr() {
9776   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
9777 }
9778 
9779 void Sema::ActOnStmtExprError() {
9780   // Note that function is also called by TreeTransform when leaving a
9781   // StmtExpr scope without rebuilding anything.
9782 
9783   DiscardCleanupsInEvaluationContext();
9784   PopExpressionEvaluationContext();
9785 }
9786 
9787 ExprResult
9788 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
9789                     SourceLocation RPLoc) { // "({..})"
9790   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
9791   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
9792 
9793   if (hasAnyUnrecoverableErrorsInThisFunction())
9794     DiscardCleanupsInEvaluationContext();
9795   assert(!ExprNeedsCleanups && "cleanups within StmtExpr not correctly bound!");
9796   PopExpressionEvaluationContext();
9797 
9798   bool isFileScope
9799     = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
9800   if (isFileScope)
9801     return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
9802 
9803   // FIXME: there are a variety of strange constraints to enforce here, for
9804   // example, it is not possible to goto into a stmt expression apparently.
9805   // More semantic analysis is needed.
9806 
9807   // If there are sub stmts in the compound stmt, take the type of the last one
9808   // as the type of the stmtexpr.
9809   QualType Ty = Context.VoidTy;
9810   bool StmtExprMayBindToTemp = false;
9811   if (!Compound->body_empty()) {
9812     Stmt *LastStmt = Compound->body_back();
9813     LabelStmt *LastLabelStmt = 0;
9814     // If LastStmt is a label, skip down through into the body.
9815     while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
9816       LastLabelStmt = Label;
9817       LastStmt = Label->getSubStmt();
9818     }
9819 
9820     if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
9821       // Do function/array conversion on the last expression, but not
9822       // lvalue-to-rvalue.  However, initialize an unqualified type.
9823       ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
9824       if (LastExpr.isInvalid())
9825         return ExprError();
9826       Ty = LastExpr.get()->getType().getUnqualifiedType();
9827 
9828       if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
9829         // In ARC, if the final expression ends in a consume, splice
9830         // the consume out and bind it later.  In the alternate case
9831         // (when dealing with a retainable type), the result
9832         // initialization will create a produce.  In both cases the
9833         // result will be +1, and we'll need to balance that out with
9834         // a bind.
9835         if (Expr *rebuiltLastStmt
9836               = maybeRebuildARCConsumingStmt(LastExpr.get())) {
9837           LastExpr = rebuiltLastStmt;
9838         } else {
9839           LastExpr = PerformCopyInitialization(
9840                             InitializedEntity::InitializeResult(LPLoc,
9841                                                                 Ty,
9842                                                                 false),
9843                                                    SourceLocation(),
9844                                                LastExpr);
9845         }
9846 
9847         if (LastExpr.isInvalid())
9848           return ExprError();
9849         if (LastExpr.get() != 0) {
9850           if (!LastLabelStmt)
9851             Compound->setLastStmt(LastExpr.take());
9852           else
9853             LastLabelStmt->setSubStmt(LastExpr.take());
9854           StmtExprMayBindToTemp = true;
9855         }
9856       }
9857     }
9858   }
9859 
9860   // FIXME: Check that expression type is complete/non-abstract; statement
9861   // expressions are not lvalues.
9862   Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
9863   if (StmtExprMayBindToTemp)
9864     return MaybeBindToTemporary(ResStmtExpr);
9865   return Owned(ResStmtExpr);
9866 }
9867 
9868 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
9869                                       TypeSourceInfo *TInfo,
9870                                       OffsetOfComponent *CompPtr,
9871                                       unsigned NumComponents,
9872                                       SourceLocation RParenLoc) {
9873   QualType ArgTy = TInfo->getType();
9874   bool Dependent = ArgTy->isDependentType();
9875   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
9876 
9877   // We must have at least one component that refers to the type, and the first
9878   // one is known to be a field designator.  Verify that the ArgTy represents
9879   // a struct/union/class.
9880   if (!Dependent && !ArgTy->isRecordType())
9881     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
9882                        << ArgTy << TypeRange);
9883 
9884   // Type must be complete per C99 7.17p3 because a declaring a variable
9885   // with an incomplete type would be ill-formed.
9886   if (!Dependent
9887       && RequireCompleteType(BuiltinLoc, ArgTy,
9888                              diag::err_offsetof_incomplete_type, TypeRange))
9889     return ExprError();
9890 
9891   // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
9892   // GCC extension, diagnose them.
9893   // FIXME: This diagnostic isn't actually visible because the location is in
9894   // a system header!
9895   if (NumComponents != 1)
9896     Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
9897       << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
9898 
9899   bool DidWarnAboutNonPOD = false;
9900   QualType CurrentType = ArgTy;
9901   typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
9902   SmallVector<OffsetOfNode, 4> Comps;
9903   SmallVector<Expr*, 4> Exprs;
9904   for (unsigned i = 0; i != NumComponents; ++i) {
9905     const OffsetOfComponent &OC = CompPtr[i];
9906     if (OC.isBrackets) {
9907       // Offset of an array sub-field.  TODO: Should we allow vector elements?
9908       if (!CurrentType->isDependentType()) {
9909         const ArrayType *AT = Context.getAsArrayType(CurrentType);
9910         if(!AT)
9911           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
9912                            << CurrentType);
9913         CurrentType = AT->getElementType();
9914       } else
9915         CurrentType = Context.DependentTy;
9916 
9917       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
9918       if (IdxRval.isInvalid())
9919         return ExprError();
9920       Expr *Idx = IdxRval.take();
9921 
9922       // The expression must be an integral expression.
9923       // FIXME: An integral constant expression?
9924       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
9925           !Idx->getType()->isIntegerType())
9926         return ExprError(Diag(Idx->getLocStart(),
9927                               diag::err_typecheck_subscript_not_integer)
9928                          << Idx->getSourceRange());
9929 
9930       // Record this array index.
9931       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
9932       Exprs.push_back(Idx);
9933       continue;
9934     }
9935 
9936     // Offset of a field.
9937     if (CurrentType->isDependentType()) {
9938       // We have the offset of a field, but we can't look into the dependent
9939       // type. Just record the identifier of the field.
9940       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
9941       CurrentType = Context.DependentTy;
9942       continue;
9943     }
9944 
9945     // We need to have a complete type to look into.
9946     if (RequireCompleteType(OC.LocStart, CurrentType,
9947                             diag::err_offsetof_incomplete_type))
9948       return ExprError();
9949 
9950     // Look for the designated field.
9951     const RecordType *RC = CurrentType->getAs<RecordType>();
9952     if (!RC)
9953       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
9954                        << CurrentType);
9955     RecordDecl *RD = RC->getDecl();
9956 
9957     // C++ [lib.support.types]p5:
9958     //   The macro offsetof accepts a restricted set of type arguments in this
9959     //   International Standard. type shall be a POD structure or a POD union
9960     //   (clause 9).
9961     // C++11 [support.types]p4:
9962     //   If type is not a standard-layout class (Clause 9), the results are
9963     //   undefined.
9964     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
9965       bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
9966       unsigned DiagID =
9967         LangOpts.CPlusPlus11? diag::warn_offsetof_non_standardlayout_type
9968                             : diag::warn_offsetof_non_pod_type;
9969 
9970       if (!IsSafe && !DidWarnAboutNonPOD &&
9971           DiagRuntimeBehavior(BuiltinLoc, 0,
9972                               PDiag(DiagID)
9973                               << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
9974                               << CurrentType))
9975         DidWarnAboutNonPOD = true;
9976     }
9977 
9978     // Look for the field.
9979     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
9980     LookupQualifiedName(R, RD);
9981     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
9982     IndirectFieldDecl *IndirectMemberDecl = 0;
9983     if (!MemberDecl) {
9984       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
9985         MemberDecl = IndirectMemberDecl->getAnonField();
9986     }
9987 
9988     if (!MemberDecl)
9989       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
9990                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
9991                                                               OC.LocEnd));
9992 
9993     // C99 7.17p3:
9994     //   (If the specified member is a bit-field, the behavior is undefined.)
9995     //
9996     // We diagnose this as an error.
9997     if (MemberDecl->isBitField()) {
9998       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
9999         << MemberDecl->getDeclName()
10000         << SourceRange(BuiltinLoc, RParenLoc);
10001       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
10002       return ExprError();
10003     }
10004 
10005     RecordDecl *Parent = MemberDecl->getParent();
10006     if (IndirectMemberDecl)
10007       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
10008 
10009     // If the member was found in a base class, introduce OffsetOfNodes for
10010     // the base class indirections.
10011     CXXBasePaths Paths;
10012     if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
10013       if (Paths.getDetectedVirtual()) {
10014         Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
10015           << MemberDecl->getDeclName()
10016           << SourceRange(BuiltinLoc, RParenLoc);
10017         return ExprError();
10018       }
10019 
10020       CXXBasePath &Path = Paths.front();
10021       for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
10022            B != BEnd; ++B)
10023         Comps.push_back(OffsetOfNode(B->Base));
10024     }
10025 
10026     if (IndirectMemberDecl) {
10027       for (IndirectFieldDecl::chain_iterator FI =
10028            IndirectMemberDecl->chain_begin(),
10029            FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
10030         assert(isa<FieldDecl>(*FI));
10031         Comps.push_back(OffsetOfNode(OC.LocStart,
10032                                      cast<FieldDecl>(*FI), OC.LocEnd));
10033       }
10034     } else
10035       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
10036 
10037     CurrentType = MemberDecl->getType().getNonReferenceType();
10038   }
10039 
10040   return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
10041                                     TInfo, Comps, Exprs, RParenLoc));
10042 }
10043 
10044 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
10045                                       SourceLocation BuiltinLoc,
10046                                       SourceLocation TypeLoc,
10047                                       ParsedType ParsedArgTy,
10048                                       OffsetOfComponent *CompPtr,
10049                                       unsigned NumComponents,
10050                                       SourceLocation RParenLoc) {
10051 
10052   TypeSourceInfo *ArgTInfo;
10053   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
10054   if (ArgTy.isNull())
10055     return ExprError();
10056 
10057   if (!ArgTInfo)
10058     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
10059 
10060   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
10061                               RParenLoc);
10062 }
10063 
10064 
10065 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
10066                                  Expr *CondExpr,
10067                                  Expr *LHSExpr, Expr *RHSExpr,
10068                                  SourceLocation RPLoc) {
10069   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
10070 
10071   ExprValueKind VK = VK_RValue;
10072   ExprObjectKind OK = OK_Ordinary;
10073   QualType resType;
10074   bool ValueDependent = false;
10075   bool CondIsTrue = false;
10076   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
10077     resType = Context.DependentTy;
10078     ValueDependent = true;
10079   } else {
10080     // The conditional expression is required to be a constant expression.
10081     llvm::APSInt condEval(32);
10082     ExprResult CondICE
10083       = VerifyIntegerConstantExpression(CondExpr, &condEval,
10084           diag::err_typecheck_choose_expr_requires_constant, false);
10085     if (CondICE.isInvalid())
10086       return ExprError();
10087     CondExpr = CondICE.take();
10088     CondIsTrue = condEval.getZExtValue();
10089 
10090     // If the condition is > zero, then the AST type is the same as the LSHExpr.
10091     Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
10092 
10093     resType = ActiveExpr->getType();
10094     ValueDependent = ActiveExpr->isValueDependent();
10095     VK = ActiveExpr->getValueKind();
10096     OK = ActiveExpr->getObjectKind();
10097   }
10098 
10099   return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
10100                                         resType, VK, OK, RPLoc, CondIsTrue,
10101                                         resType->isDependentType(),
10102                                         ValueDependent));
10103 }
10104 
10105 //===----------------------------------------------------------------------===//
10106 // Clang Extensions.
10107 //===----------------------------------------------------------------------===//
10108 
10109 /// ActOnBlockStart - This callback is invoked when a block literal is started.
10110 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
10111   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
10112 
10113   if (LangOpts.CPlusPlus) {
10114     Decl *ManglingContextDecl;
10115     if (MangleNumberingContext *MCtx =
10116             getCurrentMangleNumberContext(Block->getDeclContext(),
10117                                           ManglingContextDecl)) {
10118       unsigned ManglingNumber = MCtx->getManglingNumber(Block);
10119       Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
10120     }
10121   }
10122 
10123   PushBlockScope(CurScope, Block);
10124   CurContext->addDecl(Block);
10125   if (CurScope)
10126     PushDeclContext(CurScope, Block);
10127   else
10128     CurContext = Block;
10129 
10130   getCurBlock()->HasImplicitReturnType = true;
10131 
10132   // Enter a new evaluation context to insulate the block from any
10133   // cleanups from the enclosing full-expression.
10134   PushExpressionEvaluationContext(PotentiallyEvaluated);
10135 }
10136 
10137 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
10138                                Scope *CurScope) {
10139   assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
10140   assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
10141   BlockScopeInfo *CurBlock = getCurBlock();
10142 
10143   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
10144   QualType T = Sig->getType();
10145 
10146   // FIXME: We should allow unexpanded parameter packs here, but that would,
10147   // in turn, make the block expression contain unexpanded parameter packs.
10148   if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
10149     // Drop the parameters.
10150     FunctionProtoType::ExtProtoInfo EPI;
10151     EPI.HasTrailingReturn = false;
10152     EPI.TypeQuals |= DeclSpec::TQ_const;
10153     T = Context.getFunctionType(Context.DependentTy, None, EPI);
10154     Sig = Context.getTrivialTypeSourceInfo(T);
10155   }
10156 
10157   // GetTypeForDeclarator always produces a function type for a block
10158   // literal signature.  Furthermore, it is always a FunctionProtoType
10159   // unless the function was written with a typedef.
10160   assert(T->isFunctionType() &&
10161          "GetTypeForDeclarator made a non-function block signature");
10162 
10163   // Look for an explicit signature in that function type.
10164   FunctionProtoTypeLoc ExplicitSignature;
10165 
10166   TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
10167   if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) {
10168 
10169     // Check whether that explicit signature was synthesized by
10170     // GetTypeForDeclarator.  If so, don't save that as part of the
10171     // written signature.
10172     if (ExplicitSignature.getLocalRangeBegin() ==
10173         ExplicitSignature.getLocalRangeEnd()) {
10174       // This would be much cheaper if we stored TypeLocs instead of
10175       // TypeSourceInfos.
10176       TypeLoc Result = ExplicitSignature.getResultLoc();
10177       unsigned Size = Result.getFullDataSize();
10178       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
10179       Sig->getTypeLoc().initializeFullCopy(Result, Size);
10180 
10181       ExplicitSignature = FunctionProtoTypeLoc();
10182     }
10183   }
10184 
10185   CurBlock->TheDecl->setSignatureAsWritten(Sig);
10186   CurBlock->FunctionType = T;
10187 
10188   const FunctionType *Fn = T->getAs<FunctionType>();
10189   QualType RetTy = Fn->getResultType();
10190   bool isVariadic =
10191     (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
10192 
10193   CurBlock->TheDecl->setIsVariadic(isVariadic);
10194 
10195   // Context.DependentTy is used as a placeholder for a missing block
10196   // return type.  TODO:  what should we do with declarators like:
10197   //   ^ * { ... }
10198   // If the answer is "apply template argument deduction"....
10199   if (RetTy != Context.DependentTy) {
10200     CurBlock->ReturnType = RetTy;
10201     CurBlock->TheDecl->setBlockMissingReturnType(false);
10202     CurBlock->HasImplicitReturnType = false;
10203   }
10204 
10205   // Push block parameters from the declarator if we had them.
10206   SmallVector<ParmVarDecl*, 8> Params;
10207   if (ExplicitSignature) {
10208     for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
10209       ParmVarDecl *Param = ExplicitSignature.getArg(I);
10210       if (Param->getIdentifier() == 0 &&
10211           !Param->isImplicit() &&
10212           !Param->isInvalidDecl() &&
10213           !getLangOpts().CPlusPlus)
10214         Diag(Param->getLocation(), diag::err_parameter_name_omitted);
10215       Params.push_back(Param);
10216     }
10217 
10218   // Fake up parameter variables if we have a typedef, like
10219   //   ^ fntype { ... }
10220   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
10221     for (FunctionProtoType::arg_type_iterator
10222            I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
10223       ParmVarDecl *Param =
10224         BuildParmVarDeclForTypedef(CurBlock->TheDecl,
10225                                    ParamInfo.getLocStart(),
10226                                    *I);
10227       Params.push_back(Param);
10228     }
10229   }
10230 
10231   // Set the parameters on the block decl.
10232   if (!Params.empty()) {
10233     CurBlock->TheDecl->setParams(Params);
10234     CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
10235                              CurBlock->TheDecl->param_end(),
10236                              /*CheckParameterNames=*/false);
10237   }
10238 
10239   // Finally we can process decl attributes.
10240   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
10241 
10242   // Put the parameter variables in scope.
10243   for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
10244          E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
10245     (*AI)->setOwningFunction(CurBlock->TheDecl);
10246 
10247     // If this has an identifier, add it to the scope stack.
10248     if ((*AI)->getIdentifier()) {
10249       CheckShadow(CurBlock->TheScope, *AI);
10250 
10251       PushOnScopeChains(*AI, CurBlock->TheScope);
10252     }
10253   }
10254 }
10255 
10256 /// ActOnBlockError - If there is an error parsing a block, this callback
10257 /// is invoked to pop the information about the block from the action impl.
10258 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
10259   // Leave the expression-evaluation context.
10260   DiscardCleanupsInEvaluationContext();
10261   PopExpressionEvaluationContext();
10262 
10263   // Pop off CurBlock, handle nested blocks.
10264   PopDeclContext();
10265   PopFunctionScopeInfo();
10266 }
10267 
10268 /// ActOnBlockStmtExpr - This is called when the body of a block statement
10269 /// literal was successfully completed.  ^(int x){...}
10270 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
10271                                     Stmt *Body, Scope *CurScope) {
10272   // If blocks are disabled, emit an error.
10273   if (!LangOpts.Blocks)
10274     Diag(CaretLoc, diag::err_blocks_disable);
10275 
10276   // Leave the expression-evaluation context.
10277   if (hasAnyUnrecoverableErrorsInThisFunction())
10278     DiscardCleanupsInEvaluationContext();
10279   assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!");
10280   PopExpressionEvaluationContext();
10281 
10282   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
10283 
10284   if (BSI->HasImplicitReturnType)
10285     deduceClosureReturnType(*BSI);
10286 
10287   PopDeclContext();
10288 
10289   QualType RetTy = Context.VoidTy;
10290   if (!BSI->ReturnType.isNull())
10291     RetTy = BSI->ReturnType;
10292 
10293   bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
10294   QualType BlockTy;
10295 
10296   // Set the captured variables on the block.
10297   // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
10298   SmallVector<BlockDecl::Capture, 4> Captures;
10299   for (unsigned i = 0, e = BSI->Captures.size(); i != e; i++) {
10300     CapturingScopeInfo::Capture &Cap = BSI->Captures[i];
10301     if (Cap.isThisCapture())
10302       continue;
10303     BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
10304                               Cap.isNested(), Cap.getInitExpr());
10305     Captures.push_back(NewCap);
10306   }
10307   BSI->TheDecl->setCaptures(Context, Captures.begin(), Captures.end(),
10308                             BSI->CXXThisCaptureIndex != 0);
10309 
10310   // If the user wrote a function type in some form, try to use that.
10311   if (!BSI->FunctionType.isNull()) {
10312     const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
10313 
10314     FunctionType::ExtInfo Ext = FTy->getExtInfo();
10315     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
10316 
10317     // Turn protoless block types into nullary block types.
10318     if (isa<FunctionNoProtoType>(FTy)) {
10319       FunctionProtoType::ExtProtoInfo EPI;
10320       EPI.ExtInfo = Ext;
10321       BlockTy = Context.getFunctionType(RetTy, None, EPI);
10322 
10323     // Otherwise, if we don't need to change anything about the function type,
10324     // preserve its sugar structure.
10325     } else if (FTy->getResultType() == RetTy &&
10326                (!NoReturn || FTy->getNoReturnAttr())) {
10327       BlockTy = BSI->FunctionType;
10328 
10329     // Otherwise, make the minimal modifications to the function type.
10330     } else {
10331       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
10332       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10333       EPI.TypeQuals = 0; // FIXME: silently?
10334       EPI.ExtInfo = Ext;
10335       BlockTy = Context.getFunctionType(RetTy, FPT->getArgTypes(), EPI);
10336     }
10337 
10338   // If we don't have a function type, just build one from nothing.
10339   } else {
10340     FunctionProtoType::ExtProtoInfo EPI;
10341     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
10342     BlockTy = Context.getFunctionType(RetTy, None, EPI);
10343   }
10344 
10345   DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
10346                            BSI->TheDecl->param_end());
10347   BlockTy = Context.getBlockPointerType(BlockTy);
10348 
10349   // If needed, diagnose invalid gotos and switches in the block.
10350   if (getCurFunction()->NeedsScopeChecking() &&
10351       !hasAnyUnrecoverableErrorsInThisFunction() &&
10352       !PP.isCodeCompletionEnabled())
10353     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
10354 
10355   BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
10356 
10357   // Try to apply the named return value optimization. We have to check again
10358   // if we can do this, though, because blocks keep return statements around
10359   // to deduce an implicit return type.
10360   if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
10361       !BSI->TheDecl->isDependentContext())
10362     computeNRVO(Body, getCurBlock());
10363 
10364   BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
10365   AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
10366   PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
10367 
10368   // If the block isn't obviously global, i.e. it captures anything at
10369   // all, then we need to do a few things in the surrounding context:
10370   if (Result->getBlockDecl()->hasCaptures()) {
10371     // First, this expression has a new cleanup object.
10372     ExprCleanupObjects.push_back(Result->getBlockDecl());
10373     ExprNeedsCleanups = true;
10374 
10375     // It also gets a branch-protected scope if any of the captured
10376     // variables needs destruction.
10377     for (BlockDecl::capture_const_iterator
10378            ci = Result->getBlockDecl()->capture_begin(),
10379            ce = Result->getBlockDecl()->capture_end(); ci != ce; ++ci) {
10380       const VarDecl *var = ci->getVariable();
10381       if (var->getType().isDestructedType() != QualType::DK_none) {
10382         getCurFunction()->setHasBranchProtectedScope();
10383         break;
10384       }
10385     }
10386   }
10387 
10388   return Owned(Result);
10389 }
10390 
10391 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
10392                                         Expr *E, ParsedType Ty,
10393                                         SourceLocation RPLoc) {
10394   TypeSourceInfo *TInfo;
10395   GetTypeFromParser(Ty, &TInfo);
10396   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
10397 }
10398 
10399 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
10400                                 Expr *E, TypeSourceInfo *TInfo,
10401                                 SourceLocation RPLoc) {
10402   Expr *OrigExpr = E;
10403 
10404   // Get the va_list type
10405   QualType VaListType = Context.getBuiltinVaListType();
10406   if (VaListType->isArrayType()) {
10407     // Deal with implicit array decay; for example, on x86-64,
10408     // va_list is an array, but it's supposed to decay to
10409     // a pointer for va_arg.
10410     VaListType = Context.getArrayDecayedType(VaListType);
10411     // Make sure the input expression also decays appropriately.
10412     ExprResult Result = UsualUnaryConversions(E);
10413     if (Result.isInvalid())
10414       return ExprError();
10415     E = Result.take();
10416   } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
10417     // If va_list is a record type and we are compiling in C++ mode,
10418     // check the argument using reference binding.
10419     InitializedEntity Entity
10420       = InitializedEntity::InitializeParameter(Context,
10421           Context.getLValueReferenceType(VaListType), false);
10422     ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
10423     if (Init.isInvalid())
10424       return ExprError();
10425     E = Init.takeAs<Expr>();
10426   } else {
10427     // Otherwise, the va_list argument must be an l-value because
10428     // it is modified by va_arg.
10429     if (!E->isTypeDependent() &&
10430         CheckForModifiableLvalue(E, BuiltinLoc, *this))
10431       return ExprError();
10432   }
10433 
10434   if (!E->isTypeDependent() &&
10435       !Context.hasSameType(VaListType, E->getType())) {
10436     return ExprError(Diag(E->getLocStart(),
10437                          diag::err_first_argument_to_va_arg_not_of_type_va_list)
10438       << OrigExpr->getType() << E->getSourceRange());
10439   }
10440 
10441   if (!TInfo->getType()->isDependentType()) {
10442     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
10443                             diag::err_second_parameter_to_va_arg_incomplete,
10444                             TInfo->getTypeLoc()))
10445       return ExprError();
10446 
10447     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
10448                                TInfo->getType(),
10449                                diag::err_second_parameter_to_va_arg_abstract,
10450                                TInfo->getTypeLoc()))
10451       return ExprError();
10452 
10453     if (!TInfo->getType().isPODType(Context)) {
10454       Diag(TInfo->getTypeLoc().getBeginLoc(),
10455            TInfo->getType()->isObjCLifetimeType()
10456              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
10457              : diag::warn_second_parameter_to_va_arg_not_pod)
10458         << TInfo->getType()
10459         << TInfo->getTypeLoc().getSourceRange();
10460     }
10461 
10462     // Check for va_arg where arguments of the given type will be promoted
10463     // (i.e. this va_arg is guaranteed to have undefined behavior).
10464     QualType PromoteType;
10465     if (TInfo->getType()->isPromotableIntegerType()) {
10466       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
10467       if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
10468         PromoteType = QualType();
10469     }
10470     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
10471       PromoteType = Context.DoubleTy;
10472     if (!PromoteType.isNull())
10473       DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
10474                   PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
10475                           << TInfo->getType()
10476                           << PromoteType
10477                           << TInfo->getTypeLoc().getSourceRange());
10478   }
10479 
10480   QualType T = TInfo->getType().getNonLValueExprType(Context);
10481   return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
10482 }
10483 
10484 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
10485   // The type of __null will be int or long, depending on the size of
10486   // pointers on the target.
10487   QualType Ty;
10488   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
10489   if (pw == Context.getTargetInfo().getIntWidth())
10490     Ty = Context.IntTy;
10491   else if (pw == Context.getTargetInfo().getLongWidth())
10492     Ty = Context.LongTy;
10493   else if (pw == Context.getTargetInfo().getLongLongWidth())
10494     Ty = Context.LongLongTy;
10495   else {
10496     llvm_unreachable("I don't know size of pointer!");
10497   }
10498 
10499   return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
10500 }
10501 
10502 static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
10503                                            Expr *SrcExpr, FixItHint &Hint,
10504                                            bool &IsNSString) {
10505   if (!SemaRef.getLangOpts().ObjC1)
10506     return;
10507 
10508   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
10509   if (!PT)
10510     return;
10511 
10512   // Check if the destination is of type 'id'.
10513   if (!PT->isObjCIdType()) {
10514     // Check if the destination is the 'NSString' interface.
10515     const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
10516     if (!ID || !ID->getIdentifier()->isStr("NSString"))
10517       return;
10518     IsNSString = true;
10519   }
10520 
10521   // Ignore any parens, implicit casts (should only be
10522   // array-to-pointer decays), and not-so-opaque values.  The last is
10523   // important for making this trigger for property assignments.
10524   SrcExpr = SrcExpr->IgnoreParenImpCasts();
10525   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
10526     if (OV->getSourceExpr())
10527       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
10528 
10529   StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
10530   if (!SL || !SL->isAscii())
10531     return;
10532 
10533   Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
10534 }
10535 
10536 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
10537                                     SourceLocation Loc,
10538                                     QualType DstType, QualType SrcType,
10539                                     Expr *SrcExpr, AssignmentAction Action,
10540                                     bool *Complained) {
10541   if (Complained)
10542     *Complained = false;
10543 
10544   // Decode the result (notice that AST's are still created for extensions).
10545   bool CheckInferredResultType = false;
10546   bool isInvalid = false;
10547   unsigned DiagKind = 0;
10548   FixItHint Hint;
10549   ConversionFixItGenerator ConvHints;
10550   bool MayHaveConvFixit = false;
10551   bool MayHaveFunctionDiff = false;
10552   bool IsNSString = false;
10553 
10554   switch (ConvTy) {
10555   case Compatible:
10556       DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
10557       return false;
10558 
10559   case PointerToInt:
10560     DiagKind = diag::ext_typecheck_convert_pointer_int;
10561     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
10562     MayHaveConvFixit = true;
10563     break;
10564   case IntToPointer:
10565     DiagKind = diag::ext_typecheck_convert_int_pointer;
10566     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
10567     MayHaveConvFixit = true;
10568     break;
10569   case IncompatiblePointer:
10570     MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint, IsNSString);
10571       DiagKind =
10572         (Action == AA_Passing_CFAudited ?
10573           diag::err_arc_typecheck_convert_incompatible_pointer :
10574           diag::ext_typecheck_convert_incompatible_pointer);
10575     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
10576       SrcType->isObjCObjectPointerType();
10577     if (Hint.isNull() && !CheckInferredResultType) {
10578       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
10579     }
10580     else if (CheckInferredResultType) {
10581       SrcType = SrcType.getUnqualifiedType();
10582       DstType = DstType.getUnqualifiedType();
10583     }
10584     else if (IsNSString && !Hint.isNull())
10585       DiagKind = diag::warn_missing_atsign_prefix;
10586     MayHaveConvFixit = true;
10587     break;
10588   case IncompatiblePointerSign:
10589     DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
10590     break;
10591   case FunctionVoidPointer:
10592     DiagKind = diag::ext_typecheck_convert_pointer_void_func;
10593     break;
10594   case IncompatiblePointerDiscardsQualifiers: {
10595     // Perform array-to-pointer decay if necessary.
10596     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
10597 
10598     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
10599     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
10600     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
10601       DiagKind = diag::err_typecheck_incompatible_address_space;
10602       break;
10603 
10604 
10605     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
10606       DiagKind = diag::err_typecheck_incompatible_ownership;
10607       break;
10608     }
10609 
10610     llvm_unreachable("unknown error case for discarding qualifiers!");
10611     // fallthrough
10612   }
10613   case CompatiblePointerDiscardsQualifiers:
10614     // If the qualifiers lost were because we were applying the
10615     // (deprecated) C++ conversion from a string literal to a char*
10616     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
10617     // Ideally, this check would be performed in
10618     // checkPointerTypesForAssignment. However, that would require a
10619     // bit of refactoring (so that the second argument is an
10620     // expression, rather than a type), which should be done as part
10621     // of a larger effort to fix checkPointerTypesForAssignment for
10622     // C++ semantics.
10623     if (getLangOpts().CPlusPlus &&
10624         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
10625       return false;
10626     DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
10627     break;
10628   case IncompatibleNestedPointerQualifiers:
10629     DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
10630     break;
10631   case IntToBlockPointer:
10632     DiagKind = diag::err_int_to_block_pointer;
10633     break;
10634   case IncompatibleBlockPointer:
10635     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
10636     break;
10637   case IncompatibleObjCQualifiedId:
10638     // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
10639     // it can give a more specific diagnostic.
10640     DiagKind = diag::warn_incompatible_qualified_id;
10641     break;
10642   case IncompatibleVectors:
10643     DiagKind = diag::warn_incompatible_vectors;
10644     break;
10645   case IncompatibleObjCWeakRef:
10646     DiagKind = diag::err_arc_weak_unavailable_assign;
10647     break;
10648   case Incompatible:
10649     DiagKind = diag::err_typecheck_convert_incompatible;
10650     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
10651     MayHaveConvFixit = true;
10652     isInvalid = true;
10653     MayHaveFunctionDiff = true;
10654     break;
10655   }
10656 
10657   QualType FirstType, SecondType;
10658   switch (Action) {
10659   case AA_Assigning:
10660   case AA_Initializing:
10661     // The destination type comes first.
10662     FirstType = DstType;
10663     SecondType = SrcType;
10664     break;
10665 
10666   case AA_Returning:
10667   case AA_Passing:
10668   case AA_Passing_CFAudited:
10669   case AA_Converting:
10670   case AA_Sending:
10671   case AA_Casting:
10672     // The source type comes first.
10673     FirstType = SrcType;
10674     SecondType = DstType;
10675     break;
10676   }
10677 
10678   PartialDiagnostic FDiag = PDiag(DiagKind);
10679   if (Action == AA_Passing_CFAudited)
10680     FDiag << FirstType << SecondType << SrcExpr->getSourceRange();
10681   else
10682     FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
10683 
10684   // If we can fix the conversion, suggest the FixIts.
10685   assert(ConvHints.isNull() || Hint.isNull());
10686   if (!ConvHints.isNull()) {
10687     for (std::vector<FixItHint>::iterator HI = ConvHints.Hints.begin(),
10688          HE = ConvHints.Hints.end(); HI != HE; ++HI)
10689       FDiag << *HI;
10690   } else {
10691     FDiag << Hint;
10692   }
10693   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
10694 
10695   if (MayHaveFunctionDiff)
10696     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
10697 
10698   Diag(Loc, FDiag);
10699 
10700   if (SecondType == Context.OverloadTy)
10701     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
10702                               FirstType);
10703 
10704   if (CheckInferredResultType)
10705     EmitRelatedResultTypeNote(SrcExpr);
10706 
10707   if (Action == AA_Returning && ConvTy == IncompatiblePointer)
10708     EmitRelatedResultTypeNoteForReturn(DstType);
10709 
10710   if (Complained)
10711     *Complained = true;
10712   return isInvalid;
10713 }
10714 
10715 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
10716                                                  llvm::APSInt *Result) {
10717   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
10718   public:
10719     virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
10720       S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
10721     }
10722   } Diagnoser;
10723 
10724   return VerifyIntegerConstantExpression(E, Result, Diagnoser);
10725 }
10726 
10727 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
10728                                                  llvm::APSInt *Result,
10729                                                  unsigned DiagID,
10730                                                  bool AllowFold) {
10731   class IDDiagnoser : public VerifyICEDiagnoser {
10732     unsigned DiagID;
10733 
10734   public:
10735     IDDiagnoser(unsigned DiagID)
10736       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
10737 
10738     virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
10739       S.Diag(Loc, DiagID) << SR;
10740     }
10741   } Diagnoser(DiagID);
10742 
10743   return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
10744 }
10745 
10746 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
10747                                             SourceRange SR) {
10748   S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
10749 }
10750 
10751 ExprResult
10752 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
10753                                       VerifyICEDiagnoser &Diagnoser,
10754                                       bool AllowFold) {
10755   SourceLocation DiagLoc = E->getLocStart();
10756 
10757   if (getLangOpts().CPlusPlus11) {
10758     // C++11 [expr.const]p5:
10759     //   If an expression of literal class type is used in a context where an
10760     //   integral constant expression is required, then that class type shall
10761     //   have a single non-explicit conversion function to an integral or
10762     //   unscoped enumeration type
10763     ExprResult Converted;
10764     class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
10765     public:
10766       CXX11ConvertDiagnoser(bool Silent)
10767           : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
10768                                 Silent, true) {}
10769 
10770       virtual SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
10771                                                    QualType T) {
10772         return S.Diag(Loc, diag::err_ice_not_integral) << T;
10773       }
10774 
10775       virtual SemaDiagnosticBuilder diagnoseIncomplete(
10776           Sema &S, SourceLocation Loc, QualType T) {
10777         return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
10778       }
10779 
10780       virtual SemaDiagnosticBuilder diagnoseExplicitConv(
10781           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) {
10782         return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
10783       }
10784 
10785       virtual SemaDiagnosticBuilder noteExplicitConv(
10786           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) {
10787         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
10788                  << ConvTy->isEnumeralType() << ConvTy;
10789       }
10790 
10791       virtual SemaDiagnosticBuilder diagnoseAmbiguous(
10792           Sema &S, SourceLocation Loc, QualType T) {
10793         return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
10794       }
10795 
10796       virtual SemaDiagnosticBuilder noteAmbiguous(
10797           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) {
10798         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
10799                  << ConvTy->isEnumeralType() << ConvTy;
10800       }
10801 
10802       virtual SemaDiagnosticBuilder diagnoseConversion(
10803           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) {
10804         llvm_unreachable("conversion functions are permitted");
10805       }
10806     } ConvertDiagnoser(Diagnoser.Suppress);
10807 
10808     Converted = PerformContextualImplicitConversion(DiagLoc, E,
10809                                                     ConvertDiagnoser);
10810     if (Converted.isInvalid())
10811       return Converted;
10812     E = Converted.take();
10813     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
10814       return ExprError();
10815   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
10816     // An ICE must be of integral or unscoped enumeration type.
10817     if (!Diagnoser.Suppress)
10818       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
10819     return ExprError();
10820   }
10821 
10822   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
10823   // in the non-ICE case.
10824   if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
10825     if (Result)
10826       *Result = E->EvaluateKnownConstInt(Context);
10827     return Owned(E);
10828   }
10829 
10830   Expr::EvalResult EvalResult;
10831   SmallVector<PartialDiagnosticAt, 8> Notes;
10832   EvalResult.Diag = &Notes;
10833 
10834   // Try to evaluate the expression, and produce diagnostics explaining why it's
10835   // not a constant expression as a side-effect.
10836   bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
10837                 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
10838 
10839   // In C++11, we can rely on diagnostics being produced for any expression
10840   // which is not a constant expression. If no diagnostics were produced, then
10841   // this is a constant expression.
10842   if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
10843     if (Result)
10844       *Result = EvalResult.Val.getInt();
10845     return Owned(E);
10846   }
10847 
10848   // If our only note is the usual "invalid subexpression" note, just point
10849   // the caret at its location rather than producing an essentially
10850   // redundant note.
10851   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
10852         diag::note_invalid_subexpr_in_const_expr) {
10853     DiagLoc = Notes[0].first;
10854     Notes.clear();
10855   }
10856 
10857   if (!Folded || !AllowFold) {
10858     if (!Diagnoser.Suppress) {
10859       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
10860       for (unsigned I = 0, N = Notes.size(); I != N; ++I)
10861         Diag(Notes[I].first, Notes[I].second);
10862     }
10863 
10864     return ExprError();
10865   }
10866 
10867   Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
10868   for (unsigned I = 0, N = Notes.size(); I != N; ++I)
10869     Diag(Notes[I].first, Notes[I].second);
10870 
10871   if (Result)
10872     *Result = EvalResult.Val.getInt();
10873   return Owned(E);
10874 }
10875 
10876 namespace {
10877   // Handle the case where we conclude a expression which we speculatively
10878   // considered to be unevaluated is actually evaluated.
10879   class TransformToPE : public TreeTransform<TransformToPE> {
10880     typedef TreeTransform<TransformToPE> BaseTransform;
10881 
10882   public:
10883     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
10884 
10885     // Make sure we redo semantic analysis
10886     bool AlwaysRebuild() { return true; }
10887 
10888     // Make sure we handle LabelStmts correctly.
10889     // FIXME: This does the right thing, but maybe we need a more general
10890     // fix to TreeTransform?
10891     StmtResult TransformLabelStmt(LabelStmt *S) {
10892       S->getDecl()->setStmt(0);
10893       return BaseTransform::TransformLabelStmt(S);
10894     }
10895 
10896     // We need to special-case DeclRefExprs referring to FieldDecls which
10897     // are not part of a member pointer formation; normal TreeTransforming
10898     // doesn't catch this case because of the way we represent them in the AST.
10899     // FIXME: This is a bit ugly; is it really the best way to handle this
10900     // case?
10901     //
10902     // Error on DeclRefExprs referring to FieldDecls.
10903     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
10904       if (isa<FieldDecl>(E->getDecl()) &&
10905           !SemaRef.isUnevaluatedContext())
10906         return SemaRef.Diag(E->getLocation(),
10907                             diag::err_invalid_non_static_member_use)
10908             << E->getDecl() << E->getSourceRange();
10909 
10910       return BaseTransform::TransformDeclRefExpr(E);
10911     }
10912 
10913     // Exception: filter out member pointer formation
10914     ExprResult TransformUnaryOperator(UnaryOperator *E) {
10915       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
10916         return E;
10917 
10918       return BaseTransform::TransformUnaryOperator(E);
10919     }
10920 
10921     ExprResult TransformLambdaExpr(LambdaExpr *E) {
10922       // Lambdas never need to be transformed.
10923       return E;
10924     }
10925   };
10926 }
10927 
10928 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
10929   assert(isUnevaluatedContext() &&
10930          "Should only transform unevaluated expressions");
10931   ExprEvalContexts.back().Context =
10932       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
10933   if (isUnevaluatedContext())
10934     return E;
10935   return TransformToPE(*this).TransformExpr(E);
10936 }
10937 
10938 void
10939 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
10940                                       Decl *LambdaContextDecl,
10941                                       bool IsDecltype) {
10942   ExprEvalContexts.push_back(
10943              ExpressionEvaluationContextRecord(NewContext,
10944                                                ExprCleanupObjects.size(),
10945                                                ExprNeedsCleanups,
10946                                                LambdaContextDecl,
10947                                                IsDecltype));
10948   ExprNeedsCleanups = false;
10949   if (!MaybeODRUseExprs.empty())
10950     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
10951 }
10952 
10953 void
10954 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
10955                                       ReuseLambdaContextDecl_t,
10956                                       bool IsDecltype) {
10957   Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
10958   PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype);
10959 }
10960 
10961 void Sema::PopExpressionEvaluationContext() {
10962   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
10963 
10964   if (!Rec.Lambdas.empty()) {
10965     if (Rec.isUnevaluated()) {
10966       // C++11 [expr.prim.lambda]p2:
10967       //   A lambda-expression shall not appear in an unevaluated operand
10968       //   (Clause 5).
10969       for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I)
10970         Diag(Rec.Lambdas[I]->getLocStart(),
10971              diag::err_lambda_unevaluated_operand);
10972     } else {
10973       // Mark the capture expressions odr-used. This was deferred
10974       // during lambda expression creation.
10975       for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I) {
10976         LambdaExpr *Lambda = Rec.Lambdas[I];
10977         for (LambdaExpr::capture_init_iterator
10978                   C = Lambda->capture_init_begin(),
10979                CEnd = Lambda->capture_init_end();
10980              C != CEnd; ++C) {
10981           MarkDeclarationsReferencedInExpr(*C);
10982         }
10983       }
10984     }
10985   }
10986 
10987   // When are coming out of an unevaluated context, clear out any
10988   // temporaries that we may have created as part of the evaluation of
10989   // the expression in that context: they aren't relevant because they
10990   // will never be constructed.
10991   if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) {
10992     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
10993                              ExprCleanupObjects.end());
10994     ExprNeedsCleanups = Rec.ParentNeedsCleanups;
10995     CleanupVarDeclMarking();
10996     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
10997   // Otherwise, merge the contexts together.
10998   } else {
10999     ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
11000     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
11001                             Rec.SavedMaybeODRUseExprs.end());
11002   }
11003 
11004   // Pop the current expression evaluation context off the stack.
11005   ExprEvalContexts.pop_back();
11006 }
11007 
11008 void Sema::DiscardCleanupsInEvaluationContext() {
11009   ExprCleanupObjects.erase(
11010          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
11011          ExprCleanupObjects.end());
11012   ExprNeedsCleanups = false;
11013   MaybeODRUseExprs.clear();
11014 }
11015 
11016 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
11017   if (!E->getType()->isVariablyModifiedType())
11018     return E;
11019   return TransformToPotentiallyEvaluated(E);
11020 }
11021 
11022 static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) {
11023   // Do not mark anything as "used" within a dependent context; wait for
11024   // an instantiation.
11025   if (SemaRef.CurContext->isDependentContext())
11026     return false;
11027 
11028   switch (SemaRef.ExprEvalContexts.back().Context) {
11029     case Sema::Unevaluated:
11030     case Sema::UnevaluatedAbstract:
11031       // We are in an expression that is not potentially evaluated; do nothing.
11032       // (Depending on how you read the standard, we actually do need to do
11033       // something here for null pointer constants, but the standard's
11034       // definition of a null pointer constant is completely crazy.)
11035       return false;
11036 
11037     case Sema::ConstantEvaluated:
11038     case Sema::PotentiallyEvaluated:
11039       // We are in a potentially evaluated expression (or a constant-expression
11040       // in C++03); we need to do implicit template instantiation, implicitly
11041       // define class members, and mark most declarations as used.
11042       return true;
11043 
11044     case Sema::PotentiallyEvaluatedIfUsed:
11045       // Referenced declarations will only be used if the construct in the
11046       // containing expression is used.
11047       return false;
11048   }
11049   llvm_unreachable("Invalid context");
11050 }
11051 
11052 /// \brief Mark a function referenced, and check whether it is odr-used
11053 /// (C++ [basic.def.odr]p2, C99 6.9p3)
11054 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func) {
11055   assert(Func && "No function?");
11056 
11057   Func->setReferenced();
11058 
11059   // C++11 [basic.def.odr]p3:
11060   //   A function whose name appears as a potentially-evaluated expression is
11061   //   odr-used if it is the unique lookup result or the selected member of a
11062   //   set of overloaded functions [...].
11063   //
11064   // We (incorrectly) mark overload resolution as an unevaluated context, so we
11065   // can just check that here. Skip the rest of this function if we've already
11066   // marked the function as used.
11067   if (Func->isUsed(false) || !IsPotentiallyEvaluatedContext(*this)) {
11068     // C++11 [temp.inst]p3:
11069     //   Unless a function template specialization has been explicitly
11070     //   instantiated or explicitly specialized, the function template
11071     //   specialization is implicitly instantiated when the specialization is
11072     //   referenced in a context that requires a function definition to exist.
11073     //
11074     // We consider constexpr function templates to be referenced in a context
11075     // that requires a definition to exist whenever they are referenced.
11076     //
11077     // FIXME: This instantiates constexpr functions too frequently. If this is
11078     // really an unevaluated context (and we're not just in the definition of a
11079     // function template or overload resolution or other cases which we
11080     // incorrectly consider to be unevaluated contexts), and we're not in a
11081     // subexpression which we actually need to evaluate (for instance, a
11082     // template argument, array bound or an expression in a braced-init-list),
11083     // we are not permitted to instantiate this constexpr function definition.
11084     //
11085     // FIXME: This also implicitly defines special members too frequently. They
11086     // are only supposed to be implicitly defined if they are odr-used, but they
11087     // are not odr-used from constant expressions in unevaluated contexts.
11088     // However, they cannot be referenced if they are deleted, and they are
11089     // deleted whenever the implicit definition of the special member would
11090     // fail.
11091     if (!Func->isConstexpr() || Func->getBody())
11092       return;
11093     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
11094     if (!Func->isImplicitlyInstantiable() && (!MD || MD->isUserProvided()))
11095       return;
11096   }
11097 
11098   // Note that this declaration has been used.
11099   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
11100     if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
11101       if (Constructor->isDefaultConstructor()) {
11102         if (Constructor->isTrivial())
11103           return;
11104         if (!Constructor->isUsed(false))
11105           DefineImplicitDefaultConstructor(Loc, Constructor);
11106       } else if (Constructor->isCopyConstructor()) {
11107         if (!Constructor->isUsed(false))
11108           DefineImplicitCopyConstructor(Loc, Constructor);
11109       } else if (Constructor->isMoveConstructor()) {
11110         if (!Constructor->isUsed(false))
11111           DefineImplicitMoveConstructor(Loc, Constructor);
11112       }
11113     } else if (Constructor->getInheritedConstructor()) {
11114       if (!Constructor->isUsed(false))
11115         DefineInheritingConstructor(Loc, Constructor);
11116     }
11117 
11118     MarkVTableUsed(Loc, Constructor->getParent());
11119   } else if (CXXDestructorDecl *Destructor =
11120                  dyn_cast<CXXDestructorDecl>(Func)) {
11121     if (Destructor->isDefaulted() && !Destructor->isDeleted() &&
11122         !Destructor->isUsed(false))
11123       DefineImplicitDestructor(Loc, Destructor);
11124     if (Destructor->isVirtual())
11125       MarkVTableUsed(Loc, Destructor->getParent());
11126   } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
11127     if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted() &&
11128         MethodDecl->isOverloadedOperator() &&
11129         MethodDecl->getOverloadedOperator() == OO_Equal) {
11130       if (!MethodDecl->isUsed(false)) {
11131         if (MethodDecl->isCopyAssignmentOperator())
11132           DefineImplicitCopyAssignment(Loc, MethodDecl);
11133         else
11134           DefineImplicitMoveAssignment(Loc, MethodDecl);
11135       }
11136     } else if (isa<CXXConversionDecl>(MethodDecl) &&
11137                MethodDecl->getParent()->isLambda()) {
11138       CXXConversionDecl *Conversion = cast<CXXConversionDecl>(MethodDecl);
11139       if (Conversion->isLambdaToBlockPointerConversion())
11140         DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
11141       else
11142         DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
11143     } else if (MethodDecl->isVirtual())
11144       MarkVTableUsed(Loc, MethodDecl->getParent());
11145   }
11146 
11147   // Recursive functions should be marked when used from another function.
11148   // FIXME: Is this really right?
11149   if (CurContext == Func) return;
11150 
11151   // Resolve the exception specification for any function which is
11152   // used: CodeGen will need it.
11153   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
11154   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
11155     ResolveExceptionSpec(Loc, FPT);
11156 
11157   // Implicit instantiation of function templates and member functions of
11158   // class templates.
11159   if (Func->isImplicitlyInstantiable()) {
11160     bool AlreadyInstantiated = false;
11161     SourceLocation PointOfInstantiation = Loc;
11162     if (FunctionTemplateSpecializationInfo *SpecInfo
11163                               = Func->getTemplateSpecializationInfo()) {
11164       if (SpecInfo->getPointOfInstantiation().isInvalid())
11165         SpecInfo->setPointOfInstantiation(Loc);
11166       else if (SpecInfo->getTemplateSpecializationKind()
11167                  == TSK_ImplicitInstantiation) {
11168         AlreadyInstantiated = true;
11169         PointOfInstantiation = SpecInfo->getPointOfInstantiation();
11170       }
11171     } else if (MemberSpecializationInfo *MSInfo
11172                                 = Func->getMemberSpecializationInfo()) {
11173       if (MSInfo->getPointOfInstantiation().isInvalid())
11174         MSInfo->setPointOfInstantiation(Loc);
11175       else if (MSInfo->getTemplateSpecializationKind()
11176                  == TSK_ImplicitInstantiation) {
11177         AlreadyInstantiated = true;
11178         PointOfInstantiation = MSInfo->getPointOfInstantiation();
11179       }
11180     }
11181 
11182     if (!AlreadyInstantiated || Func->isConstexpr()) {
11183       if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
11184           cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
11185           ActiveTemplateInstantiations.size())
11186         PendingLocalImplicitInstantiations.push_back(
11187             std::make_pair(Func, PointOfInstantiation));
11188       else if (Func->isConstexpr())
11189         // Do not defer instantiations of constexpr functions, to avoid the
11190         // expression evaluator needing to call back into Sema if it sees a
11191         // call to such a function.
11192         InstantiateFunctionDefinition(PointOfInstantiation, Func);
11193       else {
11194         PendingInstantiations.push_back(std::make_pair(Func,
11195                                                        PointOfInstantiation));
11196         // Notify the consumer that a function was implicitly instantiated.
11197         Consumer.HandleCXXImplicitFunctionInstantiation(Func);
11198       }
11199     }
11200   } else {
11201     // Walk redefinitions, as some of them may be instantiable.
11202     for (FunctionDecl::redecl_iterator i(Func->redecls_begin()),
11203          e(Func->redecls_end()); i != e; ++i) {
11204       if (!i->isUsed(false) && i->isImplicitlyInstantiable())
11205         MarkFunctionReferenced(Loc, *i);
11206     }
11207   }
11208 
11209   // Keep track of used but undefined functions.
11210   if (!Func->isDefined()) {
11211     if (mightHaveNonExternalLinkage(Func))
11212       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
11213     else if (Func->getMostRecentDecl()->isInlined() &&
11214              (LangOpts.CPlusPlus || !LangOpts.GNUInline) &&
11215              !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
11216       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
11217   }
11218 
11219   // Normally the most current decl is marked used while processing the use and
11220   // any subsequent decls are marked used by decl merging. This fails with
11221   // template instantiation since marking can happen at the end of the file
11222   // and, because of the two phase lookup, this function is called with at
11223   // decl in the middle of a decl chain. We loop to maintain the invariant
11224   // that once a decl is used, all decls after it are also used.
11225   for (FunctionDecl *F = Func->getMostRecentDecl();; F = F->getPreviousDecl()) {
11226     F->markUsed(Context);
11227     if (F == Func)
11228       break;
11229   }
11230 }
11231 
11232 static void
11233 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
11234                                    VarDecl *var, DeclContext *DC) {
11235   DeclContext *VarDC = var->getDeclContext();
11236 
11237   //  If the parameter still belongs to the translation unit, then
11238   //  we're actually just using one parameter in the declaration of
11239   //  the next.
11240   if (isa<ParmVarDecl>(var) &&
11241       isa<TranslationUnitDecl>(VarDC))
11242     return;
11243 
11244   // For C code, don't diagnose about capture if we're not actually in code
11245   // right now; it's impossible to write a non-constant expression outside of
11246   // function context, so we'll get other (more useful) diagnostics later.
11247   //
11248   // For C++, things get a bit more nasty... it would be nice to suppress this
11249   // diagnostic for certain cases like using a local variable in an array bound
11250   // for a member of a local class, but the correct predicate is not obvious.
11251   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
11252     return;
11253 
11254   if (isa<CXXMethodDecl>(VarDC) &&
11255       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
11256     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda)
11257       << var->getIdentifier();
11258   } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) {
11259     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
11260       << var->getIdentifier() << fn->getDeclName();
11261   } else if (isa<BlockDecl>(VarDC)) {
11262     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block)
11263       << var->getIdentifier();
11264   } else {
11265     // FIXME: Is there any other context where a local variable can be
11266     // declared?
11267     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context)
11268       << var->getIdentifier();
11269   }
11270 
11271   S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
11272     << var->getIdentifier();
11273 
11274   // FIXME: Add additional diagnostic info about class etc. which prevents
11275   // capture.
11276 }
11277 
11278 
11279 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
11280                                       bool &SubCapturesAreNested,
11281                                       QualType &CaptureType,
11282                                       QualType &DeclRefType) {
11283    // Check whether we've already captured it.
11284   if (CSI->CaptureMap.count(Var)) {
11285     // If we found a capture, any subcaptures are nested.
11286     SubCapturesAreNested = true;
11287 
11288     // Retrieve the capture type for this variable.
11289     CaptureType = CSI->getCapture(Var).getCaptureType();
11290 
11291     // Compute the type of an expression that refers to this variable.
11292     DeclRefType = CaptureType.getNonReferenceType();
11293 
11294     const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var);
11295     if (Cap.isCopyCapture() &&
11296         !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable))
11297       DeclRefType.addConst();
11298     return true;
11299   }
11300   return false;
11301 }
11302 
11303 // Only block literals, captured statements, and lambda expressions can
11304 // capture; other scopes don't work.
11305 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
11306                                  SourceLocation Loc,
11307                                  const bool Diagnose, Sema &S) {
11308   if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC))
11309     return DC->getParent();
11310   else if (isa<CXXMethodDecl>(DC) &&
11311                 cast<CXXMethodDecl>(DC)->getOverloadedOperator() == OO_Call &&
11312                 cast<CXXRecordDecl>(DC->getParent())->isLambda())
11313     return DC->getParent()->getParent();
11314   else {
11315     if (Diagnose)
11316        diagnoseUncapturableValueReference(S, Loc, Var, DC);
11317   }
11318   return 0;
11319 }
11320 
11321 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
11322 // certain types of variables (unnamed, variably modified types etc.)
11323 // so check for eligibility.
11324 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
11325                                  SourceLocation Loc,
11326                                  const bool Diagnose, Sema &S) {
11327 
11328   bool IsBlock = isa<BlockScopeInfo>(CSI);
11329   bool IsLambda = isa<LambdaScopeInfo>(CSI);
11330 
11331   // Lambdas are not allowed to capture unnamed variables
11332   // (e.g. anonymous unions).
11333   // FIXME: The C++11 rule don't actually state this explicitly, but I'm
11334   // assuming that's the intent.
11335   if (IsLambda && !Var->getDeclName()) {
11336     if (Diagnose) {
11337       S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
11338       S.Diag(Var->getLocation(), diag::note_declared_at);
11339     }
11340     return false;
11341   }
11342 
11343   // Prohibit variably-modified types; they're difficult to deal with.
11344   if (Var->getType()->isVariablyModifiedType()) {
11345     if (Diagnose) {
11346       if (IsBlock)
11347         S.Diag(Loc, diag::err_ref_vm_type);
11348       else
11349         S.Diag(Loc, diag::err_lambda_capture_vm_type) << Var->getDeclName();
11350       S.Diag(Var->getLocation(), diag::note_previous_decl)
11351         << Var->getDeclName();
11352     }
11353     return false;
11354   }
11355   // Prohibit structs with flexible array members too.
11356   // We cannot capture what is in the tail end of the struct.
11357   if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
11358     if (VTTy->getDecl()->hasFlexibleArrayMember()) {
11359       if (Diagnose) {
11360         if (IsBlock)
11361           S.Diag(Loc, diag::err_ref_flexarray_type);
11362         else
11363           S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
11364             << Var->getDeclName();
11365         S.Diag(Var->getLocation(), diag::note_previous_decl)
11366           << Var->getDeclName();
11367       }
11368       return false;
11369     }
11370   }
11371   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
11372   // Lambdas and captured statements are not allowed to capture __block
11373   // variables; they don't support the expected semantics.
11374   if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
11375     if (Diagnose) {
11376       S.Diag(Loc, diag::err_capture_block_variable)
11377         << Var->getDeclName() << !IsLambda;
11378       S.Diag(Var->getLocation(), diag::note_previous_decl)
11379         << Var->getDeclName();
11380     }
11381     return false;
11382   }
11383 
11384   return true;
11385 }
11386 
11387 // Returns true if the capture by block was successful.
11388 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
11389                                  SourceLocation Loc,
11390                                  const bool BuildAndDiagnose,
11391                                  QualType &CaptureType,
11392                                  QualType &DeclRefType,
11393                                  const bool Nested,
11394                                  Sema &S) {
11395   Expr *CopyExpr = 0;
11396   bool ByRef = false;
11397 
11398   // Blocks are not allowed to capture arrays.
11399   if (CaptureType->isArrayType()) {
11400     if (BuildAndDiagnose) {
11401       S.Diag(Loc, diag::err_ref_array_type);
11402       S.Diag(Var->getLocation(), diag::note_previous_decl)
11403       << Var->getDeclName();
11404     }
11405     return false;
11406   }
11407 
11408   // Forbid the block-capture of autoreleasing variables.
11409   if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
11410     if (BuildAndDiagnose) {
11411       S.Diag(Loc, diag::err_arc_autoreleasing_capture)
11412         << /*block*/ 0;
11413       S.Diag(Var->getLocation(), diag::note_previous_decl)
11414         << Var->getDeclName();
11415     }
11416     return false;
11417   }
11418   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
11419   if (HasBlocksAttr || CaptureType->isReferenceType()) {
11420     // Block capture by reference does not change the capture or
11421     // declaration reference types.
11422     ByRef = true;
11423   } else {
11424     // Block capture by copy introduces 'const'.
11425     CaptureType = CaptureType.getNonReferenceType().withConst();
11426     DeclRefType = CaptureType;
11427 
11428     if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) {
11429       if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
11430         // The capture logic needs the destructor, so make sure we mark it.
11431         // Usually this is unnecessary because most local variables have
11432         // their destructors marked at declaration time, but parameters are
11433         // an exception because it's technically only the call site that
11434         // actually requires the destructor.
11435         if (isa<ParmVarDecl>(Var))
11436           S.FinalizeVarWithDestructor(Var, Record);
11437 
11438         // Enter a new evaluation context to insulate the copy
11439         // full-expression.
11440         EnterExpressionEvaluationContext scope(S, S.PotentiallyEvaluated);
11441 
11442         // According to the blocks spec, the capture of a variable from
11443         // the stack requires a const copy constructor.  This is not true
11444         // of the copy/move done to move a __block variable to the heap.
11445         Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested,
11446                                                   DeclRefType.withConst(),
11447                                                   VK_LValue, Loc);
11448 
11449         ExprResult Result
11450           = S.PerformCopyInitialization(
11451               InitializedEntity::InitializeBlock(Var->getLocation(),
11452                                                   CaptureType, false),
11453               Loc, S.Owned(DeclRef));
11454 
11455         // Build a full-expression copy expression if initialization
11456         // succeeded and used a non-trivial constructor.  Recover from
11457         // errors by pretending that the copy isn't necessary.
11458         if (!Result.isInvalid() &&
11459             !cast<CXXConstructExpr>(Result.get())->getConstructor()
11460                 ->isTrivial()) {
11461           Result = S.MaybeCreateExprWithCleanups(Result);
11462           CopyExpr = Result.take();
11463         }
11464       }
11465     }
11466   }
11467 
11468   // Actually capture the variable.
11469   if (BuildAndDiagnose)
11470     BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
11471                     SourceLocation(), CaptureType, CopyExpr);
11472 
11473   return true;
11474 
11475 }
11476 
11477 
11478 /// \brief Capture the given variable in the captured region.
11479 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
11480                                     VarDecl *Var,
11481                                     SourceLocation Loc,
11482                                     const bool BuildAndDiagnose,
11483                                     QualType &CaptureType,
11484                                     QualType &DeclRefType,
11485                                     const bool RefersToEnclosingLocal,
11486                                     Sema &S) {
11487 
11488   // By default, capture variables by reference.
11489   bool ByRef = true;
11490   // Using an LValue reference type is consistent with Lambdas (see below).
11491   CaptureType = S.Context.getLValueReferenceType(DeclRefType);
11492   Expr *CopyExpr = 0;
11493   if (BuildAndDiagnose) {
11494     // The current implementation assumes that all variables are captured
11495     // by references. Since there is no capture by copy, no expression evaluation
11496     // will be needed.
11497     //
11498     RecordDecl *RD = RSI->TheRecordDecl;
11499 
11500     FieldDecl *Field
11501       = FieldDecl::Create(S.Context, RD, Loc, Loc, 0, CaptureType,
11502                           S.Context.getTrivialTypeSourceInfo(CaptureType, Loc),
11503                           0, false, ICIS_NoInit);
11504     Field->setImplicit(true);
11505     Field->setAccess(AS_private);
11506     RD->addDecl(Field);
11507 
11508     CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToEnclosingLocal,
11509                                             DeclRefType, VK_LValue, Loc);
11510     Var->setReferenced(true);
11511     Var->markUsed(S.Context);
11512   }
11513 
11514   // Actually capture the variable.
11515   if (BuildAndDiagnose)
11516     RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToEnclosingLocal, Loc,
11517                     SourceLocation(), CaptureType, CopyExpr);
11518 
11519 
11520   return true;
11521 }
11522 
11523 /// \brief Create a field within the lambda class for the variable
11524 ///  being captured.  Handle Array captures.
11525 static ExprResult addAsFieldToClosureType(Sema &S,
11526                                  LambdaScopeInfo *LSI,
11527                                   VarDecl *Var, QualType FieldType,
11528                                   QualType DeclRefType,
11529                                   SourceLocation Loc,
11530                                   bool RefersToEnclosingLocal) {
11531   CXXRecordDecl *Lambda = LSI->Lambda;
11532 
11533   // Build the non-static data member.
11534   FieldDecl *Field
11535     = FieldDecl::Create(S.Context, Lambda, Loc, Loc, 0, FieldType,
11536                         S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
11537                         0, false, ICIS_NoInit);
11538   Field->setImplicit(true);
11539   Field->setAccess(AS_private);
11540   Lambda->addDecl(Field);
11541 
11542   // C++11 [expr.prim.lambda]p21:
11543   //   When the lambda-expression is evaluated, the entities that
11544   //   are captured by copy are used to direct-initialize each
11545   //   corresponding non-static data member of the resulting closure
11546   //   object. (For array members, the array elements are
11547   //   direct-initialized in increasing subscript order.) These
11548   //   initializations are performed in the (unspecified) order in
11549   //   which the non-static data members are declared.
11550 
11551   // Introduce a new evaluation context for the initialization, so
11552   // that temporaries introduced as part of the capture are retained
11553   // to be re-"exported" from the lambda expression itself.
11554   EnterExpressionEvaluationContext scope(S, Sema::PotentiallyEvaluated);
11555 
11556   // C++ [expr.prim.labda]p12:
11557   //   An entity captured by a lambda-expression is odr-used (3.2) in
11558   //   the scope containing the lambda-expression.
11559   Expr *Ref = new (S.Context) DeclRefExpr(Var, RefersToEnclosingLocal,
11560                                           DeclRefType, VK_LValue, Loc);
11561   Var->setReferenced(true);
11562   Var->markUsed(S.Context);
11563 
11564   // When the field has array type, create index variables for each
11565   // dimension of the array. We use these index variables to subscript
11566   // the source array, and other clients (e.g., CodeGen) will perform
11567   // the necessary iteration with these index variables.
11568   SmallVector<VarDecl *, 4> IndexVariables;
11569   QualType BaseType = FieldType;
11570   QualType SizeType = S.Context.getSizeType();
11571   LSI->ArrayIndexStarts.push_back(LSI->ArrayIndexVars.size());
11572   while (const ConstantArrayType *Array
11573                         = S.Context.getAsConstantArrayType(BaseType)) {
11574     // Create the iteration variable for this array index.
11575     IdentifierInfo *IterationVarName = 0;
11576     {
11577       SmallString<8> Str;
11578       llvm::raw_svector_ostream OS(Str);
11579       OS << "__i" << IndexVariables.size();
11580       IterationVarName = &S.Context.Idents.get(OS.str());
11581     }
11582     VarDecl *IterationVar
11583       = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
11584                         IterationVarName, SizeType,
11585                         S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
11586                         SC_None);
11587     IndexVariables.push_back(IterationVar);
11588     LSI->ArrayIndexVars.push_back(IterationVar);
11589 
11590     // Create a reference to the iteration variable.
11591     ExprResult IterationVarRef
11592       = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
11593     assert(!IterationVarRef.isInvalid() &&
11594            "Reference to invented variable cannot fail!");
11595     IterationVarRef = S.DefaultLvalueConversion(IterationVarRef.take());
11596     assert(!IterationVarRef.isInvalid() &&
11597            "Conversion of invented variable cannot fail!");
11598 
11599     // Subscript the array with this iteration variable.
11600     ExprResult Subscript = S.CreateBuiltinArraySubscriptExpr(
11601                              Ref, Loc, IterationVarRef.take(), Loc);
11602     if (Subscript.isInvalid()) {
11603       S.CleanupVarDeclMarking();
11604       S.DiscardCleanupsInEvaluationContext();
11605       return ExprError();
11606     }
11607 
11608     Ref = Subscript.take();
11609     BaseType = Array->getElementType();
11610   }
11611 
11612   // Construct the entity that we will be initializing. For an array, this
11613   // will be first element in the array, which may require several levels
11614   // of array-subscript entities.
11615   SmallVector<InitializedEntity, 4> Entities;
11616   Entities.reserve(1 + IndexVariables.size());
11617   Entities.push_back(
11618     InitializedEntity::InitializeLambdaCapture(Var, Field, Loc));
11619   for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
11620     Entities.push_back(InitializedEntity::InitializeElement(S.Context,
11621                                                             0,
11622                                                             Entities.back()));
11623 
11624   InitializationKind InitKind
11625     = InitializationKind::CreateDirect(Loc, Loc, Loc);
11626   InitializationSequence Init(S, Entities.back(), InitKind, Ref);
11627   ExprResult Result(true);
11628   if (!Init.Diagnose(S, Entities.back(), InitKind, Ref))
11629     Result = Init.Perform(S, Entities.back(), InitKind, Ref);
11630 
11631   // If this initialization requires any cleanups (e.g., due to a
11632   // default argument to a copy constructor), note that for the
11633   // lambda.
11634   if (S.ExprNeedsCleanups)
11635     LSI->ExprNeedsCleanups = true;
11636 
11637   // Exit the expression evaluation context used for the capture.
11638   S.CleanupVarDeclMarking();
11639   S.DiscardCleanupsInEvaluationContext();
11640   return Result;
11641 }
11642 
11643 
11644 
11645 /// \brief Capture the given variable in the lambda.
11646 static bool captureInLambda(LambdaScopeInfo *LSI,
11647                             VarDecl *Var,
11648                             SourceLocation Loc,
11649                             const bool BuildAndDiagnose,
11650                             QualType &CaptureType,
11651                             QualType &DeclRefType,
11652                             const bool RefersToEnclosingLocal,
11653                             const Sema::TryCaptureKind Kind,
11654                             SourceLocation EllipsisLoc,
11655                             const bool IsTopScope,
11656                             Sema &S) {
11657 
11658   // Determine whether we are capturing by reference or by value.
11659   bool ByRef = false;
11660   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
11661     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
11662   } else {
11663     ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
11664   }
11665 
11666   // Compute the type of the field that will capture this variable.
11667   if (ByRef) {
11668     // C++11 [expr.prim.lambda]p15:
11669     //   An entity is captured by reference if it is implicitly or
11670     //   explicitly captured but not captured by copy. It is
11671     //   unspecified whether additional unnamed non-static data
11672     //   members are declared in the closure type for entities
11673     //   captured by reference.
11674     //
11675     // FIXME: It is not clear whether we want to build an lvalue reference
11676     // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
11677     // to do the former, while EDG does the latter. Core issue 1249 will
11678     // clarify, but for now we follow GCC because it's a more permissive and
11679     // easily defensible position.
11680     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
11681   } else {
11682     // C++11 [expr.prim.lambda]p14:
11683     //   For each entity captured by copy, an unnamed non-static
11684     //   data member is declared in the closure type. The
11685     //   declaration order of these members is unspecified. The type
11686     //   of such a data member is the type of the corresponding
11687     //   captured entity if the entity is not a reference to an
11688     //   object, or the referenced type otherwise. [Note: If the
11689     //   captured entity is a reference to a function, the
11690     //   corresponding data member is also a reference to a
11691     //   function. - end note ]
11692     if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
11693       if (!RefType->getPointeeType()->isFunctionType())
11694         CaptureType = RefType->getPointeeType();
11695     }
11696 
11697     // Forbid the lambda copy-capture of autoreleasing variables.
11698     if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
11699       if (BuildAndDiagnose) {
11700         S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
11701         S.Diag(Var->getLocation(), diag::note_previous_decl)
11702           << Var->getDeclName();
11703       }
11704       return false;
11705     }
11706 
11707     if (S.RequireNonAbstractType(Loc, CaptureType,
11708                                  diag::err_capture_of_abstract_type))
11709       return false;
11710   }
11711 
11712   // Capture this variable in the lambda.
11713   Expr *CopyExpr = 0;
11714   if (BuildAndDiagnose) {
11715     ExprResult Result = addAsFieldToClosureType(S, LSI, Var,
11716                                         CaptureType, DeclRefType, Loc,
11717                                         RefersToEnclosingLocal);
11718     if (!Result.isInvalid())
11719       CopyExpr = Result.take();
11720   }
11721 
11722   // Compute the type of a reference to this captured variable.
11723   if (ByRef)
11724     DeclRefType = CaptureType.getNonReferenceType();
11725   else {
11726     // C++ [expr.prim.lambda]p5:
11727     //   The closure type for a lambda-expression has a public inline
11728     //   function call operator [...]. This function call operator is
11729     //   declared const (9.3.1) if and only if the lambda-expression’s
11730     //   parameter-declaration-clause is not followed by mutable.
11731     DeclRefType = CaptureType.getNonReferenceType();
11732     if (!LSI->Mutable && !CaptureType->isReferenceType())
11733       DeclRefType.addConst();
11734   }
11735 
11736   // Add the capture.
11737   if (BuildAndDiagnose)
11738     LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToEnclosingLocal,
11739                     Loc, EllipsisLoc, CaptureType, CopyExpr);
11740 
11741   return true;
11742 }
11743 
11744 
11745 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation ExprLoc,
11746                               TryCaptureKind Kind, SourceLocation EllipsisLoc,
11747                               bool BuildAndDiagnose,
11748                               QualType &CaptureType,
11749                               QualType &DeclRefType) {
11750   bool Nested = false;
11751 
11752   DeclContext *DC = CurContext;
11753   const unsigned MaxFunctionScopesIndex = FunctionScopes.size() - 1;
11754 
11755   // If the variable is declared in the current context (and is not an
11756   // init-capture), there is no need to capture it.
11757   if (!Var->isInitCapture() && Var->getDeclContext() == DC) return true;
11758   if (!Var->hasLocalStorage()) return true;
11759 
11760   // Walk up the stack to determine whether we can capture the variable,
11761   // performing the "simple" checks that don't depend on type. We stop when
11762   // we've either hit the declared scope of the variable or find an existing
11763   // capture of that variable.  We start from the innermost capturing-entity
11764   // (the DC) and ensure that all intervening capturing-entities
11765   // (blocks/lambdas etc.) between the innermost capturer and the variable`s
11766   // declcontext can either capture the variable or have already captured
11767   // the variable.
11768   CaptureType = Var->getType();
11769   DeclRefType = CaptureType.getNonReferenceType();
11770   bool Explicit = (Kind != TryCapture_Implicit);
11771   unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
11772   do {
11773     // Only block literals, captured statements, and lambda expressions can
11774     // capture; other scopes don't work.
11775     DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
11776                                                               ExprLoc,
11777                                                               BuildAndDiagnose,
11778                                                               *this);
11779     if (!ParentDC) return true;
11780 
11781     FunctionScopeInfo  *FSI = FunctionScopes[FunctionScopesIndex];
11782     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
11783 
11784 
11785     // Check whether we've already captured it.
11786     if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
11787                                              DeclRefType))
11788       break;
11789 
11790     // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
11791     // certain types of variables (unnamed, variably modified types etc.)
11792     // so check for eligibility.
11793     if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this))
11794        return true;
11795 
11796     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
11797       // No capture-default, and this is not an explicit capture
11798       // so cannot capture this variable.
11799       if (BuildAndDiagnose) {
11800         Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
11801         Diag(Var->getLocation(), diag::note_previous_decl)
11802           << Var->getDeclName();
11803         Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
11804              diag::note_lambda_decl);
11805       }
11806       return true;
11807     }
11808 
11809     FunctionScopesIndex--;
11810     DC = ParentDC;
11811     Explicit = false;
11812   } while (!Var->getDeclContext()->Equals(DC));
11813 
11814   // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
11815   // computing the type of the capture at each step, checking type-specific
11816   // requirements, and adding captures if requested.
11817   // If the variable had already been captured previously, we start capturing
11818   // at the lambda nested within that one.
11819   for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
11820        ++I) {
11821     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
11822 
11823     if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
11824       if (!captureInBlock(BSI, Var, ExprLoc,
11825                           BuildAndDiagnose, CaptureType,
11826                           DeclRefType, Nested, *this))
11827         return true;
11828       Nested = true;
11829     } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
11830       if (!captureInCapturedRegion(RSI, Var, ExprLoc,
11831                                    BuildAndDiagnose, CaptureType,
11832                                    DeclRefType, Nested, *this))
11833         return true;
11834       Nested = true;
11835     } else {
11836       LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
11837       if (!captureInLambda(LSI, Var, ExprLoc,
11838                            BuildAndDiagnose, CaptureType,
11839                            DeclRefType, Nested, Kind, EllipsisLoc,
11840                             /*IsTopScope*/I == N - 1, *this))
11841         return true;
11842       Nested = true;
11843     }
11844   }
11845   return false;
11846 }
11847 
11848 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
11849                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {
11850   QualType CaptureType;
11851   QualType DeclRefType;
11852   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
11853                             /*BuildAndDiagnose=*/true, CaptureType,
11854                             DeclRefType);
11855 }
11856 
11857 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
11858   QualType CaptureType;
11859   QualType DeclRefType;
11860 
11861   // Determine whether we can capture this variable.
11862   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
11863                          /*BuildAndDiagnose=*/false, CaptureType, DeclRefType))
11864     return QualType();
11865 
11866   return DeclRefType;
11867 }
11868 
11869 static void MarkVarDeclODRUsed(Sema &SemaRef, VarDecl *Var,
11870                                SourceLocation Loc) {
11871   // Keep track of used but undefined variables.
11872   // FIXME: We shouldn't suppress this warning for static data members.
11873   if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
11874       !Var->isExternallyVisible() &&
11875       !(Var->isStaticDataMember() && Var->hasInit())) {
11876     SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()];
11877     if (old.isInvalid()) old = Loc;
11878   }
11879 
11880   SemaRef.tryCaptureVariable(Var, Loc);
11881 
11882   Var->markUsed(SemaRef.Context);
11883 }
11884 
11885 void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
11886   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
11887   // an object that satisfies the requirements for appearing in a
11888   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
11889   // is immediately applied."  This function handles the lvalue-to-rvalue
11890   // conversion part.
11891   MaybeODRUseExprs.erase(E->IgnoreParens());
11892 }
11893 
11894 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
11895   if (!Res.isUsable())
11896     return Res;
11897 
11898   // If a constant-expression is a reference to a variable where we delay
11899   // deciding whether it is an odr-use, just assume we will apply the
11900   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
11901   // (a non-type template argument), we have special handling anyway.
11902   UpdateMarkingForLValueToRValue(Res.get());
11903   return Res;
11904 }
11905 
11906 void Sema::CleanupVarDeclMarking() {
11907   for (llvm::SmallPtrSetIterator<Expr*> i = MaybeODRUseExprs.begin(),
11908                                         e = MaybeODRUseExprs.end();
11909        i != e; ++i) {
11910     VarDecl *Var;
11911     SourceLocation Loc;
11912     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(*i)) {
11913       Var = cast<VarDecl>(DRE->getDecl());
11914       Loc = DRE->getLocation();
11915     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(*i)) {
11916       Var = cast<VarDecl>(ME->getMemberDecl());
11917       Loc = ME->getMemberLoc();
11918     } else {
11919       llvm_unreachable("Unexpcted expression");
11920     }
11921 
11922     MarkVarDeclODRUsed(*this, Var, Loc);
11923   }
11924 
11925   MaybeODRUseExprs.clear();
11926 }
11927 
11928 // Mark a VarDecl referenced, and perform the necessary handling to compute
11929 // odr-uses.
11930 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
11931                                     VarDecl *Var, Expr *E) {
11932   Var->setReferenced();
11933 
11934   if (!IsPotentiallyEvaluatedContext(SemaRef))
11935     return;
11936 
11937   VarTemplateSpecializationDecl *VarSpec =
11938       dyn_cast<VarTemplateSpecializationDecl>(Var);
11939   assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
11940          "Can't instantiate a partial template specialization.");
11941 
11942   // Implicit instantiation of static data members, static data member
11943   // templates of class templates, and variable template specializations.
11944   // Delay instantiations of variable templates, except for those
11945   // that could be used in a constant expression.
11946   TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
11947   if (isTemplateInstantiation(TSK)) {
11948     bool TryInstantiating = TSK == TSK_ImplicitInstantiation;
11949 
11950     if (TryInstantiating && !isa<VarTemplateSpecializationDecl>(Var)) {
11951       if (Var->getPointOfInstantiation().isInvalid()) {
11952         // This is a modification of an existing AST node. Notify listeners.
11953         if (ASTMutationListener *L = SemaRef.getASTMutationListener())
11954           L->StaticDataMemberInstantiated(Var);
11955       } else if (!Var->isUsableInConstantExpressions(SemaRef.Context))
11956         // Don't bother trying to instantiate it again, unless we might need
11957         // its initializer before we get to the end of the TU.
11958         TryInstantiating = false;
11959     }
11960 
11961     if (Var->getPointOfInstantiation().isInvalid())
11962       Var->setTemplateSpecializationKind(TSK, Loc);
11963 
11964     if (TryInstantiating) {
11965       SourceLocation PointOfInstantiation = Var->getPointOfInstantiation();
11966       bool InstantiationDependent = false;
11967       bool IsNonDependent =
11968           VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
11969                         VarSpec->getTemplateArgsInfo(), InstantiationDependent)
11970                   : true;
11971 
11972       // Do not instantiate specializations that are still type-dependent.
11973       if (IsNonDependent) {
11974         if (Var->isUsableInConstantExpressions(SemaRef.Context)) {
11975           // Do not defer instantiations of variables which could be used in a
11976           // constant expression.
11977           SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
11978         } else {
11979           SemaRef.PendingInstantiations
11980               .push_back(std::make_pair(Var, PointOfInstantiation));
11981         }
11982       }
11983     }
11984   }
11985 
11986   // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies
11987   // the requirements for appearing in a constant expression (5.19) and, if
11988   // it is an object, the lvalue-to-rvalue conversion (4.1)
11989   // is immediately applied."  We check the first part here, and
11990   // Sema::UpdateMarkingForLValueToRValue deals with the second part.
11991   // Note that we use the C++11 definition everywhere because nothing in
11992   // C++03 depends on whether we get the C++03 version correct. The second
11993   // part does not apply to references, since they are not objects.
11994   const VarDecl *DefVD;
11995   if (E && !isa<ParmVarDecl>(Var) &&
11996       Var->isUsableInConstantExpressions(SemaRef.Context) &&
11997       Var->getAnyInitializer(DefVD) && DefVD->checkInitIsICE()) {
11998     if (!Var->getType()->isReferenceType())
11999       SemaRef.MaybeODRUseExprs.insert(E);
12000   } else
12001     MarkVarDeclODRUsed(SemaRef, Var, Loc);
12002 }
12003 
12004 /// \brief Mark a variable referenced, and check whether it is odr-used
12005 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
12006 /// used directly for normal expressions referring to VarDecl.
12007 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
12008   DoMarkVarDeclReferenced(*this, Loc, Var, 0);
12009 }
12010 
12011 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
12012                                Decl *D, Expr *E, bool OdrUse) {
12013   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
12014     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
12015     return;
12016   }
12017 
12018   SemaRef.MarkAnyDeclReferenced(Loc, D, OdrUse);
12019 
12020   // If this is a call to a method via a cast, also mark the method in the
12021   // derived class used in case codegen can devirtualize the call.
12022   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
12023   if (!ME)
12024     return;
12025   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
12026   if (!MD)
12027     return;
12028   const Expr *Base = ME->getBase();
12029   const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
12030   if (!MostDerivedClassDecl)
12031     return;
12032   CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl);
12033   if (!DM || DM->isPure())
12034     return;
12035   SemaRef.MarkAnyDeclReferenced(Loc, DM, OdrUse);
12036 }
12037 
12038 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
12039 void Sema::MarkDeclRefReferenced(DeclRefExpr *E) {
12040   // TODO: update this with DR# once a defect report is filed.
12041   // C++11 defect. The address of a pure member should not be an ODR use, even
12042   // if it's a qualified reference.
12043   bool OdrUse = true;
12044   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
12045     if (Method->isVirtual())
12046       OdrUse = false;
12047   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
12048 }
12049 
12050 /// \brief Perform reference-marking and odr-use handling for a MemberExpr.
12051 void Sema::MarkMemberReferenced(MemberExpr *E) {
12052   // C++11 [basic.def.odr]p2:
12053   //   A non-overloaded function whose name appears as a potentially-evaluated
12054   //   expression or a member of a set of candidate functions, if selected by
12055   //   overload resolution when referred to from a potentially-evaluated
12056   //   expression, is odr-used, unless it is a pure virtual function and its
12057   //   name is not explicitly qualified.
12058   bool OdrUse = true;
12059   if (!E->hasQualifier()) {
12060     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
12061       if (Method->isPure())
12062         OdrUse = false;
12063   }
12064   SourceLocation Loc = E->getMemberLoc().isValid() ?
12065                             E->getMemberLoc() : E->getLocStart();
12066   MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, OdrUse);
12067 }
12068 
12069 /// \brief Perform marking for a reference to an arbitrary declaration.  It
12070 /// marks the declaration referenced, and performs odr-use checking for functions
12071 /// and variables. This method should not be used when building an normal
12072 /// expression which refers to a variable.
12073 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool OdrUse) {
12074   if (OdrUse) {
12075     if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
12076       MarkVariableReferenced(Loc, VD);
12077       return;
12078     }
12079     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
12080       MarkFunctionReferenced(Loc, FD);
12081       return;
12082     }
12083   }
12084   D->setReferenced();
12085 }
12086 
12087 namespace {
12088   // Mark all of the declarations referenced
12089   // FIXME: Not fully implemented yet! We need to have a better understanding
12090   // of when we're entering
12091   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
12092     Sema &S;
12093     SourceLocation Loc;
12094 
12095   public:
12096     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
12097 
12098     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
12099 
12100     bool TraverseTemplateArgument(const TemplateArgument &Arg);
12101     bool TraverseRecordType(RecordType *T);
12102   };
12103 }
12104 
12105 bool MarkReferencedDecls::TraverseTemplateArgument(
12106   const TemplateArgument &Arg) {
12107   if (Arg.getKind() == TemplateArgument::Declaration) {
12108     if (Decl *D = Arg.getAsDecl())
12109       S.MarkAnyDeclReferenced(Loc, D, true);
12110   }
12111 
12112   return Inherited::TraverseTemplateArgument(Arg);
12113 }
12114 
12115 bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
12116   if (ClassTemplateSpecializationDecl *Spec
12117                   = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
12118     const TemplateArgumentList &Args = Spec->getTemplateArgs();
12119     return TraverseTemplateArguments(Args.data(), Args.size());
12120   }
12121 
12122   return true;
12123 }
12124 
12125 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
12126   MarkReferencedDecls Marker(*this, Loc);
12127   Marker.TraverseType(Context.getCanonicalType(T));
12128 }
12129 
12130 namespace {
12131   /// \brief Helper class that marks all of the declarations referenced by
12132   /// potentially-evaluated subexpressions as "referenced".
12133   class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
12134     Sema &S;
12135     bool SkipLocalVariables;
12136 
12137   public:
12138     typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
12139 
12140     EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
12141       : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
12142 
12143     void VisitDeclRefExpr(DeclRefExpr *E) {
12144       // If we were asked not to visit local variables, don't.
12145       if (SkipLocalVariables) {
12146         if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
12147           if (VD->hasLocalStorage())
12148             return;
12149       }
12150 
12151       S.MarkDeclRefReferenced(E);
12152     }
12153 
12154     void VisitMemberExpr(MemberExpr *E) {
12155       S.MarkMemberReferenced(E);
12156       Inherited::VisitMemberExpr(E);
12157     }
12158 
12159     void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
12160       S.MarkFunctionReferenced(E->getLocStart(),
12161             const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
12162       Visit(E->getSubExpr());
12163     }
12164 
12165     void VisitCXXNewExpr(CXXNewExpr *E) {
12166       if (E->getOperatorNew())
12167         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
12168       if (E->getOperatorDelete())
12169         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
12170       Inherited::VisitCXXNewExpr(E);
12171     }
12172 
12173     void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
12174       if (E->getOperatorDelete())
12175         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
12176       QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
12177       if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
12178         CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
12179         S.MarkFunctionReferenced(E->getLocStart(),
12180                                     S.LookupDestructor(Record));
12181       }
12182 
12183       Inherited::VisitCXXDeleteExpr(E);
12184     }
12185 
12186     void VisitCXXConstructExpr(CXXConstructExpr *E) {
12187       S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
12188       Inherited::VisitCXXConstructExpr(E);
12189     }
12190 
12191     void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
12192       Visit(E->getExpr());
12193     }
12194 
12195     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
12196       Inherited::VisitImplicitCastExpr(E);
12197 
12198       if (E->getCastKind() == CK_LValueToRValue)
12199         S.UpdateMarkingForLValueToRValue(E->getSubExpr());
12200     }
12201   };
12202 }
12203 
12204 /// \brief Mark any declarations that appear within this expression or any
12205 /// potentially-evaluated subexpressions as "referenced".
12206 ///
12207 /// \param SkipLocalVariables If true, don't mark local variables as
12208 /// 'referenced'.
12209 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
12210                                             bool SkipLocalVariables) {
12211   EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
12212 }
12213 
12214 /// \brief Emit a diagnostic that describes an effect on the run-time behavior
12215 /// of the program being compiled.
12216 ///
12217 /// This routine emits the given diagnostic when the code currently being
12218 /// type-checked is "potentially evaluated", meaning that there is a
12219 /// possibility that the code will actually be executable. Code in sizeof()
12220 /// expressions, code used only during overload resolution, etc., are not
12221 /// potentially evaluated. This routine will suppress such diagnostics or,
12222 /// in the absolutely nutty case of potentially potentially evaluated
12223 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
12224 /// later.
12225 ///
12226 /// This routine should be used for all diagnostics that describe the run-time
12227 /// behavior of a program, such as passing a non-POD value through an ellipsis.
12228 /// Failure to do so will likely result in spurious diagnostics or failures
12229 /// during overload resolution or within sizeof/alignof/typeof/typeid.
12230 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
12231                                const PartialDiagnostic &PD) {
12232   switch (ExprEvalContexts.back().Context) {
12233   case Unevaluated:
12234   case UnevaluatedAbstract:
12235     // The argument will never be evaluated, so don't complain.
12236     break;
12237 
12238   case ConstantEvaluated:
12239     // Relevant diagnostics should be produced by constant evaluation.
12240     break;
12241 
12242   case PotentiallyEvaluated:
12243   case PotentiallyEvaluatedIfUsed:
12244     if (Statement && getCurFunctionOrMethodDecl()) {
12245       FunctionScopes.back()->PossiblyUnreachableDiags.
12246         push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
12247     }
12248     else
12249       Diag(Loc, PD);
12250 
12251     return true;
12252   }
12253 
12254   return false;
12255 }
12256 
12257 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
12258                                CallExpr *CE, FunctionDecl *FD) {
12259   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
12260     return false;
12261 
12262   // If we're inside a decltype's expression, don't check for a valid return
12263   // type or construct temporaries until we know whether this is the last call.
12264   if (ExprEvalContexts.back().IsDecltype) {
12265     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
12266     return false;
12267   }
12268 
12269   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
12270     FunctionDecl *FD;
12271     CallExpr *CE;
12272 
12273   public:
12274     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
12275       : FD(FD), CE(CE) { }
12276 
12277     virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
12278       if (!FD) {
12279         S.Diag(Loc, diag::err_call_incomplete_return)
12280           << T << CE->getSourceRange();
12281         return;
12282       }
12283 
12284       S.Diag(Loc, diag::err_call_function_incomplete_return)
12285         << CE->getSourceRange() << FD->getDeclName() << T;
12286       S.Diag(FD->getLocation(),
12287              diag::note_function_with_incomplete_return_type_declared_here)
12288         << FD->getDeclName();
12289     }
12290   } Diagnoser(FD, CE);
12291 
12292   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
12293     return true;
12294 
12295   return false;
12296 }
12297 
12298 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
12299 // will prevent this condition from triggering, which is what we want.
12300 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
12301   SourceLocation Loc;
12302 
12303   unsigned diagnostic = diag::warn_condition_is_assignment;
12304   bool IsOrAssign = false;
12305 
12306   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
12307     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
12308       return;
12309 
12310     IsOrAssign = Op->getOpcode() == BO_OrAssign;
12311 
12312     // Greylist some idioms by putting them into a warning subcategory.
12313     if (ObjCMessageExpr *ME
12314           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
12315       Selector Sel = ME->getSelector();
12316 
12317       // self = [<foo> init...]
12318       if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
12319         diagnostic = diag::warn_condition_is_idiomatic_assignment;
12320 
12321       // <foo> = [<bar> nextObject]
12322       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
12323         diagnostic = diag::warn_condition_is_idiomatic_assignment;
12324     }
12325 
12326     Loc = Op->getOperatorLoc();
12327   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
12328     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
12329       return;
12330 
12331     IsOrAssign = Op->getOperator() == OO_PipeEqual;
12332     Loc = Op->getOperatorLoc();
12333   } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
12334     return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
12335   else {
12336     // Not an assignment.
12337     return;
12338   }
12339 
12340   Diag(Loc, diagnostic) << E->getSourceRange();
12341 
12342   SourceLocation Open = E->getLocStart();
12343   SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
12344   Diag(Loc, diag::note_condition_assign_silence)
12345         << FixItHint::CreateInsertion(Open, "(")
12346         << FixItHint::CreateInsertion(Close, ")");
12347 
12348   if (IsOrAssign)
12349     Diag(Loc, diag::note_condition_or_assign_to_comparison)
12350       << FixItHint::CreateReplacement(Loc, "!=");
12351   else
12352     Diag(Loc, diag::note_condition_assign_to_comparison)
12353       << FixItHint::CreateReplacement(Loc, "==");
12354 }
12355 
12356 /// \brief Redundant parentheses over an equality comparison can indicate
12357 /// that the user intended an assignment used as condition.
12358 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
12359   // Don't warn if the parens came from a macro.
12360   SourceLocation parenLoc = ParenE->getLocStart();
12361   if (parenLoc.isInvalid() || parenLoc.isMacroID())
12362     return;
12363   // Don't warn for dependent expressions.
12364   if (ParenE->isTypeDependent())
12365     return;
12366 
12367   Expr *E = ParenE->IgnoreParens();
12368 
12369   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
12370     if (opE->getOpcode() == BO_EQ &&
12371         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
12372                                                            == Expr::MLV_Valid) {
12373       SourceLocation Loc = opE->getOperatorLoc();
12374 
12375       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
12376       SourceRange ParenERange = ParenE->getSourceRange();
12377       Diag(Loc, diag::note_equality_comparison_silence)
12378         << FixItHint::CreateRemoval(ParenERange.getBegin())
12379         << FixItHint::CreateRemoval(ParenERange.getEnd());
12380       Diag(Loc, diag::note_equality_comparison_to_assign)
12381         << FixItHint::CreateReplacement(Loc, "=");
12382     }
12383 }
12384 
12385 ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
12386   DiagnoseAssignmentAsCondition(E);
12387   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
12388     DiagnoseEqualityWithExtraParens(parenE);
12389 
12390   ExprResult result = CheckPlaceholderExpr(E);
12391   if (result.isInvalid()) return ExprError();
12392   E = result.take();
12393 
12394   if (!E->isTypeDependent()) {
12395     if (getLangOpts().CPlusPlus)
12396       return CheckCXXBooleanCondition(E); // C++ 6.4p4
12397 
12398     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
12399     if (ERes.isInvalid())
12400       return ExprError();
12401     E = ERes.take();
12402 
12403     QualType T = E->getType();
12404     if (!T->isScalarType()) { // C99 6.8.4.1p1
12405       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
12406         << T << E->getSourceRange();
12407       return ExprError();
12408     }
12409   }
12410 
12411   return Owned(E);
12412 }
12413 
12414 ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
12415                                        Expr *SubExpr) {
12416   if (!SubExpr)
12417     return ExprError();
12418 
12419   return CheckBooleanCondition(SubExpr, Loc);
12420 }
12421 
12422 namespace {
12423   /// A visitor for rebuilding a call to an __unknown_any expression
12424   /// to have an appropriate type.
12425   struct RebuildUnknownAnyFunction
12426     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
12427 
12428     Sema &S;
12429 
12430     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
12431 
12432     ExprResult VisitStmt(Stmt *S) {
12433       llvm_unreachable("unexpected statement!");
12434     }
12435 
12436     ExprResult VisitExpr(Expr *E) {
12437       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
12438         << E->getSourceRange();
12439       return ExprError();
12440     }
12441 
12442     /// Rebuild an expression which simply semantically wraps another
12443     /// expression which it shares the type and value kind of.
12444     template <class T> ExprResult rebuildSugarExpr(T *E) {
12445       ExprResult SubResult = Visit(E->getSubExpr());
12446       if (SubResult.isInvalid()) return ExprError();
12447 
12448       Expr *SubExpr = SubResult.take();
12449       E->setSubExpr(SubExpr);
12450       E->setType(SubExpr->getType());
12451       E->setValueKind(SubExpr->getValueKind());
12452       assert(E->getObjectKind() == OK_Ordinary);
12453       return E;
12454     }
12455 
12456     ExprResult VisitParenExpr(ParenExpr *E) {
12457       return rebuildSugarExpr(E);
12458     }
12459 
12460     ExprResult VisitUnaryExtension(UnaryOperator *E) {
12461       return rebuildSugarExpr(E);
12462     }
12463 
12464     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
12465       ExprResult SubResult = Visit(E->getSubExpr());
12466       if (SubResult.isInvalid()) return ExprError();
12467 
12468       Expr *SubExpr = SubResult.take();
12469       E->setSubExpr(SubExpr);
12470       E->setType(S.Context.getPointerType(SubExpr->getType()));
12471       assert(E->getValueKind() == VK_RValue);
12472       assert(E->getObjectKind() == OK_Ordinary);
12473       return E;
12474     }
12475 
12476     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
12477       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
12478 
12479       E->setType(VD->getType());
12480 
12481       assert(E->getValueKind() == VK_RValue);
12482       if (S.getLangOpts().CPlusPlus &&
12483           !(isa<CXXMethodDecl>(VD) &&
12484             cast<CXXMethodDecl>(VD)->isInstance()))
12485         E->setValueKind(VK_LValue);
12486 
12487       return E;
12488     }
12489 
12490     ExprResult VisitMemberExpr(MemberExpr *E) {
12491       return resolveDecl(E, E->getMemberDecl());
12492     }
12493 
12494     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
12495       return resolveDecl(E, E->getDecl());
12496     }
12497   };
12498 }
12499 
12500 /// Given a function expression of unknown-any type, try to rebuild it
12501 /// to have a function type.
12502 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
12503   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
12504   if (Result.isInvalid()) return ExprError();
12505   return S.DefaultFunctionArrayConversion(Result.take());
12506 }
12507 
12508 namespace {
12509   /// A visitor for rebuilding an expression of type __unknown_anytype
12510   /// into one which resolves the type directly on the referring
12511   /// expression.  Strict preservation of the original source
12512   /// structure is not a goal.
12513   struct RebuildUnknownAnyExpr
12514     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
12515 
12516     Sema &S;
12517 
12518     /// The current destination type.
12519     QualType DestType;
12520 
12521     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
12522       : S(S), DestType(CastType) {}
12523 
12524     ExprResult VisitStmt(Stmt *S) {
12525       llvm_unreachable("unexpected statement!");
12526     }
12527 
12528     ExprResult VisitExpr(Expr *E) {
12529       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
12530         << E->getSourceRange();
12531       return ExprError();
12532     }
12533 
12534     ExprResult VisitCallExpr(CallExpr *E);
12535     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
12536 
12537     /// Rebuild an expression which simply semantically wraps another
12538     /// expression which it shares the type and value kind of.
12539     template <class T> ExprResult rebuildSugarExpr(T *E) {
12540       ExprResult SubResult = Visit(E->getSubExpr());
12541       if (SubResult.isInvalid()) return ExprError();
12542       Expr *SubExpr = SubResult.take();
12543       E->setSubExpr(SubExpr);
12544       E->setType(SubExpr->getType());
12545       E->setValueKind(SubExpr->getValueKind());
12546       assert(E->getObjectKind() == OK_Ordinary);
12547       return E;
12548     }
12549 
12550     ExprResult VisitParenExpr(ParenExpr *E) {
12551       return rebuildSugarExpr(E);
12552     }
12553 
12554     ExprResult VisitUnaryExtension(UnaryOperator *E) {
12555       return rebuildSugarExpr(E);
12556     }
12557 
12558     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
12559       const PointerType *Ptr = DestType->getAs<PointerType>();
12560       if (!Ptr) {
12561         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
12562           << E->getSourceRange();
12563         return ExprError();
12564       }
12565       assert(E->getValueKind() == VK_RValue);
12566       assert(E->getObjectKind() == OK_Ordinary);
12567       E->setType(DestType);
12568 
12569       // Build the sub-expression as if it were an object of the pointee type.
12570       DestType = Ptr->getPointeeType();
12571       ExprResult SubResult = Visit(E->getSubExpr());
12572       if (SubResult.isInvalid()) return ExprError();
12573       E->setSubExpr(SubResult.take());
12574       return E;
12575     }
12576 
12577     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
12578 
12579     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
12580 
12581     ExprResult VisitMemberExpr(MemberExpr *E) {
12582       return resolveDecl(E, E->getMemberDecl());
12583     }
12584 
12585     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
12586       return resolveDecl(E, E->getDecl());
12587     }
12588   };
12589 }
12590 
12591 /// Rebuilds a call expression which yielded __unknown_anytype.
12592 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
12593   Expr *CalleeExpr = E->getCallee();
12594 
12595   enum FnKind {
12596     FK_MemberFunction,
12597     FK_FunctionPointer,
12598     FK_BlockPointer
12599   };
12600 
12601   FnKind Kind;
12602   QualType CalleeType = CalleeExpr->getType();
12603   if (CalleeType == S.Context.BoundMemberTy) {
12604     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
12605     Kind = FK_MemberFunction;
12606     CalleeType = Expr::findBoundMemberType(CalleeExpr);
12607   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
12608     CalleeType = Ptr->getPointeeType();
12609     Kind = FK_FunctionPointer;
12610   } else {
12611     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
12612     Kind = FK_BlockPointer;
12613   }
12614   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
12615 
12616   // Verify that this is a legal result type of a function.
12617   if (DestType->isArrayType() || DestType->isFunctionType()) {
12618     unsigned diagID = diag::err_func_returning_array_function;
12619     if (Kind == FK_BlockPointer)
12620       diagID = diag::err_block_returning_array_function;
12621 
12622     S.Diag(E->getExprLoc(), diagID)
12623       << DestType->isFunctionType() << DestType;
12624     return ExprError();
12625   }
12626 
12627   // Otherwise, go ahead and set DestType as the call's result.
12628   E->setType(DestType.getNonLValueExprType(S.Context));
12629   E->setValueKind(Expr::getValueKindForType(DestType));
12630   assert(E->getObjectKind() == OK_Ordinary);
12631 
12632   // Rebuild the function type, replacing the result type with DestType.
12633   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
12634   if (Proto) {
12635     // __unknown_anytype(...) is a special case used by the debugger when
12636     // it has no idea what a function's signature is.
12637     //
12638     // We want to build this call essentially under the K&R
12639     // unprototyped rules, but making a FunctionNoProtoType in C++
12640     // would foul up all sorts of assumptions.  However, we cannot
12641     // simply pass all arguments as variadic arguments, nor can we
12642     // portably just call the function under a non-variadic type; see
12643     // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
12644     // However, it turns out that in practice it is generally safe to
12645     // call a function declared as "A foo(B,C,D);" under the prototype
12646     // "A foo(B,C,D,...);".  The only known exception is with the
12647     // Windows ABI, where any variadic function is implicitly cdecl
12648     // regardless of its normal CC.  Therefore we change the parameter
12649     // types to match the types of the arguments.
12650     //
12651     // This is a hack, but it is far superior to moving the
12652     // corresponding target-specific code from IR-gen to Sema/AST.
12653 
12654     ArrayRef<QualType> ParamTypes = Proto->getArgTypes();
12655     SmallVector<QualType, 8> ArgTypes;
12656     if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
12657       ArgTypes.reserve(E->getNumArgs());
12658       for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
12659         Expr *Arg = E->getArg(i);
12660         QualType ArgType = Arg->getType();
12661         if (E->isLValue()) {
12662           ArgType = S.Context.getLValueReferenceType(ArgType);
12663         } else if (E->isXValue()) {
12664           ArgType = S.Context.getRValueReferenceType(ArgType);
12665         }
12666         ArgTypes.push_back(ArgType);
12667       }
12668       ParamTypes = ArgTypes;
12669     }
12670     DestType = S.Context.getFunctionType(DestType, ParamTypes,
12671                                          Proto->getExtProtoInfo());
12672   } else {
12673     DestType = S.Context.getFunctionNoProtoType(DestType,
12674                                                 FnType->getExtInfo());
12675   }
12676 
12677   // Rebuild the appropriate pointer-to-function type.
12678   switch (Kind) {
12679   case FK_MemberFunction:
12680     // Nothing to do.
12681     break;
12682 
12683   case FK_FunctionPointer:
12684     DestType = S.Context.getPointerType(DestType);
12685     break;
12686 
12687   case FK_BlockPointer:
12688     DestType = S.Context.getBlockPointerType(DestType);
12689     break;
12690   }
12691 
12692   // Finally, we can recurse.
12693   ExprResult CalleeResult = Visit(CalleeExpr);
12694   if (!CalleeResult.isUsable()) return ExprError();
12695   E->setCallee(CalleeResult.take());
12696 
12697   // Bind a temporary if necessary.
12698   return S.MaybeBindToTemporary(E);
12699 }
12700 
12701 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
12702   // Verify that this is a legal result type of a call.
12703   if (DestType->isArrayType() || DestType->isFunctionType()) {
12704     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
12705       << DestType->isFunctionType() << DestType;
12706     return ExprError();
12707   }
12708 
12709   // Rewrite the method result type if available.
12710   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
12711     assert(Method->getResultType() == S.Context.UnknownAnyTy);
12712     Method->setResultType(DestType);
12713   }
12714 
12715   // Change the type of the message.
12716   E->setType(DestType.getNonReferenceType());
12717   E->setValueKind(Expr::getValueKindForType(DestType));
12718 
12719   return S.MaybeBindToTemporary(E);
12720 }
12721 
12722 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
12723   // The only case we should ever see here is a function-to-pointer decay.
12724   if (E->getCastKind() == CK_FunctionToPointerDecay) {
12725     assert(E->getValueKind() == VK_RValue);
12726     assert(E->getObjectKind() == OK_Ordinary);
12727 
12728     E->setType(DestType);
12729 
12730     // Rebuild the sub-expression as the pointee (function) type.
12731     DestType = DestType->castAs<PointerType>()->getPointeeType();
12732 
12733     ExprResult Result = Visit(E->getSubExpr());
12734     if (!Result.isUsable()) return ExprError();
12735 
12736     E->setSubExpr(Result.take());
12737     return S.Owned(E);
12738   } else if (E->getCastKind() == CK_LValueToRValue) {
12739     assert(E->getValueKind() == VK_RValue);
12740     assert(E->getObjectKind() == OK_Ordinary);
12741 
12742     assert(isa<BlockPointerType>(E->getType()));
12743 
12744     E->setType(DestType);
12745 
12746     // The sub-expression has to be a lvalue reference, so rebuild it as such.
12747     DestType = S.Context.getLValueReferenceType(DestType);
12748 
12749     ExprResult Result = Visit(E->getSubExpr());
12750     if (!Result.isUsable()) return ExprError();
12751 
12752     E->setSubExpr(Result.take());
12753     return S.Owned(E);
12754   } else {
12755     llvm_unreachable("Unhandled cast type!");
12756   }
12757 }
12758 
12759 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
12760   ExprValueKind ValueKind = VK_LValue;
12761   QualType Type = DestType;
12762 
12763   // We know how to make this work for certain kinds of decls:
12764 
12765   //  - functions
12766   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
12767     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
12768       DestType = Ptr->getPointeeType();
12769       ExprResult Result = resolveDecl(E, VD);
12770       if (Result.isInvalid()) return ExprError();
12771       return S.ImpCastExprToType(Result.take(), Type,
12772                                  CK_FunctionToPointerDecay, VK_RValue);
12773     }
12774 
12775     if (!Type->isFunctionType()) {
12776       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
12777         << VD << E->getSourceRange();
12778       return ExprError();
12779     }
12780 
12781     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
12782       if (MD->isInstance()) {
12783         ValueKind = VK_RValue;
12784         Type = S.Context.BoundMemberTy;
12785       }
12786 
12787     // Function references aren't l-values in C.
12788     if (!S.getLangOpts().CPlusPlus)
12789       ValueKind = VK_RValue;
12790 
12791   //  - variables
12792   } else if (isa<VarDecl>(VD)) {
12793     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
12794       Type = RefTy->getPointeeType();
12795     } else if (Type->isFunctionType()) {
12796       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
12797         << VD << E->getSourceRange();
12798       return ExprError();
12799     }
12800 
12801   //  - nothing else
12802   } else {
12803     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
12804       << VD << E->getSourceRange();
12805     return ExprError();
12806   }
12807 
12808   // Modifying the declaration like this is friendly to IR-gen but
12809   // also really dangerous.
12810   VD->setType(DestType);
12811   E->setType(Type);
12812   E->setValueKind(ValueKind);
12813   return S.Owned(E);
12814 }
12815 
12816 /// Check a cast of an unknown-any type.  We intentionally only
12817 /// trigger this for C-style casts.
12818 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
12819                                      Expr *CastExpr, CastKind &CastKind,
12820                                      ExprValueKind &VK, CXXCastPath &Path) {
12821   // Rewrite the casted expression from scratch.
12822   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
12823   if (!result.isUsable()) return ExprError();
12824 
12825   CastExpr = result.take();
12826   VK = CastExpr->getValueKind();
12827   CastKind = CK_NoOp;
12828 
12829   return CastExpr;
12830 }
12831 
12832 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
12833   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
12834 }
12835 
12836 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
12837                                     Expr *arg, QualType &paramType) {
12838   // If the syntactic form of the argument is not an explicit cast of
12839   // any sort, just do default argument promotion.
12840   ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
12841   if (!castArg) {
12842     ExprResult result = DefaultArgumentPromotion(arg);
12843     if (result.isInvalid()) return ExprError();
12844     paramType = result.get()->getType();
12845     return result;
12846   }
12847 
12848   // Otherwise, use the type that was written in the explicit cast.
12849   assert(!arg->hasPlaceholderType());
12850   paramType = castArg->getTypeAsWritten();
12851 
12852   // Copy-initialize a parameter of that type.
12853   InitializedEntity entity =
12854     InitializedEntity::InitializeParameter(Context, paramType,
12855                                            /*consumed*/ false);
12856   return PerformCopyInitialization(entity, callLoc, Owned(arg));
12857 }
12858 
12859 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
12860   Expr *orig = E;
12861   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
12862   while (true) {
12863     E = E->IgnoreParenImpCasts();
12864     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
12865       E = call->getCallee();
12866       diagID = diag::err_uncasted_call_of_unknown_any;
12867     } else {
12868       break;
12869     }
12870   }
12871 
12872   SourceLocation loc;
12873   NamedDecl *d;
12874   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
12875     loc = ref->getLocation();
12876     d = ref->getDecl();
12877   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
12878     loc = mem->getMemberLoc();
12879     d = mem->getMemberDecl();
12880   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
12881     diagID = diag::err_uncasted_call_of_unknown_any;
12882     loc = msg->getSelectorStartLoc();
12883     d = msg->getMethodDecl();
12884     if (!d) {
12885       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
12886         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
12887         << orig->getSourceRange();
12888       return ExprError();
12889     }
12890   } else {
12891     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
12892       << E->getSourceRange();
12893     return ExprError();
12894   }
12895 
12896   S.Diag(loc, diagID) << d << orig->getSourceRange();
12897 
12898   // Never recoverable.
12899   return ExprError();
12900 }
12901 
12902 /// Check for operands with placeholder types and complain if found.
12903 /// Returns true if there was an error and no recovery was possible.
12904 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
12905   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
12906   if (!placeholderType) return Owned(E);
12907 
12908   switch (placeholderType->getKind()) {
12909 
12910   // Overloaded expressions.
12911   case BuiltinType::Overload: {
12912     // Try to resolve a single function template specialization.
12913     // This is obligatory.
12914     ExprResult result = Owned(E);
12915     if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) {
12916       return result;
12917 
12918     // If that failed, try to recover with a call.
12919     } else {
12920       tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable),
12921                            /*complain*/ true);
12922       return result;
12923     }
12924   }
12925 
12926   // Bound member functions.
12927   case BuiltinType::BoundMember: {
12928     ExprResult result = Owned(E);
12929     tryToRecoverWithCall(result, PDiag(diag::err_bound_member_function),
12930                          /*complain*/ true);
12931     return result;
12932   }
12933 
12934   // ARC unbridged casts.
12935   case BuiltinType::ARCUnbridgedCast: {
12936     Expr *realCast = stripARCUnbridgedCast(E);
12937     diagnoseARCUnbridgedCast(realCast);
12938     return Owned(realCast);
12939   }
12940 
12941   // Expressions of unknown type.
12942   case BuiltinType::UnknownAny:
12943     return diagnoseUnknownAnyExpr(*this, E);
12944 
12945   // Pseudo-objects.
12946   case BuiltinType::PseudoObject:
12947     return checkPseudoObjectRValue(E);
12948 
12949   case BuiltinType::BuiltinFn:
12950     Diag(E->getLocStart(), diag::err_builtin_fn_use);
12951     return ExprError();
12952 
12953   // Everything else should be impossible.
12954 #define BUILTIN_TYPE(Id, SingletonId) \
12955   case BuiltinType::Id:
12956 #define PLACEHOLDER_TYPE(Id, SingletonId)
12957 #include "clang/AST/BuiltinTypes.def"
12958     break;
12959   }
12960 
12961   llvm_unreachable("invalid placeholder type!");
12962 }
12963 
12964 bool Sema::CheckCaseExpression(Expr *E) {
12965   if (E->isTypeDependent())
12966     return true;
12967   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
12968     return E->getType()->isIntegralOrEnumerationType();
12969   return false;
12970 }
12971 
12972 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
12973 ExprResult
12974 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
12975   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
12976          "Unknown Objective-C Boolean value!");
12977   QualType BoolT = Context.ObjCBuiltinBoolTy;
12978   if (!Context.getBOOLDecl()) {
12979     LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
12980                         Sema::LookupOrdinaryName);
12981     if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
12982       NamedDecl *ND = Result.getFoundDecl();
12983       if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
12984         Context.setBOOLDecl(TD);
12985     }
12986   }
12987   if (Context.getBOOLDecl())
12988     BoolT = Context.getBOOLType();
12989   return Owned(new (Context) ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes,
12990                                         BoolT, OpLoc));
12991 }
12992