1 //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements semantic analysis for expressions.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/Sema/SemaInternal.h"
15 #include "clang/Sema/DelayedDiagnostic.h"
16 #include "clang/Sema/Initialization.h"
17 #include "clang/Sema/Lookup.h"
18 #include "clang/Sema/ScopeInfo.h"
19 #include "clang/Sema/AnalysisBasedWarnings.h"
20 #include "clang/AST/ASTContext.h"
21 #include "clang/AST/ASTConsumer.h"
22 #include "clang/AST/ASTMutationListener.h"
23 #include "clang/AST/CXXInheritance.h"
24 #include "clang/AST/DeclObjC.h"
25 #include "clang/AST/DeclTemplate.h"
26 #include "clang/AST/EvaluatedExprVisitor.h"
27 #include "clang/AST/Expr.h"
28 #include "clang/AST/ExprCXX.h"
29 #include "clang/AST/ExprObjC.h"
30 #include "clang/AST/RecursiveASTVisitor.h"
31 #include "clang/AST/TypeLoc.h"
32 #include "clang/Basic/PartialDiagnostic.h"
33 #include "clang/Basic/SourceManager.h"
34 #include "clang/Basic/TargetInfo.h"
35 #include "clang/Lex/LiteralSupport.h"
36 #include "clang/Lex/Preprocessor.h"
37 #include "clang/Sema/DeclSpec.h"
38 #include "clang/Sema/Designator.h"
39 #include "clang/Sema/Scope.h"
40 #include "clang/Sema/ScopeInfo.h"
41 #include "clang/Sema/ParsedTemplate.h"
42 #include "clang/Sema/SemaFixItUtils.h"
43 #include "clang/Sema/Template.h"
44 #include "TreeTransform.h"
45 using namespace clang;
46 using namespace sema;
47 
48 /// \brief Determine whether the use of this declaration is valid, without
49 /// emitting diagnostics.
50 bool Sema::CanUseDecl(NamedDecl *D) {
51   // See if this is an auto-typed variable whose initializer we are parsing.
52   if (ParsingInitForAutoVars.count(D))
53     return false;
54 
55   // See if this is a deleted function.
56   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
57     if (FD->isDeleted())
58       return false;
59   }
60 
61   // See if this function is unavailable.
62   if (D->getAvailability() == AR_Unavailable &&
63       cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
64     return false;
65 
66   return true;
67 }
68 
69 static AvailabilityResult DiagnoseAvailabilityOfDecl(Sema &S,
70                               NamedDecl *D, SourceLocation Loc,
71                               const ObjCInterfaceDecl *UnknownObjCClass) {
72   // See if this declaration is unavailable or deprecated.
73   std::string Message;
74   AvailabilityResult Result = D->getAvailability(&Message);
75   if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D))
76     if (Result == AR_Available) {
77       const DeclContext *DC = ECD->getDeclContext();
78       if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC))
79         Result = TheEnumDecl->getAvailability(&Message);
80     }
81 
82   switch (Result) {
83     case AR_Available:
84     case AR_NotYetIntroduced:
85       break;
86 
87     case AR_Deprecated:
88       S.EmitDeprecationWarning(D, Message, Loc, UnknownObjCClass);
89       break;
90 
91     case AR_Unavailable:
92       if (S.getCurContextAvailability() != AR_Unavailable) {
93         if (Message.empty()) {
94           if (!UnknownObjCClass)
95             S.Diag(Loc, diag::err_unavailable) << D->getDeclName();
96           else
97             S.Diag(Loc, diag::warn_unavailable_fwdclass_message)
98               << D->getDeclName();
99         }
100         else
101           S.Diag(Loc, diag::err_unavailable_message)
102             << D->getDeclName() << Message;
103           S.Diag(D->getLocation(), diag::note_unavailable_here)
104           << isa<FunctionDecl>(D) << false;
105       }
106       break;
107     }
108     return Result;
109 }
110 
111 /// \brief Emit a note explaining that this function is deleted or unavailable.
112 void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
113   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
114 
115   if (Method && Method->isDeleted() && !Method->isDeletedAsWritten()) {
116     // If the method was explicitly defaulted, point at that declaration.
117     if (!Method->isImplicit())
118       Diag(Decl->getLocation(), diag::note_implicitly_deleted);
119 
120     // Try to diagnose why this special member function was implicitly
121     // deleted. This might fail, if that reason no longer applies.
122     CXXSpecialMember CSM = getSpecialMember(Method);
123     if (CSM != CXXInvalid)
124       ShouldDeleteSpecialMember(Method, CSM, /*Diagnose=*/true);
125 
126     return;
127   }
128 
129   Diag(Decl->getLocation(), diag::note_unavailable_here)
130     << 1 << Decl->isDeleted();
131 }
132 
133 /// \brief Determine whether a FunctionDecl was ever declared with an
134 /// explicit storage class.
135 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
136   for (FunctionDecl::redecl_iterator I = D->redecls_begin(),
137                                      E = D->redecls_end();
138        I != E; ++I) {
139     if (I->getStorageClassAsWritten() != SC_None)
140       return true;
141   }
142   return false;
143 }
144 
145 /// \brief Check whether we're in an extern inline function and referring to a
146 /// variable or function with internal linkage (C11 6.7.4p3).
147 ///
148 /// This is only a warning because we used to silently accept this code, but
149 /// in many cases it will not behave correctly. This is not enabled in C++ mode
150 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
151 /// and so while there may still be user mistakes, most of the time we can't
152 /// prove that there are errors.
153 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
154                                                       const NamedDecl *D,
155                                                       SourceLocation Loc) {
156   // This is disabled under C++; there are too many ways for this to fire in
157   // contexts where the warning is a false positive, or where it is technically
158   // correct but benign.
159   if (S.getLangOpts().CPlusPlus)
160     return;
161 
162   // Check if this is an inlined function or method.
163   FunctionDecl *Current = S.getCurFunctionDecl();
164   if (!Current)
165     return;
166   if (!Current->isInlined())
167     return;
168   if (Current->getLinkage() != ExternalLinkage)
169     return;
170 
171   // Check if the decl has internal linkage.
172   if (D->getLinkage() != InternalLinkage)
173     return;
174 
175   // Downgrade from ExtWarn to Extension if
176   //  (1) the supposedly external inline function is in the main file,
177   //      and probably won't be included anywhere else.
178   //  (2) the thing we're referencing is a pure function.
179   //  (3) the thing we're referencing is another inline function.
180   // This last can give us false negatives, but it's better than warning on
181   // wrappers for simple C library functions.
182   const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
183   bool DowngradeWarning = S.getSourceManager().isFromMainFile(Loc);
184   if (!DowngradeWarning && UsedFn)
185     DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
186 
187   S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline
188                                : diag::warn_internal_in_extern_inline)
189     << /*IsVar=*/!UsedFn << D;
190 
191   // Suggest "static" on the inline function, if possible.
192   if (!hasAnyExplicitStorageClass(Current)) {
193     const FunctionDecl *FirstDecl = Current->getCanonicalDecl();
194     SourceLocation DeclBegin = FirstDecl->getSourceRange().getBegin();
195     S.Diag(DeclBegin, diag::note_convert_inline_to_static)
196       << Current << FixItHint::CreateInsertion(DeclBegin, "static ");
197   }
198 
199   S.Diag(D->getCanonicalDecl()->getLocation(),
200          diag::note_internal_decl_declared_here)
201     << D;
202 }
203 
204 /// \brief Determine whether the use of this declaration is valid, and
205 /// emit any corresponding diagnostics.
206 ///
207 /// This routine diagnoses various problems with referencing
208 /// declarations that can occur when using a declaration. For example,
209 /// it might warn if a deprecated or unavailable declaration is being
210 /// used, or produce an error (and return true) if a C++0x deleted
211 /// function is being used.
212 ///
213 /// \returns true if there was an error (this declaration cannot be
214 /// referenced), false otherwise.
215 ///
216 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
217                              const ObjCInterfaceDecl *UnknownObjCClass) {
218   if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
219     // If there were any diagnostics suppressed by template argument deduction,
220     // emit them now.
221     llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >::iterator
222       Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
223     if (Pos != SuppressedDiagnostics.end()) {
224       SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second;
225       for (unsigned I = 0, N = Suppressed.size(); I != N; ++I)
226         Diag(Suppressed[I].first, Suppressed[I].second);
227 
228       // Clear out the list of suppressed diagnostics, so that we don't emit
229       // them again for this specialization. However, we don't obsolete this
230       // entry from the table, because we want to avoid ever emitting these
231       // diagnostics again.
232       Suppressed.clear();
233     }
234   }
235 
236   // See if this is an auto-typed variable whose initializer we are parsing.
237   if (ParsingInitForAutoVars.count(D)) {
238     Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
239       << D->getDeclName();
240     return true;
241   }
242 
243   // See if this is a deleted function.
244   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
245     if (FD->isDeleted()) {
246       Diag(Loc, diag::err_deleted_function_use);
247       NoteDeletedFunction(FD);
248       return true;
249     }
250   }
251   DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass);
252 
253   // Warn if this is used but marked unused.
254   if (D->hasAttr<UnusedAttr>())
255     Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
256 
257   diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
258 
259   return false;
260 }
261 
262 /// \brief Retrieve the message suffix that should be added to a
263 /// diagnostic complaining about the given function being deleted or
264 /// unavailable.
265 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
266   // FIXME: C++0x implicitly-deleted special member functions could be
267   // detected here so that we could improve diagnostics to say, e.g.,
268   // "base class 'A' had a deleted copy constructor".
269   if (FD->isDeleted())
270     return std::string();
271 
272   std::string Message;
273   if (FD->getAvailability(&Message))
274     return ": " + Message;
275 
276   return std::string();
277 }
278 
279 /// DiagnoseSentinelCalls - This routine checks whether a call or
280 /// message-send is to a declaration with the sentinel attribute, and
281 /// if so, it checks that the requirements of the sentinel are
282 /// satisfied.
283 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
284                                  Expr **args, unsigned numArgs) {
285   const SentinelAttr *attr = D->getAttr<SentinelAttr>();
286   if (!attr)
287     return;
288 
289   // The number of formal parameters of the declaration.
290   unsigned numFormalParams;
291 
292   // The kind of declaration.  This is also an index into a %select in
293   // the diagnostic.
294   enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
295 
296   if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
297     numFormalParams = MD->param_size();
298     calleeType = CT_Method;
299   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
300     numFormalParams = FD->param_size();
301     calleeType = CT_Function;
302   } else if (isa<VarDecl>(D)) {
303     QualType type = cast<ValueDecl>(D)->getType();
304     const FunctionType *fn = 0;
305     if (const PointerType *ptr = type->getAs<PointerType>()) {
306       fn = ptr->getPointeeType()->getAs<FunctionType>();
307       if (!fn) return;
308       calleeType = CT_Function;
309     } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
310       fn = ptr->getPointeeType()->castAs<FunctionType>();
311       calleeType = CT_Block;
312     } else {
313       return;
314     }
315 
316     if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
317       numFormalParams = proto->getNumArgs();
318     } else {
319       numFormalParams = 0;
320     }
321   } else {
322     return;
323   }
324 
325   // "nullPos" is the number of formal parameters at the end which
326   // effectively count as part of the variadic arguments.  This is
327   // useful if you would prefer to not have *any* formal parameters,
328   // but the language forces you to have at least one.
329   unsigned nullPos = attr->getNullPos();
330   assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
331   numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
332 
333   // The number of arguments which should follow the sentinel.
334   unsigned numArgsAfterSentinel = attr->getSentinel();
335 
336   // If there aren't enough arguments for all the formal parameters,
337   // the sentinel, and the args after the sentinel, complain.
338   if (numArgs < numFormalParams + numArgsAfterSentinel + 1) {
339     Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
340     Diag(D->getLocation(), diag::note_sentinel_here) << calleeType;
341     return;
342   }
343 
344   // Otherwise, find the sentinel expression.
345   Expr *sentinelExpr = args[numArgs - numArgsAfterSentinel - 1];
346   if (!sentinelExpr) return;
347   if (sentinelExpr->isValueDependent()) return;
348   if (Context.isSentinelNullExpr(sentinelExpr)) return;
349 
350   // Pick a reasonable string to insert.  Optimistically use 'nil' or
351   // 'NULL' if those are actually defined in the context.  Only use
352   // 'nil' for ObjC methods, where it's much more likely that the
353   // variadic arguments form a list of object pointers.
354   SourceLocation MissingNilLoc
355     = PP.getLocForEndOfToken(sentinelExpr->getLocEnd());
356   std::string NullValue;
357   if (calleeType == CT_Method &&
358       PP.getIdentifierInfo("nil")->hasMacroDefinition())
359     NullValue = "nil";
360   else if (PP.getIdentifierInfo("NULL")->hasMacroDefinition())
361     NullValue = "NULL";
362   else
363     NullValue = "(void*) 0";
364 
365   if (MissingNilLoc.isInvalid())
366     Diag(Loc, diag::warn_missing_sentinel) << calleeType;
367   else
368     Diag(MissingNilLoc, diag::warn_missing_sentinel)
369       << calleeType
370       << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
371   Diag(D->getLocation(), diag::note_sentinel_here) << calleeType;
372 }
373 
374 SourceRange Sema::getExprRange(Expr *E) const {
375   return E ? E->getSourceRange() : SourceRange();
376 }
377 
378 //===----------------------------------------------------------------------===//
379 //  Standard Promotions and Conversions
380 //===----------------------------------------------------------------------===//
381 
382 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
383 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) {
384   // Handle any placeholder expressions which made it here.
385   if (E->getType()->isPlaceholderType()) {
386     ExprResult result = CheckPlaceholderExpr(E);
387     if (result.isInvalid()) return ExprError();
388     E = result.take();
389   }
390 
391   QualType Ty = E->getType();
392   assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
393 
394   if (Ty->isFunctionType())
395     E = ImpCastExprToType(E, Context.getPointerType(Ty),
396                           CK_FunctionToPointerDecay).take();
397   else if (Ty->isArrayType()) {
398     // In C90 mode, arrays only promote to pointers if the array expression is
399     // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
400     // type 'array of type' is converted to an expression that has type 'pointer
401     // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
402     // that has type 'array of type' ...".  The relevant change is "an lvalue"
403     // (C90) to "an expression" (C99).
404     //
405     // C++ 4.2p1:
406     // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
407     // T" can be converted to an rvalue of type "pointer to T".
408     //
409     if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
410       E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
411                             CK_ArrayToPointerDecay).take();
412   }
413   return Owned(E);
414 }
415 
416 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
417   // Check to see if we are dereferencing a null pointer.  If so,
418   // and if not volatile-qualified, this is undefined behavior that the
419   // optimizer will delete, so warn about it.  People sometimes try to use this
420   // to get a deterministic trap and are surprised by clang's behavior.  This
421   // only handles the pattern "*null", which is a very syntactic check.
422   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
423     if (UO->getOpcode() == UO_Deref &&
424         UO->getSubExpr()->IgnoreParenCasts()->
425           isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
426         !UO->getType().isVolatileQualified()) {
427     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
428                           S.PDiag(diag::warn_indirection_through_null)
429                             << UO->getSubExpr()->getSourceRange());
430     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
431                         S.PDiag(diag::note_indirection_through_null));
432   }
433 }
434 
435 ExprResult Sema::DefaultLvalueConversion(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   // C++ [conv.lval]p1:
444   //   A glvalue of a non-function, non-array type T can be
445   //   converted to a prvalue.
446   if (!E->isGLValue()) return Owned(E);
447 
448   QualType T = E->getType();
449   assert(!T.isNull() && "r-value conversion on typeless expression?");
450 
451   // We don't want to throw lvalue-to-rvalue casts on top of
452   // expressions of certain types in C++.
453   if (getLangOpts().CPlusPlus &&
454       (E->getType() == Context.OverloadTy ||
455        T->isDependentType() ||
456        T->isRecordType()))
457     return Owned(E);
458 
459   // The C standard is actually really unclear on this point, and
460   // DR106 tells us what the result should be but not why.  It's
461   // generally best to say that void types just doesn't undergo
462   // lvalue-to-rvalue at all.  Note that expressions of unqualified
463   // 'void' type are never l-values, but qualified void can be.
464   if (T->isVoidType())
465     return Owned(E);
466 
467   CheckForNullPointerDereference(*this, E);
468 
469   // C++ [conv.lval]p1:
470   //   [...] If T is a non-class type, the type of the prvalue is the
471   //   cv-unqualified version of T. Otherwise, the type of the
472   //   rvalue is T.
473   //
474   // C99 6.3.2.1p2:
475   //   If the lvalue has qualified type, the value has the unqualified
476   //   version of the type of the lvalue; otherwise, the value has the
477   //   type of the lvalue.
478   if (T.hasQualifiers())
479     T = T.getUnqualifiedType();
480 
481   UpdateMarkingForLValueToRValue(E);
482 
483   ExprResult Res = Owned(ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
484                                                   E, 0, VK_RValue));
485 
486   // C11 6.3.2.1p2:
487   //   ... if the lvalue has atomic type, the value has the non-atomic version
488   //   of the type of the lvalue ...
489   if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
490     T = Atomic->getValueType().getUnqualifiedType();
491     Res = Owned(ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic,
492                                          Res.get(), 0, VK_RValue));
493   }
494 
495   return Res;
496 }
497 
498 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) {
499   ExprResult Res = DefaultFunctionArrayConversion(E);
500   if (Res.isInvalid())
501     return ExprError();
502   Res = DefaultLvalueConversion(Res.take());
503   if (Res.isInvalid())
504     return ExprError();
505   return move(Res);
506 }
507 
508 
509 /// UsualUnaryConversions - Performs various conversions that are common to most
510 /// operators (C99 6.3). The conversions of array and function types are
511 /// sometimes suppressed. For example, the array->pointer conversion doesn't
512 /// apply if the array is an argument to the sizeof or address (&) operators.
513 /// In these instances, this routine should *not* be called.
514 ExprResult Sema::UsualUnaryConversions(Expr *E) {
515   // First, convert to an r-value.
516   ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
517   if (Res.isInvalid())
518     return Owned(E);
519   E = Res.take();
520 
521   QualType Ty = E->getType();
522   assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
523 
524   // Half FP is a bit different: it's a storage-only type, meaning that any
525   // "use" of it should be promoted to float.
526   if (Ty->isHalfType())
527     return ImpCastExprToType(Res.take(), Context.FloatTy, CK_FloatingCast);
528 
529   // Try to perform integral promotions if the object has a theoretically
530   // promotable type.
531   if (Ty->isIntegralOrUnscopedEnumerationType()) {
532     // C99 6.3.1.1p2:
533     //
534     //   The following may be used in an expression wherever an int or
535     //   unsigned int may be used:
536     //     - an object or expression with an integer type whose integer
537     //       conversion rank is less than or equal to the rank of int
538     //       and unsigned int.
539     //     - A bit-field of type _Bool, int, signed int, or unsigned int.
540     //
541     //   If an int can represent all values of the original type, the
542     //   value is converted to an int; otherwise, it is converted to an
543     //   unsigned int. These are called the integer promotions. All
544     //   other types are unchanged by the integer promotions.
545 
546     QualType PTy = Context.isPromotableBitField(E);
547     if (!PTy.isNull()) {
548       E = ImpCastExprToType(E, PTy, CK_IntegralCast).take();
549       return Owned(E);
550     }
551     if (Ty->isPromotableIntegerType()) {
552       QualType PT = Context.getPromotedIntegerType(Ty);
553       E = ImpCastExprToType(E, PT, CK_IntegralCast).take();
554       return Owned(E);
555     }
556   }
557   return Owned(E);
558 }
559 
560 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
561 /// do not have a prototype. Arguments that have type float are promoted to
562 /// double. All other argument types are converted by UsualUnaryConversions().
563 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
564   QualType Ty = E->getType();
565   assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
566 
567   ExprResult Res = UsualUnaryConversions(E);
568   if (Res.isInvalid())
569     return Owned(E);
570   E = Res.take();
571 
572   // If this is a 'float' (CVR qualified or typedef) promote to double.
573   if (Ty->isSpecificBuiltinType(BuiltinType::Float))
574     E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).take();
575 
576   // C++ performs lvalue-to-rvalue conversion as a default argument
577   // promotion, even on class types, but note:
578   //   C++11 [conv.lval]p2:
579   //     When an lvalue-to-rvalue conversion occurs in an unevaluated
580   //     operand or a subexpression thereof the value contained in the
581   //     referenced object is not accessed. Otherwise, if the glvalue
582   //     has a class type, the conversion copy-initializes a temporary
583   //     of type T from the glvalue and the result of the conversion
584   //     is a prvalue for the temporary.
585   // FIXME: add some way to gate this entire thing for correctness in
586   // potentially potentially evaluated contexts.
587   if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
588     ExprResult Temp = PerformCopyInitialization(
589                        InitializedEntity::InitializeTemporary(E->getType()),
590                                                 E->getExprLoc(),
591                                                 Owned(E));
592     if (Temp.isInvalid())
593       return ExprError();
594     E = Temp.get();
595   }
596 
597   return Owned(E);
598 }
599 
600 /// Determine the degree of POD-ness for an expression.
601 /// Incomplete types are considered POD, since this check can be performed
602 /// when we're in an unevaluated context.
603 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
604   if (Ty->isIncompleteType()) {
605     if (Ty->isObjCObjectType())
606       return VAK_Invalid;
607     return VAK_Valid;
608   }
609 
610   if (Ty.isCXX98PODType(Context))
611     return VAK_Valid;
612 
613   // C++0x [expr.call]p7:
614   //   Passing a potentially-evaluated argument of class type (Clause 9)
615   //   having a non-trivial copy constructor, a non-trivial move constructor,
616   //   or a non-trivial destructor, with no corresponding parameter,
617   //   is conditionally-supported with implementation-defined semantics.
618   if (getLangOpts().CPlusPlus0x && !Ty->isDependentType())
619     if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
620       if (Record->hasTrivialCopyConstructor() &&
621           Record->hasTrivialMoveConstructor() &&
622           Record->hasTrivialDestructor())
623         return VAK_ValidInCXX11;
624 
625   if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
626     return VAK_Valid;
627   return VAK_Invalid;
628 }
629 
630 bool Sema::variadicArgumentPODCheck(const Expr *E, VariadicCallType CT) {
631   // Don't allow one to pass an Objective-C interface to a vararg.
632   const QualType & Ty = E->getType();
633 
634   // Complain about passing non-POD types through varargs.
635   switch (isValidVarArgType(Ty)) {
636   case VAK_Valid:
637     break;
638   case VAK_ValidInCXX11:
639     DiagRuntimeBehavior(E->getLocStart(), 0,
640         PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
641         << E->getType() << CT);
642     break;
643   case VAK_Invalid: {
644     if (Ty->isObjCObjectType())
645       return DiagRuntimeBehavior(E->getLocStart(), 0,
646                           PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
647                             << Ty << CT);
648 
649     return DiagRuntimeBehavior(E->getLocStart(), 0,
650                    PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
651                    << getLangOpts().CPlusPlus0x << Ty << CT);
652   }
653   }
654   // c++ rules are enforced elsewhere.
655   return false;
656 }
657 
658 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
659 /// will create a trap if the resulting type is not a POD type.
660 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
661                                                   FunctionDecl *FDecl) {
662   if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
663     // Strip the unbridged-cast placeholder expression off, if applicable.
664     if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
665         (CT == VariadicMethod ||
666          (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
667       E = stripARCUnbridgedCast(E);
668 
669     // Otherwise, do normal placeholder checking.
670     } else {
671       ExprResult ExprRes = CheckPlaceholderExpr(E);
672       if (ExprRes.isInvalid())
673         return ExprError();
674       E = ExprRes.take();
675     }
676   }
677 
678   ExprResult ExprRes = DefaultArgumentPromotion(E);
679   if (ExprRes.isInvalid())
680     return ExprError();
681   E = ExprRes.take();
682 
683   // Diagnostics regarding non-POD argument types are
684   // emitted along with format string checking in Sema::CheckFunctionCall().
685   if (isValidVarArgType(E->getType()) == VAK_Invalid) {
686     // Turn this into a trap.
687     CXXScopeSpec SS;
688     SourceLocation TemplateKWLoc;
689     UnqualifiedId Name;
690     Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
691                        E->getLocStart());
692     ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
693                                           Name, true, false);
694     if (TrapFn.isInvalid())
695       return ExprError();
696 
697     ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(),
698                                     E->getLocStart(), MultiExprArg(),
699                                     E->getLocEnd());
700     if (Call.isInvalid())
701       return ExprError();
702 
703     ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
704                                   Call.get(), E);
705     if (Comma.isInvalid())
706       return ExprError();
707     return Comma.get();
708   }
709 
710   if (!getLangOpts().CPlusPlus &&
711       RequireCompleteType(E->getExprLoc(), E->getType(),
712                           diag::err_call_incomplete_argument))
713     return ExprError();
714 
715   return Owned(E);
716 }
717 
718 /// \brief Converts an integer to complex float type.  Helper function of
719 /// UsualArithmeticConversions()
720 ///
721 /// \return false if the integer expression is an integer type and is
722 /// successfully converted to the complex type.
723 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
724                                                   ExprResult &ComplexExpr,
725                                                   QualType IntTy,
726                                                   QualType ComplexTy,
727                                                   bool SkipCast) {
728   if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
729   if (SkipCast) return false;
730   if (IntTy->isIntegerType()) {
731     QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
732     IntExpr = S.ImpCastExprToType(IntExpr.take(), fpTy, CK_IntegralToFloating);
733     IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
734                                   CK_FloatingRealToComplex);
735   } else {
736     assert(IntTy->isComplexIntegerType());
737     IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
738                                   CK_IntegralComplexToFloatingComplex);
739   }
740   return false;
741 }
742 
743 /// \brief Takes two complex float types and converts them to the same type.
744 /// Helper function of UsualArithmeticConversions()
745 static QualType
746 handleComplexFloatToComplexFloatConverstion(Sema &S, ExprResult &LHS,
747                                             ExprResult &RHS, QualType LHSType,
748                                             QualType RHSType,
749                                             bool IsCompAssign) {
750   int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
751 
752   if (order < 0) {
753     // _Complex float -> _Complex double
754     if (!IsCompAssign)
755       LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingComplexCast);
756     return RHSType;
757   }
758   if (order > 0)
759     // _Complex float -> _Complex double
760     RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingComplexCast);
761   return LHSType;
762 }
763 
764 /// \brief Converts otherExpr to complex float and promotes complexExpr if
765 /// necessary.  Helper function of UsualArithmeticConversions()
766 static QualType handleOtherComplexFloatConversion(Sema &S,
767                                                   ExprResult &ComplexExpr,
768                                                   ExprResult &OtherExpr,
769                                                   QualType ComplexTy,
770                                                   QualType OtherTy,
771                                                   bool ConvertComplexExpr,
772                                                   bool ConvertOtherExpr) {
773   int order = S.Context.getFloatingTypeOrder(ComplexTy, OtherTy);
774 
775   // If just the complexExpr is complex, the otherExpr needs to be converted,
776   // and the complexExpr might need to be promoted.
777   if (order > 0) { // complexExpr is wider
778     // float -> _Complex double
779     if (ConvertOtherExpr) {
780       QualType fp = cast<ComplexType>(ComplexTy)->getElementType();
781       OtherExpr = S.ImpCastExprToType(OtherExpr.take(), fp, CK_FloatingCast);
782       OtherExpr = S.ImpCastExprToType(OtherExpr.take(), ComplexTy,
783                                       CK_FloatingRealToComplex);
784     }
785     return ComplexTy;
786   }
787 
788   // otherTy is at least as wide.  Find its corresponding complex type.
789   QualType result = (order == 0 ? ComplexTy :
790                                   S.Context.getComplexType(OtherTy));
791 
792   // double -> _Complex double
793   if (ConvertOtherExpr)
794     OtherExpr = S.ImpCastExprToType(OtherExpr.take(), result,
795                                     CK_FloatingRealToComplex);
796 
797   // _Complex float -> _Complex double
798   if (ConvertComplexExpr && order < 0)
799     ComplexExpr = S.ImpCastExprToType(ComplexExpr.take(), result,
800                                       CK_FloatingComplexCast);
801 
802   return result;
803 }
804 
805 /// \brief Handle arithmetic conversion with complex types.  Helper function of
806 /// UsualArithmeticConversions()
807 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
808                                              ExprResult &RHS, QualType LHSType,
809                                              QualType RHSType,
810                                              bool IsCompAssign) {
811   // if we have an integer operand, the result is the complex type.
812   if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
813                                              /*skipCast*/false))
814     return LHSType;
815   if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
816                                              /*skipCast*/IsCompAssign))
817     return RHSType;
818 
819   // This handles complex/complex, complex/float, or float/complex.
820   // When both operands are complex, the shorter operand is converted to the
821   // type of the longer, and that is the type of the result. This corresponds
822   // to what is done when combining two real floating-point operands.
823   // The fun begins when size promotion occur across type domains.
824   // From H&S 6.3.4: When one operand is complex and the other is a real
825   // floating-point type, the less precise type is converted, within it's
826   // real or complex domain, to the precision of the other type. For example,
827   // when combining a "long double" with a "double _Complex", the
828   // "double _Complex" is promoted to "long double _Complex".
829 
830   bool LHSComplexFloat = LHSType->isComplexType();
831   bool RHSComplexFloat = RHSType->isComplexType();
832 
833   // If both are complex, just cast to the more precise type.
834   if (LHSComplexFloat && RHSComplexFloat)
835     return handleComplexFloatToComplexFloatConverstion(S, LHS, RHS,
836                                                        LHSType, RHSType,
837                                                        IsCompAssign);
838 
839   // If only one operand is complex, promote it if necessary and convert the
840   // other operand to complex.
841   if (LHSComplexFloat)
842     return handleOtherComplexFloatConversion(
843         S, LHS, RHS, LHSType, RHSType, /*convertComplexExpr*/!IsCompAssign,
844         /*convertOtherExpr*/ true);
845 
846   assert(RHSComplexFloat);
847   return handleOtherComplexFloatConversion(
848       S, RHS, LHS, RHSType, LHSType, /*convertComplexExpr*/true,
849       /*convertOtherExpr*/ !IsCompAssign);
850 }
851 
852 /// \brief Hande arithmetic conversion from integer to float.  Helper function
853 /// of UsualArithmeticConversions()
854 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
855                                            ExprResult &IntExpr,
856                                            QualType FloatTy, QualType IntTy,
857                                            bool ConvertFloat, bool ConvertInt) {
858   if (IntTy->isIntegerType()) {
859     if (ConvertInt)
860       // Convert intExpr to the lhs floating point type.
861       IntExpr = S.ImpCastExprToType(IntExpr.take(), FloatTy,
862                                     CK_IntegralToFloating);
863     return FloatTy;
864   }
865 
866   // Convert both sides to the appropriate complex float.
867   assert(IntTy->isComplexIntegerType());
868   QualType result = S.Context.getComplexType(FloatTy);
869 
870   // _Complex int -> _Complex float
871   if (ConvertInt)
872     IntExpr = S.ImpCastExprToType(IntExpr.take(), result,
873                                   CK_IntegralComplexToFloatingComplex);
874 
875   // float -> _Complex float
876   if (ConvertFloat)
877     FloatExpr = S.ImpCastExprToType(FloatExpr.take(), result,
878                                     CK_FloatingRealToComplex);
879 
880   return result;
881 }
882 
883 /// \brief Handle arithmethic conversion with floating point types.  Helper
884 /// function of UsualArithmeticConversions()
885 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
886                                       ExprResult &RHS, QualType LHSType,
887                                       QualType RHSType, bool IsCompAssign) {
888   bool LHSFloat = LHSType->isRealFloatingType();
889   bool RHSFloat = RHSType->isRealFloatingType();
890 
891   // If we have two real floating types, convert the smaller operand
892   // to the bigger result.
893   if (LHSFloat && RHSFloat) {
894     int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
895     if (order > 0) {
896       RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingCast);
897       return LHSType;
898     }
899 
900     assert(order < 0 && "illegal float comparison");
901     if (!IsCompAssign)
902       LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingCast);
903     return RHSType;
904   }
905 
906   if (LHSFloat)
907     return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
908                                       /*convertFloat=*/!IsCompAssign,
909                                       /*convertInt=*/ true);
910   assert(RHSFloat);
911   return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
912                                     /*convertInt=*/ true,
913                                     /*convertFloat=*/!IsCompAssign);
914 }
915 
916 /// \brief Handle conversions with GCC complex int extension.  Helper function
917 /// of UsualArithmeticConversions()
918 // FIXME: if the operands are (int, _Complex long), we currently
919 // don't promote the complex.  Also, signedness?
920 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
921                                            ExprResult &RHS, QualType LHSType,
922                                            QualType RHSType,
923                                            bool IsCompAssign) {
924   const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
925   const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
926 
927   if (LHSComplexInt && RHSComplexInt) {
928     int order = S.Context.getIntegerTypeOrder(LHSComplexInt->getElementType(),
929                                               RHSComplexInt->getElementType());
930     assert(order && "inequal types with equal element ordering");
931     if (order > 0) {
932       // _Complex int -> _Complex long
933       RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralComplexCast);
934       return LHSType;
935     }
936 
937     if (!IsCompAssign)
938       LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralComplexCast);
939     return RHSType;
940   }
941 
942   if (LHSComplexInt) {
943     // int -> _Complex int
944     // FIXME: This needs to take integer ranks into account
945     RHS = S.ImpCastExprToType(RHS.take(), LHSComplexInt->getElementType(),
946                               CK_IntegralCast);
947     RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralRealToComplex);
948     return LHSType;
949   }
950 
951   assert(RHSComplexInt);
952   // int -> _Complex int
953   // FIXME: This needs to take integer ranks into account
954   if (!IsCompAssign) {
955     LHS = S.ImpCastExprToType(LHS.take(), RHSComplexInt->getElementType(),
956                               CK_IntegralCast);
957     LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralRealToComplex);
958   }
959   return RHSType;
960 }
961 
962 /// \brief Handle integer arithmetic conversions.  Helper function of
963 /// UsualArithmeticConversions()
964 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
965                                         ExprResult &RHS, QualType LHSType,
966                                         QualType RHSType, bool IsCompAssign) {
967   // The rules for this case are in C99 6.3.1.8
968   int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
969   bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
970   bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
971   if (LHSSigned == RHSSigned) {
972     // Same signedness; use the higher-ranked type
973     if (order >= 0) {
974       RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
975       return LHSType;
976     } else if (!IsCompAssign)
977       LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
978     return RHSType;
979   } else if (order != (LHSSigned ? 1 : -1)) {
980     // The unsigned type has greater than or equal rank to the
981     // signed type, so use the unsigned type
982     if (RHSSigned) {
983       RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
984       return LHSType;
985     } else if (!IsCompAssign)
986       LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
987     return RHSType;
988   } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
989     // The two types are different widths; if we are here, that
990     // means the signed type is larger than the unsigned type, so
991     // use the signed type.
992     if (LHSSigned) {
993       RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
994       return LHSType;
995     } else if (!IsCompAssign)
996       LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
997     return RHSType;
998   } else {
999     // The signed type is higher-ranked than the unsigned type,
1000     // but isn't actually any bigger (like unsigned int and long
1001     // on most 32-bit systems).  Use the unsigned type corresponding
1002     // to the signed type.
1003     QualType result =
1004       S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1005     RHS = S.ImpCastExprToType(RHS.take(), result, CK_IntegralCast);
1006     if (!IsCompAssign)
1007       LHS = S.ImpCastExprToType(LHS.take(), result, CK_IntegralCast);
1008     return result;
1009   }
1010 }
1011 
1012 /// UsualArithmeticConversions - Performs various conversions that are common to
1013 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1014 /// routine returns the first non-arithmetic type found. The client is
1015 /// responsible for emitting appropriate error diagnostics.
1016 /// FIXME: verify the conversion rules for "complex int" are consistent with
1017 /// GCC.
1018 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1019                                           bool IsCompAssign) {
1020   if (!IsCompAssign) {
1021     LHS = UsualUnaryConversions(LHS.take());
1022     if (LHS.isInvalid())
1023       return QualType();
1024   }
1025 
1026   RHS = UsualUnaryConversions(RHS.take());
1027   if (RHS.isInvalid())
1028     return QualType();
1029 
1030   // For conversion purposes, we ignore any qualifiers.
1031   // For example, "const float" and "float" are equivalent.
1032   QualType LHSType =
1033     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1034   QualType RHSType =
1035     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1036 
1037   // For conversion purposes, we ignore any atomic qualifier on the LHS.
1038   if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1039     LHSType = AtomicLHS->getValueType();
1040 
1041   // If both types are identical, no conversion is needed.
1042   if (LHSType == RHSType)
1043     return LHSType;
1044 
1045   // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1046   // The caller can deal with this (e.g. pointer + int).
1047   if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1048     return QualType();
1049 
1050   // Apply unary and bitfield promotions to the LHS's type.
1051   QualType LHSUnpromotedType = LHSType;
1052   if (LHSType->isPromotableIntegerType())
1053     LHSType = Context.getPromotedIntegerType(LHSType);
1054   QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1055   if (!LHSBitfieldPromoteTy.isNull())
1056     LHSType = LHSBitfieldPromoteTy;
1057   if (LHSType != LHSUnpromotedType && !IsCompAssign)
1058     LHS = ImpCastExprToType(LHS.take(), LHSType, CK_IntegralCast);
1059 
1060   // If both types are identical, no conversion is needed.
1061   if (LHSType == RHSType)
1062     return LHSType;
1063 
1064   // At this point, we have two different arithmetic types.
1065 
1066   // Handle complex types first (C99 6.3.1.8p1).
1067   if (LHSType->isComplexType() || RHSType->isComplexType())
1068     return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1069                                         IsCompAssign);
1070 
1071   // Now handle "real" floating types (i.e. float, double, long double).
1072   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1073     return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1074                                  IsCompAssign);
1075 
1076   // Handle GCC complex int extension.
1077   if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1078     return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1079                                       IsCompAssign);
1080 
1081   // Finally, we have two differing integer types.
1082   return handleIntegerConversion(*this, LHS, RHS, LHSType, RHSType,
1083                                  IsCompAssign);
1084 }
1085 
1086 //===----------------------------------------------------------------------===//
1087 //  Semantic Analysis for various Expression Types
1088 //===----------------------------------------------------------------------===//
1089 
1090 
1091 ExprResult
1092 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1093                                 SourceLocation DefaultLoc,
1094                                 SourceLocation RParenLoc,
1095                                 Expr *ControllingExpr,
1096                                 MultiTypeArg ArgTypes,
1097                                 MultiExprArg ArgExprs) {
1098   unsigned NumAssocs = ArgTypes.size();
1099   assert(NumAssocs == ArgExprs.size());
1100 
1101   ParsedType *ParsedTypes = ArgTypes.release();
1102   Expr **Exprs = ArgExprs.release();
1103 
1104   TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1105   for (unsigned i = 0; i < NumAssocs; ++i) {
1106     if (ParsedTypes[i])
1107       (void) GetTypeFromParser(ParsedTypes[i], &Types[i]);
1108     else
1109       Types[i] = 0;
1110   }
1111 
1112   ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1113                                              ControllingExpr, Types, Exprs,
1114                                              NumAssocs);
1115   delete [] Types;
1116   return ER;
1117 }
1118 
1119 ExprResult
1120 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1121                                  SourceLocation DefaultLoc,
1122                                  SourceLocation RParenLoc,
1123                                  Expr *ControllingExpr,
1124                                  TypeSourceInfo **Types,
1125                                  Expr **Exprs,
1126                                  unsigned NumAssocs) {
1127   bool TypeErrorFound = false,
1128        IsResultDependent = ControllingExpr->isTypeDependent(),
1129        ContainsUnexpandedParameterPack
1130          = ControllingExpr->containsUnexpandedParameterPack();
1131 
1132   for (unsigned i = 0; i < NumAssocs; ++i) {
1133     if (Exprs[i]->containsUnexpandedParameterPack())
1134       ContainsUnexpandedParameterPack = true;
1135 
1136     if (Types[i]) {
1137       if (Types[i]->getType()->containsUnexpandedParameterPack())
1138         ContainsUnexpandedParameterPack = true;
1139 
1140       if (Types[i]->getType()->isDependentType()) {
1141         IsResultDependent = true;
1142       } else {
1143         // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1144         // complete object type other than a variably modified type."
1145         unsigned D = 0;
1146         if (Types[i]->getType()->isIncompleteType())
1147           D = diag::err_assoc_type_incomplete;
1148         else if (!Types[i]->getType()->isObjectType())
1149           D = diag::err_assoc_type_nonobject;
1150         else if (Types[i]->getType()->isVariablyModifiedType())
1151           D = diag::err_assoc_type_variably_modified;
1152 
1153         if (D != 0) {
1154           Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1155             << Types[i]->getTypeLoc().getSourceRange()
1156             << Types[i]->getType();
1157           TypeErrorFound = true;
1158         }
1159 
1160         // C11 6.5.1.1p2 "No two generic associations in the same generic
1161         // selection shall specify compatible types."
1162         for (unsigned j = i+1; j < NumAssocs; ++j)
1163           if (Types[j] && !Types[j]->getType()->isDependentType() &&
1164               Context.typesAreCompatible(Types[i]->getType(),
1165                                          Types[j]->getType())) {
1166             Diag(Types[j]->getTypeLoc().getBeginLoc(),
1167                  diag::err_assoc_compatible_types)
1168               << Types[j]->getTypeLoc().getSourceRange()
1169               << Types[j]->getType()
1170               << Types[i]->getType();
1171             Diag(Types[i]->getTypeLoc().getBeginLoc(),
1172                  diag::note_compat_assoc)
1173               << Types[i]->getTypeLoc().getSourceRange()
1174               << Types[i]->getType();
1175             TypeErrorFound = true;
1176           }
1177       }
1178     }
1179   }
1180   if (TypeErrorFound)
1181     return ExprError();
1182 
1183   // If we determined that the generic selection is result-dependent, don't
1184   // try to compute the result expression.
1185   if (IsResultDependent)
1186     return Owned(new (Context) GenericSelectionExpr(
1187                    Context, KeyLoc, ControllingExpr,
1188                    Types, Exprs, NumAssocs, DefaultLoc,
1189                    RParenLoc, ContainsUnexpandedParameterPack));
1190 
1191   SmallVector<unsigned, 1> CompatIndices;
1192   unsigned DefaultIndex = -1U;
1193   for (unsigned i = 0; i < NumAssocs; ++i) {
1194     if (!Types[i])
1195       DefaultIndex = i;
1196     else if (Context.typesAreCompatible(ControllingExpr->getType(),
1197                                         Types[i]->getType()))
1198       CompatIndices.push_back(i);
1199   }
1200 
1201   // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1202   // type compatible with at most one of the types named in its generic
1203   // association list."
1204   if (CompatIndices.size() > 1) {
1205     // We strip parens here because the controlling expression is typically
1206     // parenthesized in macro definitions.
1207     ControllingExpr = ControllingExpr->IgnoreParens();
1208     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1209       << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1210       << (unsigned) CompatIndices.size();
1211     for (SmallVector<unsigned, 1>::iterator I = CompatIndices.begin(),
1212          E = CompatIndices.end(); I != E; ++I) {
1213       Diag(Types[*I]->getTypeLoc().getBeginLoc(),
1214            diag::note_compat_assoc)
1215         << Types[*I]->getTypeLoc().getSourceRange()
1216         << Types[*I]->getType();
1217     }
1218     return ExprError();
1219   }
1220 
1221   // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1222   // its controlling expression shall have type compatible with exactly one of
1223   // the types named in its generic association list."
1224   if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1225     // We strip parens here because the controlling expression is typically
1226     // parenthesized in macro definitions.
1227     ControllingExpr = ControllingExpr->IgnoreParens();
1228     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1229       << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1230     return ExprError();
1231   }
1232 
1233   // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1234   // type name that is compatible with the type of the controlling expression,
1235   // then the result expression of the generic selection is the expression
1236   // in that generic association. Otherwise, the result expression of the
1237   // generic selection is the expression in the default generic association."
1238   unsigned ResultIndex =
1239     CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1240 
1241   return Owned(new (Context) GenericSelectionExpr(
1242                  Context, KeyLoc, ControllingExpr,
1243                  Types, Exprs, NumAssocs, DefaultLoc,
1244                  RParenLoc, ContainsUnexpandedParameterPack,
1245                  ResultIndex));
1246 }
1247 
1248 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1249 /// location of the token and the offset of the ud-suffix within it.
1250 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1251                                      unsigned Offset) {
1252   return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1253                                         S.getLangOpts());
1254 }
1255 
1256 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1257 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1258 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1259                                                  IdentifierInfo *UDSuffix,
1260                                                  SourceLocation UDSuffixLoc,
1261                                                  ArrayRef<Expr*> Args,
1262                                                  SourceLocation LitEndLoc) {
1263   assert(Args.size() <= 2 && "too many arguments for literal operator");
1264 
1265   QualType ArgTy[2];
1266   for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1267     ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1268     if (ArgTy[ArgIdx]->isArrayType())
1269       ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1270   }
1271 
1272   DeclarationName OpName =
1273     S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1274   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1275   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1276 
1277   LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1278   if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1279                               /*AllowRawAndTemplate*/false) == Sema::LOLR_Error)
1280     return ExprError();
1281 
1282   return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1283 }
1284 
1285 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1286 /// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
1287 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1288 /// multiple tokens.  However, the common case is that StringToks points to one
1289 /// string.
1290 ///
1291 ExprResult
1292 Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks,
1293                          Scope *UDLScope) {
1294   assert(NumStringToks && "Must have at least one string!");
1295 
1296   StringLiteralParser Literal(StringToks, NumStringToks, PP);
1297   if (Literal.hadError)
1298     return ExprError();
1299 
1300   SmallVector<SourceLocation, 4> StringTokLocs;
1301   for (unsigned i = 0; i != NumStringToks; ++i)
1302     StringTokLocs.push_back(StringToks[i].getLocation());
1303 
1304   QualType StrTy = Context.CharTy;
1305   if (Literal.isWide())
1306     StrTy = Context.getWCharType();
1307   else if (Literal.isUTF16())
1308     StrTy = Context.Char16Ty;
1309   else if (Literal.isUTF32())
1310     StrTy = Context.Char32Ty;
1311   else if (Literal.isPascal())
1312     StrTy = Context.UnsignedCharTy;
1313 
1314   StringLiteral::StringKind Kind = StringLiteral::Ascii;
1315   if (Literal.isWide())
1316     Kind = StringLiteral::Wide;
1317   else if (Literal.isUTF8())
1318     Kind = StringLiteral::UTF8;
1319   else if (Literal.isUTF16())
1320     Kind = StringLiteral::UTF16;
1321   else if (Literal.isUTF32())
1322     Kind = StringLiteral::UTF32;
1323 
1324   // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
1325   if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
1326     StrTy.addConst();
1327 
1328   // Get an array type for the string, according to C99 6.4.5.  This includes
1329   // the nul terminator character as well as the string length for pascal
1330   // strings.
1331   StrTy = Context.getConstantArrayType(StrTy,
1332                                  llvm::APInt(32, Literal.GetNumStringChars()+1),
1333                                        ArrayType::Normal, 0);
1334 
1335   // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1336   StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1337                                              Kind, Literal.Pascal, StrTy,
1338                                              &StringTokLocs[0],
1339                                              StringTokLocs.size());
1340   if (Literal.getUDSuffix().empty())
1341     return Owned(Lit);
1342 
1343   // We're building a user-defined literal.
1344   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1345   SourceLocation UDSuffixLoc =
1346     getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1347                    Literal.getUDSuffixOffset());
1348 
1349   // Make sure we're allowed user-defined literals here.
1350   if (!UDLScope)
1351     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1352 
1353   // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1354   //   operator "" X (str, len)
1355   QualType SizeType = Context.getSizeType();
1356   llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1357   IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1358                                                   StringTokLocs[0]);
1359   Expr *Args[] = { Lit, LenArg };
1360   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
1361                                         Args, StringTokLocs.back());
1362 }
1363 
1364 ExprResult
1365 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1366                        SourceLocation Loc,
1367                        const CXXScopeSpec *SS) {
1368   DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1369   return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1370 }
1371 
1372 /// BuildDeclRefExpr - Build an expression that references a
1373 /// declaration that does not require a closure capture.
1374 ExprResult
1375 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1376                        const DeclarationNameInfo &NameInfo,
1377                        const CXXScopeSpec *SS) {
1378   if (getLangOpts().CUDA)
1379     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
1380       if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) {
1381         CUDAFunctionTarget CallerTarget = IdentifyCUDATarget(Caller),
1382                            CalleeTarget = IdentifyCUDATarget(Callee);
1383         if (CheckCUDATarget(CallerTarget, CalleeTarget)) {
1384           Diag(NameInfo.getLoc(), diag::err_ref_bad_target)
1385             << CalleeTarget << D->getIdentifier() << CallerTarget;
1386           Diag(D->getLocation(), diag::note_previous_decl)
1387             << D->getIdentifier();
1388           return ExprError();
1389         }
1390       }
1391 
1392   bool refersToEnclosingScope =
1393     (CurContext != D->getDeclContext() &&
1394      D->getDeclContext()->isFunctionOrMethod());
1395 
1396   DeclRefExpr *E = DeclRefExpr::Create(Context,
1397                                        SS ? SS->getWithLocInContext(Context)
1398                                               : NestedNameSpecifierLoc(),
1399                                        SourceLocation(),
1400                                        D, refersToEnclosingScope,
1401                                        NameInfo, Ty, VK);
1402 
1403   MarkDeclRefReferenced(E);
1404 
1405   // Just in case we're building an illegal pointer-to-member.
1406   FieldDecl *FD = dyn_cast<FieldDecl>(D);
1407   if (FD && FD->isBitField())
1408     E->setObjectKind(OK_BitField);
1409 
1410   return Owned(E);
1411 }
1412 
1413 /// Decomposes the given name into a DeclarationNameInfo, its location, and
1414 /// possibly a list of template arguments.
1415 ///
1416 /// If this produces template arguments, it is permitted to call
1417 /// DecomposeTemplateName.
1418 ///
1419 /// This actually loses a lot of source location information for
1420 /// non-standard name kinds; we should consider preserving that in
1421 /// some way.
1422 void
1423 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1424                              TemplateArgumentListInfo &Buffer,
1425                              DeclarationNameInfo &NameInfo,
1426                              const TemplateArgumentListInfo *&TemplateArgs) {
1427   if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1428     Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1429     Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1430 
1431     ASTTemplateArgsPtr TemplateArgsPtr(*this,
1432                                        Id.TemplateId->getTemplateArgs(),
1433                                        Id.TemplateId->NumArgs);
1434     translateTemplateArguments(TemplateArgsPtr, Buffer);
1435     TemplateArgsPtr.release();
1436 
1437     TemplateName TName = Id.TemplateId->Template.get();
1438     SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1439     NameInfo = Context.getNameForTemplate(TName, TNameLoc);
1440     TemplateArgs = &Buffer;
1441   } else {
1442     NameInfo = GetNameFromUnqualifiedId(Id);
1443     TemplateArgs = 0;
1444   }
1445 }
1446 
1447 /// Diagnose an empty lookup.
1448 ///
1449 /// \return false if new lookup candidates were found
1450 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1451                                CorrectionCandidateCallback &CCC,
1452                                TemplateArgumentListInfo *ExplicitTemplateArgs,
1453                                llvm::ArrayRef<Expr *> Args) {
1454   DeclarationName Name = R.getLookupName();
1455 
1456   unsigned diagnostic = diag::err_undeclared_var_use;
1457   unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
1458   if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1459       Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
1460       Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
1461     diagnostic = diag::err_undeclared_use;
1462     diagnostic_suggest = diag::err_undeclared_use_suggest;
1463   }
1464 
1465   // If the original lookup was an unqualified lookup, fake an
1466   // unqualified lookup.  This is useful when (for example) the
1467   // original lookup would not have found something because it was a
1468   // dependent name.
1469   DeclContext *DC = (SS.isEmpty() && !CallsUndergoingInstantiation.empty())
1470     ? CurContext : 0;
1471   while (DC) {
1472     if (isa<CXXRecordDecl>(DC)) {
1473       LookupQualifiedName(R, DC);
1474 
1475       if (!R.empty()) {
1476         // Don't give errors about ambiguities in this lookup.
1477         R.suppressDiagnostics();
1478 
1479         // During a default argument instantiation the CurContext points
1480         // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1481         // function parameter list, hence add an explicit check.
1482         bool isDefaultArgument = !ActiveTemplateInstantiations.empty() &&
1483                               ActiveTemplateInstantiations.back().Kind ==
1484             ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
1485         CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1486         bool isInstance = CurMethod &&
1487                           CurMethod->isInstance() &&
1488                           DC == CurMethod->getParent() && !isDefaultArgument;
1489 
1490 
1491         // Give a code modification hint to insert 'this->'.
1492         // TODO: fixit for inserting 'Base<T>::' in the other cases.
1493         // Actually quite difficult!
1494         if (getLangOpts().MicrosoftMode)
1495           diagnostic = diag::warn_found_via_dependent_bases_lookup;
1496         if (isInstance) {
1497           Diag(R.getNameLoc(), diagnostic) << Name
1498             << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1499           UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1500               CallsUndergoingInstantiation.back()->getCallee());
1501 
1502 
1503           CXXMethodDecl *DepMethod;
1504           if (CurMethod->getTemplatedKind() ==
1505               FunctionDecl::TK_FunctionTemplateSpecialization)
1506             DepMethod = cast<CXXMethodDecl>(CurMethod->getPrimaryTemplate()->
1507                 getInstantiatedFromMemberTemplate()->getTemplatedDecl());
1508           else
1509             DepMethod = cast<CXXMethodDecl>(
1510                 CurMethod->getInstantiatedFromMemberFunction());
1511           assert(DepMethod && "No template pattern found");
1512 
1513           QualType DepThisType = DepMethod->getThisType(Context);
1514           CheckCXXThisCapture(R.getNameLoc());
1515           CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1516                                      R.getNameLoc(), DepThisType, false);
1517           TemplateArgumentListInfo TList;
1518           if (ULE->hasExplicitTemplateArgs())
1519             ULE->copyTemplateArgumentsInto(TList);
1520 
1521           CXXScopeSpec SS;
1522           SS.Adopt(ULE->getQualifierLoc());
1523           CXXDependentScopeMemberExpr *DepExpr =
1524               CXXDependentScopeMemberExpr::Create(
1525                   Context, DepThis, DepThisType, true, SourceLocation(),
1526                   SS.getWithLocInContext(Context),
1527                   ULE->getTemplateKeywordLoc(), 0,
1528                   R.getLookupNameInfo(),
1529                   ULE->hasExplicitTemplateArgs() ? &TList : 0);
1530           CallsUndergoingInstantiation.back()->setCallee(DepExpr);
1531         } else {
1532           Diag(R.getNameLoc(), diagnostic) << Name;
1533         }
1534 
1535         // Do we really want to note all of these?
1536         for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1537           Diag((*I)->getLocation(), diag::note_dependent_var_use);
1538 
1539         // Return true if we are inside a default argument instantiation
1540         // and the found name refers to an instance member function, otherwise
1541         // the function calling DiagnoseEmptyLookup will try to create an
1542         // implicit member call and this is wrong for default argument.
1543         if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1544           Diag(R.getNameLoc(), diag::err_member_call_without_object);
1545           return true;
1546         }
1547 
1548         // Tell the callee to try to recover.
1549         return false;
1550       }
1551 
1552       R.clear();
1553     }
1554 
1555     // In Microsoft mode, if we are performing lookup from within a friend
1556     // function definition declared at class scope then we must set
1557     // DC to the lexical parent to be able to search into the parent
1558     // class.
1559     if (getLangOpts().MicrosoftMode && isa<FunctionDecl>(DC) &&
1560         cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1561         DC->getLexicalParent()->isRecord())
1562       DC = DC->getLexicalParent();
1563     else
1564       DC = DC->getParent();
1565   }
1566 
1567   // We didn't find anything, so try to correct for a typo.
1568   TypoCorrection Corrected;
1569   if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
1570                                     S, &SS, CCC))) {
1571     std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1572     std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOpts()));
1573     R.setLookupName(Corrected.getCorrection());
1574 
1575     if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
1576       if (Corrected.isOverloaded()) {
1577         OverloadCandidateSet OCS(R.getNameLoc());
1578         OverloadCandidateSet::iterator Best;
1579         for (TypoCorrection::decl_iterator CD = Corrected.begin(),
1580                                         CDEnd = Corrected.end();
1581              CD != CDEnd; ++CD) {
1582           if (FunctionTemplateDecl *FTD =
1583                    dyn_cast<FunctionTemplateDecl>(*CD))
1584             AddTemplateOverloadCandidate(
1585                 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
1586                 Args, OCS);
1587           else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
1588             if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1589               AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
1590                                    Args, OCS);
1591         }
1592         switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1593           case OR_Success:
1594             ND = Best->Function;
1595             break;
1596           default:
1597             break;
1598         }
1599       }
1600       R.addDecl(ND);
1601       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
1602         if (SS.isEmpty())
1603           Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr
1604             << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1605         else
1606           Diag(R.getNameLoc(), diag::err_no_member_suggest)
1607             << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
1608             << SS.getRange()
1609             << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1610         if (ND)
1611           Diag(ND->getLocation(), diag::note_previous_decl)
1612             << CorrectedQuotedStr;
1613 
1614         // Tell the callee to try to recover.
1615         return false;
1616       }
1617 
1618       if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) {
1619         // FIXME: If we ended up with a typo for a type name or
1620         // Objective-C class name, we're in trouble because the parser
1621         // is in the wrong place to recover. Suggest the typo
1622         // correction, but don't make it a fix-it since we're not going
1623         // to recover well anyway.
1624         if (SS.isEmpty())
1625           Diag(R.getNameLoc(), diagnostic_suggest)
1626             << Name << CorrectedQuotedStr;
1627         else
1628           Diag(R.getNameLoc(), diag::err_no_member_suggest)
1629             << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
1630             << SS.getRange();
1631 
1632         // Don't try to recover; it won't work.
1633         return true;
1634       }
1635     } else {
1636       // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
1637       // because we aren't able to recover.
1638       if (SS.isEmpty())
1639         Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr;
1640       else
1641         Diag(R.getNameLoc(), diag::err_no_member_suggest)
1642         << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
1643         << SS.getRange();
1644       return true;
1645     }
1646   }
1647   R.clear();
1648 
1649   // Emit a special diagnostic for failed member lookups.
1650   // FIXME: computing the declaration context might fail here (?)
1651   if (!SS.isEmpty()) {
1652     Diag(R.getNameLoc(), diag::err_no_member)
1653       << Name << computeDeclContext(SS, false)
1654       << SS.getRange();
1655     return true;
1656   }
1657 
1658   // Give up, we can't recover.
1659   Diag(R.getNameLoc(), diagnostic) << Name;
1660   return true;
1661 }
1662 
1663 ExprResult Sema::ActOnIdExpression(Scope *S,
1664                                    CXXScopeSpec &SS,
1665                                    SourceLocation TemplateKWLoc,
1666                                    UnqualifiedId &Id,
1667                                    bool HasTrailingLParen,
1668                                    bool IsAddressOfOperand,
1669                                    CorrectionCandidateCallback *CCC) {
1670   assert(!(IsAddressOfOperand && HasTrailingLParen) &&
1671          "cannot be direct & operand and have a trailing lparen");
1672 
1673   if (SS.isInvalid())
1674     return ExprError();
1675 
1676   TemplateArgumentListInfo TemplateArgsBuffer;
1677 
1678   // Decompose the UnqualifiedId into the following data.
1679   DeclarationNameInfo NameInfo;
1680   const TemplateArgumentListInfo *TemplateArgs;
1681   DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
1682 
1683   DeclarationName Name = NameInfo.getName();
1684   IdentifierInfo *II = Name.getAsIdentifierInfo();
1685   SourceLocation NameLoc = NameInfo.getLoc();
1686 
1687   // C++ [temp.dep.expr]p3:
1688   //   An id-expression is type-dependent if it contains:
1689   //     -- an identifier that was declared with a dependent type,
1690   //        (note: handled after lookup)
1691   //     -- a template-id that is dependent,
1692   //        (note: handled in BuildTemplateIdExpr)
1693   //     -- a conversion-function-id that specifies a dependent type,
1694   //     -- a nested-name-specifier that contains a class-name that
1695   //        names a dependent type.
1696   // Determine whether this is a member of an unknown specialization;
1697   // we need to handle these differently.
1698   bool DependentID = false;
1699   if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1700       Name.getCXXNameType()->isDependentType()) {
1701     DependentID = true;
1702   } else if (SS.isSet()) {
1703     if (DeclContext *DC = computeDeclContext(SS, false)) {
1704       if (RequireCompleteDeclContext(SS, DC))
1705         return ExprError();
1706     } else {
1707       DependentID = true;
1708     }
1709   }
1710 
1711   if (DependentID)
1712     return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1713                                       IsAddressOfOperand, TemplateArgs);
1714 
1715   // Perform the required lookup.
1716   LookupResult R(*this, NameInfo,
1717                  (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
1718                   ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
1719   if (TemplateArgs) {
1720     // Lookup the template name again to correctly establish the context in
1721     // which it was found. This is really unfortunate as we already did the
1722     // lookup to determine that it was a template name in the first place. If
1723     // this becomes a performance hit, we can work harder to preserve those
1724     // results until we get here but it's likely not worth it.
1725     bool MemberOfUnknownSpecialization;
1726     LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1727                        MemberOfUnknownSpecialization);
1728 
1729     if (MemberOfUnknownSpecialization ||
1730         (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
1731       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1732                                         IsAddressOfOperand, TemplateArgs);
1733   } else {
1734     bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
1735     LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
1736 
1737     // If the result might be in a dependent base class, this is a dependent
1738     // id-expression.
1739     if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
1740       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1741                                         IsAddressOfOperand, TemplateArgs);
1742 
1743     // If this reference is in an Objective-C method, then we need to do
1744     // some special Objective-C lookup, too.
1745     if (IvarLookupFollowUp) {
1746       ExprResult E(LookupInObjCMethod(R, S, II, true));
1747       if (E.isInvalid())
1748         return ExprError();
1749 
1750       if (Expr *Ex = E.takeAs<Expr>())
1751         return Owned(Ex);
1752     }
1753   }
1754 
1755   if (R.isAmbiguous())
1756     return ExprError();
1757 
1758   // Determine whether this name might be a candidate for
1759   // argument-dependent lookup.
1760   bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
1761 
1762   if (R.empty() && !ADL) {
1763     // Otherwise, this could be an implicitly declared function reference (legal
1764     // in C90, extension in C99, forbidden in C++).
1765     if (HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
1766       NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1767       if (D) R.addDecl(D);
1768     }
1769 
1770     // If this name wasn't predeclared and if this is not a function
1771     // call, diagnose the problem.
1772     if (R.empty()) {
1773 
1774       // In Microsoft mode, if we are inside a template class member function
1775       // and we can't resolve an identifier then assume the identifier is type
1776       // dependent. The goal is to postpone name lookup to instantiation time
1777       // to be able to search into type dependent base classes.
1778       if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
1779           isa<CXXMethodDecl>(CurContext))
1780         return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1781                                           IsAddressOfOperand, TemplateArgs);
1782 
1783       CorrectionCandidateCallback DefaultValidator;
1784       if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator))
1785         return ExprError();
1786 
1787       assert(!R.empty() &&
1788              "DiagnoseEmptyLookup returned false but added no results");
1789 
1790       // If we found an Objective-C instance variable, let
1791       // LookupInObjCMethod build the appropriate expression to
1792       // reference the ivar.
1793       if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1794         R.clear();
1795         ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
1796         // In a hopelessly buggy code, Objective-C instance variable
1797         // lookup fails and no expression will be built to reference it.
1798         if (!E.isInvalid() && !E.get())
1799           return ExprError();
1800         return move(E);
1801       }
1802     }
1803   }
1804 
1805   // This is guaranteed from this point on.
1806   assert(!R.empty() || ADL);
1807 
1808   // Check whether this might be a C++ implicit instance member access.
1809   // C++ [class.mfct.non-static]p3:
1810   //   When an id-expression that is not part of a class member access
1811   //   syntax and not used to form a pointer to member is used in the
1812   //   body of a non-static member function of class X, if name lookup
1813   //   resolves the name in the id-expression to a non-static non-type
1814   //   member of some class C, the id-expression is transformed into a
1815   //   class member access expression using (*this) as the
1816   //   postfix-expression to the left of the . operator.
1817   //
1818   // But we don't actually need to do this for '&' operands if R
1819   // resolved to a function or overloaded function set, because the
1820   // expression is ill-formed if it actually works out to be a
1821   // non-static member function:
1822   //
1823   // C++ [expr.ref]p4:
1824   //   Otherwise, if E1.E2 refers to a non-static member function. . .
1825   //   [t]he expression can be used only as the left-hand operand of a
1826   //   member function call.
1827   //
1828   // There are other safeguards against such uses, but it's important
1829   // to get this right here so that we don't end up making a
1830   // spuriously dependent expression if we're inside a dependent
1831   // instance method.
1832   if (!R.empty() && (*R.begin())->isCXXClassMember()) {
1833     bool MightBeImplicitMember;
1834     if (!IsAddressOfOperand)
1835       MightBeImplicitMember = true;
1836     else if (!SS.isEmpty())
1837       MightBeImplicitMember = false;
1838     else if (R.isOverloadedResult())
1839       MightBeImplicitMember = false;
1840     else if (R.isUnresolvableResult())
1841       MightBeImplicitMember = true;
1842     else
1843       MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
1844                               isa<IndirectFieldDecl>(R.getFoundDecl());
1845 
1846     if (MightBeImplicitMember)
1847       return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
1848                                              R, TemplateArgs);
1849   }
1850 
1851   if (TemplateArgs || TemplateKWLoc.isValid())
1852     return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
1853 
1854   return BuildDeclarationNameExpr(SS, R, ADL);
1855 }
1856 
1857 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1858 /// declaration name, generally during template instantiation.
1859 /// There's a large number of things which don't need to be done along
1860 /// this path.
1861 ExprResult
1862 Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
1863                                         const DeclarationNameInfo &NameInfo) {
1864   DeclContext *DC;
1865   if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
1866     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
1867                                      NameInfo, /*TemplateArgs=*/0);
1868 
1869   if (RequireCompleteDeclContext(SS, DC))
1870     return ExprError();
1871 
1872   LookupResult R(*this, NameInfo, LookupOrdinaryName);
1873   LookupQualifiedName(R, DC);
1874 
1875   if (R.isAmbiguous())
1876     return ExprError();
1877 
1878   if (R.empty()) {
1879     Diag(NameInfo.getLoc(), diag::err_no_member)
1880       << NameInfo.getName() << DC << SS.getRange();
1881     return ExprError();
1882   }
1883 
1884   return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1885 }
1886 
1887 /// LookupInObjCMethod - The parser has read a name in, and Sema has
1888 /// detected that we're currently inside an ObjC method.  Perform some
1889 /// additional lookup.
1890 ///
1891 /// Ideally, most of this would be done by lookup, but there's
1892 /// actually quite a lot of extra work involved.
1893 ///
1894 /// Returns a null sentinel to indicate trivial success.
1895 ExprResult
1896 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
1897                          IdentifierInfo *II, bool AllowBuiltinCreation) {
1898   SourceLocation Loc = Lookup.getNameLoc();
1899   ObjCMethodDecl *CurMethod = getCurMethodDecl();
1900 
1901   // There are two cases to handle here.  1) scoped lookup could have failed,
1902   // in which case we should look for an ivar.  2) scoped lookup could have
1903   // found a decl, but that decl is outside the current instance method (i.e.
1904   // a global variable).  In these two cases, we do a lookup for an ivar with
1905   // this name, if the lookup sucedes, we replace it our current decl.
1906 
1907   // If we're in a class method, we don't normally want to look for
1908   // ivars.  But if we don't find anything else, and there's an
1909   // ivar, that's an error.
1910   bool IsClassMethod = CurMethod->isClassMethod();
1911 
1912   bool LookForIvars;
1913   if (Lookup.empty())
1914     LookForIvars = true;
1915   else if (IsClassMethod)
1916     LookForIvars = false;
1917   else
1918     LookForIvars = (Lookup.isSingleResult() &&
1919                     Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
1920   ObjCInterfaceDecl *IFace = 0;
1921   if (LookForIvars) {
1922     IFace = CurMethod->getClassInterface();
1923     ObjCInterfaceDecl *ClassDeclared;
1924     ObjCIvarDecl *IV = 0;
1925     if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
1926       // Diagnose using an ivar in a class method.
1927       if (IsClassMethod)
1928         return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1929                          << IV->getDeclName());
1930 
1931       // If we're referencing an invalid decl, just return this as a silent
1932       // error node.  The error diagnostic was already emitted on the decl.
1933       if (IV->isInvalidDecl())
1934         return ExprError();
1935 
1936       // Check if referencing a field with __attribute__((deprecated)).
1937       if (DiagnoseUseOfDecl(IV, Loc))
1938         return ExprError();
1939 
1940       // Diagnose the use of an ivar outside of the declaring class.
1941       if (IV->getAccessControl() == ObjCIvarDecl::Private &&
1942           !declaresSameEntity(ClassDeclared, IFace) &&
1943           !getLangOpts().DebuggerSupport)
1944         Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1945 
1946       // FIXME: This should use a new expr for a direct reference, don't
1947       // turn this into Self->ivar, just return a BareIVarExpr or something.
1948       IdentifierInfo &II = Context.Idents.get("self");
1949       UnqualifiedId SelfName;
1950       SelfName.setIdentifier(&II, SourceLocation());
1951       SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
1952       CXXScopeSpec SelfScopeSpec;
1953       SourceLocation TemplateKWLoc;
1954       ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
1955                                               SelfName, false, false);
1956       if (SelfExpr.isInvalid())
1957         return ExprError();
1958 
1959       SelfExpr = DefaultLvalueConversion(SelfExpr.take());
1960       if (SelfExpr.isInvalid())
1961         return ExprError();
1962 
1963       MarkAnyDeclReferenced(Loc, IV);
1964 
1965       ObjCMethodFamily MF = CurMethod->getMethodFamily();
1966       if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize)
1967         Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
1968       return Owned(new (Context)
1969                    ObjCIvarRefExpr(IV, IV->getType(), Loc,
1970                                    SelfExpr.take(), true, true));
1971     }
1972   } else if (CurMethod->isInstanceMethod()) {
1973     // We should warn if a local variable hides an ivar.
1974     if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
1975       ObjCInterfaceDecl *ClassDeclared;
1976       if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1977         if (IV->getAccessControl() != ObjCIvarDecl::Private ||
1978             declaresSameEntity(IFace, ClassDeclared))
1979           Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
1980       }
1981     }
1982   } else if (Lookup.isSingleResult() &&
1983              Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
1984     // If accessing a stand-alone ivar in a class method, this is an error.
1985     if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
1986       return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1987                        << IV->getDeclName());
1988   }
1989 
1990   if (Lookup.empty() && II && AllowBuiltinCreation) {
1991     // FIXME. Consolidate this with similar code in LookupName.
1992     if (unsigned BuiltinID = II->getBuiltinID()) {
1993       if (!(getLangOpts().CPlusPlus &&
1994             Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
1995         NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
1996                                            S, Lookup.isForRedeclaration(),
1997                                            Lookup.getNameLoc());
1998         if (D) Lookup.addDecl(D);
1999       }
2000     }
2001   }
2002   // Sentinel value saying that we didn't do anything special.
2003   return Owned((Expr*) 0);
2004 }
2005 
2006 /// \brief Cast a base object to a member's actual type.
2007 ///
2008 /// Logically this happens in three phases:
2009 ///
2010 /// * First we cast from the base type to the naming class.
2011 ///   The naming class is the class into which we were looking
2012 ///   when we found the member;  it's the qualifier type if a
2013 ///   qualifier was provided, and otherwise it's the base type.
2014 ///
2015 /// * Next we cast from the naming class to the declaring class.
2016 ///   If the member we found was brought into a class's scope by
2017 ///   a using declaration, this is that class;  otherwise it's
2018 ///   the class declaring the member.
2019 ///
2020 /// * Finally we cast from the declaring class to the "true"
2021 ///   declaring class of the member.  This conversion does not
2022 ///   obey access control.
2023 ExprResult
2024 Sema::PerformObjectMemberConversion(Expr *From,
2025                                     NestedNameSpecifier *Qualifier,
2026                                     NamedDecl *FoundDecl,
2027                                     NamedDecl *Member) {
2028   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2029   if (!RD)
2030     return Owned(From);
2031 
2032   QualType DestRecordType;
2033   QualType DestType;
2034   QualType FromRecordType;
2035   QualType FromType = From->getType();
2036   bool PointerConversions = false;
2037   if (isa<FieldDecl>(Member)) {
2038     DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2039 
2040     if (FromType->getAs<PointerType>()) {
2041       DestType = Context.getPointerType(DestRecordType);
2042       FromRecordType = FromType->getPointeeType();
2043       PointerConversions = true;
2044     } else {
2045       DestType = DestRecordType;
2046       FromRecordType = FromType;
2047     }
2048   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2049     if (Method->isStatic())
2050       return Owned(From);
2051 
2052     DestType = Method->getThisType(Context);
2053     DestRecordType = DestType->getPointeeType();
2054 
2055     if (FromType->getAs<PointerType>()) {
2056       FromRecordType = FromType->getPointeeType();
2057       PointerConversions = true;
2058     } else {
2059       FromRecordType = FromType;
2060       DestType = DestRecordType;
2061     }
2062   } else {
2063     // No conversion necessary.
2064     return Owned(From);
2065   }
2066 
2067   if (DestType->isDependentType() || FromType->isDependentType())
2068     return Owned(From);
2069 
2070   // If the unqualified types are the same, no conversion is necessary.
2071   if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2072     return Owned(From);
2073 
2074   SourceRange FromRange = From->getSourceRange();
2075   SourceLocation FromLoc = FromRange.getBegin();
2076 
2077   ExprValueKind VK = From->getValueKind();
2078 
2079   // C++ [class.member.lookup]p8:
2080   //   [...] Ambiguities can often be resolved by qualifying a name with its
2081   //   class name.
2082   //
2083   // If the member was a qualified name and the qualified referred to a
2084   // specific base subobject type, we'll cast to that intermediate type
2085   // first and then to the object in which the member is declared. That allows
2086   // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2087   //
2088   //   class Base { public: int x; };
2089   //   class Derived1 : public Base { };
2090   //   class Derived2 : public Base { };
2091   //   class VeryDerived : public Derived1, public Derived2 { void f(); };
2092   //
2093   //   void VeryDerived::f() {
2094   //     x = 17; // error: ambiguous base subobjects
2095   //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
2096   //   }
2097   if (Qualifier) {
2098     QualType QType = QualType(Qualifier->getAsType(), 0);
2099     assert(!QType.isNull() && "lookup done with dependent qualifier?");
2100     assert(QType->isRecordType() && "lookup done with non-record type");
2101 
2102     QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2103 
2104     // In C++98, the qualifier type doesn't actually have to be a base
2105     // type of the object type, in which case we just ignore it.
2106     // Otherwise build the appropriate casts.
2107     if (IsDerivedFrom(FromRecordType, QRecordType)) {
2108       CXXCastPath BasePath;
2109       if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2110                                        FromLoc, FromRange, &BasePath))
2111         return ExprError();
2112 
2113       if (PointerConversions)
2114         QType = Context.getPointerType(QType);
2115       From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2116                                VK, &BasePath).take();
2117 
2118       FromType = QType;
2119       FromRecordType = QRecordType;
2120 
2121       // If the qualifier type was the same as the destination type,
2122       // we're done.
2123       if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2124         return Owned(From);
2125     }
2126   }
2127 
2128   bool IgnoreAccess = false;
2129 
2130   // If we actually found the member through a using declaration, cast
2131   // down to the using declaration's type.
2132   //
2133   // Pointer equality is fine here because only one declaration of a
2134   // class ever has member declarations.
2135   if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2136     assert(isa<UsingShadowDecl>(FoundDecl));
2137     QualType URecordType = Context.getTypeDeclType(
2138                            cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2139 
2140     // We only need to do this if the naming-class to declaring-class
2141     // conversion is non-trivial.
2142     if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2143       assert(IsDerivedFrom(FromRecordType, URecordType));
2144       CXXCastPath BasePath;
2145       if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2146                                        FromLoc, FromRange, &BasePath))
2147         return ExprError();
2148 
2149       QualType UType = URecordType;
2150       if (PointerConversions)
2151         UType = Context.getPointerType(UType);
2152       From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2153                                VK, &BasePath).take();
2154       FromType = UType;
2155       FromRecordType = URecordType;
2156     }
2157 
2158     // We don't do access control for the conversion from the
2159     // declaring class to the true declaring class.
2160     IgnoreAccess = true;
2161   }
2162 
2163   CXXCastPath BasePath;
2164   if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2165                                    FromLoc, FromRange, &BasePath,
2166                                    IgnoreAccess))
2167     return ExprError();
2168 
2169   return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2170                            VK, &BasePath);
2171 }
2172 
2173 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2174                                       const LookupResult &R,
2175                                       bool HasTrailingLParen) {
2176   // Only when used directly as the postfix-expression of a call.
2177   if (!HasTrailingLParen)
2178     return false;
2179 
2180   // Never if a scope specifier was provided.
2181   if (SS.isSet())
2182     return false;
2183 
2184   // Only in C++ or ObjC++.
2185   if (!getLangOpts().CPlusPlus)
2186     return false;
2187 
2188   // Turn off ADL when we find certain kinds of declarations during
2189   // normal lookup:
2190   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2191     NamedDecl *D = *I;
2192 
2193     // C++0x [basic.lookup.argdep]p3:
2194     //     -- a declaration of a class member
2195     // Since using decls preserve this property, we check this on the
2196     // original decl.
2197     if (D->isCXXClassMember())
2198       return false;
2199 
2200     // C++0x [basic.lookup.argdep]p3:
2201     //     -- a block-scope function declaration that is not a
2202     //        using-declaration
2203     // NOTE: we also trigger this for function templates (in fact, we
2204     // don't check the decl type at all, since all other decl types
2205     // turn off ADL anyway).
2206     if (isa<UsingShadowDecl>(D))
2207       D = cast<UsingShadowDecl>(D)->getTargetDecl();
2208     else if (D->getDeclContext()->isFunctionOrMethod())
2209       return false;
2210 
2211     // C++0x [basic.lookup.argdep]p3:
2212     //     -- a declaration that is neither a function or a function
2213     //        template
2214     // And also for builtin functions.
2215     if (isa<FunctionDecl>(D)) {
2216       FunctionDecl *FDecl = cast<FunctionDecl>(D);
2217 
2218       // But also builtin functions.
2219       if (FDecl->getBuiltinID() && FDecl->isImplicit())
2220         return false;
2221     } else if (!isa<FunctionTemplateDecl>(D))
2222       return false;
2223   }
2224 
2225   return true;
2226 }
2227 
2228 
2229 /// Diagnoses obvious problems with the use of the given declaration
2230 /// as an expression.  This is only actually called for lookups that
2231 /// were not overloaded, and it doesn't promise that the declaration
2232 /// will in fact be used.
2233 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2234   if (isa<TypedefNameDecl>(D)) {
2235     S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2236     return true;
2237   }
2238 
2239   if (isa<ObjCInterfaceDecl>(D)) {
2240     S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2241     return true;
2242   }
2243 
2244   if (isa<NamespaceDecl>(D)) {
2245     S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2246     return true;
2247   }
2248 
2249   return false;
2250 }
2251 
2252 ExprResult
2253 Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2254                                LookupResult &R,
2255                                bool NeedsADL) {
2256   // If this is a single, fully-resolved result and we don't need ADL,
2257   // just build an ordinary singleton decl ref.
2258   if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
2259     return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
2260                                     R.getFoundDecl());
2261 
2262   // We only need to check the declaration if there's exactly one
2263   // result, because in the overloaded case the results can only be
2264   // functions and function templates.
2265   if (R.isSingleResult() &&
2266       CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
2267     return ExprError();
2268 
2269   // Otherwise, just build an unresolved lookup expression.  Suppress
2270   // any lookup-related diagnostics; we'll hash these out later, when
2271   // we've picked a target.
2272   R.suppressDiagnostics();
2273 
2274   UnresolvedLookupExpr *ULE
2275     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2276                                    SS.getWithLocInContext(Context),
2277                                    R.getLookupNameInfo(),
2278                                    NeedsADL, R.isOverloadedResult(),
2279                                    R.begin(), R.end());
2280 
2281   return Owned(ULE);
2282 }
2283 
2284 /// \brief Complete semantic analysis for a reference to the given declaration.
2285 ExprResult
2286 Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2287                                const DeclarationNameInfo &NameInfo,
2288                                NamedDecl *D) {
2289   assert(D && "Cannot refer to a NULL declaration");
2290   assert(!isa<FunctionTemplateDecl>(D) &&
2291          "Cannot refer unambiguously to a function template");
2292 
2293   SourceLocation Loc = NameInfo.getLoc();
2294   if (CheckDeclInExpr(*this, Loc, D))
2295     return ExprError();
2296 
2297   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2298     // Specifically diagnose references to class templates that are missing
2299     // a template argument list.
2300     Diag(Loc, diag::err_template_decl_ref)
2301       << Template << SS.getRange();
2302     Diag(Template->getLocation(), diag::note_template_decl_here);
2303     return ExprError();
2304   }
2305 
2306   // Make sure that we're referring to a value.
2307   ValueDecl *VD = dyn_cast<ValueDecl>(D);
2308   if (!VD) {
2309     Diag(Loc, diag::err_ref_non_value)
2310       << D << SS.getRange();
2311     Diag(D->getLocation(), diag::note_declared_at);
2312     return ExprError();
2313   }
2314 
2315   // Check whether this declaration can be used. Note that we suppress
2316   // this check when we're going to perform argument-dependent lookup
2317   // on this function name, because this might not be the function
2318   // that overload resolution actually selects.
2319   if (DiagnoseUseOfDecl(VD, Loc))
2320     return ExprError();
2321 
2322   // Only create DeclRefExpr's for valid Decl's.
2323   if (VD->isInvalidDecl())
2324     return ExprError();
2325 
2326   // Handle members of anonymous structs and unions.  If we got here,
2327   // and the reference is to a class member indirect field, then this
2328   // must be the subject of a pointer-to-member expression.
2329   if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2330     if (!indirectField->isCXXClassMember())
2331       return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2332                                                       indirectField);
2333 
2334   {
2335     QualType type = VD->getType();
2336     ExprValueKind valueKind = VK_RValue;
2337 
2338     switch (D->getKind()) {
2339     // Ignore all the non-ValueDecl kinds.
2340 #define ABSTRACT_DECL(kind)
2341 #define VALUE(type, base)
2342 #define DECL(type, base) \
2343     case Decl::type:
2344 #include "clang/AST/DeclNodes.inc"
2345       llvm_unreachable("invalid value decl kind");
2346 
2347     // These shouldn't make it here.
2348     case Decl::ObjCAtDefsField:
2349     case Decl::ObjCIvar:
2350       llvm_unreachable("forming non-member reference to ivar?");
2351 
2352     // Enum constants are always r-values and never references.
2353     // Unresolved using declarations are dependent.
2354     case Decl::EnumConstant:
2355     case Decl::UnresolvedUsingValue:
2356       valueKind = VK_RValue;
2357       break;
2358 
2359     // Fields and indirect fields that got here must be for
2360     // pointer-to-member expressions; we just call them l-values for
2361     // internal consistency, because this subexpression doesn't really
2362     // exist in the high-level semantics.
2363     case Decl::Field:
2364     case Decl::IndirectField:
2365       assert(getLangOpts().CPlusPlus &&
2366              "building reference to field in C?");
2367 
2368       // These can't have reference type in well-formed programs, but
2369       // for internal consistency we do this anyway.
2370       type = type.getNonReferenceType();
2371       valueKind = VK_LValue;
2372       break;
2373 
2374     // Non-type template parameters are either l-values or r-values
2375     // depending on the type.
2376     case Decl::NonTypeTemplateParm: {
2377       if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2378         type = reftype->getPointeeType();
2379         valueKind = VK_LValue; // even if the parameter is an r-value reference
2380         break;
2381       }
2382 
2383       // For non-references, we need to strip qualifiers just in case
2384       // the template parameter was declared as 'const int' or whatever.
2385       valueKind = VK_RValue;
2386       type = type.getUnqualifiedType();
2387       break;
2388     }
2389 
2390     case Decl::Var:
2391       // In C, "extern void blah;" is valid and is an r-value.
2392       if (!getLangOpts().CPlusPlus &&
2393           !type.hasQualifiers() &&
2394           type->isVoidType()) {
2395         valueKind = VK_RValue;
2396         break;
2397       }
2398       // fallthrough
2399 
2400     case Decl::ImplicitParam:
2401     case Decl::ParmVar: {
2402       // These are always l-values.
2403       valueKind = VK_LValue;
2404       type = type.getNonReferenceType();
2405 
2406       // FIXME: Does the addition of const really only apply in
2407       // potentially-evaluated contexts? Since the variable isn't actually
2408       // captured in an unevaluated context, it seems that the answer is no.
2409       if (!isUnevaluatedContext()) {
2410         QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
2411         if (!CapturedType.isNull())
2412           type = CapturedType;
2413       }
2414 
2415       break;
2416     }
2417 
2418     case Decl::Function: {
2419       const FunctionType *fty = type->castAs<FunctionType>();
2420 
2421       // If we're referring to a function with an __unknown_anytype
2422       // result type, make the entire expression __unknown_anytype.
2423       if (fty->getResultType() == Context.UnknownAnyTy) {
2424         type = Context.UnknownAnyTy;
2425         valueKind = VK_RValue;
2426         break;
2427       }
2428 
2429       // Functions are l-values in C++.
2430       if (getLangOpts().CPlusPlus) {
2431         valueKind = VK_LValue;
2432         break;
2433       }
2434 
2435       // C99 DR 316 says that, if a function type comes from a
2436       // function definition (without a prototype), that type is only
2437       // used for checking compatibility. Therefore, when referencing
2438       // the function, we pretend that we don't have the full function
2439       // type.
2440       if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2441           isa<FunctionProtoType>(fty))
2442         type = Context.getFunctionNoProtoType(fty->getResultType(),
2443                                               fty->getExtInfo());
2444 
2445       // Functions are r-values in C.
2446       valueKind = VK_RValue;
2447       break;
2448     }
2449 
2450     case Decl::CXXMethod:
2451       // If we're referring to a method with an __unknown_anytype
2452       // result type, make the entire expression __unknown_anytype.
2453       // This should only be possible with a type written directly.
2454       if (const FunctionProtoType *proto
2455             = dyn_cast<FunctionProtoType>(VD->getType()))
2456         if (proto->getResultType() == Context.UnknownAnyTy) {
2457           type = Context.UnknownAnyTy;
2458           valueKind = VK_RValue;
2459           break;
2460         }
2461 
2462       // C++ methods are l-values if static, r-values if non-static.
2463       if (cast<CXXMethodDecl>(VD)->isStatic()) {
2464         valueKind = VK_LValue;
2465         break;
2466       }
2467       // fallthrough
2468 
2469     case Decl::CXXConversion:
2470     case Decl::CXXDestructor:
2471     case Decl::CXXConstructor:
2472       valueKind = VK_RValue;
2473       break;
2474     }
2475 
2476     return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS);
2477   }
2478 }
2479 
2480 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
2481   PredefinedExpr::IdentType IT;
2482 
2483   switch (Kind) {
2484   default: llvm_unreachable("Unknown simple primary expr!");
2485   case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2486   case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
2487   case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break;
2488   case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
2489   }
2490 
2491   // Pre-defined identifiers are of type char[x], where x is the length of the
2492   // string.
2493 
2494   Decl *currentDecl = getCurFunctionOrMethodDecl();
2495   if (!currentDecl && getCurBlock())
2496     currentDecl = getCurBlock()->TheDecl;
2497   if (!currentDecl) {
2498     Diag(Loc, diag::ext_predef_outside_function);
2499     currentDecl = Context.getTranslationUnitDecl();
2500   }
2501 
2502   QualType ResTy;
2503   if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2504     ResTy = Context.DependentTy;
2505   } else {
2506     unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
2507 
2508     llvm::APInt LengthI(32, Length + 1);
2509     if (IT == PredefinedExpr::LFunction)
2510       ResTy = Context.WCharTy.withConst();
2511     else
2512       ResTy = Context.CharTy.withConst();
2513     ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2514   }
2515   return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
2516 }
2517 
2518 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
2519   SmallString<16> CharBuffer;
2520   bool Invalid = false;
2521   StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
2522   if (Invalid)
2523     return ExprError();
2524 
2525   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
2526                             PP, Tok.getKind());
2527   if (Literal.hadError())
2528     return ExprError();
2529 
2530   QualType Ty;
2531   if (Literal.isWide())
2532     Ty = Context.WCharTy; // L'x' -> wchar_t in C and C++.
2533   else if (Literal.isUTF16())
2534     Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
2535   else if (Literal.isUTF32())
2536     Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
2537   else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
2538     Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
2539   else
2540     Ty = Context.CharTy;  // 'x' -> char in C++
2541 
2542   CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
2543   if (Literal.isWide())
2544     Kind = CharacterLiteral::Wide;
2545   else if (Literal.isUTF16())
2546     Kind = CharacterLiteral::UTF16;
2547   else if (Literal.isUTF32())
2548     Kind = CharacterLiteral::UTF32;
2549 
2550   Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
2551                                              Tok.getLocation());
2552 
2553   if (Literal.getUDSuffix().empty())
2554     return Owned(Lit);
2555 
2556   // We're building a user-defined literal.
2557   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2558   SourceLocation UDSuffixLoc =
2559     getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
2560 
2561   // Make sure we're allowed user-defined literals here.
2562   if (!UDLScope)
2563     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
2564 
2565   // C++11 [lex.ext]p6: The literal L is treated as a call of the form
2566   //   operator "" X (ch)
2567   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
2568                                         llvm::makeArrayRef(&Lit, 1),
2569                                         Tok.getLocation());
2570 }
2571 
2572 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
2573   unsigned IntSize = Context.getTargetInfo().getIntWidth();
2574   return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
2575                                       Context.IntTy, Loc));
2576 }
2577 
2578 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
2579                                   QualType Ty, SourceLocation Loc) {
2580   const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
2581 
2582   using llvm::APFloat;
2583   APFloat Val(Format);
2584 
2585   APFloat::opStatus result = Literal.GetFloatValue(Val);
2586 
2587   // Overflow is always an error, but underflow is only an error if
2588   // we underflowed to zero (APFloat reports denormals as underflow).
2589   if ((result & APFloat::opOverflow) ||
2590       ((result & APFloat::opUnderflow) && Val.isZero())) {
2591     unsigned diagnostic;
2592     SmallString<20> buffer;
2593     if (result & APFloat::opOverflow) {
2594       diagnostic = diag::warn_float_overflow;
2595       APFloat::getLargest(Format).toString(buffer);
2596     } else {
2597       diagnostic = diag::warn_float_underflow;
2598       APFloat::getSmallest(Format).toString(buffer);
2599     }
2600 
2601     S.Diag(Loc, diagnostic)
2602       << Ty
2603       << StringRef(buffer.data(), buffer.size());
2604   }
2605 
2606   bool isExact = (result == APFloat::opOK);
2607   return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
2608 }
2609 
2610 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
2611   // Fast path for a single digit (which is quite common).  A single digit
2612   // cannot have a trigraph, escaped newline, radix prefix, or suffix.
2613   if (Tok.getLength() == 1) {
2614     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
2615     return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
2616   }
2617 
2618   SmallString<512> IntegerBuffer;
2619   // Add padding so that NumericLiteralParser can overread by one character.
2620   IntegerBuffer.resize(Tok.getLength()+1);
2621   const char *ThisTokBegin = &IntegerBuffer[0];
2622 
2623   // Get the spelling of the token, which eliminates trigraphs, etc.
2624   bool Invalid = false;
2625   unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
2626   if (Invalid)
2627     return ExprError();
2628 
2629   NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
2630                                Tok.getLocation(), PP);
2631   if (Literal.hadError)
2632     return ExprError();
2633 
2634   if (Literal.hasUDSuffix()) {
2635     // We're building a user-defined literal.
2636     IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2637     SourceLocation UDSuffixLoc =
2638       getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
2639 
2640     // Make sure we're allowed user-defined literals here.
2641     if (!UDLScope)
2642       return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
2643 
2644     QualType CookedTy;
2645     if (Literal.isFloatingLiteral()) {
2646       // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
2647       // long double, the literal is treated as a call of the form
2648       //   operator "" X (f L)
2649       CookedTy = Context.LongDoubleTy;
2650     } else {
2651       // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
2652       // unsigned long long, the literal is treated as a call of the form
2653       //   operator "" X (n ULL)
2654       CookedTy = Context.UnsignedLongLongTy;
2655     }
2656 
2657     DeclarationName OpName =
2658       Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
2659     DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
2660     OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
2661 
2662     // Perform literal operator lookup to determine if we're building a raw
2663     // literal or a cooked one.
2664     LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
2665     switch (LookupLiteralOperator(UDLScope, R, llvm::makeArrayRef(&CookedTy, 1),
2666                                   /*AllowRawAndTemplate*/true)) {
2667     case LOLR_Error:
2668       return ExprError();
2669 
2670     case LOLR_Cooked: {
2671       Expr *Lit;
2672       if (Literal.isFloatingLiteral()) {
2673         Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
2674       } else {
2675         llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
2676         if (Literal.GetIntegerValue(ResultVal))
2677           Diag(Tok.getLocation(), diag::warn_integer_too_large);
2678         Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
2679                                      Tok.getLocation());
2680       }
2681       return BuildLiteralOperatorCall(R, OpNameInfo,
2682                                       llvm::makeArrayRef(&Lit, 1),
2683                                       Tok.getLocation());
2684     }
2685 
2686     case LOLR_Raw: {
2687       // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
2688       // literal is treated as a call of the form
2689       //   operator "" X ("n")
2690       SourceLocation TokLoc = Tok.getLocation();
2691       unsigned Length = Literal.getUDSuffixOffset();
2692       QualType StrTy = Context.getConstantArrayType(
2693           Context.CharTy, llvm::APInt(32, Length + 1),
2694           ArrayType::Normal, 0);
2695       Expr *Lit = StringLiteral::Create(
2696           Context, StringRef(ThisTokBegin, Length), StringLiteral::Ascii,
2697           /*Pascal*/false, StrTy, &TokLoc, 1);
2698       return BuildLiteralOperatorCall(R, OpNameInfo,
2699                                       llvm::makeArrayRef(&Lit, 1), TokLoc);
2700     }
2701 
2702     case LOLR_Template:
2703       // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
2704       // template), L is treated as a call fo the form
2705       //   operator "" X <'c1', 'c2', ... 'ck'>()
2706       // where n is the source character sequence c1 c2 ... ck.
2707       TemplateArgumentListInfo ExplicitArgs;
2708       unsigned CharBits = Context.getIntWidth(Context.CharTy);
2709       bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
2710       llvm::APSInt Value(CharBits, CharIsUnsigned);
2711       for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
2712         Value = ThisTokBegin[I];
2713         TemplateArgument Arg(Context, Value, Context.CharTy);
2714         TemplateArgumentLocInfo ArgInfo;
2715         ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
2716       }
2717       return BuildLiteralOperatorCall(R, OpNameInfo, ArrayRef<Expr*>(),
2718                                       Tok.getLocation(), &ExplicitArgs);
2719     }
2720 
2721     llvm_unreachable("unexpected literal operator lookup result");
2722   }
2723 
2724   Expr *Res;
2725 
2726   if (Literal.isFloatingLiteral()) {
2727     QualType Ty;
2728     if (Literal.isFloat)
2729       Ty = Context.FloatTy;
2730     else if (!Literal.isLong)
2731       Ty = Context.DoubleTy;
2732     else
2733       Ty = Context.LongDoubleTy;
2734 
2735     Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
2736 
2737     if (Ty == Context.DoubleTy) {
2738       if (getLangOpts().SinglePrecisionConstants) {
2739         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
2740       } else if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
2741         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
2742         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
2743       }
2744     }
2745   } else if (!Literal.isIntegerLiteral()) {
2746     return ExprError();
2747   } else {
2748     QualType Ty;
2749 
2750     // long long is a C99 feature.
2751     if (!getLangOpts().C99 && Literal.isLongLong)
2752       Diag(Tok.getLocation(),
2753            getLangOpts().CPlusPlus0x ?
2754              diag::warn_cxx98_compat_longlong : diag::ext_longlong);
2755 
2756     // Get the value in the widest-possible width.
2757     unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
2758     // The microsoft literal suffix extensions support 128-bit literals, which
2759     // may be wider than [u]intmax_t.
2760     if (Literal.isMicrosoftInteger && MaxWidth < 128)
2761       MaxWidth = 128;
2762     llvm::APInt ResultVal(MaxWidth, 0);
2763 
2764     if (Literal.GetIntegerValue(ResultVal)) {
2765       // If this value didn't fit into uintmax_t, warn and force to ull.
2766       Diag(Tok.getLocation(), diag::warn_integer_too_large);
2767       Ty = Context.UnsignedLongLongTy;
2768       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
2769              "long long is not intmax_t?");
2770     } else {
2771       // If this value fits into a ULL, try to figure out what else it fits into
2772       // according to the rules of C99 6.4.4.1p5.
2773 
2774       // Octal, Hexadecimal, and integers with a U suffix are allowed to
2775       // be an unsigned int.
2776       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2777 
2778       // Check from smallest to largest, picking the smallest type we can.
2779       unsigned Width = 0;
2780       if (!Literal.isLong && !Literal.isLongLong) {
2781         // Are int/unsigned possibilities?
2782         unsigned IntSize = Context.getTargetInfo().getIntWidth();
2783 
2784         // Does it fit in a unsigned int?
2785         if (ResultVal.isIntN(IntSize)) {
2786           // Does it fit in a signed int?
2787           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
2788             Ty = Context.IntTy;
2789           else if (AllowUnsigned)
2790             Ty = Context.UnsignedIntTy;
2791           Width = IntSize;
2792         }
2793       }
2794 
2795       // Are long/unsigned long possibilities?
2796       if (Ty.isNull() && !Literal.isLongLong) {
2797         unsigned LongSize = Context.getTargetInfo().getLongWidth();
2798 
2799         // Does it fit in a unsigned long?
2800         if (ResultVal.isIntN(LongSize)) {
2801           // Does it fit in a signed long?
2802           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
2803             Ty = Context.LongTy;
2804           else if (AllowUnsigned)
2805             Ty = Context.UnsignedLongTy;
2806           Width = LongSize;
2807         }
2808       }
2809 
2810       // Check long long if needed.
2811       if (Ty.isNull()) {
2812         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
2813 
2814         // Does it fit in a unsigned long long?
2815         if (ResultVal.isIntN(LongLongSize)) {
2816           // Does it fit in a signed long long?
2817           // To be compatible with MSVC, hex integer literals ending with the
2818           // LL or i64 suffix are always signed in Microsoft mode.
2819           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
2820               (getLangOpts().MicrosoftExt && Literal.isLongLong)))
2821             Ty = Context.LongLongTy;
2822           else if (AllowUnsigned)
2823             Ty = Context.UnsignedLongLongTy;
2824           Width = LongLongSize;
2825         }
2826       }
2827 
2828       // If it doesn't fit in unsigned long long, and we're using Microsoft
2829       // extensions, then its a 128-bit integer literal.
2830       if (Ty.isNull() && Literal.isMicrosoftInteger) {
2831         if (Literal.isUnsigned)
2832           Ty = Context.UnsignedInt128Ty;
2833         else
2834           Ty = Context.Int128Ty;
2835         Width = 128;
2836       }
2837 
2838       // If we still couldn't decide a type, we probably have something that
2839       // does not fit in a signed long long, but has no U suffix.
2840       if (Ty.isNull()) {
2841         Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
2842         Ty = Context.UnsignedLongLongTy;
2843         Width = Context.getTargetInfo().getLongLongWidth();
2844       }
2845 
2846       if (ResultVal.getBitWidth() != Width)
2847         ResultVal = ResultVal.trunc(Width);
2848     }
2849     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
2850   }
2851 
2852   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
2853   if (Literal.isImaginary)
2854     Res = new (Context) ImaginaryLiteral(Res,
2855                                         Context.getComplexType(Res->getType()));
2856 
2857   return Owned(Res);
2858 }
2859 
2860 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
2861   assert((E != 0) && "ActOnParenExpr() missing expr");
2862   return Owned(new (Context) ParenExpr(L, R, E));
2863 }
2864 
2865 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
2866                                          SourceLocation Loc,
2867                                          SourceRange ArgRange) {
2868   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
2869   // scalar or vector data type argument..."
2870   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
2871   // type (C99 6.2.5p18) or void.
2872   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
2873     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
2874       << T << ArgRange;
2875     return true;
2876   }
2877 
2878   assert((T->isVoidType() || !T->isIncompleteType()) &&
2879          "Scalar types should always be complete");
2880   return false;
2881 }
2882 
2883 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
2884                                            SourceLocation Loc,
2885                                            SourceRange ArgRange,
2886                                            UnaryExprOrTypeTrait TraitKind) {
2887   // C99 6.5.3.4p1:
2888   if (T->isFunctionType()) {
2889     // alignof(function) is allowed as an extension.
2890     if (TraitKind == UETT_SizeOf)
2891       S.Diag(Loc, diag::ext_sizeof_function_type) << ArgRange;
2892     return false;
2893   }
2894 
2895   // Allow sizeof(void)/alignof(void) as an extension.
2896   if (T->isVoidType()) {
2897     S.Diag(Loc, diag::ext_sizeof_void_type) << TraitKind << ArgRange;
2898     return false;
2899   }
2900 
2901   return true;
2902 }
2903 
2904 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
2905                                              SourceLocation Loc,
2906                                              SourceRange ArgRange,
2907                                              UnaryExprOrTypeTrait TraitKind) {
2908   // Reject sizeof(interface) and sizeof(interface<proto>) if the
2909   // runtime doesn't allow it.
2910   if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
2911     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
2912       << T << (TraitKind == UETT_SizeOf)
2913       << ArgRange;
2914     return true;
2915   }
2916 
2917   return false;
2918 }
2919 
2920 /// \brief Check the constrains on expression operands to unary type expression
2921 /// and type traits.
2922 ///
2923 /// Completes any types necessary and validates the constraints on the operand
2924 /// expression. The logic mostly mirrors the type-based overload, but may modify
2925 /// the expression as it completes the type for that expression through template
2926 /// instantiation, etc.
2927 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
2928                                             UnaryExprOrTypeTrait ExprKind) {
2929   QualType ExprTy = E->getType();
2930 
2931   // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2932   //   the result is the size of the referenced type."
2933   // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2934   //   result shall be the alignment of the referenced type."
2935   if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2936     ExprTy = Ref->getPointeeType();
2937 
2938   if (ExprKind == UETT_VecStep)
2939     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
2940                                         E->getSourceRange());
2941 
2942   // Whitelist some types as extensions
2943   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
2944                                       E->getSourceRange(), ExprKind))
2945     return false;
2946 
2947   if (RequireCompleteExprType(E,
2948                               diag::err_sizeof_alignof_incomplete_type,
2949                               ExprKind, E->getSourceRange()))
2950     return true;
2951 
2952   // Completeing the expression's type may have changed it.
2953   ExprTy = E->getType();
2954   if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2955     ExprTy = Ref->getPointeeType();
2956 
2957   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
2958                                        E->getSourceRange(), ExprKind))
2959     return true;
2960 
2961   if (ExprKind == UETT_SizeOf) {
2962     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
2963       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
2964         QualType OType = PVD->getOriginalType();
2965         QualType Type = PVD->getType();
2966         if (Type->isPointerType() && OType->isArrayType()) {
2967           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
2968             << Type << OType;
2969           Diag(PVD->getLocation(), diag::note_declared_at);
2970         }
2971       }
2972     }
2973   }
2974 
2975   return false;
2976 }
2977 
2978 /// \brief Check the constraints on operands to unary expression and type
2979 /// traits.
2980 ///
2981 /// This will complete any types necessary, and validate the various constraints
2982 /// on those operands.
2983 ///
2984 /// The UsualUnaryConversions() function is *not* called by this routine.
2985 /// C99 6.3.2.1p[2-4] all state:
2986 ///   Except when it is the operand of the sizeof operator ...
2987 ///
2988 /// C++ [expr.sizeof]p4
2989 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
2990 ///   standard conversions are not applied to the operand of sizeof.
2991 ///
2992 /// This policy is followed for all of the unary trait expressions.
2993 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
2994                                             SourceLocation OpLoc,
2995                                             SourceRange ExprRange,
2996                                             UnaryExprOrTypeTrait ExprKind) {
2997   if (ExprType->isDependentType())
2998     return false;
2999 
3000   // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
3001   //   the result is the size of the referenced type."
3002   // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
3003   //   result shall be the alignment of the referenced type."
3004   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3005     ExprType = Ref->getPointeeType();
3006 
3007   if (ExprKind == UETT_VecStep)
3008     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
3009 
3010   // Whitelist some types as extensions
3011   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
3012                                       ExprKind))
3013     return false;
3014 
3015   if (RequireCompleteType(OpLoc, ExprType,
3016                           diag::err_sizeof_alignof_incomplete_type,
3017                           ExprKind, ExprRange))
3018     return true;
3019 
3020   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
3021                                        ExprKind))
3022     return true;
3023 
3024   return false;
3025 }
3026 
3027 static bool CheckAlignOfExpr(Sema &S, Expr *E) {
3028   E = E->IgnoreParens();
3029 
3030   // alignof decl is always ok.
3031   if (isa<DeclRefExpr>(E))
3032     return false;
3033 
3034   // Cannot know anything else if the expression is dependent.
3035   if (E->isTypeDependent())
3036     return false;
3037 
3038   if (E->getBitField()) {
3039     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield)
3040        << 1 << E->getSourceRange();
3041     return true;
3042   }
3043 
3044   // Alignment of a field access is always okay, so long as it isn't a
3045   // bit-field.
3046   if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
3047     if (isa<FieldDecl>(ME->getMemberDecl()))
3048       return false;
3049 
3050   return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
3051 }
3052 
3053 bool Sema::CheckVecStepExpr(Expr *E) {
3054   E = E->IgnoreParens();
3055 
3056   // Cannot know anything else if the expression is dependent.
3057   if (E->isTypeDependent())
3058     return false;
3059 
3060   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
3061 }
3062 
3063 /// \brief Build a sizeof or alignof expression given a type operand.
3064 ExprResult
3065 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3066                                      SourceLocation OpLoc,
3067                                      UnaryExprOrTypeTrait ExprKind,
3068                                      SourceRange R) {
3069   if (!TInfo)
3070     return ExprError();
3071 
3072   QualType T = TInfo->getType();
3073 
3074   if (!T->isDependentType() &&
3075       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
3076     return ExprError();
3077 
3078   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
3079   return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo,
3080                                                       Context.getSizeType(),
3081                                                       OpLoc, R.getEnd()));
3082 }
3083 
3084 /// \brief Build a sizeof or alignof expression given an expression
3085 /// operand.
3086 ExprResult
3087 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
3088                                      UnaryExprOrTypeTrait ExprKind) {
3089   ExprResult PE = CheckPlaceholderExpr(E);
3090   if (PE.isInvalid())
3091     return ExprError();
3092 
3093   E = PE.get();
3094 
3095   // Verify that the operand is valid.
3096   bool isInvalid = false;
3097   if (E->isTypeDependent()) {
3098     // Delay type-checking for type-dependent expressions.
3099   } else if (ExprKind == UETT_AlignOf) {
3100     isInvalid = CheckAlignOfExpr(*this, E);
3101   } else if (ExprKind == UETT_VecStep) {
3102     isInvalid = CheckVecStepExpr(E);
3103   } else if (E->getBitField()) {  // C99 6.5.3.4p1.
3104     Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0;
3105     isInvalid = true;
3106   } else {
3107     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
3108   }
3109 
3110   if (isInvalid)
3111     return ExprError();
3112 
3113   if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
3114     PE = TranformToPotentiallyEvaluated(E);
3115     if (PE.isInvalid()) return ExprError();
3116     E = PE.take();
3117   }
3118 
3119   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
3120   return Owned(new (Context) UnaryExprOrTypeTraitExpr(
3121       ExprKind, E, Context.getSizeType(), OpLoc,
3122       E->getSourceRange().getEnd()));
3123 }
3124 
3125 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
3126 /// expr and the same for @c alignof and @c __alignof
3127 /// Note that the ArgRange is invalid if isType is false.
3128 ExprResult
3129 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
3130                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
3131                                     void *TyOrEx, const SourceRange &ArgRange) {
3132   // If error parsing type, ignore.
3133   if (TyOrEx == 0) return ExprError();
3134 
3135   if (IsType) {
3136     TypeSourceInfo *TInfo;
3137     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
3138     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
3139   }
3140 
3141   Expr *ArgEx = (Expr *)TyOrEx;
3142   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
3143   return move(Result);
3144 }
3145 
3146 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
3147                                      bool IsReal) {
3148   if (V.get()->isTypeDependent())
3149     return S.Context.DependentTy;
3150 
3151   // _Real and _Imag are only l-values for normal l-values.
3152   if (V.get()->getObjectKind() != OK_Ordinary) {
3153     V = S.DefaultLvalueConversion(V.take());
3154     if (V.isInvalid())
3155       return QualType();
3156   }
3157 
3158   // These operators return the element type of a complex type.
3159   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
3160     return CT->getElementType();
3161 
3162   // Otherwise they pass through real integer and floating point types here.
3163   if (V.get()->getType()->isArithmeticType())
3164     return V.get()->getType();
3165 
3166   // Test for placeholders.
3167   ExprResult PR = S.CheckPlaceholderExpr(V.get());
3168   if (PR.isInvalid()) return QualType();
3169   if (PR.get() != V.get()) {
3170     V = move(PR);
3171     return CheckRealImagOperand(S, V, Loc, IsReal);
3172   }
3173 
3174   // Reject anything else.
3175   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
3176     << (IsReal ? "__real" : "__imag");
3177   return QualType();
3178 }
3179 
3180 
3181 
3182 ExprResult
3183 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
3184                           tok::TokenKind Kind, Expr *Input) {
3185   UnaryOperatorKind Opc;
3186   switch (Kind) {
3187   default: llvm_unreachable("Unknown unary op!");
3188   case tok::plusplus:   Opc = UO_PostInc; break;
3189   case tok::minusminus: Opc = UO_PostDec; break;
3190   }
3191 
3192   // Since this might is a postfix expression, get rid of ParenListExprs.
3193   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
3194   if (Result.isInvalid()) return ExprError();
3195   Input = Result.take();
3196 
3197   return BuildUnaryOp(S, OpLoc, Opc, Input);
3198 }
3199 
3200 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal.
3201 ///
3202 /// \return true on error
3203 static bool checkArithmeticOnObjCPointer(Sema &S,
3204                                          SourceLocation opLoc,
3205                                          Expr *op) {
3206   assert(op->getType()->isObjCObjectPointerType());
3207   if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic())
3208     return false;
3209 
3210   S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
3211     << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
3212     << op->getSourceRange();
3213   return true;
3214 }
3215 
3216 ExprResult
3217 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
3218                               Expr *Idx, SourceLocation RLoc) {
3219   // Since this might be a postfix expression, get rid of ParenListExprs.
3220   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
3221   if (Result.isInvalid()) return ExprError();
3222   Base = Result.take();
3223 
3224   Expr *LHSExp = Base, *RHSExp = Idx;
3225 
3226   if (getLangOpts().CPlusPlus &&
3227       (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
3228     return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
3229                                                   Context.DependentTy,
3230                                                   VK_LValue, OK_Ordinary,
3231                                                   RLoc));
3232   }
3233 
3234   if (getLangOpts().CPlusPlus &&
3235       (LHSExp->getType()->isRecordType() ||
3236        LHSExp->getType()->isEnumeralType() ||
3237        RHSExp->getType()->isRecordType() ||
3238        RHSExp->getType()->isEnumeralType()) &&
3239       !LHSExp->getType()->isObjCObjectPointerType()) {
3240     return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
3241   }
3242 
3243   return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
3244 }
3245 
3246 ExprResult
3247 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
3248                                       Expr *Idx, SourceLocation RLoc) {
3249   Expr *LHSExp = Base;
3250   Expr *RHSExp = Idx;
3251 
3252   // Perform default conversions.
3253   if (!LHSExp->getType()->getAs<VectorType>()) {
3254     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
3255     if (Result.isInvalid())
3256       return ExprError();
3257     LHSExp = Result.take();
3258   }
3259   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
3260   if (Result.isInvalid())
3261     return ExprError();
3262   RHSExp = Result.take();
3263 
3264   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
3265   ExprValueKind VK = VK_LValue;
3266   ExprObjectKind OK = OK_Ordinary;
3267 
3268   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
3269   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
3270   // in the subscript position. As a result, we need to derive the array base
3271   // and index from the expression types.
3272   Expr *BaseExpr, *IndexExpr;
3273   QualType ResultType;
3274   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3275     BaseExpr = LHSExp;
3276     IndexExpr = RHSExp;
3277     ResultType = Context.DependentTy;
3278   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
3279     BaseExpr = LHSExp;
3280     IndexExpr = RHSExp;
3281     ResultType = PTy->getPointeeType();
3282   } else if (const ObjCObjectPointerType *PTy =
3283                LHSTy->getAs<ObjCObjectPointerType>()) {
3284     BaseExpr = LHSExp;
3285     IndexExpr = RHSExp;
3286 
3287     // Use custom logic if this should be the pseudo-object subscript
3288     // expression.
3289     if (!LangOpts.ObjCRuntime.isSubscriptPointerArithmetic())
3290       return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, 0, 0);
3291 
3292     ResultType = PTy->getPointeeType();
3293     if (!LangOpts.ObjCRuntime.allowsPointerArithmetic()) {
3294       Diag(LLoc, diag::err_subscript_nonfragile_interface)
3295         << ResultType << BaseExpr->getSourceRange();
3296       return ExprError();
3297     }
3298   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
3299      // Handle the uncommon case of "123[Ptr]".
3300     BaseExpr = RHSExp;
3301     IndexExpr = LHSExp;
3302     ResultType = PTy->getPointeeType();
3303   } else if (const ObjCObjectPointerType *PTy =
3304                RHSTy->getAs<ObjCObjectPointerType>()) {
3305      // Handle the uncommon case of "123[Ptr]".
3306     BaseExpr = RHSExp;
3307     IndexExpr = LHSExp;
3308     ResultType = PTy->getPointeeType();
3309     if (!LangOpts.ObjCRuntime.allowsPointerArithmetic()) {
3310       Diag(LLoc, diag::err_subscript_nonfragile_interface)
3311         << ResultType << BaseExpr->getSourceRange();
3312       return ExprError();
3313     }
3314   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
3315     BaseExpr = LHSExp;    // vectors: V[123]
3316     IndexExpr = RHSExp;
3317     VK = LHSExp->getValueKind();
3318     if (VK != VK_RValue)
3319       OK = OK_VectorComponent;
3320 
3321     // FIXME: need to deal with const...
3322     ResultType = VTy->getElementType();
3323   } else if (LHSTy->isArrayType()) {
3324     // If we see an array that wasn't promoted by
3325     // DefaultFunctionArrayLvalueConversion, it must be an array that
3326     // wasn't promoted because of the C90 rule that doesn't
3327     // allow promoting non-lvalue arrays.  Warn, then
3328     // force the promotion here.
3329     Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3330         LHSExp->getSourceRange();
3331     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
3332                                CK_ArrayToPointerDecay).take();
3333     LHSTy = LHSExp->getType();
3334 
3335     BaseExpr = LHSExp;
3336     IndexExpr = RHSExp;
3337     ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
3338   } else if (RHSTy->isArrayType()) {
3339     // Same as previous, except for 123[f().a] case
3340     Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3341         RHSExp->getSourceRange();
3342     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
3343                                CK_ArrayToPointerDecay).take();
3344     RHSTy = RHSExp->getType();
3345 
3346     BaseExpr = RHSExp;
3347     IndexExpr = LHSExp;
3348     ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
3349   } else {
3350     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3351        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
3352   }
3353   // C99 6.5.2.1p1
3354   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
3355     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3356                      << IndexExpr->getSourceRange());
3357 
3358   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
3359        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3360          && !IndexExpr->isTypeDependent())
3361     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3362 
3363   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
3364   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3365   // type. Note that Functions are not objects, and that (in C99 parlance)
3366   // incomplete types are not object types.
3367   if (ResultType->isFunctionType()) {
3368     Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3369       << ResultType << BaseExpr->getSourceRange();
3370     return ExprError();
3371   }
3372 
3373   if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
3374     // GNU extension: subscripting on pointer to void
3375     Diag(LLoc, diag::ext_gnu_subscript_void_type)
3376       << BaseExpr->getSourceRange();
3377 
3378     // C forbids expressions of unqualified void type from being l-values.
3379     // See IsCForbiddenLValueType.
3380     if (!ResultType.hasQualifiers()) VK = VK_RValue;
3381   } else if (!ResultType->isDependentType() &&
3382       RequireCompleteType(LLoc, ResultType,
3383                           diag::err_subscript_incomplete_type, BaseExpr))
3384     return ExprError();
3385 
3386   assert(VK == VK_RValue || LangOpts.CPlusPlus ||
3387          !ResultType.isCForbiddenLValueType());
3388 
3389   return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
3390                                                 ResultType, VK, OK, RLoc));
3391 }
3392 
3393 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
3394                                         FunctionDecl *FD,
3395                                         ParmVarDecl *Param) {
3396   if (Param->hasUnparsedDefaultArg()) {
3397     Diag(CallLoc,
3398          diag::err_use_of_default_argument_to_function_declared_later) <<
3399       FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
3400     Diag(UnparsedDefaultArgLocs[Param],
3401          diag::note_default_argument_declared_here);
3402     return ExprError();
3403   }
3404 
3405   if (Param->hasUninstantiatedDefaultArg()) {
3406     Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
3407 
3408     EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated,
3409                                                  Param);
3410 
3411     // Instantiate the expression.
3412     MultiLevelTemplateArgumentList ArgList
3413       = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
3414 
3415     std::pair<const TemplateArgument *, unsigned> Innermost
3416       = ArgList.getInnermost();
3417     InstantiatingTemplate Inst(*this, CallLoc, Param,
3418                                ArrayRef<TemplateArgument>(Innermost.first,
3419                                                           Innermost.second));
3420     if (Inst)
3421       return ExprError();
3422 
3423     ExprResult Result;
3424     {
3425       // C++ [dcl.fct.default]p5:
3426       //   The names in the [default argument] expression are bound, and
3427       //   the semantic constraints are checked, at the point where the
3428       //   default argument expression appears.
3429       ContextRAII SavedContext(*this, FD);
3430       LocalInstantiationScope Local(*this);
3431       Result = SubstExpr(UninstExpr, ArgList);
3432     }
3433     if (Result.isInvalid())
3434       return ExprError();
3435 
3436     // Check the expression as an initializer for the parameter.
3437     InitializedEntity Entity
3438       = InitializedEntity::InitializeParameter(Context, Param);
3439     InitializationKind Kind
3440       = InitializationKind::CreateCopy(Param->getLocation(),
3441              /*FIXME:EqualLoc*/UninstExpr->getLocStart());
3442     Expr *ResultE = Result.takeAs<Expr>();
3443 
3444     InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
3445     Result = InitSeq.Perform(*this, Entity, Kind,
3446                              MultiExprArg(*this, &ResultE, 1));
3447     if (Result.isInvalid())
3448       return ExprError();
3449 
3450     Expr *Arg = Result.takeAs<Expr>();
3451     CheckImplicitConversions(Arg, Param->getOuterLocStart());
3452     // Build the default argument expression.
3453     return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param, Arg));
3454   }
3455 
3456   // If the default expression creates temporaries, we need to
3457   // push them to the current stack of expression temporaries so they'll
3458   // be properly destroyed.
3459   // FIXME: We should really be rebuilding the default argument with new
3460   // bound temporaries; see the comment in PR5810.
3461   // We don't need to do that with block decls, though, because
3462   // blocks in default argument expression can never capture anything.
3463   if (isa<ExprWithCleanups>(Param->getInit())) {
3464     // Set the "needs cleanups" bit regardless of whether there are
3465     // any explicit objects.
3466     ExprNeedsCleanups = true;
3467 
3468     // Append all the objects to the cleanup list.  Right now, this
3469     // should always be a no-op, because blocks in default argument
3470     // expressions should never be able to capture anything.
3471     assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() &&
3472            "default argument expression has capturing blocks?");
3473   }
3474 
3475   // We already type-checked the argument, so we know it works.
3476   // Just mark all of the declarations in this potentially-evaluated expression
3477   // as being "referenced".
3478   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
3479                                    /*SkipLocalVariables=*/true);
3480   return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
3481 }
3482 
3483 
3484 Sema::VariadicCallType
3485 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
3486                           Expr *Fn) {
3487   if (Proto && Proto->isVariadic()) {
3488     if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
3489       return VariadicConstructor;
3490     else if (Fn && Fn->getType()->isBlockPointerType())
3491       return VariadicBlock;
3492     else if (FDecl) {
3493       if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3494         if (Method->isInstance())
3495           return VariadicMethod;
3496     }
3497     return VariadicFunction;
3498   }
3499   return VariadicDoesNotApply;
3500 }
3501 
3502 /// ConvertArgumentsForCall - Converts the arguments specified in
3503 /// Args/NumArgs to the parameter types of the function FDecl with
3504 /// function prototype Proto. Call is the call expression itself, and
3505 /// Fn is the function expression. For a C++ member function, this
3506 /// routine does not attempt to convert the object argument. Returns
3507 /// true if the call is ill-formed.
3508 bool
3509 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
3510                               FunctionDecl *FDecl,
3511                               const FunctionProtoType *Proto,
3512                               Expr **Args, unsigned NumArgs,
3513                               SourceLocation RParenLoc,
3514                               bool IsExecConfig) {
3515   // Bail out early if calling a builtin with custom typechecking.
3516   // We don't need to do this in the
3517   if (FDecl)
3518     if (unsigned ID = FDecl->getBuiltinID())
3519       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
3520         return false;
3521 
3522   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
3523   // assignment, to the types of the corresponding parameter, ...
3524   unsigned NumArgsInProto = Proto->getNumArgs();
3525   bool Invalid = false;
3526   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumArgsInProto;
3527   unsigned FnKind = Fn->getType()->isBlockPointerType()
3528                        ? 1 /* block */
3529                        : (IsExecConfig ? 3 /* kernel function (exec config) */
3530                                        : 0 /* function */);
3531 
3532   // If too few arguments are available (and we don't have default
3533   // arguments for the remaining parameters), don't make the call.
3534   if (NumArgs < NumArgsInProto) {
3535     if (NumArgs < MinArgs) {
3536       if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
3537         Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic()
3538                           ? diag::err_typecheck_call_too_few_args_one
3539                           : diag::err_typecheck_call_too_few_args_at_least_one)
3540           << FnKind
3541           << FDecl->getParamDecl(0) << Fn->getSourceRange();
3542       else
3543         Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic()
3544                           ? diag::err_typecheck_call_too_few_args
3545                           : diag::err_typecheck_call_too_few_args_at_least)
3546           << FnKind
3547           << MinArgs << NumArgs << Fn->getSourceRange();
3548 
3549       // Emit the location of the prototype.
3550       if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
3551         Diag(FDecl->getLocStart(), diag::note_callee_decl)
3552           << FDecl;
3553 
3554       return true;
3555     }
3556     Call->setNumArgs(Context, NumArgsInProto);
3557   }
3558 
3559   // If too many are passed and not variadic, error on the extras and drop
3560   // them.
3561   if (NumArgs > NumArgsInProto) {
3562     if (!Proto->isVariadic()) {
3563       if (NumArgsInProto == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
3564         Diag(Args[NumArgsInProto]->getLocStart(),
3565              MinArgs == NumArgsInProto
3566                ? diag::err_typecheck_call_too_many_args_one
3567                : diag::err_typecheck_call_too_many_args_at_most_one)
3568           << FnKind
3569           << FDecl->getParamDecl(0) << NumArgs << Fn->getSourceRange()
3570           << SourceRange(Args[NumArgsInProto]->getLocStart(),
3571                          Args[NumArgs-1]->getLocEnd());
3572       else
3573         Diag(Args[NumArgsInProto]->getLocStart(),
3574              MinArgs == NumArgsInProto
3575                ? diag::err_typecheck_call_too_many_args
3576                : diag::err_typecheck_call_too_many_args_at_most)
3577           << FnKind
3578           << NumArgsInProto << NumArgs << Fn->getSourceRange()
3579           << SourceRange(Args[NumArgsInProto]->getLocStart(),
3580                          Args[NumArgs-1]->getLocEnd());
3581 
3582       // Emit the location of the prototype.
3583       if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
3584         Diag(FDecl->getLocStart(), diag::note_callee_decl)
3585           << FDecl;
3586 
3587       // This deletes the extra arguments.
3588       Call->setNumArgs(Context, NumArgsInProto);
3589       return true;
3590     }
3591   }
3592   SmallVector<Expr *, 8> AllArgs;
3593   VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
3594 
3595   Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
3596                                    Proto, 0, Args, NumArgs, AllArgs, CallType);
3597   if (Invalid)
3598     return true;
3599   unsigned TotalNumArgs = AllArgs.size();
3600   for (unsigned i = 0; i < TotalNumArgs; ++i)
3601     Call->setArg(i, AllArgs[i]);
3602 
3603   return false;
3604 }
3605 
3606 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
3607                                   FunctionDecl *FDecl,
3608                                   const FunctionProtoType *Proto,
3609                                   unsigned FirstProtoArg,
3610                                   Expr **Args, unsigned NumArgs,
3611                                   SmallVector<Expr *, 8> &AllArgs,
3612                                   VariadicCallType CallType,
3613                                   bool AllowExplicit) {
3614   unsigned NumArgsInProto = Proto->getNumArgs();
3615   unsigned NumArgsToCheck = NumArgs;
3616   bool Invalid = false;
3617   if (NumArgs != NumArgsInProto)
3618     // Use default arguments for missing arguments
3619     NumArgsToCheck = NumArgsInProto;
3620   unsigned ArgIx = 0;
3621   // Continue to check argument types (even if we have too few/many args).
3622   for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
3623     QualType ProtoArgType = Proto->getArgType(i);
3624 
3625     Expr *Arg;
3626     ParmVarDecl *Param;
3627     if (ArgIx < NumArgs) {
3628       Arg = Args[ArgIx++];
3629 
3630       if (RequireCompleteType(Arg->getLocStart(),
3631                               ProtoArgType,
3632                               diag::err_call_incomplete_argument, Arg))
3633         return true;
3634 
3635       // Pass the argument
3636       Param = 0;
3637       if (FDecl && i < FDecl->getNumParams())
3638         Param = FDecl->getParamDecl(i);
3639 
3640       // Strip the unbridged-cast placeholder expression off, if applicable.
3641       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
3642           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
3643           (!Param || !Param->hasAttr<CFConsumedAttr>()))
3644         Arg = stripARCUnbridgedCast(Arg);
3645 
3646       InitializedEntity Entity =
3647         Param? InitializedEntity::InitializeParameter(Context, Param)
3648              : InitializedEntity::InitializeParameter(Context, ProtoArgType,
3649                                                       Proto->isArgConsumed(i));
3650       ExprResult ArgE = PerformCopyInitialization(Entity,
3651                                                   SourceLocation(),
3652                                                   Owned(Arg),
3653                                                   /*TopLevelOfInitList=*/false,
3654                                                   AllowExplicit);
3655       if (ArgE.isInvalid())
3656         return true;
3657 
3658       Arg = ArgE.takeAs<Expr>();
3659     } else {
3660       Param = FDecl->getParamDecl(i);
3661 
3662       ExprResult ArgExpr =
3663         BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
3664       if (ArgExpr.isInvalid())
3665         return true;
3666 
3667       Arg = ArgExpr.takeAs<Expr>();
3668     }
3669 
3670     // Check for array bounds violations for each argument to the call. This
3671     // check only triggers warnings when the argument isn't a more complex Expr
3672     // with its own checking, such as a BinaryOperator.
3673     CheckArrayAccess(Arg);
3674 
3675     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
3676     CheckStaticArrayArgument(CallLoc, Param, Arg);
3677 
3678     AllArgs.push_back(Arg);
3679   }
3680 
3681   // If this is a variadic call, handle args passed through "...".
3682   if (CallType != VariadicDoesNotApply) {
3683     // Assume that extern "C" functions with variadic arguments that
3684     // return __unknown_anytype aren't *really* variadic.
3685     if (Proto->getResultType() == Context.UnknownAnyTy &&
3686         FDecl && FDecl->isExternC()) {
3687       for (unsigned i = ArgIx; i != NumArgs; ++i) {
3688         ExprResult arg;
3689         if (isa<ExplicitCastExpr>(Args[i]->IgnoreParens()))
3690           arg = DefaultFunctionArrayLvalueConversion(Args[i]);
3691         else
3692           arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl);
3693         Invalid |= arg.isInvalid();
3694         AllArgs.push_back(arg.take());
3695       }
3696 
3697     // Otherwise do argument promotion, (C99 6.5.2.2p7).
3698     } else {
3699       for (unsigned i = ArgIx; i != NumArgs; ++i) {
3700         ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType,
3701                                                           FDecl);
3702         Invalid |= Arg.isInvalid();
3703         AllArgs.push_back(Arg.take());
3704       }
3705     }
3706 
3707     // Check for array bounds violations.
3708     for (unsigned i = ArgIx; i != NumArgs; ++i)
3709       CheckArrayAccess(Args[i]);
3710   }
3711   return Invalid;
3712 }
3713 
3714 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
3715   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
3716   if (ArrayTypeLoc *ATL = dyn_cast<ArrayTypeLoc>(&TL))
3717     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
3718       << ATL->getLocalSourceRange();
3719 }
3720 
3721 /// CheckStaticArrayArgument - If the given argument corresponds to a static
3722 /// array parameter, check that it is non-null, and that if it is formed by
3723 /// array-to-pointer decay, the underlying array is sufficiently large.
3724 ///
3725 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
3726 /// array type derivation, then for each call to the function, the value of the
3727 /// corresponding actual argument shall provide access to the first element of
3728 /// an array with at least as many elements as specified by the size expression.
3729 void
3730 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
3731                                ParmVarDecl *Param,
3732                                const Expr *ArgExpr) {
3733   // Static array parameters are not supported in C++.
3734   if (!Param || getLangOpts().CPlusPlus)
3735     return;
3736 
3737   QualType OrigTy = Param->getOriginalType();
3738 
3739   const ArrayType *AT = Context.getAsArrayType(OrigTy);
3740   if (!AT || AT->getSizeModifier() != ArrayType::Static)
3741     return;
3742 
3743   if (ArgExpr->isNullPointerConstant(Context,
3744                                      Expr::NPC_NeverValueDependent)) {
3745     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
3746     DiagnoseCalleeStaticArrayParam(*this, Param);
3747     return;
3748   }
3749 
3750   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
3751   if (!CAT)
3752     return;
3753 
3754   const ConstantArrayType *ArgCAT =
3755     Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
3756   if (!ArgCAT)
3757     return;
3758 
3759   if (ArgCAT->getSize().ult(CAT->getSize())) {
3760     Diag(CallLoc, diag::warn_static_array_too_small)
3761       << ArgExpr->getSourceRange()
3762       << (unsigned) ArgCAT->getSize().getZExtValue()
3763       << (unsigned) CAT->getSize().getZExtValue();
3764     DiagnoseCalleeStaticArrayParam(*this, Param);
3765   }
3766 }
3767 
3768 /// Given a function expression of unknown-any type, try to rebuild it
3769 /// to have a function type.
3770 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
3771 
3772 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
3773 /// This provides the location of the left/right parens and a list of comma
3774 /// locations.
3775 ExprResult
3776 Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
3777                     MultiExprArg ArgExprs, SourceLocation RParenLoc,
3778                     Expr *ExecConfig, bool IsExecConfig) {
3779   unsigned NumArgs = ArgExprs.size();
3780 
3781   // Since this might be a postfix expression, get rid of ParenListExprs.
3782   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
3783   if (Result.isInvalid()) return ExprError();
3784   Fn = Result.take();
3785 
3786   Expr **Args = ArgExprs.release();
3787 
3788   if (getLangOpts().CPlusPlus) {
3789     // If this is a pseudo-destructor expression, build the call immediately.
3790     if (isa<CXXPseudoDestructorExpr>(Fn)) {
3791       if (NumArgs > 0) {
3792         // Pseudo-destructor calls should not have any arguments.
3793         Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
3794           << FixItHint::CreateRemoval(
3795                                     SourceRange(Args[0]->getLocStart(),
3796                                                 Args[NumArgs-1]->getLocEnd()));
3797       }
3798 
3799       return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
3800                                           VK_RValue, RParenLoc));
3801     }
3802 
3803     // Determine whether this is a dependent call inside a C++ template,
3804     // in which case we won't do any semantic analysis now.
3805     // FIXME: Will need to cache the results of name lookup (including ADL) in
3806     // Fn.
3807     bool Dependent = false;
3808     if (Fn->isTypeDependent())
3809       Dependent = true;
3810     else if (Expr::hasAnyTypeDependentArguments(
3811         llvm::makeArrayRef(Args, NumArgs)))
3812       Dependent = true;
3813 
3814     if (Dependent) {
3815       if (ExecConfig) {
3816         return Owned(new (Context) CUDAKernelCallExpr(
3817             Context, Fn, cast<CallExpr>(ExecConfig), Args, NumArgs,
3818             Context.DependentTy, VK_RValue, RParenLoc));
3819       } else {
3820         return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
3821                                             Context.DependentTy, VK_RValue,
3822                                             RParenLoc));
3823       }
3824     }
3825 
3826     // Determine whether this is a call to an object (C++ [over.call.object]).
3827     if (Fn->getType()->isRecordType())
3828       return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
3829                                                 RParenLoc));
3830 
3831     if (Fn->getType() == Context.UnknownAnyTy) {
3832       ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
3833       if (result.isInvalid()) return ExprError();
3834       Fn = result.take();
3835     }
3836 
3837     if (Fn->getType() == Context.BoundMemberTy) {
3838       return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
3839                                        RParenLoc);
3840     }
3841   }
3842 
3843   // Check for overloaded calls.  This can happen even in C due to extensions.
3844   if (Fn->getType() == Context.OverloadTy) {
3845     OverloadExpr::FindResult find = OverloadExpr::find(Fn);
3846 
3847     // We aren't supposed to apply this logic for if there's an '&' involved.
3848     if (!find.HasFormOfMemberPointer) {
3849       OverloadExpr *ovl = find.Expression;
3850       if (isa<UnresolvedLookupExpr>(ovl)) {
3851         UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
3852         return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, Args, NumArgs,
3853                                        RParenLoc, ExecConfig);
3854       } else {
3855         return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
3856                                          RParenLoc);
3857       }
3858     }
3859   }
3860 
3861   // If we're directly calling a function, get the appropriate declaration.
3862   if (Fn->getType() == Context.UnknownAnyTy) {
3863     ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
3864     if (result.isInvalid()) return ExprError();
3865     Fn = result.take();
3866   }
3867 
3868   Expr *NakedFn = Fn->IgnoreParens();
3869 
3870   NamedDecl *NDecl = 0;
3871   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
3872     if (UnOp->getOpcode() == UO_AddrOf)
3873       NakedFn = UnOp->getSubExpr()->IgnoreParens();
3874 
3875   if (isa<DeclRefExpr>(NakedFn))
3876     NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
3877   else if (isa<MemberExpr>(NakedFn))
3878     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
3879 
3880   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc,
3881                                ExecConfig, IsExecConfig);
3882 }
3883 
3884 ExprResult
3885 Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
3886                               MultiExprArg ExecConfig, SourceLocation GGGLoc) {
3887   FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
3888   if (!ConfigDecl)
3889     return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
3890                           << "cudaConfigureCall");
3891   QualType ConfigQTy = ConfigDecl->getType();
3892 
3893   DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
3894       ConfigDecl, false, ConfigQTy, VK_LValue, LLLLoc);
3895   MarkFunctionReferenced(LLLLoc, ConfigDecl);
3896 
3897   return ActOnCallExpr(S, ConfigDR, LLLLoc, ExecConfig, GGGLoc, 0,
3898                        /*IsExecConfig=*/true);
3899 }
3900 
3901 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
3902 ///
3903 /// __builtin_astype( value, dst type )
3904 ///
3905 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
3906                                  SourceLocation BuiltinLoc,
3907                                  SourceLocation RParenLoc) {
3908   ExprValueKind VK = VK_RValue;
3909   ExprObjectKind OK = OK_Ordinary;
3910   QualType DstTy = GetTypeFromParser(ParsedDestTy);
3911   QualType SrcTy = E->getType();
3912   if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
3913     return ExprError(Diag(BuiltinLoc,
3914                           diag::err_invalid_astype_of_different_size)
3915                      << DstTy
3916                      << SrcTy
3917                      << E->getSourceRange());
3918   return Owned(new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc,
3919                RParenLoc));
3920 }
3921 
3922 /// BuildResolvedCallExpr - Build a call to a resolved expression,
3923 /// i.e. an expression not of \p OverloadTy.  The expression should
3924 /// unary-convert to an expression of function-pointer or
3925 /// block-pointer type.
3926 ///
3927 /// \param NDecl the declaration being called, if available
3928 ExprResult
3929 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
3930                             SourceLocation LParenLoc,
3931                             Expr **Args, unsigned NumArgs,
3932                             SourceLocation RParenLoc,
3933                             Expr *Config, bool IsExecConfig) {
3934   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
3935 
3936   // Promote the function operand.
3937   ExprResult Result = UsualUnaryConversions(Fn);
3938   if (Result.isInvalid())
3939     return ExprError();
3940   Fn = Result.take();
3941 
3942   // Make the call expr early, before semantic checks.  This guarantees cleanup
3943   // of arguments and function on error.
3944   CallExpr *TheCall;
3945   if (Config)
3946     TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
3947                                                cast<CallExpr>(Config),
3948                                                Args, NumArgs,
3949                                                Context.BoolTy,
3950                                                VK_RValue,
3951                                                RParenLoc);
3952   else
3953     TheCall = new (Context) CallExpr(Context, Fn,
3954                                      Args, NumArgs,
3955                                      Context.BoolTy,
3956                                      VK_RValue,
3957                                      RParenLoc);
3958 
3959   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
3960 
3961   // Bail out early if calling a builtin with custom typechecking.
3962   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
3963     return CheckBuiltinFunctionCall(BuiltinID, TheCall);
3964 
3965  retry:
3966   const FunctionType *FuncT;
3967   if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
3968     // C99 6.5.2.2p1 - "The expression that denotes the called function shall
3969     // have type pointer to function".
3970     FuncT = PT->getPointeeType()->getAs<FunctionType>();
3971     if (FuncT == 0)
3972       return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3973                          << Fn->getType() << Fn->getSourceRange());
3974   } else if (const BlockPointerType *BPT =
3975                Fn->getType()->getAs<BlockPointerType>()) {
3976     FuncT = BPT->getPointeeType()->castAs<FunctionType>();
3977   } else {
3978     // Handle calls to expressions of unknown-any type.
3979     if (Fn->getType() == Context.UnknownAnyTy) {
3980       ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
3981       if (rewrite.isInvalid()) return ExprError();
3982       Fn = rewrite.take();
3983       TheCall->setCallee(Fn);
3984       goto retry;
3985     }
3986 
3987     return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3988       << Fn->getType() << Fn->getSourceRange());
3989   }
3990 
3991   if (getLangOpts().CUDA) {
3992     if (Config) {
3993       // CUDA: Kernel calls must be to global functions
3994       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
3995         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
3996             << FDecl->getName() << Fn->getSourceRange());
3997 
3998       // CUDA: Kernel function must have 'void' return type
3999       if (!FuncT->getResultType()->isVoidType())
4000         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
4001             << Fn->getType() << Fn->getSourceRange());
4002     } else {
4003       // CUDA: Calls to global functions must be configured
4004       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
4005         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
4006             << FDecl->getName() << Fn->getSourceRange());
4007     }
4008   }
4009 
4010   // Check for a valid return type
4011   if (CheckCallReturnType(FuncT->getResultType(),
4012                           Fn->getLocStart(), TheCall,
4013                           FDecl))
4014     return ExprError();
4015 
4016   // We know the result type of the call, set it.
4017   TheCall->setType(FuncT->getCallResultType(Context));
4018   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
4019 
4020   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
4021   if (Proto) {
4022     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
4023                                 RParenLoc, IsExecConfig))
4024       return ExprError();
4025   } else {
4026     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
4027 
4028     if (FDecl) {
4029       // Check if we have too few/too many template arguments, based
4030       // on our knowledge of the function definition.
4031       const FunctionDecl *Def = 0;
4032       if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
4033         Proto = Def->getType()->getAs<FunctionProtoType>();
4034         if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
4035           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
4036             << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
4037       }
4038 
4039       // If the function we're calling isn't a function prototype, but we have
4040       // a function prototype from a prior declaratiom, use that prototype.
4041       if (!FDecl->hasPrototype())
4042         Proto = FDecl->getType()->getAs<FunctionProtoType>();
4043     }
4044 
4045     // Promote the arguments (C99 6.5.2.2p6).
4046     for (unsigned i = 0; i != NumArgs; i++) {
4047       Expr *Arg = Args[i];
4048 
4049       if (Proto && i < Proto->getNumArgs()) {
4050         InitializedEntity Entity
4051           = InitializedEntity::InitializeParameter(Context,
4052                                                    Proto->getArgType(i),
4053                                                    Proto->isArgConsumed(i));
4054         ExprResult ArgE = PerformCopyInitialization(Entity,
4055                                                     SourceLocation(),
4056                                                     Owned(Arg));
4057         if (ArgE.isInvalid())
4058           return true;
4059 
4060         Arg = ArgE.takeAs<Expr>();
4061 
4062       } else {
4063         ExprResult ArgE = DefaultArgumentPromotion(Arg);
4064 
4065         if (ArgE.isInvalid())
4066           return true;
4067 
4068         Arg = ArgE.takeAs<Expr>();
4069       }
4070 
4071       if (RequireCompleteType(Arg->getLocStart(),
4072                               Arg->getType(),
4073                               diag::err_call_incomplete_argument, Arg))
4074         return ExprError();
4075 
4076       TheCall->setArg(i, Arg);
4077     }
4078   }
4079 
4080   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4081     if (!Method->isStatic())
4082       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
4083         << Fn->getSourceRange());
4084 
4085   // Check for sentinels
4086   if (NDecl)
4087     DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
4088 
4089   // Do special checking on direct calls to functions.
4090   if (FDecl) {
4091     if (CheckFunctionCall(FDecl, TheCall, Proto))
4092       return ExprError();
4093 
4094     if (BuiltinID)
4095       return CheckBuiltinFunctionCall(BuiltinID, TheCall);
4096   } else if (NDecl) {
4097     if (CheckBlockCall(NDecl, TheCall, Proto))
4098       return ExprError();
4099   }
4100 
4101   return MaybeBindToTemporary(TheCall);
4102 }
4103 
4104 ExprResult
4105 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
4106                            SourceLocation RParenLoc, Expr *InitExpr) {
4107   assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
4108   // FIXME: put back this assert when initializers are worked out.
4109   //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
4110 
4111   TypeSourceInfo *TInfo;
4112   QualType literalType = GetTypeFromParser(Ty, &TInfo);
4113   if (!TInfo)
4114     TInfo = Context.getTrivialTypeSourceInfo(literalType);
4115 
4116   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
4117 }
4118 
4119 ExprResult
4120 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
4121                                SourceLocation RParenLoc, Expr *LiteralExpr) {
4122   QualType literalType = TInfo->getType();
4123 
4124   if (literalType->isArrayType()) {
4125     if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
4126           diag::err_illegal_decl_array_incomplete_type,
4127           SourceRange(LParenLoc,
4128                       LiteralExpr->getSourceRange().getEnd())))
4129       return ExprError();
4130     if (literalType->isVariableArrayType())
4131       return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
4132         << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
4133   } else if (!literalType->isDependentType() &&
4134              RequireCompleteType(LParenLoc, literalType,
4135                diag::err_typecheck_decl_incomplete_type,
4136                SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
4137     return ExprError();
4138 
4139   InitializedEntity Entity
4140     = InitializedEntity::InitializeTemporary(literalType);
4141   InitializationKind Kind
4142     = InitializationKind::CreateCStyleCast(LParenLoc,
4143                                            SourceRange(LParenLoc, RParenLoc),
4144                                            /*InitList=*/true);
4145   InitializationSequence InitSeq(*this, Entity, Kind, &LiteralExpr, 1);
4146   ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
4147                                        MultiExprArg(*this, &LiteralExpr, 1),
4148                                             &literalType);
4149   if (Result.isInvalid())
4150     return ExprError();
4151   LiteralExpr = Result.get();
4152 
4153   bool isFileScope = getCurFunctionOrMethodDecl() == 0;
4154   if (isFileScope) { // 6.5.2.5p3
4155     if (CheckForConstantInitializer(LiteralExpr, literalType))
4156       return ExprError();
4157   }
4158 
4159   // In C, compound literals are l-values for some reason.
4160   ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue;
4161 
4162   return MaybeBindToTemporary(
4163            new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
4164                                              VK, LiteralExpr, isFileScope));
4165 }
4166 
4167 ExprResult
4168 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
4169                     SourceLocation RBraceLoc) {
4170   unsigned NumInit = InitArgList.size();
4171   Expr **InitList = InitArgList.release();
4172 
4173   // Immediately handle non-overload placeholders.  Overloads can be
4174   // resolved contextually, but everything else here can't.
4175   for (unsigned I = 0; I != NumInit; ++I) {
4176     if (InitList[I]->getType()->isNonOverloadPlaceholderType()) {
4177       ExprResult result = CheckPlaceholderExpr(InitList[I]);
4178 
4179       // Ignore failures; dropping the entire initializer list because
4180       // of one failure would be terrible for indexing/etc.
4181       if (result.isInvalid()) continue;
4182 
4183       InitList[I] = result.take();
4184     }
4185   }
4186 
4187   // Semantic analysis for initializers is done by ActOnDeclarator() and
4188   // CheckInitializer() - it requires knowledge of the object being intialized.
4189 
4190   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitList,
4191                                                NumInit, RBraceLoc);
4192   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
4193   return Owned(E);
4194 }
4195 
4196 /// Do an explicit extend of the given block pointer if we're in ARC.
4197 static void maybeExtendBlockObject(Sema &S, ExprResult &E) {
4198   assert(E.get()->getType()->isBlockPointerType());
4199   assert(E.get()->isRValue());
4200 
4201   // Only do this in an r-value context.
4202   if (!S.getLangOpts().ObjCAutoRefCount) return;
4203 
4204   E = ImplicitCastExpr::Create(S.Context, E.get()->getType(),
4205                                CK_ARCExtendBlockObject, E.get(),
4206                                /*base path*/ 0, VK_RValue);
4207   S.ExprNeedsCleanups = true;
4208 }
4209 
4210 /// Prepare a conversion of the given expression to an ObjC object
4211 /// pointer type.
4212 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
4213   QualType type = E.get()->getType();
4214   if (type->isObjCObjectPointerType()) {
4215     return CK_BitCast;
4216   } else if (type->isBlockPointerType()) {
4217     maybeExtendBlockObject(*this, E);
4218     return CK_BlockPointerToObjCPointerCast;
4219   } else {
4220     assert(type->isPointerType());
4221     return CK_CPointerToObjCPointerCast;
4222   }
4223 }
4224 
4225 /// Prepares for a scalar cast, performing all the necessary stages
4226 /// except the final cast and returning the kind required.
4227 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
4228   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
4229   // Also, callers should have filtered out the invalid cases with
4230   // pointers.  Everything else should be possible.
4231 
4232   QualType SrcTy = Src.get()->getType();
4233   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
4234     return CK_NoOp;
4235 
4236   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
4237   case Type::STK_MemberPointer:
4238     llvm_unreachable("member pointer type in C");
4239 
4240   case Type::STK_CPointer:
4241   case Type::STK_BlockPointer:
4242   case Type::STK_ObjCObjectPointer:
4243     switch (DestTy->getScalarTypeKind()) {
4244     case Type::STK_CPointer:
4245       return CK_BitCast;
4246     case Type::STK_BlockPointer:
4247       return (SrcKind == Type::STK_BlockPointer
4248                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
4249     case Type::STK_ObjCObjectPointer:
4250       if (SrcKind == Type::STK_ObjCObjectPointer)
4251         return CK_BitCast;
4252       if (SrcKind == Type::STK_CPointer)
4253         return CK_CPointerToObjCPointerCast;
4254       maybeExtendBlockObject(*this, Src);
4255       return CK_BlockPointerToObjCPointerCast;
4256     case Type::STK_Bool:
4257       return CK_PointerToBoolean;
4258     case Type::STK_Integral:
4259       return CK_PointerToIntegral;
4260     case Type::STK_Floating:
4261     case Type::STK_FloatingComplex:
4262     case Type::STK_IntegralComplex:
4263     case Type::STK_MemberPointer:
4264       llvm_unreachable("illegal cast from pointer");
4265     }
4266     llvm_unreachable("Should have returned before this");
4267 
4268   case Type::STK_Bool: // casting from bool is like casting from an integer
4269   case Type::STK_Integral:
4270     switch (DestTy->getScalarTypeKind()) {
4271     case Type::STK_CPointer:
4272     case Type::STK_ObjCObjectPointer:
4273     case Type::STK_BlockPointer:
4274       if (Src.get()->isNullPointerConstant(Context,
4275                                            Expr::NPC_ValueDependentIsNull))
4276         return CK_NullToPointer;
4277       return CK_IntegralToPointer;
4278     case Type::STK_Bool:
4279       return CK_IntegralToBoolean;
4280     case Type::STK_Integral:
4281       return CK_IntegralCast;
4282     case Type::STK_Floating:
4283       return CK_IntegralToFloating;
4284     case Type::STK_IntegralComplex:
4285       Src = ImpCastExprToType(Src.take(),
4286                               DestTy->castAs<ComplexType>()->getElementType(),
4287                               CK_IntegralCast);
4288       return CK_IntegralRealToComplex;
4289     case Type::STK_FloatingComplex:
4290       Src = ImpCastExprToType(Src.take(),
4291                               DestTy->castAs<ComplexType>()->getElementType(),
4292                               CK_IntegralToFloating);
4293       return CK_FloatingRealToComplex;
4294     case Type::STK_MemberPointer:
4295       llvm_unreachable("member pointer type in C");
4296     }
4297     llvm_unreachable("Should have returned before this");
4298 
4299   case Type::STK_Floating:
4300     switch (DestTy->getScalarTypeKind()) {
4301     case Type::STK_Floating:
4302       return CK_FloatingCast;
4303     case Type::STK_Bool:
4304       return CK_FloatingToBoolean;
4305     case Type::STK_Integral:
4306       return CK_FloatingToIntegral;
4307     case Type::STK_FloatingComplex:
4308       Src = ImpCastExprToType(Src.take(),
4309                               DestTy->castAs<ComplexType>()->getElementType(),
4310                               CK_FloatingCast);
4311       return CK_FloatingRealToComplex;
4312     case Type::STK_IntegralComplex:
4313       Src = ImpCastExprToType(Src.take(),
4314                               DestTy->castAs<ComplexType>()->getElementType(),
4315                               CK_FloatingToIntegral);
4316       return CK_IntegralRealToComplex;
4317     case Type::STK_CPointer:
4318     case Type::STK_ObjCObjectPointer:
4319     case Type::STK_BlockPointer:
4320       llvm_unreachable("valid float->pointer cast?");
4321     case Type::STK_MemberPointer:
4322       llvm_unreachable("member pointer type in C");
4323     }
4324     llvm_unreachable("Should have returned before this");
4325 
4326   case Type::STK_FloatingComplex:
4327     switch (DestTy->getScalarTypeKind()) {
4328     case Type::STK_FloatingComplex:
4329       return CK_FloatingComplexCast;
4330     case Type::STK_IntegralComplex:
4331       return CK_FloatingComplexToIntegralComplex;
4332     case Type::STK_Floating: {
4333       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
4334       if (Context.hasSameType(ET, DestTy))
4335         return CK_FloatingComplexToReal;
4336       Src = ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal);
4337       return CK_FloatingCast;
4338     }
4339     case Type::STK_Bool:
4340       return CK_FloatingComplexToBoolean;
4341     case Type::STK_Integral:
4342       Src = ImpCastExprToType(Src.take(),
4343                               SrcTy->castAs<ComplexType>()->getElementType(),
4344                               CK_FloatingComplexToReal);
4345       return CK_FloatingToIntegral;
4346     case Type::STK_CPointer:
4347     case Type::STK_ObjCObjectPointer:
4348     case Type::STK_BlockPointer:
4349       llvm_unreachable("valid complex float->pointer cast?");
4350     case Type::STK_MemberPointer:
4351       llvm_unreachable("member pointer type in C");
4352     }
4353     llvm_unreachable("Should have returned before this");
4354 
4355   case Type::STK_IntegralComplex:
4356     switch (DestTy->getScalarTypeKind()) {
4357     case Type::STK_FloatingComplex:
4358       return CK_IntegralComplexToFloatingComplex;
4359     case Type::STK_IntegralComplex:
4360       return CK_IntegralComplexCast;
4361     case Type::STK_Integral: {
4362       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
4363       if (Context.hasSameType(ET, DestTy))
4364         return CK_IntegralComplexToReal;
4365       Src = ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal);
4366       return CK_IntegralCast;
4367     }
4368     case Type::STK_Bool:
4369       return CK_IntegralComplexToBoolean;
4370     case Type::STK_Floating:
4371       Src = ImpCastExprToType(Src.take(),
4372                               SrcTy->castAs<ComplexType>()->getElementType(),
4373                               CK_IntegralComplexToReal);
4374       return CK_IntegralToFloating;
4375     case Type::STK_CPointer:
4376     case Type::STK_ObjCObjectPointer:
4377     case Type::STK_BlockPointer:
4378       llvm_unreachable("valid complex int->pointer cast?");
4379     case Type::STK_MemberPointer:
4380       llvm_unreachable("member pointer type in C");
4381     }
4382     llvm_unreachable("Should have returned before this");
4383   }
4384 
4385   llvm_unreachable("Unhandled scalar cast");
4386 }
4387 
4388 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
4389                            CastKind &Kind) {
4390   assert(VectorTy->isVectorType() && "Not a vector type!");
4391 
4392   if (Ty->isVectorType() || Ty->isIntegerType()) {
4393     if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
4394       return Diag(R.getBegin(),
4395                   Ty->isVectorType() ?
4396                   diag::err_invalid_conversion_between_vectors :
4397                   diag::err_invalid_conversion_between_vector_and_integer)
4398         << VectorTy << Ty << R;
4399   } else
4400     return Diag(R.getBegin(),
4401                 diag::err_invalid_conversion_between_vector_and_scalar)
4402       << VectorTy << Ty << R;
4403 
4404   Kind = CK_BitCast;
4405   return false;
4406 }
4407 
4408 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
4409                                     Expr *CastExpr, CastKind &Kind) {
4410   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
4411 
4412   QualType SrcTy = CastExpr->getType();
4413 
4414   // If SrcTy is a VectorType, the total size must match to explicitly cast to
4415   // an ExtVectorType.
4416   // In OpenCL, casts between vectors of different types are not allowed.
4417   // (See OpenCL 6.2).
4418   if (SrcTy->isVectorType()) {
4419     if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)
4420         || (getLangOpts().OpenCL &&
4421             (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
4422       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
4423         << DestTy << SrcTy << R;
4424       return ExprError();
4425     }
4426     Kind = CK_BitCast;
4427     return Owned(CastExpr);
4428   }
4429 
4430   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
4431   // conversion will take place first from scalar to elt type, and then
4432   // splat from elt type to vector.
4433   if (SrcTy->isPointerType())
4434     return Diag(R.getBegin(),
4435                 diag::err_invalid_conversion_between_vector_and_scalar)
4436       << DestTy << SrcTy << R;
4437 
4438   QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
4439   ExprResult CastExprRes = Owned(CastExpr);
4440   CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy);
4441   if (CastExprRes.isInvalid())
4442     return ExprError();
4443   CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take();
4444 
4445   Kind = CK_VectorSplat;
4446   return Owned(CastExpr);
4447 }
4448 
4449 ExprResult
4450 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
4451                     Declarator &D, ParsedType &Ty,
4452                     SourceLocation RParenLoc, Expr *CastExpr) {
4453   assert(!D.isInvalidType() && (CastExpr != 0) &&
4454          "ActOnCastExpr(): missing type or expr");
4455 
4456   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
4457   if (D.isInvalidType())
4458     return ExprError();
4459 
4460   if (getLangOpts().CPlusPlus) {
4461     // Check that there are no default arguments (C++ only).
4462     CheckExtraCXXDefaultArguments(D);
4463   }
4464 
4465   checkUnusedDeclAttributes(D);
4466 
4467   QualType castType = castTInfo->getType();
4468   Ty = CreateParsedType(castType, castTInfo);
4469 
4470   bool isVectorLiteral = false;
4471 
4472   // Check for an altivec or OpenCL literal,
4473   // i.e. all the elements are integer constants.
4474   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
4475   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
4476   if ((getLangOpts().AltiVec || getLangOpts().OpenCL)
4477        && castType->isVectorType() && (PE || PLE)) {
4478     if (PLE && PLE->getNumExprs() == 0) {
4479       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
4480       return ExprError();
4481     }
4482     if (PE || PLE->getNumExprs() == 1) {
4483       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
4484       if (!E->getType()->isVectorType())
4485         isVectorLiteral = true;
4486     }
4487     else
4488       isVectorLiteral = true;
4489   }
4490 
4491   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
4492   // then handle it as such.
4493   if (isVectorLiteral)
4494     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
4495 
4496   // If the Expr being casted is a ParenListExpr, handle it specially.
4497   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
4498   // sequence of BinOp comma operators.
4499   if (isa<ParenListExpr>(CastExpr)) {
4500     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
4501     if (Result.isInvalid()) return ExprError();
4502     CastExpr = Result.take();
4503   }
4504 
4505   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
4506 }
4507 
4508 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
4509                                     SourceLocation RParenLoc, Expr *E,
4510                                     TypeSourceInfo *TInfo) {
4511   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
4512          "Expected paren or paren list expression");
4513 
4514   Expr **exprs;
4515   unsigned numExprs;
4516   Expr *subExpr;
4517   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
4518     exprs = PE->getExprs();
4519     numExprs = PE->getNumExprs();
4520   } else {
4521     subExpr = cast<ParenExpr>(E)->getSubExpr();
4522     exprs = &subExpr;
4523     numExprs = 1;
4524   }
4525 
4526   QualType Ty = TInfo->getType();
4527   assert(Ty->isVectorType() && "Expected vector type");
4528 
4529   SmallVector<Expr *, 8> initExprs;
4530   const VectorType *VTy = Ty->getAs<VectorType>();
4531   unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
4532 
4533   // '(...)' form of vector initialization in AltiVec: the number of
4534   // initializers must be one or must match the size of the vector.
4535   // If a single value is specified in the initializer then it will be
4536   // replicated to all the components of the vector
4537   if (VTy->getVectorKind() == VectorType::AltiVecVector) {
4538     // The number of initializers must be one or must match the size of the
4539     // vector. If a single value is specified in the initializer then it will
4540     // be replicated to all the components of the vector
4541     if (numExprs == 1) {
4542       QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
4543       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
4544       if (Literal.isInvalid())
4545         return ExprError();
4546       Literal = ImpCastExprToType(Literal.take(), ElemTy,
4547                                   PrepareScalarCast(Literal, ElemTy));
4548       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4549     }
4550     else if (numExprs < numElems) {
4551       Diag(E->getExprLoc(),
4552            diag::err_incorrect_number_of_vector_initializers);
4553       return ExprError();
4554     }
4555     else
4556       initExprs.append(exprs, exprs + numExprs);
4557   }
4558   else {
4559     // For OpenCL, when the number of initializers is a single value,
4560     // it will be replicated to all components of the vector.
4561     if (getLangOpts().OpenCL &&
4562         VTy->getVectorKind() == VectorType::GenericVector &&
4563         numExprs == 1) {
4564         QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
4565         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
4566         if (Literal.isInvalid())
4567           return ExprError();
4568         Literal = ImpCastExprToType(Literal.take(), ElemTy,
4569                                     PrepareScalarCast(Literal, ElemTy));
4570         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4571     }
4572 
4573     initExprs.append(exprs, exprs + numExprs);
4574   }
4575   // FIXME: This means that pretty-printing the final AST will produce curly
4576   // braces instead of the original commas.
4577   InitListExpr *initE = new (Context) InitListExpr(Context, LParenLoc,
4578                                                    &initExprs[0],
4579                                                    initExprs.size(), RParenLoc);
4580   initE->setType(Ty);
4581   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
4582 }
4583 
4584 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
4585 /// the ParenListExpr into a sequence of comma binary operators.
4586 ExprResult
4587 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
4588   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
4589   if (!E)
4590     return Owned(OrigExpr);
4591 
4592   ExprResult Result(E->getExpr(0));
4593 
4594   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
4595     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
4596                         E->getExpr(i));
4597 
4598   if (Result.isInvalid()) return ExprError();
4599 
4600   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
4601 }
4602 
4603 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
4604                                     SourceLocation R,
4605                                     MultiExprArg Val) {
4606   unsigned nexprs = Val.size();
4607   Expr **exprs = reinterpret_cast<Expr**>(Val.release());
4608   assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
4609   Expr *expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
4610   return Owned(expr);
4611 }
4612 
4613 /// \brief Emit a specialized diagnostic when one expression is a null pointer
4614 /// constant and the other is not a pointer.  Returns true if a diagnostic is
4615 /// emitted.
4616 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
4617                                       SourceLocation QuestionLoc) {
4618   Expr *NullExpr = LHSExpr;
4619   Expr *NonPointerExpr = RHSExpr;
4620   Expr::NullPointerConstantKind NullKind =
4621       NullExpr->isNullPointerConstant(Context,
4622                                       Expr::NPC_ValueDependentIsNotNull);
4623 
4624   if (NullKind == Expr::NPCK_NotNull) {
4625     NullExpr = RHSExpr;
4626     NonPointerExpr = LHSExpr;
4627     NullKind =
4628         NullExpr->isNullPointerConstant(Context,
4629                                         Expr::NPC_ValueDependentIsNotNull);
4630   }
4631 
4632   if (NullKind == Expr::NPCK_NotNull)
4633     return false;
4634 
4635   if (NullKind == Expr::NPCK_ZeroExpression)
4636     return false;
4637 
4638   if (NullKind == Expr::NPCK_ZeroLiteral) {
4639     // In this case, check to make sure that we got here from a "NULL"
4640     // string in the source code.
4641     NullExpr = NullExpr->IgnoreParenImpCasts();
4642     SourceLocation loc = NullExpr->getExprLoc();
4643     if (!findMacroSpelling(loc, "NULL"))
4644       return false;
4645   }
4646 
4647   int DiagType = (NullKind == Expr::NPCK_CXX0X_nullptr);
4648   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
4649       << NonPointerExpr->getType() << DiagType
4650       << NonPointerExpr->getSourceRange();
4651   return true;
4652 }
4653 
4654 /// \brief Return false if the condition expression is valid, true otherwise.
4655 static bool checkCondition(Sema &S, Expr *Cond) {
4656   QualType CondTy = Cond->getType();
4657 
4658   // C99 6.5.15p2
4659   if (CondTy->isScalarType()) return false;
4660 
4661   // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
4662   if (S.getLangOpts().OpenCL && CondTy->isVectorType())
4663     return false;
4664 
4665   // Emit the proper error message.
4666   S.Diag(Cond->getLocStart(), S.getLangOpts().OpenCL ?
4667                               diag::err_typecheck_cond_expect_scalar :
4668                               diag::err_typecheck_cond_expect_scalar_or_vector)
4669     << CondTy;
4670   return true;
4671 }
4672 
4673 /// \brief Return false if the two expressions can be converted to a vector,
4674 /// true otherwise
4675 static bool checkConditionalConvertScalarsToVectors(Sema &S, ExprResult &LHS,
4676                                                     ExprResult &RHS,
4677                                                     QualType CondTy) {
4678   // Both operands should be of scalar type.
4679   if (!LHS.get()->getType()->isScalarType()) {
4680     S.Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4681       << CondTy;
4682     return true;
4683   }
4684   if (!RHS.get()->getType()->isScalarType()) {
4685     S.Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4686       << CondTy;
4687     return true;
4688   }
4689 
4690   // Implicity convert these scalars to the type of the condition.
4691   LHS = S.ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast);
4692   RHS = S.ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast);
4693   return false;
4694 }
4695 
4696 /// \brief Handle when one or both operands are void type.
4697 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
4698                                          ExprResult &RHS) {
4699     Expr *LHSExpr = LHS.get();
4700     Expr *RHSExpr = RHS.get();
4701 
4702     if (!LHSExpr->getType()->isVoidType())
4703       S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4704         << RHSExpr->getSourceRange();
4705     if (!RHSExpr->getType()->isVoidType())
4706       S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4707         << LHSExpr->getSourceRange();
4708     LHS = S.ImpCastExprToType(LHS.take(), S.Context.VoidTy, CK_ToVoid);
4709     RHS = S.ImpCastExprToType(RHS.take(), S.Context.VoidTy, CK_ToVoid);
4710     return S.Context.VoidTy;
4711 }
4712 
4713 /// \brief Return false if the NullExpr can be promoted to PointerTy,
4714 /// true otherwise.
4715 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
4716                                         QualType PointerTy) {
4717   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
4718       !NullExpr.get()->isNullPointerConstant(S.Context,
4719                                             Expr::NPC_ValueDependentIsNull))
4720     return true;
4721 
4722   NullExpr = S.ImpCastExprToType(NullExpr.take(), PointerTy, CK_NullToPointer);
4723   return false;
4724 }
4725 
4726 /// \brief Checks compatibility between two pointers and return the resulting
4727 /// type.
4728 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
4729                                                      ExprResult &RHS,
4730                                                      SourceLocation Loc) {
4731   QualType LHSTy = LHS.get()->getType();
4732   QualType RHSTy = RHS.get()->getType();
4733 
4734   if (S.Context.hasSameType(LHSTy, RHSTy)) {
4735     // Two identical pointers types are always compatible.
4736     return LHSTy;
4737   }
4738 
4739   QualType lhptee, rhptee;
4740 
4741   // Get the pointee types.
4742   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
4743     lhptee = LHSBTy->getPointeeType();
4744     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
4745   } else {
4746     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
4747     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
4748   }
4749 
4750   // C99 6.5.15p6: If both operands are pointers to compatible types or to
4751   // differently qualified versions of compatible types, the result type is
4752   // a pointer to an appropriately qualified version of the composite
4753   // type.
4754 
4755   // Only CVR-qualifiers exist in the standard, and the differently-qualified
4756   // clause doesn't make sense for our extensions. E.g. address space 2 should
4757   // be incompatible with address space 3: they may live on different devices or
4758   // anything.
4759   Qualifiers lhQual = lhptee.getQualifiers();
4760   Qualifiers rhQual = rhptee.getQualifiers();
4761 
4762   unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
4763   lhQual.removeCVRQualifiers();
4764   rhQual.removeCVRQualifiers();
4765 
4766   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
4767   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
4768 
4769   QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
4770 
4771   if (CompositeTy.isNull()) {
4772     S.Diag(Loc, diag::warn_typecheck_cond_incompatible_pointers)
4773       << LHSTy << RHSTy << LHS.get()->getSourceRange()
4774       << RHS.get()->getSourceRange();
4775     // In this situation, we assume void* type. No especially good
4776     // reason, but this is what gcc does, and we do have to pick
4777     // to get a consistent AST.
4778     QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy);
4779     LHS = S.ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4780     RHS = S.ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
4781     return incompatTy;
4782   }
4783 
4784   // The pointer types are compatible.
4785   QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual);
4786   ResultTy = S.Context.getPointerType(ResultTy);
4787 
4788   LHS = S.ImpCastExprToType(LHS.take(), ResultTy, CK_BitCast);
4789   RHS = S.ImpCastExprToType(RHS.take(), ResultTy, CK_BitCast);
4790   return ResultTy;
4791 }
4792 
4793 /// \brief Return the resulting type when the operands are both block pointers.
4794 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
4795                                                           ExprResult &LHS,
4796                                                           ExprResult &RHS,
4797                                                           SourceLocation Loc) {
4798   QualType LHSTy = LHS.get()->getType();
4799   QualType RHSTy = RHS.get()->getType();
4800 
4801   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
4802     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
4803       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
4804       LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4805       RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4806       return destType;
4807     }
4808     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
4809       << LHSTy << RHSTy << LHS.get()->getSourceRange()
4810       << RHS.get()->getSourceRange();
4811     return QualType();
4812   }
4813 
4814   // We have 2 block pointer types.
4815   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
4816 }
4817 
4818 /// \brief Return the resulting type when the operands are both pointers.
4819 static QualType
4820 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
4821                                             ExprResult &RHS,
4822                                             SourceLocation Loc) {
4823   // get the pointer types
4824   QualType LHSTy = LHS.get()->getType();
4825   QualType RHSTy = RHS.get()->getType();
4826 
4827   // get the "pointed to" types
4828   QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4829   QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4830 
4831   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
4832   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
4833     // Figure out necessary qualifiers (C99 6.5.15p6)
4834     QualType destPointee
4835       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4836     QualType destType = S.Context.getPointerType(destPointee);
4837     // Add qualifiers if necessary.
4838     LHS = S.ImpCastExprToType(LHS.take(), destType, CK_NoOp);
4839     // Promote to void*.
4840     RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4841     return destType;
4842   }
4843   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
4844     QualType destPointee
4845       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4846     QualType destType = S.Context.getPointerType(destPointee);
4847     // Add qualifiers if necessary.
4848     RHS = S.ImpCastExprToType(RHS.take(), destType, CK_NoOp);
4849     // Promote to void*.
4850     LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4851     return destType;
4852   }
4853 
4854   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
4855 }
4856 
4857 /// \brief Return false if the first expression is not an integer and the second
4858 /// expression is not a pointer, true otherwise.
4859 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
4860                                         Expr* PointerExpr, SourceLocation Loc,
4861                                         bool IsIntFirstExpr) {
4862   if (!PointerExpr->getType()->isPointerType() ||
4863       !Int.get()->getType()->isIntegerType())
4864     return false;
4865 
4866   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
4867   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
4868 
4869   S.Diag(Loc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4870     << Expr1->getType() << Expr2->getType()
4871     << Expr1->getSourceRange() << Expr2->getSourceRange();
4872   Int = S.ImpCastExprToType(Int.take(), PointerExpr->getType(),
4873                             CK_IntegralToPointer);
4874   return true;
4875 }
4876 
4877 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
4878 /// In that case, LHS = cond.
4879 /// C99 6.5.15
4880 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
4881                                         ExprResult &RHS, ExprValueKind &VK,
4882                                         ExprObjectKind &OK,
4883                                         SourceLocation QuestionLoc) {
4884 
4885   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
4886   if (!LHSResult.isUsable()) return QualType();
4887   LHS = move(LHSResult);
4888 
4889   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
4890   if (!RHSResult.isUsable()) return QualType();
4891   RHS = move(RHSResult);
4892 
4893   // C++ is sufficiently different to merit its own checker.
4894   if (getLangOpts().CPlusPlus)
4895     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
4896 
4897   VK = VK_RValue;
4898   OK = OK_Ordinary;
4899 
4900   Cond = UsualUnaryConversions(Cond.take());
4901   if (Cond.isInvalid())
4902     return QualType();
4903   LHS = UsualUnaryConversions(LHS.take());
4904   if (LHS.isInvalid())
4905     return QualType();
4906   RHS = UsualUnaryConversions(RHS.take());
4907   if (RHS.isInvalid())
4908     return QualType();
4909 
4910   QualType CondTy = Cond.get()->getType();
4911   QualType LHSTy = LHS.get()->getType();
4912   QualType RHSTy = RHS.get()->getType();
4913 
4914   // first, check the condition.
4915   if (checkCondition(*this, Cond.get()))
4916     return QualType();
4917 
4918   // Now check the two expressions.
4919   if (LHSTy->isVectorType() || RHSTy->isVectorType())
4920     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
4921 
4922   // OpenCL: If the condition is a vector, and both operands are scalar,
4923   // attempt to implicity convert them to the vector type to act like the
4924   // built in select.
4925   if (getLangOpts().OpenCL && CondTy->isVectorType())
4926     if (checkConditionalConvertScalarsToVectors(*this, LHS, RHS, CondTy))
4927       return QualType();
4928 
4929   // If both operands have arithmetic type, do the usual arithmetic conversions
4930   // to find a common type: C99 6.5.15p3,5.
4931   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
4932     UsualArithmeticConversions(LHS, RHS);
4933     if (LHS.isInvalid() || RHS.isInvalid())
4934       return QualType();
4935     return LHS.get()->getType();
4936   }
4937 
4938   // If both operands are the same structure or union type, the result is that
4939   // type.
4940   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
4941     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
4942       if (LHSRT->getDecl() == RHSRT->getDecl())
4943         // "If both the operands have structure or union type, the result has
4944         // that type."  This implies that CV qualifiers are dropped.
4945         return LHSTy.getUnqualifiedType();
4946     // FIXME: Type of conditional expression must be complete in C mode.
4947   }
4948 
4949   // C99 6.5.15p5: "If both operands have void type, the result has void type."
4950   // The following || allows only one side to be void (a GCC-ism).
4951   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
4952     return checkConditionalVoidType(*this, LHS, RHS);
4953   }
4954 
4955   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
4956   // the type of the other operand."
4957   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
4958   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
4959 
4960   // All objective-c pointer type analysis is done here.
4961   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
4962                                                         QuestionLoc);
4963   if (LHS.isInvalid() || RHS.isInvalid())
4964     return QualType();
4965   if (!compositeType.isNull())
4966     return compositeType;
4967 
4968 
4969   // Handle block pointer types.
4970   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
4971     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
4972                                                      QuestionLoc);
4973 
4974   // Check constraints for C object pointers types (C99 6.5.15p3,6).
4975   if (LHSTy->isPointerType() && RHSTy->isPointerType())
4976     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
4977                                                        QuestionLoc);
4978 
4979   // GCC compatibility: soften pointer/integer mismatch.  Note that
4980   // null pointers have been filtered out by this point.
4981   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
4982       /*isIntFirstExpr=*/true))
4983     return RHSTy;
4984   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
4985       /*isIntFirstExpr=*/false))
4986     return LHSTy;
4987 
4988   // Emit a better diagnostic if one of the expressions is a null pointer
4989   // constant and the other is not a pointer type. In this case, the user most
4990   // likely forgot to take the address of the other expression.
4991   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
4992     return QualType();
4993 
4994   // Otherwise, the operands are not compatible.
4995   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
4996     << LHSTy << RHSTy << LHS.get()->getSourceRange()
4997     << RHS.get()->getSourceRange();
4998   return QualType();
4999 }
5000 
5001 /// FindCompositeObjCPointerType - Helper method to find composite type of
5002 /// two objective-c pointer types of the two input expressions.
5003 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
5004                                             SourceLocation QuestionLoc) {
5005   QualType LHSTy = LHS.get()->getType();
5006   QualType RHSTy = RHS.get()->getType();
5007 
5008   // Handle things like Class and struct objc_class*.  Here we case the result
5009   // to the pseudo-builtin, because that will be implicitly cast back to the
5010   // redefinition type if an attempt is made to access its fields.
5011   if (LHSTy->isObjCClassType() &&
5012       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
5013     RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
5014     return LHSTy;
5015   }
5016   if (RHSTy->isObjCClassType() &&
5017       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
5018     LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
5019     return RHSTy;
5020   }
5021   // And the same for struct objc_object* / id
5022   if (LHSTy->isObjCIdType() &&
5023       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
5024     RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
5025     return LHSTy;
5026   }
5027   if (RHSTy->isObjCIdType() &&
5028       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
5029     LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
5030     return RHSTy;
5031   }
5032   // And the same for struct objc_selector* / SEL
5033   if (Context.isObjCSelType(LHSTy) &&
5034       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
5035     RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
5036     return LHSTy;
5037   }
5038   if (Context.isObjCSelType(RHSTy) &&
5039       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
5040     LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
5041     return RHSTy;
5042   }
5043   // Check constraints for Objective-C object pointers types.
5044   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
5045 
5046     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5047       // Two identical object pointer types are always compatible.
5048       return LHSTy;
5049     }
5050     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
5051     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
5052     QualType compositeType = LHSTy;
5053 
5054     // If both operands are interfaces and either operand can be
5055     // assigned to the other, use that type as the composite
5056     // type. This allows
5057     //   xxx ? (A*) a : (B*) b
5058     // where B is a subclass of A.
5059     //
5060     // Additionally, as for assignment, if either type is 'id'
5061     // allow silent coercion. Finally, if the types are
5062     // incompatible then make sure to use 'id' as the composite
5063     // type so the result is acceptable for sending messages to.
5064 
5065     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
5066     // It could return the composite type.
5067     if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
5068       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
5069     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
5070       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
5071     } else if ((LHSTy->isObjCQualifiedIdType() ||
5072                 RHSTy->isObjCQualifiedIdType()) &&
5073                Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
5074       // Need to handle "id<xx>" explicitly.
5075       // GCC allows qualified id and any Objective-C type to devolve to
5076       // id. Currently localizing to here until clear this should be
5077       // part of ObjCQualifiedIdTypesAreCompatible.
5078       compositeType = Context.getObjCIdType();
5079     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
5080       compositeType = Context.getObjCIdType();
5081     } else if (!(compositeType =
5082                  Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
5083       ;
5084     else {
5085       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
5086       << LHSTy << RHSTy
5087       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5088       QualType incompatTy = Context.getObjCIdType();
5089       LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
5090       RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
5091       return incompatTy;
5092     }
5093     // The object pointer types are compatible.
5094     LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast);
5095     RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast);
5096     return compositeType;
5097   }
5098   // Check Objective-C object pointer types and 'void *'
5099   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
5100     if (getLangOpts().ObjCAutoRefCount) {
5101       // ARC forbids the implicit conversion of object pointers to 'void *',
5102       // so these types are not compatible.
5103       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
5104           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5105       LHS = RHS = true;
5106       return QualType();
5107     }
5108     QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5109     QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5110     QualType destPointee
5111     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
5112     QualType destType = Context.getPointerType(destPointee);
5113     // Add qualifiers if necessary.
5114     LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
5115     // Promote to void*.
5116     RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
5117     return destType;
5118   }
5119   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
5120     if (getLangOpts().ObjCAutoRefCount) {
5121       // ARC forbids the implicit conversion of object pointers to 'void *',
5122       // so these types are not compatible.
5123       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
5124           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5125       LHS = RHS = true;
5126       return QualType();
5127     }
5128     QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5129     QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
5130     QualType destPointee
5131     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
5132     QualType destType = Context.getPointerType(destPointee);
5133     // Add qualifiers if necessary.
5134     RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
5135     // Promote to void*.
5136     LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
5137     return destType;
5138   }
5139   return QualType();
5140 }
5141 
5142 /// SuggestParentheses - Emit a note with a fixit hint that wraps
5143 /// ParenRange in parentheses.
5144 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
5145                                const PartialDiagnostic &Note,
5146                                SourceRange ParenRange) {
5147   SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
5148   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
5149       EndLoc.isValid()) {
5150     Self.Diag(Loc, Note)
5151       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
5152       << FixItHint::CreateInsertion(EndLoc, ")");
5153   } else {
5154     // We can't display the parentheses, so just show the bare note.
5155     Self.Diag(Loc, Note) << ParenRange;
5156   }
5157 }
5158 
5159 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
5160   return Opc >= BO_Mul && Opc <= BO_Shr;
5161 }
5162 
5163 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
5164 /// expression, either using a built-in or overloaded operator,
5165 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
5166 /// expression.
5167 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
5168                                    Expr **RHSExprs) {
5169   // Don't strip parenthesis: we should not warn if E is in parenthesis.
5170   E = E->IgnoreImpCasts();
5171   E = E->IgnoreConversionOperator();
5172   E = E->IgnoreImpCasts();
5173 
5174   // Built-in binary operator.
5175   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
5176     if (IsArithmeticOp(OP->getOpcode())) {
5177       *Opcode = OP->getOpcode();
5178       *RHSExprs = OP->getRHS();
5179       return true;
5180     }
5181   }
5182 
5183   // Overloaded operator.
5184   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
5185     if (Call->getNumArgs() != 2)
5186       return false;
5187 
5188     // Make sure this is really a binary operator that is safe to pass into
5189     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
5190     OverloadedOperatorKind OO = Call->getOperator();
5191     if (OO < OO_Plus || OO > OO_Arrow)
5192       return false;
5193 
5194     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
5195     if (IsArithmeticOp(OpKind)) {
5196       *Opcode = OpKind;
5197       *RHSExprs = Call->getArg(1);
5198       return true;
5199     }
5200   }
5201 
5202   return false;
5203 }
5204 
5205 static bool IsLogicOp(BinaryOperatorKind Opc) {
5206   return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
5207 }
5208 
5209 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
5210 /// or is a logical expression such as (x==y) which has int type, but is
5211 /// commonly interpreted as boolean.
5212 static bool ExprLooksBoolean(Expr *E) {
5213   E = E->IgnoreParenImpCasts();
5214 
5215   if (E->getType()->isBooleanType())
5216     return true;
5217   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
5218     return IsLogicOp(OP->getOpcode());
5219   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
5220     return OP->getOpcode() == UO_LNot;
5221 
5222   return false;
5223 }
5224 
5225 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
5226 /// and binary operator are mixed in a way that suggests the programmer assumed
5227 /// the conditional operator has higher precedence, for example:
5228 /// "int x = a + someBinaryCondition ? 1 : 2".
5229 static void DiagnoseConditionalPrecedence(Sema &Self,
5230                                           SourceLocation OpLoc,
5231                                           Expr *Condition,
5232                                           Expr *LHSExpr,
5233                                           Expr *RHSExpr) {
5234   BinaryOperatorKind CondOpcode;
5235   Expr *CondRHS;
5236 
5237   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
5238     return;
5239   if (!ExprLooksBoolean(CondRHS))
5240     return;
5241 
5242   // The condition is an arithmetic binary expression, with a right-
5243   // hand side that looks boolean, so warn.
5244 
5245   Self.Diag(OpLoc, diag::warn_precedence_conditional)
5246       << Condition->getSourceRange()
5247       << BinaryOperator::getOpcodeStr(CondOpcode);
5248 
5249   SuggestParentheses(Self, OpLoc,
5250     Self.PDiag(diag::note_precedence_conditional_silence)
5251       << BinaryOperator::getOpcodeStr(CondOpcode),
5252     SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
5253 
5254   SuggestParentheses(Self, OpLoc,
5255     Self.PDiag(diag::note_precedence_conditional_first),
5256     SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
5257 }
5258 
5259 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
5260 /// in the case of a the GNU conditional expr extension.
5261 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
5262                                     SourceLocation ColonLoc,
5263                                     Expr *CondExpr, Expr *LHSExpr,
5264                                     Expr *RHSExpr) {
5265   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
5266   // was the condition.
5267   OpaqueValueExpr *opaqueValue = 0;
5268   Expr *commonExpr = 0;
5269   if (LHSExpr == 0) {
5270     commonExpr = CondExpr;
5271 
5272     // We usually want to apply unary conversions *before* saving, except
5273     // in the special case of a C++ l-value conditional.
5274     if (!(getLangOpts().CPlusPlus
5275           && !commonExpr->isTypeDependent()
5276           && commonExpr->getValueKind() == RHSExpr->getValueKind()
5277           && commonExpr->isGLValue()
5278           && commonExpr->isOrdinaryOrBitFieldObject()
5279           && RHSExpr->isOrdinaryOrBitFieldObject()
5280           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
5281       ExprResult commonRes = UsualUnaryConversions(commonExpr);
5282       if (commonRes.isInvalid())
5283         return ExprError();
5284       commonExpr = commonRes.take();
5285     }
5286 
5287     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
5288                                                 commonExpr->getType(),
5289                                                 commonExpr->getValueKind(),
5290                                                 commonExpr->getObjectKind(),
5291                                                 commonExpr);
5292     LHSExpr = CondExpr = opaqueValue;
5293   }
5294 
5295   ExprValueKind VK = VK_RValue;
5296   ExprObjectKind OK = OK_Ordinary;
5297   ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
5298   QualType result = CheckConditionalOperands(Cond, LHS, RHS,
5299                                              VK, OK, QuestionLoc);
5300   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
5301       RHS.isInvalid())
5302     return ExprError();
5303 
5304   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
5305                                 RHS.get());
5306 
5307   if (!commonExpr)
5308     return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc,
5309                                                    LHS.take(), ColonLoc,
5310                                                    RHS.take(), result, VK, OK));
5311 
5312   return Owned(new (Context)
5313     BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(),
5314                               RHS.take(), QuestionLoc, ColonLoc, result, VK,
5315                               OK));
5316 }
5317 
5318 // checkPointerTypesForAssignment - This is a very tricky routine (despite
5319 // being closely modeled after the C99 spec:-). The odd characteristic of this
5320 // routine is it effectively iqnores the qualifiers on the top level pointee.
5321 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
5322 // FIXME: add a couple examples in this comment.
5323 static Sema::AssignConvertType
5324 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
5325   assert(LHSType.isCanonical() && "LHS not canonicalized!");
5326   assert(RHSType.isCanonical() && "RHS not canonicalized!");
5327 
5328   // get the "pointed to" type (ignoring qualifiers at the top level)
5329   const Type *lhptee, *rhptee;
5330   Qualifiers lhq, rhq;
5331   llvm::tie(lhptee, lhq) = cast<PointerType>(LHSType)->getPointeeType().split();
5332   llvm::tie(rhptee, rhq) = cast<PointerType>(RHSType)->getPointeeType().split();
5333 
5334   Sema::AssignConvertType ConvTy = Sema::Compatible;
5335 
5336   // C99 6.5.16.1p1: This following citation is common to constraints
5337   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
5338   // qualifiers of the type *pointed to* by the right;
5339   Qualifiers lq;
5340 
5341   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
5342   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
5343       lhq.compatiblyIncludesObjCLifetime(rhq)) {
5344     // Ignore lifetime for further calculation.
5345     lhq.removeObjCLifetime();
5346     rhq.removeObjCLifetime();
5347   }
5348 
5349   if (!lhq.compatiblyIncludes(rhq)) {
5350     // Treat address-space mismatches as fatal.  TODO: address subspaces
5351     if (lhq.getAddressSpace() != rhq.getAddressSpace())
5352       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5353 
5354     // It's okay to add or remove GC or lifetime qualifiers when converting to
5355     // and from void*.
5356     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
5357                         .compatiblyIncludes(
5358                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
5359              && (lhptee->isVoidType() || rhptee->isVoidType()))
5360       ; // keep old
5361 
5362     // Treat lifetime mismatches as fatal.
5363     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
5364       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5365 
5366     // For GCC compatibility, other qualifier mismatches are treated
5367     // as still compatible in C.
5368     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
5369   }
5370 
5371   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
5372   // incomplete type and the other is a pointer to a qualified or unqualified
5373   // version of void...
5374   if (lhptee->isVoidType()) {
5375     if (rhptee->isIncompleteOrObjectType())
5376       return ConvTy;
5377 
5378     // As an extension, we allow cast to/from void* to function pointer.
5379     assert(rhptee->isFunctionType());
5380     return Sema::FunctionVoidPointer;
5381   }
5382 
5383   if (rhptee->isVoidType()) {
5384     if (lhptee->isIncompleteOrObjectType())
5385       return ConvTy;
5386 
5387     // As an extension, we allow cast to/from void* to function pointer.
5388     assert(lhptee->isFunctionType());
5389     return Sema::FunctionVoidPointer;
5390   }
5391 
5392   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
5393   // unqualified versions of compatible types, ...
5394   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
5395   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
5396     // Check if the pointee types are compatible ignoring the sign.
5397     // We explicitly check for char so that we catch "char" vs
5398     // "unsigned char" on systems where "char" is unsigned.
5399     if (lhptee->isCharType())
5400       ltrans = S.Context.UnsignedCharTy;
5401     else if (lhptee->hasSignedIntegerRepresentation())
5402       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
5403 
5404     if (rhptee->isCharType())
5405       rtrans = S.Context.UnsignedCharTy;
5406     else if (rhptee->hasSignedIntegerRepresentation())
5407       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
5408 
5409     if (ltrans == rtrans) {
5410       // Types are compatible ignoring the sign. Qualifier incompatibility
5411       // takes priority over sign incompatibility because the sign
5412       // warning can be disabled.
5413       if (ConvTy != Sema::Compatible)
5414         return ConvTy;
5415 
5416       return Sema::IncompatiblePointerSign;
5417     }
5418 
5419     // If we are a multi-level pointer, it's possible that our issue is simply
5420     // one of qualification - e.g. char ** -> const char ** is not allowed. If
5421     // the eventual target type is the same and the pointers have the same
5422     // level of indirection, this must be the issue.
5423     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
5424       do {
5425         lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
5426         rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
5427       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
5428 
5429       if (lhptee == rhptee)
5430         return Sema::IncompatibleNestedPointerQualifiers;
5431     }
5432 
5433     // General pointer incompatibility takes priority over qualifiers.
5434     return Sema::IncompatiblePointer;
5435   }
5436   if (!S.getLangOpts().CPlusPlus &&
5437       S.IsNoReturnConversion(ltrans, rtrans, ltrans))
5438     return Sema::IncompatiblePointer;
5439   return ConvTy;
5440 }
5441 
5442 /// checkBlockPointerTypesForAssignment - This routine determines whether two
5443 /// block pointer types are compatible or whether a block and normal pointer
5444 /// are compatible. It is more restrict than comparing two function pointer
5445 // types.
5446 static Sema::AssignConvertType
5447 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
5448                                     QualType RHSType) {
5449   assert(LHSType.isCanonical() && "LHS not canonicalized!");
5450   assert(RHSType.isCanonical() && "RHS not canonicalized!");
5451 
5452   QualType lhptee, rhptee;
5453 
5454   // get the "pointed to" type (ignoring qualifiers at the top level)
5455   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
5456   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
5457 
5458   // In C++, the types have to match exactly.
5459   if (S.getLangOpts().CPlusPlus)
5460     return Sema::IncompatibleBlockPointer;
5461 
5462   Sema::AssignConvertType ConvTy = Sema::Compatible;
5463 
5464   // For blocks we enforce that qualifiers are identical.
5465   if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
5466     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
5467 
5468   if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
5469     return Sema::IncompatibleBlockPointer;
5470 
5471   return ConvTy;
5472 }
5473 
5474 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
5475 /// for assignment compatibility.
5476 static Sema::AssignConvertType
5477 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
5478                                    QualType RHSType) {
5479   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
5480   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
5481 
5482   if (LHSType->isObjCBuiltinType()) {
5483     // Class is not compatible with ObjC object pointers.
5484     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
5485         !RHSType->isObjCQualifiedClassType())
5486       return Sema::IncompatiblePointer;
5487     return Sema::Compatible;
5488   }
5489   if (RHSType->isObjCBuiltinType()) {
5490     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
5491         !LHSType->isObjCQualifiedClassType())
5492       return Sema::IncompatiblePointer;
5493     return Sema::Compatible;
5494   }
5495   QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
5496   QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
5497 
5498   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
5499       // make an exception for id<P>
5500       !LHSType->isObjCQualifiedIdType())
5501     return Sema::CompatiblePointerDiscardsQualifiers;
5502 
5503   if (S.Context.typesAreCompatible(LHSType, RHSType))
5504     return Sema::Compatible;
5505   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
5506     return Sema::IncompatibleObjCQualifiedId;
5507   return Sema::IncompatiblePointer;
5508 }
5509 
5510 Sema::AssignConvertType
5511 Sema::CheckAssignmentConstraints(SourceLocation Loc,
5512                                  QualType LHSType, QualType RHSType) {
5513   // Fake up an opaque expression.  We don't actually care about what
5514   // cast operations are required, so if CheckAssignmentConstraints
5515   // adds casts to this they'll be wasted, but fortunately that doesn't
5516   // usually happen on valid code.
5517   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
5518   ExprResult RHSPtr = &RHSExpr;
5519   CastKind K = CK_Invalid;
5520 
5521   return CheckAssignmentConstraints(LHSType, RHSPtr, K);
5522 }
5523 
5524 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
5525 /// has code to accommodate several GCC extensions when type checking
5526 /// pointers. Here are some objectionable examples that GCC considers warnings:
5527 ///
5528 ///  int a, *pint;
5529 ///  short *pshort;
5530 ///  struct foo *pfoo;
5531 ///
5532 ///  pint = pshort; // warning: assignment from incompatible pointer type
5533 ///  a = pint; // warning: assignment makes integer from pointer without a cast
5534 ///  pint = a; // warning: assignment makes pointer from integer without a cast
5535 ///  pint = pfoo; // warning: assignment from incompatible pointer type
5536 ///
5537 /// As a result, the code for dealing with pointers is more complex than the
5538 /// C99 spec dictates.
5539 ///
5540 /// Sets 'Kind' for any result kind except Incompatible.
5541 Sema::AssignConvertType
5542 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
5543                                  CastKind &Kind) {
5544   QualType RHSType = RHS.get()->getType();
5545   QualType OrigLHSType = LHSType;
5546 
5547   // Get canonical types.  We're not formatting these types, just comparing
5548   // them.
5549   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
5550   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
5551 
5552 
5553   // Common case: no conversion required.
5554   if (LHSType == RHSType) {
5555     Kind = CK_NoOp;
5556     return Compatible;
5557   }
5558 
5559   // If we have an atomic type, try a non-atomic assignment, then just add an
5560   // atomic qualification step.
5561   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
5562     Sema::AssignConvertType result =
5563       CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
5564     if (result != Compatible)
5565       return result;
5566     if (Kind != CK_NoOp)
5567       RHS = ImpCastExprToType(RHS.take(), AtomicTy->getValueType(), Kind);
5568     Kind = CK_NonAtomicToAtomic;
5569     return Compatible;
5570   }
5571 
5572   // If the left-hand side is a reference type, then we are in a
5573   // (rare!) case where we've allowed the use of references in C,
5574   // e.g., as a parameter type in a built-in function. In this case,
5575   // just make sure that the type referenced is compatible with the
5576   // right-hand side type. The caller is responsible for adjusting
5577   // LHSType so that the resulting expression does not have reference
5578   // type.
5579   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
5580     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
5581       Kind = CK_LValueBitCast;
5582       return Compatible;
5583     }
5584     return Incompatible;
5585   }
5586 
5587   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
5588   // to the same ExtVector type.
5589   if (LHSType->isExtVectorType()) {
5590     if (RHSType->isExtVectorType())
5591       return Incompatible;
5592     if (RHSType->isArithmeticType()) {
5593       // CK_VectorSplat does T -> vector T, so first cast to the
5594       // element type.
5595       QualType elType = cast<ExtVectorType>(LHSType)->getElementType();
5596       if (elType != RHSType) {
5597         Kind = PrepareScalarCast(RHS, elType);
5598         RHS = ImpCastExprToType(RHS.take(), elType, Kind);
5599       }
5600       Kind = CK_VectorSplat;
5601       return Compatible;
5602     }
5603   }
5604 
5605   // Conversions to or from vector type.
5606   if (LHSType->isVectorType() || RHSType->isVectorType()) {
5607     if (LHSType->isVectorType() && RHSType->isVectorType()) {
5608       // Allow assignments of an AltiVec vector type to an equivalent GCC
5609       // vector type and vice versa
5610       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
5611         Kind = CK_BitCast;
5612         return Compatible;
5613       }
5614 
5615       // If we are allowing lax vector conversions, and LHS and RHS are both
5616       // vectors, the total size only needs to be the same. This is a bitcast;
5617       // no bits are changed but the result type is different.
5618       if (getLangOpts().LaxVectorConversions &&
5619           (Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType))) {
5620         Kind = CK_BitCast;
5621         return IncompatibleVectors;
5622       }
5623     }
5624     return Incompatible;
5625   }
5626 
5627   // Arithmetic conversions.
5628   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
5629       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
5630     Kind = PrepareScalarCast(RHS, LHSType);
5631     return Compatible;
5632   }
5633 
5634   // Conversions to normal pointers.
5635   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
5636     // U* -> T*
5637     if (isa<PointerType>(RHSType)) {
5638       Kind = CK_BitCast;
5639       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
5640     }
5641 
5642     // int -> T*
5643     if (RHSType->isIntegerType()) {
5644       Kind = CK_IntegralToPointer; // FIXME: null?
5645       return IntToPointer;
5646     }
5647 
5648     // C pointers are not compatible with ObjC object pointers,
5649     // with two exceptions:
5650     if (isa<ObjCObjectPointerType>(RHSType)) {
5651       //  - conversions to void*
5652       if (LHSPointer->getPointeeType()->isVoidType()) {
5653         Kind = CK_BitCast;
5654         return Compatible;
5655       }
5656 
5657       //  - conversions from 'Class' to the redefinition type
5658       if (RHSType->isObjCClassType() &&
5659           Context.hasSameType(LHSType,
5660                               Context.getObjCClassRedefinitionType())) {
5661         Kind = CK_BitCast;
5662         return Compatible;
5663       }
5664 
5665       Kind = CK_BitCast;
5666       return IncompatiblePointer;
5667     }
5668 
5669     // U^ -> void*
5670     if (RHSType->getAs<BlockPointerType>()) {
5671       if (LHSPointer->getPointeeType()->isVoidType()) {
5672         Kind = CK_BitCast;
5673         return Compatible;
5674       }
5675     }
5676 
5677     return Incompatible;
5678   }
5679 
5680   // Conversions to block pointers.
5681   if (isa<BlockPointerType>(LHSType)) {
5682     // U^ -> T^
5683     if (RHSType->isBlockPointerType()) {
5684       Kind = CK_BitCast;
5685       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
5686     }
5687 
5688     // int or null -> T^
5689     if (RHSType->isIntegerType()) {
5690       Kind = CK_IntegralToPointer; // FIXME: null
5691       return IntToBlockPointer;
5692     }
5693 
5694     // id -> T^
5695     if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
5696       Kind = CK_AnyPointerToBlockPointerCast;
5697       return Compatible;
5698     }
5699 
5700     // void* -> T^
5701     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
5702       if (RHSPT->getPointeeType()->isVoidType()) {
5703         Kind = CK_AnyPointerToBlockPointerCast;
5704         return Compatible;
5705       }
5706 
5707     return Incompatible;
5708   }
5709 
5710   // Conversions to Objective-C pointers.
5711   if (isa<ObjCObjectPointerType>(LHSType)) {
5712     // A* -> B*
5713     if (RHSType->isObjCObjectPointerType()) {
5714       Kind = CK_BitCast;
5715       Sema::AssignConvertType result =
5716         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
5717       if (getLangOpts().ObjCAutoRefCount &&
5718           result == Compatible &&
5719           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
5720         result = IncompatibleObjCWeakRef;
5721       return result;
5722     }
5723 
5724     // int or null -> A*
5725     if (RHSType->isIntegerType()) {
5726       Kind = CK_IntegralToPointer; // FIXME: null
5727       return IntToPointer;
5728     }
5729 
5730     // In general, C pointers are not compatible with ObjC object pointers,
5731     // with two exceptions:
5732     if (isa<PointerType>(RHSType)) {
5733       Kind = CK_CPointerToObjCPointerCast;
5734 
5735       //  - conversions from 'void*'
5736       if (RHSType->isVoidPointerType()) {
5737         return Compatible;
5738       }
5739 
5740       //  - conversions to 'Class' from its redefinition type
5741       if (LHSType->isObjCClassType() &&
5742           Context.hasSameType(RHSType,
5743                               Context.getObjCClassRedefinitionType())) {
5744         return Compatible;
5745       }
5746 
5747       return IncompatiblePointer;
5748     }
5749 
5750     // T^ -> A*
5751     if (RHSType->isBlockPointerType()) {
5752       maybeExtendBlockObject(*this, RHS);
5753       Kind = CK_BlockPointerToObjCPointerCast;
5754       return Compatible;
5755     }
5756 
5757     return Incompatible;
5758   }
5759 
5760   // Conversions from pointers that are not covered by the above.
5761   if (isa<PointerType>(RHSType)) {
5762     // T* -> _Bool
5763     if (LHSType == Context.BoolTy) {
5764       Kind = CK_PointerToBoolean;
5765       return Compatible;
5766     }
5767 
5768     // T* -> int
5769     if (LHSType->isIntegerType()) {
5770       Kind = CK_PointerToIntegral;
5771       return PointerToInt;
5772     }
5773 
5774     return Incompatible;
5775   }
5776 
5777   // Conversions from Objective-C pointers that are not covered by the above.
5778   if (isa<ObjCObjectPointerType>(RHSType)) {
5779     // T* -> _Bool
5780     if (LHSType == Context.BoolTy) {
5781       Kind = CK_PointerToBoolean;
5782       return Compatible;
5783     }
5784 
5785     // T* -> int
5786     if (LHSType->isIntegerType()) {
5787       Kind = CK_PointerToIntegral;
5788       return PointerToInt;
5789     }
5790 
5791     return Incompatible;
5792   }
5793 
5794   // struct A -> struct B
5795   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
5796     if (Context.typesAreCompatible(LHSType, RHSType)) {
5797       Kind = CK_NoOp;
5798       return Compatible;
5799     }
5800   }
5801 
5802   return Incompatible;
5803 }
5804 
5805 /// \brief Constructs a transparent union from an expression that is
5806 /// used to initialize the transparent union.
5807 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
5808                                       ExprResult &EResult, QualType UnionType,
5809                                       FieldDecl *Field) {
5810   // Build an initializer list that designates the appropriate member
5811   // of the transparent union.
5812   Expr *E = EResult.take();
5813   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
5814                                                    &E, 1,
5815                                                    SourceLocation());
5816   Initializer->setType(UnionType);
5817   Initializer->setInitializedFieldInUnion(Field);
5818 
5819   // Build a compound literal constructing a value of the transparent
5820   // union type from this initializer list.
5821   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
5822   EResult = S.Owned(
5823     new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
5824                                 VK_RValue, Initializer, false));
5825 }
5826 
5827 Sema::AssignConvertType
5828 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
5829                                                ExprResult &RHS) {
5830   QualType RHSType = RHS.get()->getType();
5831 
5832   // If the ArgType is a Union type, we want to handle a potential
5833   // transparent_union GCC extension.
5834   const RecordType *UT = ArgType->getAsUnionType();
5835   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
5836     return Incompatible;
5837 
5838   // The field to initialize within the transparent union.
5839   RecordDecl *UD = UT->getDecl();
5840   FieldDecl *InitField = 0;
5841   // It's compatible if the expression matches any of the fields.
5842   for (RecordDecl::field_iterator it = UD->field_begin(),
5843          itend = UD->field_end();
5844        it != itend; ++it) {
5845     if (it->getType()->isPointerType()) {
5846       // If the transparent union contains a pointer type, we allow:
5847       // 1) void pointer
5848       // 2) null pointer constant
5849       if (RHSType->isPointerType())
5850         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
5851           RHS = ImpCastExprToType(RHS.take(), it->getType(), CK_BitCast);
5852           InitField = *it;
5853           break;
5854         }
5855 
5856       if (RHS.get()->isNullPointerConstant(Context,
5857                                            Expr::NPC_ValueDependentIsNull)) {
5858         RHS = ImpCastExprToType(RHS.take(), it->getType(),
5859                                 CK_NullToPointer);
5860         InitField = *it;
5861         break;
5862       }
5863     }
5864 
5865     CastKind Kind = CK_Invalid;
5866     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
5867           == Compatible) {
5868       RHS = ImpCastExprToType(RHS.take(), it->getType(), Kind);
5869       InitField = *it;
5870       break;
5871     }
5872   }
5873 
5874   if (!InitField)
5875     return Incompatible;
5876 
5877   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
5878   return Compatible;
5879 }
5880 
5881 Sema::AssignConvertType
5882 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS,
5883                                        bool Diagnose) {
5884   if (getLangOpts().CPlusPlus) {
5885     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
5886       // C++ 5.17p3: If the left operand is not of class type, the
5887       // expression is implicitly converted (C++ 4) to the
5888       // cv-unqualified type of the left operand.
5889       ExprResult Res;
5890       if (Diagnose) {
5891         Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5892                                         AA_Assigning);
5893       } else {
5894         ImplicitConversionSequence ICS =
5895             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5896                                   /*SuppressUserConversions=*/false,
5897                                   /*AllowExplicit=*/false,
5898                                   /*InOverloadResolution=*/false,
5899                                   /*CStyle=*/false,
5900                                   /*AllowObjCWritebackConversion=*/false);
5901         if (ICS.isFailure())
5902           return Incompatible;
5903         Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5904                                         ICS, AA_Assigning);
5905       }
5906       if (Res.isInvalid())
5907         return Incompatible;
5908       Sema::AssignConvertType result = Compatible;
5909       if (getLangOpts().ObjCAutoRefCount &&
5910           !CheckObjCARCUnavailableWeakConversion(LHSType,
5911                                                  RHS.get()->getType()))
5912         result = IncompatibleObjCWeakRef;
5913       RHS = move(Res);
5914       return result;
5915     }
5916 
5917     // FIXME: Currently, we fall through and treat C++ classes like C
5918     // structures.
5919     // FIXME: We also fall through for atomics; not sure what should
5920     // happen there, though.
5921   }
5922 
5923   // C99 6.5.16.1p1: the left operand is a pointer and the right is
5924   // a null pointer constant.
5925   if ((LHSType->isPointerType() ||
5926        LHSType->isObjCObjectPointerType() ||
5927        LHSType->isBlockPointerType())
5928       && RHS.get()->isNullPointerConstant(Context,
5929                                           Expr::NPC_ValueDependentIsNull)) {
5930     RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
5931     return Compatible;
5932   }
5933 
5934   // This check seems unnatural, however it is necessary to ensure the proper
5935   // conversion of functions/arrays. If the conversion were done for all
5936   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
5937   // expressions that suppress this implicit conversion (&, sizeof).
5938   //
5939   // Suppress this for references: C++ 8.5.3p5.
5940   if (!LHSType->isReferenceType()) {
5941     RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
5942     if (RHS.isInvalid())
5943       return Incompatible;
5944   }
5945 
5946   CastKind Kind = CK_Invalid;
5947   Sema::AssignConvertType result =
5948     CheckAssignmentConstraints(LHSType, RHS, Kind);
5949 
5950   // C99 6.5.16.1p2: The value of the right operand is converted to the
5951   // type of the assignment expression.
5952   // CheckAssignmentConstraints allows the left-hand side to be a reference,
5953   // so that we can use references in built-in functions even in C.
5954   // The getNonReferenceType() call makes sure that the resulting expression
5955   // does not have reference type.
5956   if (result != Incompatible && RHS.get()->getType() != LHSType)
5957     RHS = ImpCastExprToType(RHS.take(),
5958                             LHSType.getNonLValueExprType(Context), Kind);
5959   return result;
5960 }
5961 
5962 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
5963                                ExprResult &RHS) {
5964   Diag(Loc, diag::err_typecheck_invalid_operands)
5965     << LHS.get()->getType() << RHS.get()->getType()
5966     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5967   return QualType();
5968 }
5969 
5970 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
5971                                    SourceLocation Loc, bool IsCompAssign) {
5972   if (!IsCompAssign) {
5973     LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
5974     if (LHS.isInvalid())
5975       return QualType();
5976   }
5977   RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
5978   if (RHS.isInvalid())
5979     return QualType();
5980 
5981   // For conversion purposes, we ignore any qualifiers.
5982   // For example, "const float" and "float" are equivalent.
5983   QualType LHSType =
5984     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
5985   QualType RHSType =
5986     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
5987 
5988   // If the vector types are identical, return.
5989   if (LHSType == RHSType)
5990     return LHSType;
5991 
5992   // Handle the case of equivalent AltiVec and GCC vector types
5993   if (LHSType->isVectorType() && RHSType->isVectorType() &&
5994       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
5995     if (LHSType->isExtVectorType()) {
5996       RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
5997       return LHSType;
5998     }
5999 
6000     if (!IsCompAssign)
6001       LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
6002     return RHSType;
6003   }
6004 
6005   if (getLangOpts().LaxVectorConversions &&
6006       Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType)) {
6007     // If we are allowing lax vector conversions, and LHS and RHS are both
6008     // vectors, the total size only needs to be the same. This is a
6009     // bitcast; no bits are changed but the result type is different.
6010     // FIXME: Should we really be allowing this?
6011     RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
6012     return LHSType;
6013   }
6014 
6015   // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
6016   // swap back (so that we don't reverse the inputs to a subtract, for instance.
6017   bool swapped = false;
6018   if (RHSType->isExtVectorType() && !IsCompAssign) {
6019     swapped = true;
6020     std::swap(RHS, LHS);
6021     std::swap(RHSType, LHSType);
6022   }
6023 
6024   // Handle the case of an ext vector and scalar.
6025   if (const ExtVectorType *LV = LHSType->getAs<ExtVectorType>()) {
6026     QualType EltTy = LV->getElementType();
6027     if (EltTy->isIntegralType(Context) && RHSType->isIntegralType(Context)) {
6028       int order = Context.getIntegerTypeOrder(EltTy, RHSType);
6029       if (order > 0)
6030         RHS = ImpCastExprToType(RHS.take(), EltTy, CK_IntegralCast);
6031       if (order >= 0) {
6032         RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
6033         if (swapped) std::swap(RHS, LHS);
6034         return LHSType;
6035       }
6036     }
6037     if (EltTy->isRealFloatingType() && RHSType->isScalarType() &&
6038         RHSType->isRealFloatingType()) {
6039       int order = Context.getFloatingTypeOrder(EltTy, RHSType);
6040       if (order > 0)
6041         RHS = ImpCastExprToType(RHS.take(), EltTy, CK_FloatingCast);
6042       if (order >= 0) {
6043         RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
6044         if (swapped) std::swap(RHS, LHS);
6045         return LHSType;
6046       }
6047     }
6048   }
6049 
6050   // Vectors of different size or scalar and non-ext-vector are errors.
6051   if (swapped) std::swap(RHS, LHS);
6052   Diag(Loc, diag::err_typecheck_vector_not_convertable)
6053     << LHS.get()->getType() << RHS.get()->getType()
6054     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6055   return QualType();
6056 }
6057 
6058 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
6059 // expression.  These are mainly cases where the null pointer is used as an
6060 // integer instead of a pointer.
6061 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
6062                                 SourceLocation Loc, bool IsCompare) {
6063   // The canonical way to check for a GNU null is with isNullPointerConstant,
6064   // but we use a bit of a hack here for speed; this is a relatively
6065   // hot path, and isNullPointerConstant is slow.
6066   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
6067   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
6068 
6069   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
6070 
6071   // Avoid analyzing cases where the result will either be invalid (and
6072   // diagnosed as such) or entirely valid and not something to warn about.
6073   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
6074       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
6075     return;
6076 
6077   // Comparison operations would not make sense with a null pointer no matter
6078   // what the other expression is.
6079   if (!IsCompare) {
6080     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
6081         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
6082         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
6083     return;
6084   }
6085 
6086   // The rest of the operations only make sense with a null pointer
6087   // if the other expression is a pointer.
6088   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
6089       NonNullType->canDecayToPointerType())
6090     return;
6091 
6092   S.Diag(Loc, diag::warn_null_in_comparison_operation)
6093       << LHSNull /* LHS is NULL */ << NonNullType
6094       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6095 }
6096 
6097 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
6098                                            SourceLocation Loc,
6099                                            bool IsCompAssign, bool IsDiv) {
6100   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6101 
6102   if (LHS.get()->getType()->isVectorType() ||
6103       RHS.get()->getType()->isVectorType())
6104     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
6105 
6106   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
6107   if (LHS.isInvalid() || RHS.isInvalid())
6108     return QualType();
6109 
6110 
6111   if (compType.isNull() || !compType->isArithmeticType())
6112     return InvalidOperands(Loc, LHS, RHS);
6113 
6114   // Check for division by zero.
6115   if (IsDiv &&
6116       RHS.get()->isNullPointerConstant(Context,
6117                                        Expr::NPC_ValueDependentIsNotNull))
6118     DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_division_by_zero)
6119                                           << RHS.get()->getSourceRange());
6120 
6121   return compType;
6122 }
6123 
6124 QualType Sema::CheckRemainderOperands(
6125   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
6126   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6127 
6128   if (LHS.get()->getType()->isVectorType() ||
6129       RHS.get()->getType()->isVectorType()) {
6130     if (LHS.get()->getType()->hasIntegerRepresentation() &&
6131         RHS.get()->getType()->hasIntegerRepresentation())
6132       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
6133     return InvalidOperands(Loc, LHS, RHS);
6134   }
6135 
6136   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
6137   if (LHS.isInvalid() || RHS.isInvalid())
6138     return QualType();
6139 
6140   if (compType.isNull() || !compType->isIntegerType())
6141     return InvalidOperands(Loc, LHS, RHS);
6142 
6143   // Check for remainder by zero.
6144   if (RHS.get()->isNullPointerConstant(Context,
6145                                        Expr::NPC_ValueDependentIsNotNull))
6146     DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_remainder_by_zero)
6147                                  << RHS.get()->getSourceRange());
6148 
6149   return compType;
6150 }
6151 
6152 /// \brief Diagnose invalid arithmetic on two void pointers.
6153 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
6154                                                 Expr *LHSExpr, Expr *RHSExpr) {
6155   S.Diag(Loc, S.getLangOpts().CPlusPlus
6156                 ? diag::err_typecheck_pointer_arith_void_type
6157                 : diag::ext_gnu_void_ptr)
6158     << 1 /* two pointers */ << LHSExpr->getSourceRange()
6159                             << RHSExpr->getSourceRange();
6160 }
6161 
6162 /// \brief Diagnose invalid arithmetic on a void pointer.
6163 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
6164                                             Expr *Pointer) {
6165   S.Diag(Loc, S.getLangOpts().CPlusPlus
6166                 ? diag::err_typecheck_pointer_arith_void_type
6167                 : diag::ext_gnu_void_ptr)
6168     << 0 /* one pointer */ << Pointer->getSourceRange();
6169 }
6170 
6171 /// \brief Diagnose invalid arithmetic on two function pointers.
6172 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
6173                                                     Expr *LHS, Expr *RHS) {
6174   assert(LHS->getType()->isAnyPointerType());
6175   assert(RHS->getType()->isAnyPointerType());
6176   S.Diag(Loc, S.getLangOpts().CPlusPlus
6177                 ? diag::err_typecheck_pointer_arith_function_type
6178                 : diag::ext_gnu_ptr_func_arith)
6179     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
6180     // We only show the second type if it differs from the first.
6181     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
6182                                                    RHS->getType())
6183     << RHS->getType()->getPointeeType()
6184     << LHS->getSourceRange() << RHS->getSourceRange();
6185 }
6186 
6187 /// \brief Diagnose invalid arithmetic on a function pointer.
6188 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
6189                                                 Expr *Pointer) {
6190   assert(Pointer->getType()->isAnyPointerType());
6191   S.Diag(Loc, S.getLangOpts().CPlusPlus
6192                 ? diag::err_typecheck_pointer_arith_function_type
6193                 : diag::ext_gnu_ptr_func_arith)
6194     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
6195     << 0 /* one pointer, so only one type */
6196     << Pointer->getSourceRange();
6197 }
6198 
6199 /// \brief Emit error if Operand is incomplete pointer type
6200 ///
6201 /// \returns True if pointer has incomplete type
6202 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
6203                                                  Expr *Operand) {
6204   assert(Operand->getType()->isAnyPointerType() &&
6205          !Operand->getType()->isDependentType());
6206   QualType PointeeTy = Operand->getType()->getPointeeType();
6207   return S.RequireCompleteType(Loc, PointeeTy,
6208                                diag::err_typecheck_arithmetic_incomplete_type,
6209                                PointeeTy, Operand->getSourceRange());
6210 }
6211 
6212 /// \brief Check the validity of an arithmetic pointer operand.
6213 ///
6214 /// If the operand has pointer type, this code will check for pointer types
6215 /// which are invalid in arithmetic operations. These will be diagnosed
6216 /// appropriately, including whether or not the use is supported as an
6217 /// extension.
6218 ///
6219 /// \returns True when the operand is valid to use (even if as an extension).
6220 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
6221                                             Expr *Operand) {
6222   if (!Operand->getType()->isAnyPointerType()) return true;
6223 
6224   QualType PointeeTy = Operand->getType()->getPointeeType();
6225   if (PointeeTy->isVoidType()) {
6226     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
6227     return !S.getLangOpts().CPlusPlus;
6228   }
6229   if (PointeeTy->isFunctionType()) {
6230     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
6231     return !S.getLangOpts().CPlusPlus;
6232   }
6233 
6234   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
6235 
6236   return true;
6237 }
6238 
6239 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
6240 /// operands.
6241 ///
6242 /// This routine will diagnose any invalid arithmetic on pointer operands much
6243 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
6244 /// for emitting a single diagnostic even for operations where both LHS and RHS
6245 /// are (potentially problematic) pointers.
6246 ///
6247 /// \returns True when the operand is valid to use (even if as an extension).
6248 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
6249                                                 Expr *LHSExpr, Expr *RHSExpr) {
6250   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
6251   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
6252   if (!isLHSPointer && !isRHSPointer) return true;
6253 
6254   QualType LHSPointeeTy, RHSPointeeTy;
6255   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
6256   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
6257 
6258   // Check for arithmetic on pointers to incomplete types.
6259   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
6260   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
6261   if (isLHSVoidPtr || isRHSVoidPtr) {
6262     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
6263     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
6264     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
6265 
6266     return !S.getLangOpts().CPlusPlus;
6267   }
6268 
6269   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
6270   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
6271   if (isLHSFuncPtr || isRHSFuncPtr) {
6272     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
6273     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
6274                                                                 RHSExpr);
6275     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
6276 
6277     return !S.getLangOpts().CPlusPlus;
6278   }
6279 
6280   if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
6281     return false;
6282   if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
6283     return false;
6284 
6285   return true;
6286 }
6287 
6288 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
6289 /// literal.
6290 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
6291                                   Expr *LHSExpr, Expr *RHSExpr) {
6292   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
6293   Expr* IndexExpr = RHSExpr;
6294   if (!StrExpr) {
6295     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
6296     IndexExpr = LHSExpr;
6297   }
6298 
6299   bool IsStringPlusInt = StrExpr &&
6300       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
6301   if (!IsStringPlusInt)
6302     return;
6303 
6304   llvm::APSInt index;
6305   if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
6306     unsigned StrLenWithNull = StrExpr->getLength() + 1;
6307     if (index.isNonNegative() &&
6308         index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
6309                               index.isUnsigned()))
6310       return;
6311   }
6312 
6313   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
6314   Self.Diag(OpLoc, diag::warn_string_plus_int)
6315       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
6316 
6317   // Only print a fixit for "str" + int, not for int + "str".
6318   if (IndexExpr == RHSExpr) {
6319     SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd());
6320     Self.Diag(OpLoc, diag::note_string_plus_int_silence)
6321         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
6322         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
6323         << FixItHint::CreateInsertion(EndLoc, "]");
6324   } else
6325     Self.Diag(OpLoc, diag::note_string_plus_int_silence);
6326 }
6327 
6328 /// \brief Emit error when two pointers are incompatible.
6329 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
6330                                            Expr *LHSExpr, Expr *RHSExpr) {
6331   assert(LHSExpr->getType()->isAnyPointerType());
6332   assert(RHSExpr->getType()->isAnyPointerType());
6333   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
6334     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
6335     << RHSExpr->getSourceRange();
6336 }
6337 
6338 QualType Sema::CheckAdditionOperands( // C99 6.5.6
6339     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc,
6340     QualType* CompLHSTy) {
6341   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6342 
6343   if (LHS.get()->getType()->isVectorType() ||
6344       RHS.get()->getType()->isVectorType()) {
6345     QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
6346     if (CompLHSTy) *CompLHSTy = compType;
6347     return compType;
6348   }
6349 
6350   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6351   if (LHS.isInvalid() || RHS.isInvalid())
6352     return QualType();
6353 
6354   // Diagnose "string literal" '+' int.
6355   if (Opc == BO_Add)
6356     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
6357 
6358   // handle the common case first (both operands are arithmetic).
6359   if (!compType.isNull() && compType->isArithmeticType()) {
6360     if (CompLHSTy) *CompLHSTy = compType;
6361     return compType;
6362   }
6363 
6364   // Type-checking.  Ultimately the pointer's going to be in PExp;
6365   // note that we bias towards the LHS being the pointer.
6366   Expr *PExp = LHS.get(), *IExp = RHS.get();
6367 
6368   bool isObjCPointer;
6369   if (PExp->getType()->isPointerType()) {
6370     isObjCPointer = false;
6371   } else if (PExp->getType()->isObjCObjectPointerType()) {
6372     isObjCPointer = true;
6373   } else {
6374     std::swap(PExp, IExp);
6375     if (PExp->getType()->isPointerType()) {
6376       isObjCPointer = false;
6377     } else if (PExp->getType()->isObjCObjectPointerType()) {
6378       isObjCPointer = true;
6379     } else {
6380       return InvalidOperands(Loc, LHS, RHS);
6381     }
6382   }
6383   assert(PExp->getType()->isAnyPointerType());
6384 
6385   if (!IExp->getType()->isIntegerType())
6386     return InvalidOperands(Loc, LHS, RHS);
6387 
6388   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
6389     return QualType();
6390 
6391   if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
6392     return QualType();
6393 
6394   // Check array bounds for pointer arithemtic
6395   CheckArrayAccess(PExp, IExp);
6396 
6397   if (CompLHSTy) {
6398     QualType LHSTy = Context.isPromotableBitField(LHS.get());
6399     if (LHSTy.isNull()) {
6400       LHSTy = LHS.get()->getType();
6401       if (LHSTy->isPromotableIntegerType())
6402         LHSTy = Context.getPromotedIntegerType(LHSTy);
6403     }
6404     *CompLHSTy = LHSTy;
6405   }
6406 
6407   return PExp->getType();
6408 }
6409 
6410 // C99 6.5.6
6411 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
6412                                         SourceLocation Loc,
6413                                         QualType* CompLHSTy) {
6414   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6415 
6416   if (LHS.get()->getType()->isVectorType() ||
6417       RHS.get()->getType()->isVectorType()) {
6418     QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
6419     if (CompLHSTy) *CompLHSTy = compType;
6420     return compType;
6421   }
6422 
6423   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6424   if (LHS.isInvalid() || RHS.isInvalid())
6425     return QualType();
6426 
6427   // Enforce type constraints: C99 6.5.6p3.
6428 
6429   // Handle the common case first (both operands are arithmetic).
6430   if (!compType.isNull() && compType->isArithmeticType()) {
6431     if (CompLHSTy) *CompLHSTy = compType;
6432     return compType;
6433   }
6434 
6435   // Either ptr - int   or   ptr - ptr.
6436   if (LHS.get()->getType()->isAnyPointerType()) {
6437     QualType lpointee = LHS.get()->getType()->getPointeeType();
6438 
6439     // Diagnose bad cases where we step over interface counts.
6440     if (LHS.get()->getType()->isObjCObjectPointerType() &&
6441         checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
6442       return QualType();
6443 
6444     // The result type of a pointer-int computation is the pointer type.
6445     if (RHS.get()->getType()->isIntegerType()) {
6446       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
6447         return QualType();
6448 
6449       // Check array bounds for pointer arithemtic
6450       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/0,
6451                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
6452 
6453       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
6454       return LHS.get()->getType();
6455     }
6456 
6457     // Handle pointer-pointer subtractions.
6458     if (const PointerType *RHSPTy
6459           = RHS.get()->getType()->getAs<PointerType>()) {
6460       QualType rpointee = RHSPTy->getPointeeType();
6461 
6462       if (getLangOpts().CPlusPlus) {
6463         // Pointee types must be the same: C++ [expr.add]
6464         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
6465           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
6466         }
6467       } else {
6468         // Pointee types must be compatible C99 6.5.6p3
6469         if (!Context.typesAreCompatible(
6470                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
6471                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
6472           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
6473           return QualType();
6474         }
6475       }
6476 
6477       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
6478                                                LHS.get(), RHS.get()))
6479         return QualType();
6480 
6481       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
6482       return Context.getPointerDiffType();
6483     }
6484   }
6485 
6486   return InvalidOperands(Loc, LHS, RHS);
6487 }
6488 
6489 static bool isScopedEnumerationType(QualType T) {
6490   if (const EnumType *ET = dyn_cast<EnumType>(T))
6491     return ET->getDecl()->isScoped();
6492   return false;
6493 }
6494 
6495 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
6496                                    SourceLocation Loc, unsigned Opc,
6497                                    QualType LHSType) {
6498   llvm::APSInt Right;
6499   // Check right/shifter operand
6500   if (RHS.get()->isValueDependent() ||
6501       !RHS.get()->isIntegerConstantExpr(Right, S.Context))
6502     return;
6503 
6504   if (Right.isNegative()) {
6505     S.DiagRuntimeBehavior(Loc, RHS.get(),
6506                           S.PDiag(diag::warn_shift_negative)
6507                             << RHS.get()->getSourceRange());
6508     return;
6509   }
6510   llvm::APInt LeftBits(Right.getBitWidth(),
6511                        S.Context.getTypeSize(LHS.get()->getType()));
6512   if (Right.uge(LeftBits)) {
6513     S.DiagRuntimeBehavior(Loc, RHS.get(),
6514                           S.PDiag(diag::warn_shift_gt_typewidth)
6515                             << RHS.get()->getSourceRange());
6516     return;
6517   }
6518   if (Opc != BO_Shl)
6519     return;
6520 
6521   // When left shifting an ICE which is signed, we can check for overflow which
6522   // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
6523   // integers have defined behavior modulo one more than the maximum value
6524   // representable in the result type, so never warn for those.
6525   llvm::APSInt Left;
6526   if (LHS.get()->isValueDependent() ||
6527       !LHS.get()->isIntegerConstantExpr(Left, S.Context) ||
6528       LHSType->hasUnsignedIntegerRepresentation())
6529     return;
6530   llvm::APInt ResultBits =
6531       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
6532   if (LeftBits.uge(ResultBits))
6533     return;
6534   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
6535   Result = Result.shl(Right);
6536 
6537   // Print the bit representation of the signed integer as an unsigned
6538   // hexadecimal number.
6539   SmallString<40> HexResult;
6540   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
6541 
6542   // If we are only missing a sign bit, this is less likely to result in actual
6543   // bugs -- if the result is cast back to an unsigned type, it will have the
6544   // expected value. Thus we place this behind a different warning that can be
6545   // turned off separately if needed.
6546   if (LeftBits == ResultBits - 1) {
6547     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
6548         << HexResult.str() << LHSType
6549         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6550     return;
6551   }
6552 
6553   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
6554     << HexResult.str() << Result.getMinSignedBits() << LHSType
6555     << Left.getBitWidth() << LHS.get()->getSourceRange()
6556     << RHS.get()->getSourceRange();
6557 }
6558 
6559 // C99 6.5.7
6560 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
6561                                   SourceLocation Loc, unsigned Opc,
6562                                   bool IsCompAssign) {
6563   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6564 
6565   // C99 6.5.7p2: Each of the operands shall have integer type.
6566   if (!LHS.get()->getType()->hasIntegerRepresentation() ||
6567       !RHS.get()->getType()->hasIntegerRepresentation())
6568     return InvalidOperands(Loc, LHS, RHS);
6569 
6570   // C++0x: Don't allow scoped enums. FIXME: Use something better than
6571   // hasIntegerRepresentation() above instead of this.
6572   if (isScopedEnumerationType(LHS.get()->getType()) ||
6573       isScopedEnumerationType(RHS.get()->getType())) {
6574     return InvalidOperands(Loc, LHS, RHS);
6575   }
6576 
6577   // Vector shifts promote their scalar inputs to vector type.
6578   if (LHS.get()->getType()->isVectorType() ||
6579       RHS.get()->getType()->isVectorType())
6580     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
6581 
6582   // Shifts don't perform usual arithmetic conversions, they just do integer
6583   // promotions on each operand. C99 6.5.7p3
6584 
6585   // For the LHS, do usual unary conversions, but then reset them away
6586   // if this is a compound assignment.
6587   ExprResult OldLHS = LHS;
6588   LHS = UsualUnaryConversions(LHS.take());
6589   if (LHS.isInvalid())
6590     return QualType();
6591   QualType LHSType = LHS.get()->getType();
6592   if (IsCompAssign) LHS = OldLHS;
6593 
6594   // The RHS is simpler.
6595   RHS = UsualUnaryConversions(RHS.take());
6596   if (RHS.isInvalid())
6597     return QualType();
6598 
6599   // Sanity-check shift operands
6600   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
6601 
6602   // "The type of the result is that of the promoted left operand."
6603   return LHSType;
6604 }
6605 
6606 static bool IsWithinTemplateSpecialization(Decl *D) {
6607   if (DeclContext *DC = D->getDeclContext()) {
6608     if (isa<ClassTemplateSpecializationDecl>(DC))
6609       return true;
6610     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
6611       return FD->isFunctionTemplateSpecialization();
6612   }
6613   return false;
6614 }
6615 
6616 /// If two different enums are compared, raise a warning.
6617 static void checkEnumComparison(Sema &S, SourceLocation Loc, ExprResult &LHS,
6618                                 ExprResult &RHS) {
6619   QualType LHSStrippedType = LHS.get()->IgnoreParenImpCasts()->getType();
6620   QualType RHSStrippedType = RHS.get()->IgnoreParenImpCasts()->getType();
6621 
6622   const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
6623   if (!LHSEnumType)
6624     return;
6625   const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
6626   if (!RHSEnumType)
6627     return;
6628 
6629   // Ignore anonymous enums.
6630   if (!LHSEnumType->getDecl()->getIdentifier())
6631     return;
6632   if (!RHSEnumType->getDecl()->getIdentifier())
6633     return;
6634 
6635   if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
6636     return;
6637 
6638   S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
6639       << LHSStrippedType << RHSStrippedType
6640       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6641 }
6642 
6643 /// \brief Diagnose bad pointer comparisons.
6644 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
6645                                               ExprResult &LHS, ExprResult &RHS,
6646                                               bool IsError) {
6647   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
6648                       : diag::ext_typecheck_comparison_of_distinct_pointers)
6649     << LHS.get()->getType() << RHS.get()->getType()
6650     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6651 }
6652 
6653 /// \brief Returns false if the pointers are converted to a composite type,
6654 /// true otherwise.
6655 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
6656                                            ExprResult &LHS, ExprResult &RHS) {
6657   // C++ [expr.rel]p2:
6658   //   [...] Pointer conversions (4.10) and qualification
6659   //   conversions (4.4) are performed on pointer operands (or on
6660   //   a pointer operand and a null pointer constant) to bring
6661   //   them to their composite pointer type. [...]
6662   //
6663   // C++ [expr.eq]p1 uses the same notion for (in)equality
6664   // comparisons of pointers.
6665 
6666   // C++ [expr.eq]p2:
6667   //   In addition, pointers to members can be compared, or a pointer to
6668   //   member and a null pointer constant. Pointer to member conversions
6669   //   (4.11) and qualification conversions (4.4) are performed to bring
6670   //   them to a common type. If one operand is a null pointer constant,
6671   //   the common type is the type of the other operand. Otherwise, the
6672   //   common type is a pointer to member type similar (4.4) to the type
6673   //   of one of the operands, with a cv-qualification signature (4.4)
6674   //   that is the union of the cv-qualification signatures of the operand
6675   //   types.
6676 
6677   QualType LHSType = LHS.get()->getType();
6678   QualType RHSType = RHS.get()->getType();
6679   assert((LHSType->isPointerType() && RHSType->isPointerType()) ||
6680          (LHSType->isMemberPointerType() && RHSType->isMemberPointerType()));
6681 
6682   bool NonStandardCompositeType = false;
6683   bool *BoolPtr = S.isSFINAEContext() ? 0 : &NonStandardCompositeType;
6684   QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr);
6685   if (T.isNull()) {
6686     diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
6687     return true;
6688   }
6689 
6690   if (NonStandardCompositeType)
6691     S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
6692       << LHSType << RHSType << T << LHS.get()->getSourceRange()
6693       << RHS.get()->getSourceRange();
6694 
6695   LHS = S.ImpCastExprToType(LHS.take(), T, CK_BitCast);
6696   RHS = S.ImpCastExprToType(RHS.take(), T, CK_BitCast);
6697   return false;
6698 }
6699 
6700 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
6701                                                     ExprResult &LHS,
6702                                                     ExprResult &RHS,
6703                                                     bool IsError) {
6704   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
6705                       : diag::ext_typecheck_comparison_of_fptr_to_void)
6706     << LHS.get()->getType() << RHS.get()->getType()
6707     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6708 }
6709 
6710 static bool isObjCObjectLiteral(ExprResult &E) {
6711   switch (E.get()->getStmtClass()) {
6712   case Stmt::ObjCArrayLiteralClass:
6713   case Stmt::ObjCDictionaryLiteralClass:
6714   case Stmt::ObjCStringLiteralClass:
6715   case Stmt::ObjCBoxedExprClass:
6716     return true;
6717   default:
6718     // Note that ObjCBoolLiteral is NOT an object literal!
6719     return false;
6720   }
6721 }
6722 
6723 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
6724   // Get the LHS object's interface type.
6725   QualType Type = LHS->getType();
6726   QualType InterfaceType;
6727   if (const ObjCObjectPointerType *PTy = Type->getAs<ObjCObjectPointerType>()) {
6728     InterfaceType = PTy->getPointeeType();
6729     if (const ObjCObjectType *iQFaceTy =
6730         InterfaceType->getAsObjCQualifiedInterfaceType())
6731       InterfaceType = iQFaceTy->getBaseType();
6732   } else {
6733     // If this is not actually an Objective-C object, bail out.
6734     return false;
6735   }
6736 
6737   // If the RHS isn't an Objective-C object, bail out.
6738   if (!RHS->getType()->isObjCObjectPointerType())
6739     return false;
6740 
6741   // Try to find the -isEqual: method.
6742   Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
6743   ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
6744                                                       InterfaceType,
6745                                                       /*instance=*/true);
6746   if (!Method) {
6747     if (Type->isObjCIdType()) {
6748       // For 'id', just check the global pool.
6749       Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
6750                                                   /*receiverId=*/true,
6751                                                   /*warn=*/false);
6752     } else {
6753       // Check protocols.
6754       Method = S.LookupMethodInQualifiedType(IsEqualSel,
6755                                              cast<ObjCObjectPointerType>(Type),
6756                                              /*instance=*/true);
6757     }
6758   }
6759 
6760   if (!Method)
6761     return false;
6762 
6763   QualType T = Method->param_begin()[0]->getType();
6764   if (!T->isObjCObjectPointerType())
6765     return false;
6766 
6767   QualType R = Method->getResultType();
6768   if (!R->isScalarType())
6769     return false;
6770 
6771   return true;
6772 }
6773 
6774 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
6775                                           ExprResult &LHS, ExprResult &RHS,
6776                                           BinaryOperator::Opcode Opc){
6777   Expr *Literal;
6778   Expr *Other;
6779   if (isObjCObjectLiteral(LHS)) {
6780     Literal = LHS.get();
6781     Other = RHS.get();
6782   } else {
6783     Literal = RHS.get();
6784     Other = LHS.get();
6785   }
6786 
6787   // Don't warn on comparisons against nil.
6788   Other = Other->IgnoreParenCasts();
6789   if (Other->isNullPointerConstant(S.getASTContext(),
6790                                    Expr::NPC_ValueDependentIsNotNull))
6791     return;
6792 
6793   // This should be kept in sync with warn_objc_literal_comparison.
6794   // LK_String should always be last, since it has its own warning flag.
6795   enum {
6796     LK_Array,
6797     LK_Dictionary,
6798     LK_Numeric,
6799     LK_Boxed,
6800     LK_String
6801   } LiteralKind;
6802 
6803   switch (Literal->getStmtClass()) {
6804   case Stmt::ObjCStringLiteralClass:
6805     // "string literal"
6806     LiteralKind = LK_String;
6807     break;
6808   case Stmt::ObjCArrayLiteralClass:
6809     // "array literal"
6810     LiteralKind = LK_Array;
6811     break;
6812   case Stmt::ObjCDictionaryLiteralClass:
6813     // "dictionary literal"
6814     LiteralKind = LK_Dictionary;
6815     break;
6816   case Stmt::ObjCBoxedExprClass: {
6817     Expr *Inner = cast<ObjCBoxedExpr>(Literal)->getSubExpr();
6818     switch (Inner->getStmtClass()) {
6819     case Stmt::IntegerLiteralClass:
6820     case Stmt::FloatingLiteralClass:
6821     case Stmt::CharacterLiteralClass:
6822     case Stmt::ObjCBoolLiteralExprClass:
6823     case Stmt::CXXBoolLiteralExprClass:
6824       // "numeric literal"
6825       LiteralKind = LK_Numeric;
6826       break;
6827     case Stmt::ImplicitCastExprClass: {
6828       CastKind CK = cast<CastExpr>(Inner)->getCastKind();
6829       // Boolean literals can be represented by implicit casts.
6830       if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) {
6831         LiteralKind = LK_Numeric;
6832         break;
6833       }
6834       // FALLTHROUGH
6835     }
6836     default:
6837       // "boxed expression"
6838       LiteralKind = LK_Boxed;
6839       break;
6840     }
6841     break;
6842   }
6843   default:
6844     llvm_unreachable("Unknown Objective-C object literal kind");
6845   }
6846 
6847   if (LiteralKind == LK_String)
6848     S.Diag(Loc, diag::warn_objc_string_literal_comparison)
6849       << Literal->getSourceRange();
6850   else
6851     S.Diag(Loc, diag::warn_objc_literal_comparison)
6852       << LiteralKind << Literal->getSourceRange();
6853 
6854   if (BinaryOperator::isEqualityOp(Opc) &&
6855       hasIsEqualMethod(S, LHS.get(), RHS.get())) {
6856     SourceLocation Start = LHS.get()->getLocStart();
6857     SourceLocation End = S.PP.getLocForEndOfToken(RHS.get()->getLocEnd());
6858     SourceRange OpRange(Loc, S.PP.getLocForEndOfToken(Loc));
6859 
6860     S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
6861       << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
6862       << FixItHint::CreateReplacement(OpRange, "isEqual:")
6863       << FixItHint::CreateInsertion(End, "]");
6864   }
6865 }
6866 
6867 // C99 6.5.8, C++ [expr.rel]
6868 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
6869                                     SourceLocation Loc, unsigned OpaqueOpc,
6870                                     bool IsRelational) {
6871   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
6872 
6873   BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
6874 
6875   // Handle vector comparisons separately.
6876   if (LHS.get()->getType()->isVectorType() ||
6877       RHS.get()->getType()->isVectorType())
6878     return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
6879 
6880   QualType LHSType = LHS.get()->getType();
6881   QualType RHSType = RHS.get()->getType();
6882 
6883   Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
6884   Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
6885 
6886   checkEnumComparison(*this, Loc, LHS, RHS);
6887 
6888   if (!LHSType->hasFloatingRepresentation() &&
6889       !(LHSType->isBlockPointerType() && IsRelational) &&
6890       !LHS.get()->getLocStart().isMacroID() &&
6891       !RHS.get()->getLocStart().isMacroID()) {
6892     // For non-floating point types, check for self-comparisons of the form
6893     // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
6894     // often indicate logic errors in the program.
6895     //
6896     // NOTE: Don't warn about comparison expressions resulting from macro
6897     // expansion. Also don't warn about comparisons which are only self
6898     // comparisons within a template specialization. The warnings should catch
6899     // obvious cases in the definition of the template anyways. The idea is to
6900     // warn when the typed comparison operator will always evaluate to the same
6901     // result.
6902     if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
6903       if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
6904         if (DRL->getDecl() == DRR->getDecl() &&
6905             !IsWithinTemplateSpecialization(DRL->getDecl())) {
6906           DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
6907                               << 0 // self-
6908                               << (Opc == BO_EQ
6909                                   || Opc == BO_LE
6910                                   || Opc == BO_GE));
6911         } else if (LHSType->isArrayType() && RHSType->isArrayType() &&
6912                    !DRL->getDecl()->getType()->isReferenceType() &&
6913                    !DRR->getDecl()->getType()->isReferenceType()) {
6914             // what is it always going to eval to?
6915             char always_evals_to;
6916             switch(Opc) {
6917             case BO_EQ: // e.g. array1 == array2
6918               always_evals_to = 0; // false
6919               break;
6920             case BO_NE: // e.g. array1 != array2
6921               always_evals_to = 1; // true
6922               break;
6923             default:
6924               // best we can say is 'a constant'
6925               always_evals_to = 2; // e.g. array1 <= array2
6926               break;
6927             }
6928             DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
6929                                 << 1 // array
6930                                 << always_evals_to);
6931         }
6932       }
6933     }
6934 
6935     if (isa<CastExpr>(LHSStripped))
6936       LHSStripped = LHSStripped->IgnoreParenCasts();
6937     if (isa<CastExpr>(RHSStripped))
6938       RHSStripped = RHSStripped->IgnoreParenCasts();
6939 
6940     // Warn about comparisons against a string constant (unless the other
6941     // operand is null), the user probably wants strcmp.
6942     Expr *literalString = 0;
6943     Expr *literalStringStripped = 0;
6944     if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
6945         !RHSStripped->isNullPointerConstant(Context,
6946                                             Expr::NPC_ValueDependentIsNull)) {
6947       literalString = LHS.get();
6948       literalStringStripped = LHSStripped;
6949     } else if ((isa<StringLiteral>(RHSStripped) ||
6950                 isa<ObjCEncodeExpr>(RHSStripped)) &&
6951                !LHSStripped->isNullPointerConstant(Context,
6952                                             Expr::NPC_ValueDependentIsNull)) {
6953       literalString = RHS.get();
6954       literalStringStripped = RHSStripped;
6955     }
6956 
6957     if (literalString) {
6958       std::string resultComparison;
6959       switch (Opc) {
6960       case BO_LT: resultComparison = ") < 0"; break;
6961       case BO_GT: resultComparison = ") > 0"; break;
6962       case BO_LE: resultComparison = ") <= 0"; break;
6963       case BO_GE: resultComparison = ") >= 0"; break;
6964       case BO_EQ: resultComparison = ") == 0"; break;
6965       case BO_NE: resultComparison = ") != 0"; break;
6966       default: llvm_unreachable("Invalid comparison operator");
6967       }
6968 
6969       DiagRuntimeBehavior(Loc, 0,
6970         PDiag(diag::warn_stringcompare)
6971           << isa<ObjCEncodeExpr>(literalStringStripped)
6972           << literalString->getSourceRange());
6973     }
6974   }
6975 
6976   // C99 6.5.8p3 / C99 6.5.9p4
6977   if (LHS.get()->getType()->isArithmeticType() &&
6978       RHS.get()->getType()->isArithmeticType()) {
6979     UsualArithmeticConversions(LHS, RHS);
6980     if (LHS.isInvalid() || RHS.isInvalid())
6981       return QualType();
6982   }
6983   else {
6984     LHS = UsualUnaryConversions(LHS.take());
6985     if (LHS.isInvalid())
6986       return QualType();
6987 
6988     RHS = UsualUnaryConversions(RHS.take());
6989     if (RHS.isInvalid())
6990       return QualType();
6991   }
6992 
6993   LHSType = LHS.get()->getType();
6994   RHSType = RHS.get()->getType();
6995 
6996   // The result of comparisons is 'bool' in C++, 'int' in C.
6997   QualType ResultTy = Context.getLogicalOperationType();
6998 
6999   if (IsRelational) {
7000     if (LHSType->isRealType() && RHSType->isRealType())
7001       return ResultTy;
7002   } else {
7003     // Check for comparisons of floating point operands using != and ==.
7004     if (LHSType->hasFloatingRepresentation())
7005       CheckFloatComparison(Loc, LHS.get(), RHS.get());
7006 
7007     if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
7008       return ResultTy;
7009   }
7010 
7011   bool LHSIsNull = LHS.get()->isNullPointerConstant(Context,
7012                                               Expr::NPC_ValueDependentIsNull);
7013   bool RHSIsNull = RHS.get()->isNullPointerConstant(Context,
7014                                               Expr::NPC_ValueDependentIsNull);
7015 
7016   // All of the following pointer-related warnings are GCC extensions, except
7017   // when handling null pointer constants.
7018   if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2
7019     QualType LCanPointeeTy =
7020       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
7021     QualType RCanPointeeTy =
7022       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
7023 
7024     if (getLangOpts().CPlusPlus) {
7025       if (LCanPointeeTy == RCanPointeeTy)
7026         return ResultTy;
7027       if (!IsRelational &&
7028           (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7029         // Valid unless comparison between non-null pointer and function pointer
7030         // This is a gcc extension compatibility comparison.
7031         // In a SFINAE context, we treat this as a hard error to maintain
7032         // conformance with the C++ standard.
7033         if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
7034             && !LHSIsNull && !RHSIsNull) {
7035           diagnoseFunctionPointerToVoidComparison(
7036               *this, Loc, LHS, RHS, /*isError*/ isSFINAEContext());
7037 
7038           if (isSFINAEContext())
7039             return QualType();
7040 
7041           RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
7042           return ResultTy;
7043         }
7044       }
7045 
7046       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
7047         return QualType();
7048       else
7049         return ResultTy;
7050     }
7051     // C99 6.5.9p2 and C99 6.5.8p2
7052     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
7053                                    RCanPointeeTy.getUnqualifiedType())) {
7054       // Valid unless a relational comparison of function pointers
7055       if (IsRelational && LCanPointeeTy->isFunctionType()) {
7056         Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
7057           << LHSType << RHSType << LHS.get()->getSourceRange()
7058           << RHS.get()->getSourceRange();
7059       }
7060     } else if (!IsRelational &&
7061                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7062       // Valid unless comparison between non-null pointer and function pointer
7063       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
7064           && !LHSIsNull && !RHSIsNull)
7065         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
7066                                                 /*isError*/false);
7067     } else {
7068       // Invalid
7069       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
7070     }
7071     if (LCanPointeeTy != RCanPointeeTy) {
7072       if (LHSIsNull && !RHSIsNull)
7073         LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
7074       else
7075         RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
7076     }
7077     return ResultTy;
7078   }
7079 
7080   if (getLangOpts().CPlusPlus) {
7081     // Comparison of nullptr_t with itself.
7082     if (LHSType->isNullPtrType() && RHSType->isNullPtrType())
7083       return ResultTy;
7084 
7085     // Comparison of pointers with null pointer constants and equality
7086     // comparisons of member pointers to null pointer constants.
7087     if (RHSIsNull &&
7088         ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) ||
7089          (!IsRelational &&
7090           (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) {
7091       RHS = ImpCastExprToType(RHS.take(), LHSType,
7092                         LHSType->isMemberPointerType()
7093                           ? CK_NullToMemberPointer
7094                           : CK_NullToPointer);
7095       return ResultTy;
7096     }
7097     if (LHSIsNull &&
7098         ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) ||
7099          (!IsRelational &&
7100           (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) {
7101       LHS = ImpCastExprToType(LHS.take(), RHSType,
7102                         RHSType->isMemberPointerType()
7103                           ? CK_NullToMemberPointer
7104                           : CK_NullToPointer);
7105       return ResultTy;
7106     }
7107 
7108     // Comparison of member pointers.
7109     if (!IsRelational &&
7110         LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) {
7111       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
7112         return QualType();
7113       else
7114         return ResultTy;
7115     }
7116 
7117     // Handle scoped enumeration types specifically, since they don't promote
7118     // to integers.
7119     if (LHS.get()->getType()->isEnumeralType() &&
7120         Context.hasSameUnqualifiedType(LHS.get()->getType(),
7121                                        RHS.get()->getType()))
7122       return ResultTy;
7123   }
7124 
7125   // Handle block pointer types.
7126   if (!IsRelational && LHSType->isBlockPointerType() &&
7127       RHSType->isBlockPointerType()) {
7128     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
7129     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
7130 
7131     if (!LHSIsNull && !RHSIsNull &&
7132         !Context.typesAreCompatible(lpointee, rpointee)) {
7133       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
7134         << LHSType << RHSType << LHS.get()->getSourceRange()
7135         << RHS.get()->getSourceRange();
7136     }
7137     RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
7138     return ResultTy;
7139   }
7140 
7141   // Allow block pointers to be compared with null pointer constants.
7142   if (!IsRelational
7143       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
7144           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
7145     if (!LHSIsNull && !RHSIsNull) {
7146       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
7147              ->getPointeeType()->isVoidType())
7148             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
7149                 ->getPointeeType()->isVoidType())))
7150         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
7151           << LHSType << RHSType << LHS.get()->getSourceRange()
7152           << RHS.get()->getSourceRange();
7153     }
7154     if (LHSIsNull && !RHSIsNull)
7155       LHS = ImpCastExprToType(LHS.take(), RHSType,
7156                               RHSType->isPointerType() ? CK_BitCast
7157                                 : CK_AnyPointerToBlockPointerCast);
7158     else
7159       RHS = ImpCastExprToType(RHS.take(), LHSType,
7160                               LHSType->isPointerType() ? CK_BitCast
7161                                 : CK_AnyPointerToBlockPointerCast);
7162     return ResultTy;
7163   }
7164 
7165   if (LHSType->isObjCObjectPointerType() ||
7166       RHSType->isObjCObjectPointerType()) {
7167     const PointerType *LPT = LHSType->getAs<PointerType>();
7168     const PointerType *RPT = RHSType->getAs<PointerType>();
7169     if (LPT || RPT) {
7170       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
7171       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
7172 
7173       if (!LPtrToVoid && !RPtrToVoid &&
7174           !Context.typesAreCompatible(LHSType, RHSType)) {
7175         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
7176                                           /*isError*/false);
7177       }
7178       if (LHSIsNull && !RHSIsNull)
7179         LHS = ImpCastExprToType(LHS.take(), RHSType,
7180                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
7181       else
7182         RHS = ImpCastExprToType(RHS.take(), LHSType,
7183                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
7184       return ResultTy;
7185     }
7186     if (LHSType->isObjCObjectPointerType() &&
7187         RHSType->isObjCObjectPointerType()) {
7188       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
7189         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
7190                                           /*isError*/false);
7191       if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
7192         diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
7193 
7194       if (LHSIsNull && !RHSIsNull)
7195         LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
7196       else
7197         RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
7198       return ResultTy;
7199     }
7200   }
7201   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
7202       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
7203     unsigned DiagID = 0;
7204     bool isError = false;
7205     if ((LHSIsNull && LHSType->isIntegerType()) ||
7206         (RHSIsNull && RHSType->isIntegerType())) {
7207       if (IsRelational && !getLangOpts().CPlusPlus)
7208         DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
7209     } else if (IsRelational && !getLangOpts().CPlusPlus)
7210       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
7211     else if (getLangOpts().CPlusPlus) {
7212       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
7213       isError = true;
7214     } else
7215       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
7216 
7217     if (DiagID) {
7218       Diag(Loc, DiagID)
7219         << LHSType << RHSType << LHS.get()->getSourceRange()
7220         << RHS.get()->getSourceRange();
7221       if (isError)
7222         return QualType();
7223     }
7224 
7225     if (LHSType->isIntegerType())
7226       LHS = ImpCastExprToType(LHS.take(), RHSType,
7227                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
7228     else
7229       RHS = ImpCastExprToType(RHS.take(), LHSType,
7230                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
7231     return ResultTy;
7232   }
7233 
7234   // Handle block pointers.
7235   if (!IsRelational && RHSIsNull
7236       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
7237     RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
7238     return ResultTy;
7239   }
7240   if (!IsRelational && LHSIsNull
7241       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
7242     LHS = ImpCastExprToType(LHS.take(), RHSType, CK_NullToPointer);
7243     return ResultTy;
7244   }
7245 
7246   return InvalidOperands(Loc, LHS, RHS);
7247 }
7248 
7249 
7250 // Return a signed type that is of identical size and number of elements.
7251 // For floating point vectors, return an integer type of identical size
7252 // and number of elements.
7253 QualType Sema::GetSignedVectorType(QualType V) {
7254   const VectorType *VTy = V->getAs<VectorType>();
7255   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
7256   if (TypeSize == Context.getTypeSize(Context.CharTy))
7257     return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
7258   else if (TypeSize == Context.getTypeSize(Context.ShortTy))
7259     return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
7260   else if (TypeSize == Context.getTypeSize(Context.IntTy))
7261     return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
7262   else if (TypeSize == Context.getTypeSize(Context.LongTy))
7263     return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
7264   assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
7265          "Unhandled vector element size in vector compare");
7266   return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
7267 }
7268 
7269 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
7270 /// operates on extended vector types.  Instead of producing an IntTy result,
7271 /// like a scalar comparison, a vector comparison produces a vector of integer
7272 /// types.
7273 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
7274                                           SourceLocation Loc,
7275                                           bool IsRelational) {
7276   // Check to make sure we're operating on vectors of the same type and width,
7277   // Allowing one side to be a scalar of element type.
7278   QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false);
7279   if (vType.isNull())
7280     return vType;
7281 
7282   QualType LHSType = LHS.get()->getType();
7283 
7284   // If AltiVec, the comparison results in a numeric type, i.e.
7285   // bool for C++, int for C
7286   if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
7287     return Context.getLogicalOperationType();
7288 
7289   // For non-floating point types, check for self-comparisons of the form
7290   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
7291   // often indicate logic errors in the program.
7292   if (!LHSType->hasFloatingRepresentation()) {
7293     if (DeclRefExpr* DRL
7294           = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
7295       if (DeclRefExpr* DRR
7296             = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
7297         if (DRL->getDecl() == DRR->getDecl())
7298           DiagRuntimeBehavior(Loc, 0,
7299                               PDiag(diag::warn_comparison_always)
7300                                 << 0 // self-
7301                                 << 2 // "a constant"
7302                               );
7303   }
7304 
7305   // Check for comparisons of floating point operands using != and ==.
7306   if (!IsRelational && LHSType->hasFloatingRepresentation()) {
7307     assert (RHS.get()->getType()->hasFloatingRepresentation());
7308     CheckFloatComparison(Loc, LHS.get(), RHS.get());
7309   }
7310 
7311   // Return a signed type for the vector.
7312   return GetSignedVectorType(LHSType);
7313 }
7314 
7315 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
7316                                           SourceLocation Loc) {
7317   // Ensure that either both operands are of the same vector type, or
7318   // one operand is of a vector type and the other is of its element type.
7319   QualType vType = CheckVectorOperands(LHS, RHS, Loc, false);
7320   if (vType.isNull() || vType->isFloatingType())
7321     return InvalidOperands(Loc, LHS, RHS);
7322 
7323   return GetSignedVectorType(LHS.get()->getType());
7324 }
7325 
7326 inline QualType Sema::CheckBitwiseOperands(
7327   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
7328   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7329 
7330   if (LHS.get()->getType()->isVectorType() ||
7331       RHS.get()->getType()->isVectorType()) {
7332     if (LHS.get()->getType()->hasIntegerRepresentation() &&
7333         RHS.get()->getType()->hasIntegerRepresentation())
7334       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
7335 
7336     return InvalidOperands(Loc, LHS, RHS);
7337   }
7338 
7339   ExprResult LHSResult = Owned(LHS), RHSResult = Owned(RHS);
7340   QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
7341                                                  IsCompAssign);
7342   if (LHSResult.isInvalid() || RHSResult.isInvalid())
7343     return QualType();
7344   LHS = LHSResult.take();
7345   RHS = RHSResult.take();
7346 
7347   if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
7348     return compType;
7349   return InvalidOperands(Loc, LHS, RHS);
7350 }
7351 
7352 inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
7353   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) {
7354 
7355   // Check vector operands differently.
7356   if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
7357     return CheckVectorLogicalOperands(LHS, RHS, Loc);
7358 
7359   // Diagnose cases where the user write a logical and/or but probably meant a
7360   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
7361   // is a constant.
7362   if (LHS.get()->getType()->isIntegerType() &&
7363       !LHS.get()->getType()->isBooleanType() &&
7364       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
7365       // Don't warn in macros or template instantiations.
7366       !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
7367     // If the RHS can be constant folded, and if it constant folds to something
7368     // that isn't 0 or 1 (which indicate a potential logical operation that
7369     // happened to fold to true/false) then warn.
7370     // Parens on the RHS are ignored.
7371     llvm::APSInt Result;
7372     if (RHS.get()->EvaluateAsInt(Result, Context))
7373       if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType()) ||
7374           (Result != 0 && Result != 1)) {
7375         Diag(Loc, diag::warn_logical_instead_of_bitwise)
7376           << RHS.get()->getSourceRange()
7377           << (Opc == BO_LAnd ? "&&" : "||");
7378         // Suggest replacing the logical operator with the bitwise version
7379         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
7380             << (Opc == BO_LAnd ? "&" : "|")
7381             << FixItHint::CreateReplacement(SourceRange(
7382                 Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(),
7383                                                 getLangOpts())),
7384                                             Opc == BO_LAnd ? "&" : "|");
7385         if (Opc == BO_LAnd)
7386           // Suggest replacing "Foo() && kNonZero" with "Foo()"
7387           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
7388               << FixItHint::CreateRemoval(
7389                   SourceRange(
7390                       Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(),
7391                                                  0, getSourceManager(),
7392                                                  getLangOpts()),
7393                       RHS.get()->getLocEnd()));
7394       }
7395   }
7396 
7397   if (!Context.getLangOpts().CPlusPlus) {
7398     LHS = UsualUnaryConversions(LHS.take());
7399     if (LHS.isInvalid())
7400       return QualType();
7401 
7402     RHS = UsualUnaryConversions(RHS.take());
7403     if (RHS.isInvalid())
7404       return QualType();
7405 
7406     if (!LHS.get()->getType()->isScalarType() ||
7407         !RHS.get()->getType()->isScalarType())
7408       return InvalidOperands(Loc, LHS, RHS);
7409 
7410     return Context.IntTy;
7411   }
7412 
7413   // The following is safe because we only use this method for
7414   // non-overloadable operands.
7415 
7416   // C++ [expr.log.and]p1
7417   // C++ [expr.log.or]p1
7418   // The operands are both contextually converted to type bool.
7419   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
7420   if (LHSRes.isInvalid())
7421     return InvalidOperands(Loc, LHS, RHS);
7422   LHS = move(LHSRes);
7423 
7424   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
7425   if (RHSRes.isInvalid())
7426     return InvalidOperands(Loc, LHS, RHS);
7427   RHS = move(RHSRes);
7428 
7429   // C++ [expr.log.and]p2
7430   // C++ [expr.log.or]p2
7431   // The result is a bool.
7432   return Context.BoolTy;
7433 }
7434 
7435 /// IsReadonlyProperty - Verify that otherwise a valid l-value expression
7436 /// is a read-only property; return true if so. A readonly property expression
7437 /// depends on various declarations and thus must be treated specially.
7438 ///
7439 static bool IsReadonlyProperty(Expr *E, Sema &S) {
7440   const ObjCPropertyRefExpr *PropExpr = dyn_cast<ObjCPropertyRefExpr>(E);
7441   if (!PropExpr) return false;
7442   if (PropExpr->isImplicitProperty()) return false;
7443 
7444   ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
7445   QualType BaseType = PropExpr->isSuperReceiver() ?
7446                             PropExpr->getSuperReceiverType() :
7447                             PropExpr->getBase()->getType();
7448 
7449   if (const ObjCObjectPointerType *OPT =
7450       BaseType->getAsObjCInterfacePointerType())
7451     if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
7452       if (S.isPropertyReadonly(PDecl, IFace))
7453         return true;
7454   return false;
7455 }
7456 
7457 static bool IsReadonlyMessage(Expr *E, Sema &S) {
7458   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
7459   if (!ME) return false;
7460   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
7461   ObjCMessageExpr *Base =
7462     dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts());
7463   if (!Base) return false;
7464   return Base->getMethodDecl() != 0;
7465 }
7466 
7467 /// Is the given expression (which must be 'const') a reference to a
7468 /// variable which was originally non-const, but which has become
7469 /// 'const' due to being captured within a block?
7470 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
7471 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
7472   assert(E->isLValue() && E->getType().isConstQualified());
7473   E = E->IgnoreParens();
7474 
7475   // Must be a reference to a declaration from an enclosing scope.
7476   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
7477   if (!DRE) return NCCK_None;
7478   if (!DRE->refersToEnclosingLocal()) return NCCK_None;
7479 
7480   // The declaration must be a variable which is not declared 'const'.
7481   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
7482   if (!var) return NCCK_None;
7483   if (var->getType().isConstQualified()) return NCCK_None;
7484   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
7485 
7486   // Decide whether the first capture was for a block or a lambda.
7487   DeclContext *DC = S.CurContext;
7488   while (DC->getParent() != var->getDeclContext())
7489     DC = DC->getParent();
7490   return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
7491 }
7492 
7493 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
7494 /// emit an error and return true.  If so, return false.
7495 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
7496   assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
7497   SourceLocation OrigLoc = Loc;
7498   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
7499                                                               &Loc);
7500   if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
7501     IsLV = Expr::MLV_ReadonlyProperty;
7502   else if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
7503     IsLV = Expr::MLV_InvalidMessageExpression;
7504   if (IsLV == Expr::MLV_Valid)
7505     return false;
7506 
7507   unsigned Diag = 0;
7508   bool NeedType = false;
7509   switch (IsLV) { // C99 6.5.16p2
7510   case Expr::MLV_ConstQualified:
7511     Diag = diag::err_typecheck_assign_const;
7512 
7513     // Use a specialized diagnostic when we're assigning to an object
7514     // from an enclosing function or block.
7515     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
7516       if (NCCK == NCCK_Block)
7517         Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
7518       else
7519         Diag = diag::err_lambda_decl_ref_not_modifiable_lvalue;
7520       break;
7521     }
7522 
7523     // In ARC, use some specialized diagnostics for occasions where we
7524     // infer 'const'.  These are always pseudo-strong variables.
7525     if (S.getLangOpts().ObjCAutoRefCount) {
7526       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
7527       if (declRef && isa<VarDecl>(declRef->getDecl())) {
7528         VarDecl *var = cast<VarDecl>(declRef->getDecl());
7529 
7530         // Use the normal diagnostic if it's pseudo-__strong but the
7531         // user actually wrote 'const'.
7532         if (var->isARCPseudoStrong() &&
7533             (!var->getTypeSourceInfo() ||
7534              !var->getTypeSourceInfo()->getType().isConstQualified())) {
7535           // There are two pseudo-strong cases:
7536           //  - self
7537           ObjCMethodDecl *method = S.getCurMethodDecl();
7538           if (method && var == method->getSelfDecl())
7539             Diag = method->isClassMethod()
7540               ? diag::err_typecheck_arc_assign_self_class_method
7541               : diag::err_typecheck_arc_assign_self;
7542 
7543           //  - fast enumeration variables
7544           else
7545             Diag = diag::err_typecheck_arr_assign_enumeration;
7546 
7547           SourceRange Assign;
7548           if (Loc != OrigLoc)
7549             Assign = SourceRange(OrigLoc, OrigLoc);
7550           S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
7551           // We need to preserve the AST regardless, so migration tool
7552           // can do its job.
7553           return false;
7554         }
7555       }
7556     }
7557 
7558     break;
7559   case Expr::MLV_ArrayType:
7560   case Expr::MLV_ArrayTemporary:
7561     Diag = diag::err_typecheck_array_not_modifiable_lvalue;
7562     NeedType = true;
7563     break;
7564   case Expr::MLV_NotObjectType:
7565     Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
7566     NeedType = true;
7567     break;
7568   case Expr::MLV_LValueCast:
7569     Diag = diag::err_typecheck_lvalue_casts_not_supported;
7570     break;
7571   case Expr::MLV_Valid:
7572     llvm_unreachable("did not take early return for MLV_Valid");
7573   case Expr::MLV_InvalidExpression:
7574   case Expr::MLV_MemberFunction:
7575   case Expr::MLV_ClassTemporary:
7576     Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
7577     break;
7578   case Expr::MLV_IncompleteType:
7579   case Expr::MLV_IncompleteVoidType:
7580     return S.RequireCompleteType(Loc, E->getType(),
7581              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
7582   case Expr::MLV_DuplicateVectorComponents:
7583     Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
7584     break;
7585   case Expr::MLV_ReadonlyProperty:
7586   case Expr::MLV_NoSetterProperty:
7587     llvm_unreachable("readonly properties should be processed differently");
7588   case Expr::MLV_InvalidMessageExpression:
7589     Diag = diag::error_readonly_message_assignment;
7590     break;
7591   case Expr::MLV_SubObjCPropertySetting:
7592     Diag = diag::error_no_subobject_property_setting;
7593     break;
7594   }
7595 
7596   SourceRange Assign;
7597   if (Loc != OrigLoc)
7598     Assign = SourceRange(OrigLoc, OrigLoc);
7599   if (NeedType)
7600     S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
7601   else
7602     S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
7603   return true;
7604 }
7605 
7606 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
7607                                          SourceLocation Loc,
7608                                          Sema &Sema) {
7609   // C / C++ fields
7610   MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
7611   MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
7612   if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) {
7613     if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))
7614       Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
7615   }
7616 
7617   // Objective-C instance variables
7618   ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
7619   ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
7620   if (OL && OR && OL->getDecl() == OR->getDecl()) {
7621     DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
7622     DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
7623     if (RL && RR && RL->getDecl() == RR->getDecl())
7624       Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
7625   }
7626 }
7627 
7628 // C99 6.5.16.1
7629 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
7630                                        SourceLocation Loc,
7631                                        QualType CompoundType) {
7632   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
7633 
7634   // Verify that LHS is a modifiable lvalue, and emit error if not.
7635   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
7636     return QualType();
7637 
7638   QualType LHSType = LHSExpr->getType();
7639   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
7640                                              CompoundType;
7641   AssignConvertType ConvTy;
7642   if (CompoundType.isNull()) {
7643     Expr *RHSCheck = RHS.get();
7644 
7645     CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
7646 
7647     QualType LHSTy(LHSType);
7648     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
7649     if (RHS.isInvalid())
7650       return QualType();
7651     // Special case of NSObject attributes on c-style pointer types.
7652     if (ConvTy == IncompatiblePointer &&
7653         ((Context.isObjCNSObjectType(LHSType) &&
7654           RHSType->isObjCObjectPointerType()) ||
7655          (Context.isObjCNSObjectType(RHSType) &&
7656           LHSType->isObjCObjectPointerType())))
7657       ConvTy = Compatible;
7658 
7659     if (ConvTy == Compatible &&
7660         LHSType->isObjCObjectType())
7661         Diag(Loc, diag::err_objc_object_assignment)
7662           << LHSType;
7663 
7664     // If the RHS is a unary plus or minus, check to see if they = and + are
7665     // right next to each other.  If so, the user may have typo'd "x =+ 4"
7666     // instead of "x += 4".
7667     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
7668       RHSCheck = ICE->getSubExpr();
7669     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
7670       if ((UO->getOpcode() == UO_Plus ||
7671            UO->getOpcode() == UO_Minus) &&
7672           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
7673           // Only if the two operators are exactly adjacent.
7674           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
7675           // And there is a space or other character before the subexpr of the
7676           // unary +/-.  We don't want to warn on "x=-1".
7677           Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
7678           UO->getSubExpr()->getLocStart().isFileID()) {
7679         Diag(Loc, diag::warn_not_compound_assign)
7680           << (UO->getOpcode() == UO_Plus ? "+" : "-")
7681           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
7682       }
7683     }
7684 
7685     if (ConvTy == Compatible) {
7686       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong)
7687         checkRetainCycles(LHSExpr, RHS.get());
7688       else if (getLangOpts().ObjCAutoRefCount)
7689         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
7690     }
7691   } else {
7692     // Compound assignment "x += y"
7693     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
7694   }
7695 
7696   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
7697                                RHS.get(), AA_Assigning))
7698     return QualType();
7699 
7700   CheckForNullPointerDereference(*this, LHSExpr);
7701 
7702   // C99 6.5.16p3: The type of an assignment expression is the type of the
7703   // left operand unless the left operand has qualified type, in which case
7704   // it is the unqualified version of the type of the left operand.
7705   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
7706   // is converted to the type of the assignment expression (above).
7707   // C++ 5.17p1: the type of the assignment expression is that of its left
7708   // operand.
7709   return (getLangOpts().CPlusPlus
7710           ? LHSType : LHSType.getUnqualifiedType());
7711 }
7712 
7713 // C99 6.5.17
7714 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
7715                                    SourceLocation Loc) {
7716   LHS = S.CheckPlaceholderExpr(LHS.take());
7717   RHS = S.CheckPlaceholderExpr(RHS.take());
7718   if (LHS.isInvalid() || RHS.isInvalid())
7719     return QualType();
7720 
7721   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
7722   // operands, but not unary promotions.
7723   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
7724 
7725   // So we treat the LHS as a ignored value, and in C++ we allow the
7726   // containing site to determine what should be done with the RHS.
7727   LHS = S.IgnoredValueConversions(LHS.take());
7728   if (LHS.isInvalid())
7729     return QualType();
7730 
7731   S.DiagnoseUnusedExprResult(LHS.get());
7732 
7733   if (!S.getLangOpts().CPlusPlus) {
7734     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take());
7735     if (RHS.isInvalid())
7736       return QualType();
7737     if (!RHS.get()->getType()->isVoidType())
7738       S.RequireCompleteType(Loc, RHS.get()->getType(),
7739                             diag::err_incomplete_type);
7740   }
7741 
7742   return RHS.get()->getType();
7743 }
7744 
7745 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
7746 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
7747 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
7748                                                ExprValueKind &VK,
7749                                                SourceLocation OpLoc,
7750                                                bool IsInc, bool IsPrefix) {
7751   if (Op->isTypeDependent())
7752     return S.Context.DependentTy;
7753 
7754   QualType ResType = Op->getType();
7755   // Atomic types can be used for increment / decrement where the non-atomic
7756   // versions can, so ignore the _Atomic() specifier for the purpose of
7757   // checking.
7758   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
7759     ResType = ResAtomicType->getValueType();
7760 
7761   assert(!ResType.isNull() && "no type for increment/decrement expression");
7762 
7763   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
7764     // Decrement of bool is not allowed.
7765     if (!IsInc) {
7766       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
7767       return QualType();
7768     }
7769     // Increment of bool sets it to true, but is deprecated.
7770     S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
7771   } else if (ResType->isRealType()) {
7772     // OK!
7773   } else if (ResType->isPointerType()) {
7774     // C99 6.5.2.4p2, 6.5.6p2
7775     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
7776       return QualType();
7777   } else if (ResType->isObjCObjectPointerType()) {
7778     // On modern runtimes, ObjC pointer arithmetic is forbidden.
7779     // Otherwise, we just need a complete type.
7780     if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
7781         checkArithmeticOnObjCPointer(S, OpLoc, Op))
7782       return QualType();
7783   } else if (ResType->isAnyComplexType()) {
7784     // C99 does not support ++/-- on complex types, we allow as an extension.
7785     S.Diag(OpLoc, diag::ext_integer_increment_complex)
7786       << ResType << Op->getSourceRange();
7787   } else if (ResType->isPlaceholderType()) {
7788     ExprResult PR = S.CheckPlaceholderExpr(Op);
7789     if (PR.isInvalid()) return QualType();
7790     return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
7791                                           IsInc, IsPrefix);
7792   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
7793     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
7794   } else {
7795     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
7796       << ResType << int(IsInc) << Op->getSourceRange();
7797     return QualType();
7798   }
7799   // At this point, we know we have a real, complex or pointer type.
7800   // Now make sure the operand is a modifiable lvalue.
7801   if (CheckForModifiableLvalue(Op, OpLoc, S))
7802     return QualType();
7803   // In C++, a prefix increment is the same type as the operand. Otherwise
7804   // (in C or with postfix), the increment is the unqualified type of the
7805   // operand.
7806   if (IsPrefix && S.getLangOpts().CPlusPlus) {
7807     VK = VK_LValue;
7808     return ResType;
7809   } else {
7810     VK = VK_RValue;
7811     return ResType.getUnqualifiedType();
7812   }
7813 }
7814 
7815 
7816 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
7817 /// This routine allows us to typecheck complex/recursive expressions
7818 /// where the declaration is needed for type checking. We only need to
7819 /// handle cases when the expression references a function designator
7820 /// or is an lvalue. Here are some examples:
7821 ///  - &(x) => x
7822 ///  - &*****f => f for f a function designator.
7823 ///  - &s.xx => s
7824 ///  - &s.zz[1].yy -> s, if zz is an array
7825 ///  - *(x + 1) -> x, if x is an array
7826 ///  - &"123"[2] -> 0
7827 ///  - & __real__ x -> x
7828 static ValueDecl *getPrimaryDecl(Expr *E) {
7829   switch (E->getStmtClass()) {
7830   case Stmt::DeclRefExprClass:
7831     return cast<DeclRefExpr>(E)->getDecl();
7832   case Stmt::MemberExprClass:
7833     // If this is an arrow operator, the address is an offset from
7834     // the base's value, so the object the base refers to is
7835     // irrelevant.
7836     if (cast<MemberExpr>(E)->isArrow())
7837       return 0;
7838     // Otherwise, the expression refers to a part of the base
7839     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
7840   case Stmt::ArraySubscriptExprClass: {
7841     // FIXME: This code shouldn't be necessary!  We should catch the implicit
7842     // promotion of register arrays earlier.
7843     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
7844     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
7845       if (ICE->getSubExpr()->getType()->isArrayType())
7846         return getPrimaryDecl(ICE->getSubExpr());
7847     }
7848     return 0;
7849   }
7850   case Stmt::UnaryOperatorClass: {
7851     UnaryOperator *UO = cast<UnaryOperator>(E);
7852 
7853     switch(UO->getOpcode()) {
7854     case UO_Real:
7855     case UO_Imag:
7856     case UO_Extension:
7857       return getPrimaryDecl(UO->getSubExpr());
7858     default:
7859       return 0;
7860     }
7861   }
7862   case Stmt::ParenExprClass:
7863     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
7864   case Stmt::ImplicitCastExprClass:
7865     // If the result of an implicit cast is an l-value, we care about
7866     // the sub-expression; otherwise, the result here doesn't matter.
7867     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
7868   default:
7869     return 0;
7870   }
7871 }
7872 
7873 namespace {
7874   enum {
7875     AO_Bit_Field = 0,
7876     AO_Vector_Element = 1,
7877     AO_Property_Expansion = 2,
7878     AO_Register_Variable = 3,
7879     AO_No_Error = 4
7880   };
7881 }
7882 /// \brief Diagnose invalid operand for address of operations.
7883 ///
7884 /// \param Type The type of operand which cannot have its address taken.
7885 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
7886                                          Expr *E, unsigned Type) {
7887   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
7888 }
7889 
7890 /// CheckAddressOfOperand - The operand of & must be either a function
7891 /// designator or an lvalue designating an object. If it is an lvalue, the
7892 /// object cannot be declared with storage class register or be a bit field.
7893 /// Note: The usual conversions are *not* applied to the operand of the &
7894 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
7895 /// In C++, the operand might be an overloaded function name, in which case
7896 /// we allow the '&' but retain the overloaded-function type.
7897 static QualType CheckAddressOfOperand(Sema &S, ExprResult &OrigOp,
7898                                       SourceLocation OpLoc) {
7899   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
7900     if (PTy->getKind() == BuiltinType::Overload) {
7901       if (!isa<OverloadExpr>(OrigOp.get()->IgnoreParens())) {
7902         S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
7903           << OrigOp.get()->getSourceRange();
7904         return QualType();
7905       }
7906 
7907       return S.Context.OverloadTy;
7908     }
7909 
7910     if (PTy->getKind() == BuiltinType::UnknownAny)
7911       return S.Context.UnknownAnyTy;
7912 
7913     if (PTy->getKind() == BuiltinType::BoundMember) {
7914       S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
7915         << OrigOp.get()->getSourceRange();
7916       return QualType();
7917     }
7918 
7919     OrigOp = S.CheckPlaceholderExpr(OrigOp.take());
7920     if (OrigOp.isInvalid()) return QualType();
7921   }
7922 
7923   if (OrigOp.get()->isTypeDependent())
7924     return S.Context.DependentTy;
7925 
7926   assert(!OrigOp.get()->getType()->isPlaceholderType());
7927 
7928   // Make sure to ignore parentheses in subsequent checks
7929   Expr *op = OrigOp.get()->IgnoreParens();
7930 
7931   if (S.getLangOpts().C99) {
7932     // Implement C99-only parts of addressof rules.
7933     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
7934       if (uOp->getOpcode() == UO_Deref)
7935         // Per C99 6.5.3.2, the address of a deref always returns a valid result
7936         // (assuming the deref expression is valid).
7937         return uOp->getSubExpr()->getType();
7938     }
7939     // Technically, there should be a check for array subscript
7940     // expressions here, but the result of one is always an lvalue anyway.
7941   }
7942   ValueDecl *dcl = getPrimaryDecl(op);
7943   Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
7944   unsigned AddressOfError = AO_No_Error;
7945 
7946   if (lval == Expr::LV_ClassTemporary) {
7947     bool sfinae = S.isSFINAEContext();
7948     S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
7949                          : diag::ext_typecheck_addrof_class_temporary)
7950       << op->getType() << op->getSourceRange();
7951     if (sfinae)
7952       return QualType();
7953   } else if (isa<ObjCSelectorExpr>(op)) {
7954     return S.Context.getPointerType(op->getType());
7955   } else if (lval == Expr::LV_MemberFunction) {
7956     // If it's an instance method, make a member pointer.
7957     // The expression must have exactly the form &A::foo.
7958 
7959     // If the underlying expression isn't a decl ref, give up.
7960     if (!isa<DeclRefExpr>(op)) {
7961       S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
7962         << OrigOp.get()->getSourceRange();
7963       return QualType();
7964     }
7965     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
7966     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
7967 
7968     // The id-expression was parenthesized.
7969     if (OrigOp.get() != DRE) {
7970       S.Diag(OpLoc, diag::err_parens_pointer_member_function)
7971         << OrigOp.get()->getSourceRange();
7972 
7973     // The method was named without a qualifier.
7974     } else if (!DRE->getQualifier()) {
7975       S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
7976         << op->getSourceRange();
7977     }
7978 
7979     return S.Context.getMemberPointerType(op->getType(),
7980               S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
7981   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
7982     // C99 6.5.3.2p1
7983     // The operand must be either an l-value or a function designator
7984     if (!op->getType()->isFunctionType()) {
7985       // Use a special diagnostic for loads from property references.
7986       if (isa<PseudoObjectExpr>(op)) {
7987         AddressOfError = AO_Property_Expansion;
7988       } else {
7989         // FIXME: emit more specific diag...
7990         S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
7991           << op->getSourceRange();
7992         return QualType();
7993       }
7994     }
7995   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
7996     // The operand cannot be a bit-field
7997     AddressOfError = AO_Bit_Field;
7998   } else if (op->getObjectKind() == OK_VectorComponent) {
7999     // The operand cannot be an element of a vector
8000     AddressOfError = AO_Vector_Element;
8001   } else if (dcl) { // C99 6.5.3.2p1
8002     // We have an lvalue with a decl. Make sure the decl is not declared
8003     // with the register storage-class specifier.
8004     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
8005       // in C++ it is not error to take address of a register
8006       // variable (c++03 7.1.1P3)
8007       if (vd->getStorageClass() == SC_Register &&
8008           !S.getLangOpts().CPlusPlus) {
8009         AddressOfError = AO_Register_Variable;
8010       }
8011     } else if (isa<FunctionTemplateDecl>(dcl)) {
8012       return S.Context.OverloadTy;
8013     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
8014       // Okay: we can take the address of a field.
8015       // Could be a pointer to member, though, if there is an explicit
8016       // scope qualifier for the class.
8017       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
8018         DeclContext *Ctx = dcl->getDeclContext();
8019         if (Ctx && Ctx->isRecord()) {
8020           if (dcl->getType()->isReferenceType()) {
8021             S.Diag(OpLoc,
8022                    diag::err_cannot_form_pointer_to_member_of_reference_type)
8023               << dcl->getDeclName() << dcl->getType();
8024             return QualType();
8025           }
8026 
8027           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
8028             Ctx = Ctx->getParent();
8029           return S.Context.getMemberPointerType(op->getType(),
8030                 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
8031         }
8032       }
8033     } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl))
8034       llvm_unreachable("Unknown/unexpected decl type");
8035   }
8036 
8037   if (AddressOfError != AO_No_Error) {
8038     diagnoseAddressOfInvalidType(S, OpLoc, op, AddressOfError);
8039     return QualType();
8040   }
8041 
8042   if (lval == Expr::LV_IncompleteVoidType) {
8043     // Taking the address of a void variable is technically illegal, but we
8044     // allow it in cases which are otherwise valid.
8045     // Example: "extern void x; void* y = &x;".
8046     S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
8047   }
8048 
8049   // If the operand has type "type", the result has type "pointer to type".
8050   if (op->getType()->isObjCObjectType())
8051     return S.Context.getObjCObjectPointerType(op->getType());
8052   return S.Context.getPointerType(op->getType());
8053 }
8054 
8055 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
8056 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
8057                                         SourceLocation OpLoc) {
8058   if (Op->isTypeDependent())
8059     return S.Context.DependentTy;
8060 
8061   ExprResult ConvResult = S.UsualUnaryConversions(Op);
8062   if (ConvResult.isInvalid())
8063     return QualType();
8064   Op = ConvResult.take();
8065   QualType OpTy = Op->getType();
8066   QualType Result;
8067 
8068   if (isa<CXXReinterpretCastExpr>(Op)) {
8069     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
8070     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
8071                                      Op->getSourceRange());
8072   }
8073 
8074   // Note that per both C89 and C99, indirection is always legal, even if OpTy
8075   // is an incomplete type or void.  It would be possible to warn about
8076   // dereferencing a void pointer, but it's completely well-defined, and such a
8077   // warning is unlikely to catch any mistakes.
8078   if (const PointerType *PT = OpTy->getAs<PointerType>())
8079     Result = PT->getPointeeType();
8080   else if (const ObjCObjectPointerType *OPT =
8081              OpTy->getAs<ObjCObjectPointerType>())
8082     Result = OPT->getPointeeType();
8083   else {
8084     ExprResult PR = S.CheckPlaceholderExpr(Op);
8085     if (PR.isInvalid()) return QualType();
8086     if (PR.take() != Op)
8087       return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
8088   }
8089 
8090   if (Result.isNull()) {
8091     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
8092       << OpTy << Op->getSourceRange();
8093     return QualType();
8094   }
8095 
8096   // Dereferences are usually l-values...
8097   VK = VK_LValue;
8098 
8099   // ...except that certain expressions are never l-values in C.
8100   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
8101     VK = VK_RValue;
8102 
8103   return Result;
8104 }
8105 
8106 static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
8107   tok::TokenKind Kind) {
8108   BinaryOperatorKind Opc;
8109   switch (Kind) {
8110   default: llvm_unreachable("Unknown binop!");
8111   case tok::periodstar:           Opc = BO_PtrMemD; break;
8112   case tok::arrowstar:            Opc = BO_PtrMemI; break;
8113   case tok::star:                 Opc = BO_Mul; break;
8114   case tok::slash:                Opc = BO_Div; break;
8115   case tok::percent:              Opc = BO_Rem; break;
8116   case tok::plus:                 Opc = BO_Add; break;
8117   case tok::minus:                Opc = BO_Sub; break;
8118   case tok::lessless:             Opc = BO_Shl; break;
8119   case tok::greatergreater:       Opc = BO_Shr; break;
8120   case tok::lessequal:            Opc = BO_LE; break;
8121   case tok::less:                 Opc = BO_LT; break;
8122   case tok::greaterequal:         Opc = BO_GE; break;
8123   case tok::greater:              Opc = BO_GT; break;
8124   case tok::exclaimequal:         Opc = BO_NE; break;
8125   case tok::equalequal:           Opc = BO_EQ; break;
8126   case tok::amp:                  Opc = BO_And; break;
8127   case tok::caret:                Opc = BO_Xor; break;
8128   case tok::pipe:                 Opc = BO_Or; break;
8129   case tok::ampamp:               Opc = BO_LAnd; break;
8130   case tok::pipepipe:             Opc = BO_LOr; break;
8131   case tok::equal:                Opc = BO_Assign; break;
8132   case tok::starequal:            Opc = BO_MulAssign; break;
8133   case tok::slashequal:           Opc = BO_DivAssign; break;
8134   case tok::percentequal:         Opc = BO_RemAssign; break;
8135   case tok::plusequal:            Opc = BO_AddAssign; break;
8136   case tok::minusequal:           Opc = BO_SubAssign; break;
8137   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
8138   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
8139   case tok::ampequal:             Opc = BO_AndAssign; break;
8140   case tok::caretequal:           Opc = BO_XorAssign; break;
8141   case tok::pipeequal:            Opc = BO_OrAssign; break;
8142   case tok::comma:                Opc = BO_Comma; break;
8143   }
8144   return Opc;
8145 }
8146 
8147 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
8148   tok::TokenKind Kind) {
8149   UnaryOperatorKind Opc;
8150   switch (Kind) {
8151   default: llvm_unreachable("Unknown unary op!");
8152   case tok::plusplus:     Opc = UO_PreInc; break;
8153   case tok::minusminus:   Opc = UO_PreDec; break;
8154   case tok::amp:          Opc = UO_AddrOf; break;
8155   case tok::star:         Opc = UO_Deref; break;
8156   case tok::plus:         Opc = UO_Plus; break;
8157   case tok::minus:        Opc = UO_Minus; break;
8158   case tok::tilde:        Opc = UO_Not; break;
8159   case tok::exclaim:      Opc = UO_LNot; break;
8160   case tok::kw___real:    Opc = UO_Real; break;
8161   case tok::kw___imag:    Opc = UO_Imag; break;
8162   case tok::kw___extension__: Opc = UO_Extension; break;
8163   }
8164   return Opc;
8165 }
8166 
8167 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
8168 /// This warning is only emitted for builtin assignment operations. It is also
8169 /// suppressed in the event of macro expansions.
8170 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
8171                                    SourceLocation OpLoc) {
8172   if (!S.ActiveTemplateInstantiations.empty())
8173     return;
8174   if (OpLoc.isInvalid() || OpLoc.isMacroID())
8175     return;
8176   LHSExpr = LHSExpr->IgnoreParenImpCasts();
8177   RHSExpr = RHSExpr->IgnoreParenImpCasts();
8178   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
8179   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
8180   if (!LHSDeclRef || !RHSDeclRef ||
8181       LHSDeclRef->getLocation().isMacroID() ||
8182       RHSDeclRef->getLocation().isMacroID())
8183     return;
8184   const ValueDecl *LHSDecl =
8185     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
8186   const ValueDecl *RHSDecl =
8187     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
8188   if (LHSDecl != RHSDecl)
8189     return;
8190   if (LHSDecl->getType().isVolatileQualified())
8191     return;
8192   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
8193     if (RefTy->getPointeeType().isVolatileQualified())
8194       return;
8195 
8196   S.Diag(OpLoc, diag::warn_self_assignment)
8197       << LHSDeclRef->getType()
8198       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
8199 }
8200 
8201 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
8202 /// operator @p Opc at location @c TokLoc. This routine only supports
8203 /// built-in operations; ActOnBinOp handles overloaded operators.
8204 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
8205                                     BinaryOperatorKind Opc,
8206                                     Expr *LHSExpr, Expr *RHSExpr) {
8207   if (getLangOpts().CPlusPlus0x && isa<InitListExpr>(RHSExpr)) {
8208     // The syntax only allows initializer lists on the RHS of assignment,
8209     // so we don't need to worry about accepting invalid code for
8210     // non-assignment operators.
8211     // C++11 5.17p9:
8212     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
8213     //   of x = {} is x = T().
8214     InitializationKind Kind =
8215         InitializationKind::CreateDirectList(RHSExpr->getLocStart());
8216     InitializedEntity Entity =
8217         InitializedEntity::InitializeTemporary(LHSExpr->getType());
8218     InitializationSequence InitSeq(*this, Entity, Kind, &RHSExpr, 1);
8219     ExprResult Init = InitSeq.Perform(*this, Entity, Kind,
8220                                       MultiExprArg(&RHSExpr, 1));
8221     if (Init.isInvalid())
8222       return Init;
8223     RHSExpr = Init.take();
8224   }
8225 
8226   ExprResult LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
8227   QualType ResultTy;     // Result type of the binary operator.
8228   // The following two variables are used for compound assignment operators
8229   QualType CompLHSTy;    // Type of LHS after promotions for computation
8230   QualType CompResultTy; // Type of computation result
8231   ExprValueKind VK = VK_RValue;
8232   ExprObjectKind OK = OK_Ordinary;
8233 
8234   switch (Opc) {
8235   case BO_Assign:
8236     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
8237     if (getLangOpts().CPlusPlus &&
8238         LHS.get()->getObjectKind() != OK_ObjCProperty) {
8239       VK = LHS.get()->getValueKind();
8240       OK = LHS.get()->getObjectKind();
8241     }
8242     if (!ResultTy.isNull())
8243       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
8244     break;
8245   case BO_PtrMemD:
8246   case BO_PtrMemI:
8247     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
8248                                             Opc == BO_PtrMemI);
8249     break;
8250   case BO_Mul:
8251   case BO_Div:
8252     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
8253                                            Opc == BO_Div);
8254     break;
8255   case BO_Rem:
8256     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
8257     break;
8258   case BO_Add:
8259     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
8260     break;
8261   case BO_Sub:
8262     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
8263     break;
8264   case BO_Shl:
8265   case BO_Shr:
8266     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
8267     break;
8268   case BO_LE:
8269   case BO_LT:
8270   case BO_GE:
8271   case BO_GT:
8272     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
8273     break;
8274   case BO_EQ:
8275   case BO_NE:
8276     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
8277     break;
8278   case BO_And:
8279   case BO_Xor:
8280   case BO_Or:
8281     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc);
8282     break;
8283   case BO_LAnd:
8284   case BO_LOr:
8285     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
8286     break;
8287   case BO_MulAssign:
8288   case BO_DivAssign:
8289     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
8290                                                Opc == BO_DivAssign);
8291     CompLHSTy = CompResultTy;
8292     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8293       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
8294     break;
8295   case BO_RemAssign:
8296     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
8297     CompLHSTy = CompResultTy;
8298     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8299       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
8300     break;
8301   case BO_AddAssign:
8302     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
8303     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8304       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
8305     break;
8306   case BO_SubAssign:
8307     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
8308     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8309       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
8310     break;
8311   case BO_ShlAssign:
8312   case BO_ShrAssign:
8313     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
8314     CompLHSTy = CompResultTy;
8315     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8316       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
8317     break;
8318   case BO_AndAssign:
8319   case BO_XorAssign:
8320   case BO_OrAssign:
8321     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true);
8322     CompLHSTy = CompResultTy;
8323     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8324       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
8325     break;
8326   case BO_Comma:
8327     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
8328     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
8329       VK = RHS.get()->getValueKind();
8330       OK = RHS.get()->getObjectKind();
8331     }
8332     break;
8333   }
8334   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
8335     return ExprError();
8336 
8337   // Check for array bounds violations for both sides of the BinaryOperator
8338   CheckArrayAccess(LHS.get());
8339   CheckArrayAccess(RHS.get());
8340 
8341   if (CompResultTy.isNull())
8342     return Owned(new (Context) BinaryOperator(LHS.take(), RHS.take(), Opc,
8343                                               ResultTy, VK, OK, OpLoc));
8344   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
8345       OK_ObjCProperty) {
8346     VK = VK_LValue;
8347     OK = LHS.get()->getObjectKind();
8348   }
8349   return Owned(new (Context) CompoundAssignOperator(LHS.take(), RHS.take(), Opc,
8350                                                     ResultTy, VK, OK, CompLHSTy,
8351                                                     CompResultTy, OpLoc));
8352 }
8353 
8354 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
8355 /// operators are mixed in a way that suggests that the programmer forgot that
8356 /// comparison operators have higher precedence. The most typical example of
8357 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
8358 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
8359                                       SourceLocation OpLoc, Expr *LHSExpr,
8360                                       Expr *RHSExpr) {
8361   typedef BinaryOperator BinOp;
8362   BinOp::Opcode LHSopc = static_cast<BinOp::Opcode>(-1),
8363                 RHSopc = static_cast<BinOp::Opcode>(-1);
8364   if (BinOp *BO = dyn_cast<BinOp>(LHSExpr))
8365     LHSopc = BO->getOpcode();
8366   if (BinOp *BO = dyn_cast<BinOp>(RHSExpr))
8367     RHSopc = BO->getOpcode();
8368 
8369   // Subs are not binary operators.
8370   if (LHSopc == -1 && RHSopc == -1)
8371     return;
8372 
8373   // Bitwise operations are sometimes used as eager logical ops.
8374   // Don't diagnose this.
8375   if ((BinOp::isComparisonOp(LHSopc) || BinOp::isBitwiseOp(LHSopc)) &&
8376       (BinOp::isComparisonOp(RHSopc) || BinOp::isBitwiseOp(RHSopc)))
8377     return;
8378 
8379   bool isLeftComp = BinOp::isComparisonOp(LHSopc);
8380   bool isRightComp = BinOp::isComparisonOp(RHSopc);
8381   if (!isLeftComp && !isRightComp) return;
8382 
8383   SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
8384                                                    OpLoc)
8385                                      : SourceRange(OpLoc, RHSExpr->getLocEnd());
8386   std::string OpStr = isLeftComp ? BinOp::getOpcodeStr(LHSopc)
8387                                  : BinOp::getOpcodeStr(RHSopc);
8388   SourceRange ParensRange = isLeftComp ?
8389       SourceRange(cast<BinOp>(LHSExpr)->getRHS()->getLocStart(),
8390                   RHSExpr->getLocEnd())
8391     : SourceRange(LHSExpr->getLocStart(),
8392                   cast<BinOp>(RHSExpr)->getLHS()->getLocStart());
8393 
8394   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
8395     << DiagRange << BinOp::getOpcodeStr(Opc) << OpStr;
8396   SuggestParentheses(Self, OpLoc,
8397     Self.PDiag(diag::note_precedence_bitwise_silence) << OpStr,
8398     (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
8399   SuggestParentheses(Self, OpLoc,
8400     Self.PDiag(diag::note_precedence_bitwise_first) << BinOp::getOpcodeStr(Opc),
8401     ParensRange);
8402 }
8403 
8404 /// \brief It accepts a '&' expr that is inside a '|' one.
8405 /// Emit a diagnostic together with a fixit hint that wraps the '&' expression
8406 /// in parentheses.
8407 static void
8408 EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc,
8409                                        BinaryOperator *Bop) {
8410   assert(Bop->getOpcode() == BO_And);
8411   Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or)
8412       << Bop->getSourceRange() << OpLoc;
8413   SuggestParentheses(Self, Bop->getOperatorLoc(),
8414     Self.PDiag(diag::note_bitwise_and_in_bitwise_or_silence),
8415     Bop->getSourceRange());
8416 }
8417 
8418 /// \brief It accepts a '&&' expr that is inside a '||' one.
8419 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
8420 /// in parentheses.
8421 static void
8422 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
8423                                        BinaryOperator *Bop) {
8424   assert(Bop->getOpcode() == BO_LAnd);
8425   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
8426       << Bop->getSourceRange() << OpLoc;
8427   SuggestParentheses(Self, Bop->getOperatorLoc(),
8428     Self.PDiag(diag::note_logical_and_in_logical_or_silence),
8429     Bop->getSourceRange());
8430 }
8431 
8432 /// \brief Returns true if the given expression can be evaluated as a constant
8433 /// 'true'.
8434 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
8435   bool Res;
8436   return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
8437 }
8438 
8439 /// \brief Returns true if the given expression can be evaluated as a constant
8440 /// 'false'.
8441 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
8442   bool Res;
8443   return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
8444 }
8445 
8446 /// \brief Look for '&&' in the left hand of a '||' expr.
8447 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
8448                                              Expr *LHSExpr, Expr *RHSExpr) {
8449   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
8450     if (Bop->getOpcode() == BO_LAnd) {
8451       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
8452       if (EvaluatesAsFalse(S, RHSExpr))
8453         return;
8454       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
8455       if (!EvaluatesAsTrue(S, Bop->getLHS()))
8456         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
8457     } else if (Bop->getOpcode() == BO_LOr) {
8458       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
8459         // If it's "a || b && 1 || c" we didn't warn earlier for
8460         // "a || b && 1", but warn now.
8461         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
8462           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
8463       }
8464     }
8465   }
8466 }
8467 
8468 /// \brief Look for '&&' in the right hand of a '||' expr.
8469 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
8470                                              Expr *LHSExpr, Expr *RHSExpr) {
8471   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
8472     if (Bop->getOpcode() == BO_LAnd) {
8473       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
8474       if (EvaluatesAsFalse(S, LHSExpr))
8475         return;
8476       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
8477       if (!EvaluatesAsTrue(S, Bop->getRHS()))
8478         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
8479     }
8480   }
8481 }
8482 
8483 /// \brief Look for '&' in the left or right hand of a '|' expr.
8484 static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc,
8485                                              Expr *OrArg) {
8486   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) {
8487     if (Bop->getOpcode() == BO_And)
8488       return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop);
8489   }
8490 }
8491 
8492 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
8493 /// precedence.
8494 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
8495                                     SourceLocation OpLoc, Expr *LHSExpr,
8496                                     Expr *RHSExpr){
8497   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
8498   if (BinaryOperator::isBitwiseOp(Opc))
8499     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
8500 
8501   // Diagnose "arg1 & arg2 | arg3"
8502   if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) {
8503     DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr);
8504     DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr);
8505   }
8506 
8507   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
8508   // We don't warn for 'assert(a || b && "bad")' since this is safe.
8509   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
8510     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
8511     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
8512   }
8513 }
8514 
8515 // Binary Operators.  'Tok' is the token for the operator.
8516 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
8517                             tok::TokenKind Kind,
8518                             Expr *LHSExpr, Expr *RHSExpr) {
8519   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
8520   assert((LHSExpr != 0) && "ActOnBinOp(): missing left expression");
8521   assert((RHSExpr != 0) && "ActOnBinOp(): missing right expression");
8522 
8523   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
8524   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
8525 
8526   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
8527 }
8528 
8529 /// Build an overloaded binary operator expression in the given scope.
8530 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
8531                                        BinaryOperatorKind Opc,
8532                                        Expr *LHS, Expr *RHS) {
8533   // Find all of the overloaded operators visible from this
8534   // point. We perform both an operator-name lookup from the local
8535   // scope and an argument-dependent lookup based on the types of
8536   // the arguments.
8537   UnresolvedSet<16> Functions;
8538   OverloadedOperatorKind OverOp
8539     = BinaryOperator::getOverloadedOperator(Opc);
8540   if (Sc && OverOp != OO_None)
8541     S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
8542                                    RHS->getType(), Functions);
8543 
8544   // Build the (potentially-overloaded, potentially-dependent)
8545   // binary operation.
8546   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
8547 }
8548 
8549 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
8550                             BinaryOperatorKind Opc,
8551                             Expr *LHSExpr, Expr *RHSExpr) {
8552   // We want to end up calling one of checkPseudoObjectAssignment
8553   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
8554   // both expressions are overloadable or either is type-dependent),
8555   // or CreateBuiltinBinOp (in any other case).  We also want to get
8556   // any placeholder types out of the way.
8557 
8558   // Handle pseudo-objects in the LHS.
8559   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
8560     // Assignments with a pseudo-object l-value need special analysis.
8561     if (pty->getKind() == BuiltinType::PseudoObject &&
8562         BinaryOperator::isAssignmentOp(Opc))
8563       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
8564 
8565     // Don't resolve overloads if the other type is overloadable.
8566     if (pty->getKind() == BuiltinType::Overload) {
8567       // We can't actually test that if we still have a placeholder,
8568       // though.  Fortunately, none of the exceptions we see in that
8569       // code below are valid when the LHS is an overload set.  Note
8570       // that an overload set can be dependently-typed, but it never
8571       // instantiates to having an overloadable type.
8572       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
8573       if (resolvedRHS.isInvalid()) return ExprError();
8574       RHSExpr = resolvedRHS.take();
8575 
8576       if (RHSExpr->isTypeDependent() ||
8577           RHSExpr->getType()->isOverloadableType())
8578         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8579     }
8580 
8581     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
8582     if (LHS.isInvalid()) return ExprError();
8583     LHSExpr = LHS.take();
8584   }
8585 
8586   // Handle pseudo-objects in the RHS.
8587   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
8588     // An overload in the RHS can potentially be resolved by the type
8589     // being assigned to.
8590     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
8591       if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
8592         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8593 
8594       if (LHSExpr->getType()->isOverloadableType())
8595         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8596 
8597       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
8598     }
8599 
8600     // Don't resolve overloads if the other type is overloadable.
8601     if (pty->getKind() == BuiltinType::Overload &&
8602         LHSExpr->getType()->isOverloadableType())
8603       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8604 
8605     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
8606     if (!resolvedRHS.isUsable()) return ExprError();
8607     RHSExpr = resolvedRHS.take();
8608   }
8609 
8610   if (getLangOpts().CPlusPlus) {
8611     // If either expression is type-dependent, always build an
8612     // overloaded op.
8613     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
8614       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8615 
8616     // Otherwise, build an overloaded op if either expression has an
8617     // overloadable type.
8618     if (LHSExpr->getType()->isOverloadableType() ||
8619         RHSExpr->getType()->isOverloadableType())
8620       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8621   }
8622 
8623   // Build a built-in binary operation.
8624   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
8625 }
8626 
8627 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
8628                                       UnaryOperatorKind Opc,
8629                                       Expr *InputExpr) {
8630   ExprResult Input = Owned(InputExpr);
8631   ExprValueKind VK = VK_RValue;
8632   ExprObjectKind OK = OK_Ordinary;
8633   QualType resultType;
8634   switch (Opc) {
8635   case UO_PreInc:
8636   case UO_PreDec:
8637   case UO_PostInc:
8638   case UO_PostDec:
8639     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc,
8640                                                 Opc == UO_PreInc ||
8641                                                 Opc == UO_PostInc,
8642                                                 Opc == UO_PreInc ||
8643                                                 Opc == UO_PreDec);
8644     break;
8645   case UO_AddrOf:
8646     resultType = CheckAddressOfOperand(*this, Input, OpLoc);
8647     break;
8648   case UO_Deref: {
8649     Input = DefaultFunctionArrayLvalueConversion(Input.take());
8650     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
8651     break;
8652   }
8653   case UO_Plus:
8654   case UO_Minus:
8655     Input = UsualUnaryConversions(Input.take());
8656     if (Input.isInvalid()) return ExprError();
8657     resultType = Input.get()->getType();
8658     if (resultType->isDependentType())
8659       break;
8660     if (resultType->isArithmeticType() || // C99 6.5.3.3p1
8661         resultType->isVectorType())
8662       break;
8663     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6-7
8664              resultType->isEnumeralType())
8665       break;
8666     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
8667              Opc == UO_Plus &&
8668              resultType->isPointerType())
8669       break;
8670 
8671     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
8672       << resultType << Input.get()->getSourceRange());
8673 
8674   case UO_Not: // bitwise complement
8675     Input = UsualUnaryConversions(Input.take());
8676     if (Input.isInvalid()) return ExprError();
8677     resultType = Input.get()->getType();
8678     if (resultType->isDependentType())
8679       break;
8680     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
8681     if (resultType->isComplexType() || resultType->isComplexIntegerType())
8682       // C99 does not support '~' for complex conjugation.
8683       Diag(OpLoc, diag::ext_integer_complement_complex)
8684         << resultType << Input.get()->getSourceRange();
8685     else if (resultType->hasIntegerRepresentation())
8686       break;
8687     else {
8688       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
8689         << resultType << Input.get()->getSourceRange());
8690     }
8691     break;
8692 
8693   case UO_LNot: // logical negation
8694     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
8695     Input = DefaultFunctionArrayLvalueConversion(Input.take());
8696     if (Input.isInvalid()) return ExprError();
8697     resultType = Input.get()->getType();
8698 
8699     // Though we still have to promote half FP to float...
8700     if (resultType->isHalfType()) {
8701       Input = ImpCastExprToType(Input.take(), Context.FloatTy, CK_FloatingCast).take();
8702       resultType = Context.FloatTy;
8703     }
8704 
8705     if (resultType->isDependentType())
8706       break;
8707     if (resultType->isScalarType()) {
8708       // C99 6.5.3.3p1: ok, fallthrough;
8709       if (Context.getLangOpts().CPlusPlus) {
8710         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
8711         // operand contextually converted to bool.
8712         Input = ImpCastExprToType(Input.take(), Context.BoolTy,
8713                                   ScalarTypeToBooleanCastKind(resultType));
8714       }
8715     } else if (resultType->isExtVectorType()) {
8716       // Vector logical not returns the signed variant of the operand type.
8717       resultType = GetSignedVectorType(resultType);
8718       break;
8719     } else {
8720       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
8721         << resultType << Input.get()->getSourceRange());
8722     }
8723 
8724     // LNot always has type int. C99 6.5.3.3p5.
8725     // In C++, it's bool. C++ 5.3.1p8
8726     resultType = Context.getLogicalOperationType();
8727     break;
8728   case UO_Real:
8729   case UO_Imag:
8730     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
8731     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
8732     // complex l-values to ordinary l-values and all other values to r-values.
8733     if (Input.isInvalid()) return ExprError();
8734     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
8735       if (Input.get()->getValueKind() != VK_RValue &&
8736           Input.get()->getObjectKind() == OK_Ordinary)
8737         VK = Input.get()->getValueKind();
8738     } else if (!getLangOpts().CPlusPlus) {
8739       // In C, a volatile scalar is read by __imag. In C++, it is not.
8740       Input = DefaultLvalueConversion(Input.take());
8741     }
8742     break;
8743   case UO_Extension:
8744     resultType = Input.get()->getType();
8745     VK = Input.get()->getValueKind();
8746     OK = Input.get()->getObjectKind();
8747     break;
8748   }
8749   if (resultType.isNull() || Input.isInvalid())
8750     return ExprError();
8751 
8752   // Check for array bounds violations in the operand of the UnaryOperator,
8753   // except for the '*' and '&' operators that have to be handled specially
8754   // by CheckArrayAccess (as there are special cases like &array[arraysize]
8755   // that are explicitly defined as valid by the standard).
8756   if (Opc != UO_AddrOf && Opc != UO_Deref)
8757     CheckArrayAccess(Input.get());
8758 
8759   return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType,
8760                                            VK, OK, OpLoc));
8761 }
8762 
8763 /// \brief Determine whether the given expression is a qualified member
8764 /// access expression, of a form that could be turned into a pointer to member
8765 /// with the address-of operator.
8766 static bool isQualifiedMemberAccess(Expr *E) {
8767   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
8768     if (!DRE->getQualifier())
8769       return false;
8770 
8771     ValueDecl *VD = DRE->getDecl();
8772     if (!VD->isCXXClassMember())
8773       return false;
8774 
8775     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
8776       return true;
8777     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
8778       return Method->isInstance();
8779 
8780     return false;
8781   }
8782 
8783   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
8784     if (!ULE->getQualifier())
8785       return false;
8786 
8787     for (UnresolvedLookupExpr::decls_iterator D = ULE->decls_begin(),
8788                                            DEnd = ULE->decls_end();
8789          D != DEnd; ++D) {
8790       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*D)) {
8791         if (Method->isInstance())
8792           return true;
8793       } else {
8794         // Overload set does not contain methods.
8795         break;
8796       }
8797     }
8798 
8799     return false;
8800   }
8801 
8802   return false;
8803 }
8804 
8805 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
8806                               UnaryOperatorKind Opc, Expr *Input) {
8807   // First things first: handle placeholders so that the
8808   // overloaded-operator check considers the right type.
8809   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
8810     // Increment and decrement of pseudo-object references.
8811     if (pty->getKind() == BuiltinType::PseudoObject &&
8812         UnaryOperator::isIncrementDecrementOp(Opc))
8813       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
8814 
8815     // extension is always a builtin operator.
8816     if (Opc == UO_Extension)
8817       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
8818 
8819     // & gets special logic for several kinds of placeholder.
8820     // The builtin code knows what to do.
8821     if (Opc == UO_AddrOf &&
8822         (pty->getKind() == BuiltinType::Overload ||
8823          pty->getKind() == BuiltinType::UnknownAny ||
8824          pty->getKind() == BuiltinType::BoundMember))
8825       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
8826 
8827     // Anything else needs to be handled now.
8828     ExprResult Result = CheckPlaceholderExpr(Input);
8829     if (Result.isInvalid()) return ExprError();
8830     Input = Result.take();
8831   }
8832 
8833   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
8834       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
8835       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
8836     // Find all of the overloaded operators visible from this
8837     // point. We perform both an operator-name lookup from the local
8838     // scope and an argument-dependent lookup based on the types of
8839     // the arguments.
8840     UnresolvedSet<16> Functions;
8841     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
8842     if (S && OverOp != OO_None)
8843       LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
8844                                    Functions);
8845 
8846     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
8847   }
8848 
8849   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
8850 }
8851 
8852 // Unary Operators.  'Tok' is the token for the operator.
8853 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
8854                               tok::TokenKind Op, Expr *Input) {
8855   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
8856 }
8857 
8858 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
8859 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
8860                                 LabelDecl *TheDecl) {
8861   TheDecl->setUsed();
8862   // Create the AST node.  The address of a label always has type 'void*'.
8863   return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
8864                                        Context.getPointerType(Context.VoidTy)));
8865 }
8866 
8867 /// Given the last statement in a statement-expression, check whether
8868 /// the result is a producing expression (like a call to an
8869 /// ns_returns_retained function) and, if so, rebuild it to hoist the
8870 /// release out of the full-expression.  Otherwise, return null.
8871 /// Cannot fail.
8872 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
8873   // Should always be wrapped with one of these.
8874   ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
8875   if (!cleanups) return 0;
8876 
8877   ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
8878   if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
8879     return 0;
8880 
8881   // Splice out the cast.  This shouldn't modify any interesting
8882   // features of the statement.
8883   Expr *producer = cast->getSubExpr();
8884   assert(producer->getType() == cast->getType());
8885   assert(producer->getValueKind() == cast->getValueKind());
8886   cleanups->setSubExpr(producer);
8887   return cleanups;
8888 }
8889 
8890 void Sema::ActOnStartStmtExpr() {
8891   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
8892 }
8893 
8894 void Sema::ActOnStmtExprError() {
8895   // Note that function is also called by TreeTransform when leaving a
8896   // StmtExpr scope without rebuilding anything.
8897 
8898   DiscardCleanupsInEvaluationContext();
8899   PopExpressionEvaluationContext();
8900 }
8901 
8902 ExprResult
8903 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
8904                     SourceLocation RPLoc) { // "({..})"
8905   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
8906   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
8907 
8908   if (hasAnyUnrecoverableErrorsInThisFunction())
8909     DiscardCleanupsInEvaluationContext();
8910   assert(!ExprNeedsCleanups && "cleanups within StmtExpr not correctly bound!");
8911   PopExpressionEvaluationContext();
8912 
8913   bool isFileScope
8914     = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
8915   if (isFileScope)
8916     return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
8917 
8918   // FIXME: there are a variety of strange constraints to enforce here, for
8919   // example, it is not possible to goto into a stmt expression apparently.
8920   // More semantic analysis is needed.
8921 
8922   // If there are sub stmts in the compound stmt, take the type of the last one
8923   // as the type of the stmtexpr.
8924   QualType Ty = Context.VoidTy;
8925   bool StmtExprMayBindToTemp = false;
8926   if (!Compound->body_empty()) {
8927     Stmt *LastStmt = Compound->body_back();
8928     LabelStmt *LastLabelStmt = 0;
8929     // If LastStmt is a label, skip down through into the body.
8930     while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
8931       LastLabelStmt = Label;
8932       LastStmt = Label->getSubStmt();
8933     }
8934 
8935     if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
8936       // Do function/array conversion on the last expression, but not
8937       // lvalue-to-rvalue.  However, initialize an unqualified type.
8938       ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
8939       if (LastExpr.isInvalid())
8940         return ExprError();
8941       Ty = LastExpr.get()->getType().getUnqualifiedType();
8942 
8943       if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
8944         // In ARC, if the final expression ends in a consume, splice
8945         // the consume out and bind it later.  In the alternate case
8946         // (when dealing with a retainable type), the result
8947         // initialization will create a produce.  In both cases the
8948         // result will be +1, and we'll need to balance that out with
8949         // a bind.
8950         if (Expr *rebuiltLastStmt
8951               = maybeRebuildARCConsumingStmt(LastExpr.get())) {
8952           LastExpr = rebuiltLastStmt;
8953         } else {
8954           LastExpr = PerformCopyInitialization(
8955                             InitializedEntity::InitializeResult(LPLoc,
8956                                                                 Ty,
8957                                                                 false),
8958                                                    SourceLocation(),
8959                                                LastExpr);
8960         }
8961 
8962         if (LastExpr.isInvalid())
8963           return ExprError();
8964         if (LastExpr.get() != 0) {
8965           if (!LastLabelStmt)
8966             Compound->setLastStmt(LastExpr.take());
8967           else
8968             LastLabelStmt->setSubStmt(LastExpr.take());
8969           StmtExprMayBindToTemp = true;
8970         }
8971       }
8972     }
8973   }
8974 
8975   // FIXME: Check that expression type is complete/non-abstract; statement
8976   // expressions are not lvalues.
8977   Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
8978   if (StmtExprMayBindToTemp)
8979     return MaybeBindToTemporary(ResStmtExpr);
8980   return Owned(ResStmtExpr);
8981 }
8982 
8983 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
8984                                       TypeSourceInfo *TInfo,
8985                                       OffsetOfComponent *CompPtr,
8986                                       unsigned NumComponents,
8987                                       SourceLocation RParenLoc) {
8988   QualType ArgTy = TInfo->getType();
8989   bool Dependent = ArgTy->isDependentType();
8990   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
8991 
8992   // We must have at least one component that refers to the type, and the first
8993   // one is known to be a field designator.  Verify that the ArgTy represents
8994   // a struct/union/class.
8995   if (!Dependent && !ArgTy->isRecordType())
8996     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
8997                        << ArgTy << TypeRange);
8998 
8999   // Type must be complete per C99 7.17p3 because a declaring a variable
9000   // with an incomplete type would be ill-formed.
9001   if (!Dependent
9002       && RequireCompleteType(BuiltinLoc, ArgTy,
9003                              diag::err_offsetof_incomplete_type, TypeRange))
9004     return ExprError();
9005 
9006   // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
9007   // GCC extension, diagnose them.
9008   // FIXME: This diagnostic isn't actually visible because the location is in
9009   // a system header!
9010   if (NumComponents != 1)
9011     Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
9012       << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
9013 
9014   bool DidWarnAboutNonPOD = false;
9015   QualType CurrentType = ArgTy;
9016   typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
9017   SmallVector<OffsetOfNode, 4> Comps;
9018   SmallVector<Expr*, 4> Exprs;
9019   for (unsigned i = 0; i != NumComponents; ++i) {
9020     const OffsetOfComponent &OC = CompPtr[i];
9021     if (OC.isBrackets) {
9022       // Offset of an array sub-field.  TODO: Should we allow vector elements?
9023       if (!CurrentType->isDependentType()) {
9024         const ArrayType *AT = Context.getAsArrayType(CurrentType);
9025         if(!AT)
9026           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
9027                            << CurrentType);
9028         CurrentType = AT->getElementType();
9029       } else
9030         CurrentType = Context.DependentTy;
9031 
9032       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
9033       if (IdxRval.isInvalid())
9034         return ExprError();
9035       Expr *Idx = IdxRval.take();
9036 
9037       // The expression must be an integral expression.
9038       // FIXME: An integral constant expression?
9039       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
9040           !Idx->getType()->isIntegerType())
9041         return ExprError(Diag(Idx->getLocStart(),
9042                               diag::err_typecheck_subscript_not_integer)
9043                          << Idx->getSourceRange());
9044 
9045       // Record this array index.
9046       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
9047       Exprs.push_back(Idx);
9048       continue;
9049     }
9050 
9051     // Offset of a field.
9052     if (CurrentType->isDependentType()) {
9053       // We have the offset of a field, but we can't look into the dependent
9054       // type. Just record the identifier of the field.
9055       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
9056       CurrentType = Context.DependentTy;
9057       continue;
9058     }
9059 
9060     // We need to have a complete type to look into.
9061     if (RequireCompleteType(OC.LocStart, CurrentType,
9062                             diag::err_offsetof_incomplete_type))
9063       return ExprError();
9064 
9065     // Look for the designated field.
9066     const RecordType *RC = CurrentType->getAs<RecordType>();
9067     if (!RC)
9068       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
9069                        << CurrentType);
9070     RecordDecl *RD = RC->getDecl();
9071 
9072     // C++ [lib.support.types]p5:
9073     //   The macro offsetof accepts a restricted set of type arguments in this
9074     //   International Standard. type shall be a POD structure or a POD union
9075     //   (clause 9).
9076     // C++11 [support.types]p4:
9077     //   If type is not a standard-layout class (Clause 9), the results are
9078     //   undefined.
9079     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
9080       bool IsSafe = LangOpts.CPlusPlus0x? CRD->isStandardLayout() : CRD->isPOD();
9081       unsigned DiagID =
9082         LangOpts.CPlusPlus0x? diag::warn_offsetof_non_standardlayout_type
9083                             : diag::warn_offsetof_non_pod_type;
9084 
9085       if (!IsSafe && !DidWarnAboutNonPOD &&
9086           DiagRuntimeBehavior(BuiltinLoc, 0,
9087                               PDiag(DiagID)
9088                               << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
9089                               << CurrentType))
9090         DidWarnAboutNonPOD = true;
9091     }
9092 
9093     // Look for the field.
9094     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
9095     LookupQualifiedName(R, RD);
9096     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
9097     IndirectFieldDecl *IndirectMemberDecl = 0;
9098     if (!MemberDecl) {
9099       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
9100         MemberDecl = IndirectMemberDecl->getAnonField();
9101     }
9102 
9103     if (!MemberDecl)
9104       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
9105                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
9106                                                               OC.LocEnd));
9107 
9108     // C99 7.17p3:
9109     //   (If the specified member is a bit-field, the behavior is undefined.)
9110     //
9111     // We diagnose this as an error.
9112     if (MemberDecl->isBitField()) {
9113       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
9114         << MemberDecl->getDeclName()
9115         << SourceRange(BuiltinLoc, RParenLoc);
9116       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
9117       return ExprError();
9118     }
9119 
9120     RecordDecl *Parent = MemberDecl->getParent();
9121     if (IndirectMemberDecl)
9122       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
9123 
9124     // If the member was found in a base class, introduce OffsetOfNodes for
9125     // the base class indirections.
9126     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
9127                        /*DetectVirtual=*/false);
9128     if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
9129       CXXBasePath &Path = Paths.front();
9130       for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
9131            B != BEnd; ++B)
9132         Comps.push_back(OffsetOfNode(B->Base));
9133     }
9134 
9135     if (IndirectMemberDecl) {
9136       for (IndirectFieldDecl::chain_iterator FI =
9137            IndirectMemberDecl->chain_begin(),
9138            FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
9139         assert(isa<FieldDecl>(*FI));
9140         Comps.push_back(OffsetOfNode(OC.LocStart,
9141                                      cast<FieldDecl>(*FI), OC.LocEnd));
9142       }
9143     } else
9144       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
9145 
9146     CurrentType = MemberDecl->getType().getNonReferenceType();
9147   }
9148 
9149   return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
9150                                     TInfo, Comps.data(), Comps.size(),
9151                                     Exprs.data(), Exprs.size(), RParenLoc));
9152 }
9153 
9154 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
9155                                       SourceLocation BuiltinLoc,
9156                                       SourceLocation TypeLoc,
9157                                       ParsedType ParsedArgTy,
9158                                       OffsetOfComponent *CompPtr,
9159                                       unsigned NumComponents,
9160                                       SourceLocation RParenLoc) {
9161 
9162   TypeSourceInfo *ArgTInfo;
9163   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
9164   if (ArgTy.isNull())
9165     return ExprError();
9166 
9167   if (!ArgTInfo)
9168     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
9169 
9170   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
9171                               RParenLoc);
9172 }
9173 
9174 
9175 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
9176                                  Expr *CondExpr,
9177                                  Expr *LHSExpr, Expr *RHSExpr,
9178                                  SourceLocation RPLoc) {
9179   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
9180 
9181   ExprValueKind VK = VK_RValue;
9182   ExprObjectKind OK = OK_Ordinary;
9183   QualType resType;
9184   bool ValueDependent = false;
9185   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
9186     resType = Context.DependentTy;
9187     ValueDependent = true;
9188   } else {
9189     // The conditional expression is required to be a constant expression.
9190     llvm::APSInt condEval(32);
9191     ExprResult CondICE
9192       = VerifyIntegerConstantExpression(CondExpr, &condEval,
9193           diag::err_typecheck_choose_expr_requires_constant, false);
9194     if (CondICE.isInvalid())
9195       return ExprError();
9196     CondExpr = CondICE.take();
9197 
9198     // If the condition is > zero, then the AST type is the same as the LSHExpr.
9199     Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
9200 
9201     resType = ActiveExpr->getType();
9202     ValueDependent = ActiveExpr->isValueDependent();
9203     VK = ActiveExpr->getValueKind();
9204     OK = ActiveExpr->getObjectKind();
9205   }
9206 
9207   return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
9208                                         resType, VK, OK, RPLoc,
9209                                         resType->isDependentType(),
9210                                         ValueDependent));
9211 }
9212 
9213 //===----------------------------------------------------------------------===//
9214 // Clang Extensions.
9215 //===----------------------------------------------------------------------===//
9216 
9217 /// ActOnBlockStart - This callback is invoked when a block literal is started.
9218 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
9219   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
9220   PushBlockScope(CurScope, Block);
9221   CurContext->addDecl(Block);
9222   if (CurScope)
9223     PushDeclContext(CurScope, Block);
9224   else
9225     CurContext = Block;
9226 
9227   getCurBlock()->HasImplicitReturnType = true;
9228 
9229   // Enter a new evaluation context to insulate the block from any
9230   // cleanups from the enclosing full-expression.
9231   PushExpressionEvaluationContext(PotentiallyEvaluated);
9232 }
9233 
9234 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
9235                                Scope *CurScope) {
9236   assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
9237   assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
9238   BlockScopeInfo *CurBlock = getCurBlock();
9239 
9240   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
9241   QualType T = Sig->getType();
9242 
9243   // FIXME: We should allow unexpanded parameter packs here, but that would,
9244   // in turn, make the block expression contain unexpanded parameter packs.
9245   if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
9246     // Drop the parameters.
9247     FunctionProtoType::ExtProtoInfo EPI;
9248     EPI.HasTrailingReturn = false;
9249     EPI.TypeQuals |= DeclSpec::TQ_const;
9250     T = Context.getFunctionType(Context.DependentTy, /*Args=*/0, /*NumArgs=*/0,
9251                                 EPI);
9252     Sig = Context.getTrivialTypeSourceInfo(T);
9253   }
9254 
9255   // GetTypeForDeclarator always produces a function type for a block
9256   // literal signature.  Furthermore, it is always a FunctionProtoType
9257   // unless the function was written with a typedef.
9258   assert(T->isFunctionType() &&
9259          "GetTypeForDeclarator made a non-function block signature");
9260 
9261   // Look for an explicit signature in that function type.
9262   FunctionProtoTypeLoc ExplicitSignature;
9263 
9264   TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
9265   if (isa<FunctionProtoTypeLoc>(tmp)) {
9266     ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp);
9267 
9268     // Check whether that explicit signature was synthesized by
9269     // GetTypeForDeclarator.  If so, don't save that as part of the
9270     // written signature.
9271     if (ExplicitSignature.getLocalRangeBegin() ==
9272         ExplicitSignature.getLocalRangeEnd()) {
9273       // This would be much cheaper if we stored TypeLocs instead of
9274       // TypeSourceInfos.
9275       TypeLoc Result = ExplicitSignature.getResultLoc();
9276       unsigned Size = Result.getFullDataSize();
9277       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
9278       Sig->getTypeLoc().initializeFullCopy(Result, Size);
9279 
9280       ExplicitSignature = FunctionProtoTypeLoc();
9281     }
9282   }
9283 
9284   CurBlock->TheDecl->setSignatureAsWritten(Sig);
9285   CurBlock->FunctionType = T;
9286 
9287   const FunctionType *Fn = T->getAs<FunctionType>();
9288   QualType RetTy = Fn->getResultType();
9289   bool isVariadic =
9290     (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
9291 
9292   CurBlock->TheDecl->setIsVariadic(isVariadic);
9293 
9294   // Don't allow returning a objc interface by value.
9295   if (RetTy->isObjCObjectType()) {
9296     Diag(ParamInfo.getLocStart(),
9297          diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
9298     return;
9299   }
9300 
9301   // Context.DependentTy is used as a placeholder for a missing block
9302   // return type.  TODO:  what should we do with declarators like:
9303   //   ^ * { ... }
9304   // If the answer is "apply template argument deduction"....
9305   if (RetTy != Context.DependentTy) {
9306     CurBlock->ReturnType = RetTy;
9307     CurBlock->TheDecl->setBlockMissingReturnType(false);
9308     CurBlock->HasImplicitReturnType = false;
9309   }
9310 
9311   // Push block parameters from the declarator if we had them.
9312   SmallVector<ParmVarDecl*, 8> Params;
9313   if (ExplicitSignature) {
9314     for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
9315       ParmVarDecl *Param = ExplicitSignature.getArg(I);
9316       if (Param->getIdentifier() == 0 &&
9317           !Param->isImplicit() &&
9318           !Param->isInvalidDecl() &&
9319           !getLangOpts().CPlusPlus)
9320         Diag(Param->getLocation(), diag::err_parameter_name_omitted);
9321       Params.push_back(Param);
9322     }
9323 
9324   // Fake up parameter variables if we have a typedef, like
9325   //   ^ fntype { ... }
9326   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
9327     for (FunctionProtoType::arg_type_iterator
9328            I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
9329       ParmVarDecl *Param =
9330         BuildParmVarDeclForTypedef(CurBlock->TheDecl,
9331                                    ParamInfo.getLocStart(),
9332                                    *I);
9333       Params.push_back(Param);
9334     }
9335   }
9336 
9337   // Set the parameters on the block decl.
9338   if (!Params.empty()) {
9339     CurBlock->TheDecl->setParams(Params);
9340     CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
9341                              CurBlock->TheDecl->param_end(),
9342                              /*CheckParameterNames=*/false);
9343   }
9344 
9345   // Finally we can process decl attributes.
9346   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
9347 
9348   // Put the parameter variables in scope.  We can bail out immediately
9349   // if we don't have any.
9350   if (Params.empty())
9351     return;
9352 
9353   for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
9354          E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
9355     (*AI)->setOwningFunction(CurBlock->TheDecl);
9356 
9357     // If this has an identifier, add it to the scope stack.
9358     if ((*AI)->getIdentifier()) {
9359       CheckShadow(CurBlock->TheScope, *AI);
9360 
9361       PushOnScopeChains(*AI, CurBlock->TheScope);
9362     }
9363   }
9364 }
9365 
9366 /// ActOnBlockError - If there is an error parsing a block, this callback
9367 /// is invoked to pop the information about the block from the action impl.
9368 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
9369   // Leave the expression-evaluation context.
9370   DiscardCleanupsInEvaluationContext();
9371   PopExpressionEvaluationContext();
9372 
9373   // Pop off CurBlock, handle nested blocks.
9374   PopDeclContext();
9375   PopFunctionScopeInfo();
9376 }
9377 
9378 /// ActOnBlockStmtExpr - This is called when the body of a block statement
9379 /// literal was successfully completed.  ^(int x){...}
9380 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
9381                                     Stmt *Body, Scope *CurScope) {
9382   // If blocks are disabled, emit an error.
9383   if (!LangOpts.Blocks)
9384     Diag(CaretLoc, diag::err_blocks_disable);
9385 
9386   // Leave the expression-evaluation context.
9387   if (hasAnyUnrecoverableErrorsInThisFunction())
9388     DiscardCleanupsInEvaluationContext();
9389   assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!");
9390   PopExpressionEvaluationContext();
9391 
9392   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
9393 
9394   if (BSI->HasImplicitReturnType)
9395     deduceClosureReturnType(*BSI);
9396 
9397   PopDeclContext();
9398 
9399   QualType RetTy = Context.VoidTy;
9400   if (!BSI->ReturnType.isNull())
9401     RetTy = BSI->ReturnType;
9402 
9403   bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
9404   QualType BlockTy;
9405 
9406   // Set the captured variables on the block.
9407   // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
9408   SmallVector<BlockDecl::Capture, 4> Captures;
9409   for (unsigned i = 0, e = BSI->Captures.size(); i != e; i++) {
9410     CapturingScopeInfo::Capture &Cap = BSI->Captures[i];
9411     if (Cap.isThisCapture())
9412       continue;
9413     BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
9414                               Cap.isNested(), Cap.getCopyExpr());
9415     Captures.push_back(NewCap);
9416   }
9417   BSI->TheDecl->setCaptures(Context, Captures.begin(), Captures.end(),
9418                             BSI->CXXThisCaptureIndex != 0);
9419 
9420   // If the user wrote a function type in some form, try to use that.
9421   if (!BSI->FunctionType.isNull()) {
9422     const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
9423 
9424     FunctionType::ExtInfo Ext = FTy->getExtInfo();
9425     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
9426 
9427     // Turn protoless block types into nullary block types.
9428     if (isa<FunctionNoProtoType>(FTy)) {
9429       FunctionProtoType::ExtProtoInfo EPI;
9430       EPI.ExtInfo = Ext;
9431       BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
9432 
9433     // Otherwise, if we don't need to change anything about the function type,
9434     // preserve its sugar structure.
9435     } else if (FTy->getResultType() == RetTy &&
9436                (!NoReturn || FTy->getNoReturnAttr())) {
9437       BlockTy = BSI->FunctionType;
9438 
9439     // Otherwise, make the minimal modifications to the function type.
9440     } else {
9441       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
9442       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9443       EPI.TypeQuals = 0; // FIXME: silently?
9444       EPI.ExtInfo = Ext;
9445       BlockTy = Context.getFunctionType(RetTy,
9446                                         FPT->arg_type_begin(),
9447                                         FPT->getNumArgs(),
9448                                         EPI);
9449     }
9450 
9451   // If we don't have a function type, just build one from nothing.
9452   } else {
9453     FunctionProtoType::ExtProtoInfo EPI;
9454     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
9455     BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
9456   }
9457 
9458   DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
9459                            BSI->TheDecl->param_end());
9460   BlockTy = Context.getBlockPointerType(BlockTy);
9461 
9462   // If needed, diagnose invalid gotos and switches in the block.
9463   if (getCurFunction()->NeedsScopeChecking() &&
9464       !hasAnyUnrecoverableErrorsInThisFunction() &&
9465       !PP.isCodeCompletionEnabled())
9466     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
9467 
9468   BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
9469 
9470   // Try to apply the named return value optimization. We have to check again
9471   // if we can do this, though, because blocks keep return statements around
9472   // to deduce an implicit return type.
9473   if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
9474       !BSI->TheDecl->isDependentContext())
9475     computeNRVO(Body, getCurBlock());
9476 
9477   BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
9478   const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy();
9479   PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
9480 
9481   // If the block isn't obviously global, i.e. it captures anything at
9482   // all, then we need to do a few things in the surrounding context:
9483   if (Result->getBlockDecl()->hasCaptures()) {
9484     // First, this expression has a new cleanup object.
9485     ExprCleanupObjects.push_back(Result->getBlockDecl());
9486     ExprNeedsCleanups = true;
9487 
9488     // It also gets a branch-protected scope if any of the captured
9489     // variables needs destruction.
9490     for (BlockDecl::capture_const_iterator
9491            ci = Result->getBlockDecl()->capture_begin(),
9492            ce = Result->getBlockDecl()->capture_end(); ci != ce; ++ci) {
9493       const VarDecl *var = ci->getVariable();
9494       if (var->getType().isDestructedType() != QualType::DK_none) {
9495         getCurFunction()->setHasBranchProtectedScope();
9496         break;
9497       }
9498     }
9499   }
9500 
9501   return Owned(Result);
9502 }
9503 
9504 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
9505                                         Expr *E, ParsedType Ty,
9506                                         SourceLocation RPLoc) {
9507   TypeSourceInfo *TInfo;
9508   GetTypeFromParser(Ty, &TInfo);
9509   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
9510 }
9511 
9512 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
9513                                 Expr *E, TypeSourceInfo *TInfo,
9514                                 SourceLocation RPLoc) {
9515   Expr *OrigExpr = E;
9516 
9517   // Get the va_list type
9518   QualType VaListType = Context.getBuiltinVaListType();
9519   if (VaListType->isArrayType()) {
9520     // Deal with implicit array decay; for example, on x86-64,
9521     // va_list is an array, but it's supposed to decay to
9522     // a pointer for va_arg.
9523     VaListType = Context.getArrayDecayedType(VaListType);
9524     // Make sure the input expression also decays appropriately.
9525     ExprResult Result = UsualUnaryConversions(E);
9526     if (Result.isInvalid())
9527       return ExprError();
9528     E = Result.take();
9529   } else {
9530     // Otherwise, the va_list argument must be an l-value because
9531     // it is modified by va_arg.
9532     if (!E->isTypeDependent() &&
9533         CheckForModifiableLvalue(E, BuiltinLoc, *this))
9534       return ExprError();
9535   }
9536 
9537   if (!E->isTypeDependent() &&
9538       !Context.hasSameType(VaListType, E->getType())) {
9539     return ExprError(Diag(E->getLocStart(),
9540                          diag::err_first_argument_to_va_arg_not_of_type_va_list)
9541       << OrigExpr->getType() << E->getSourceRange());
9542   }
9543 
9544   if (!TInfo->getType()->isDependentType()) {
9545     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
9546                             diag::err_second_parameter_to_va_arg_incomplete,
9547                             TInfo->getTypeLoc()))
9548       return ExprError();
9549 
9550     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
9551                                TInfo->getType(),
9552                                diag::err_second_parameter_to_va_arg_abstract,
9553                                TInfo->getTypeLoc()))
9554       return ExprError();
9555 
9556     if (!TInfo->getType().isPODType(Context)) {
9557       Diag(TInfo->getTypeLoc().getBeginLoc(),
9558            TInfo->getType()->isObjCLifetimeType()
9559              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
9560              : diag::warn_second_parameter_to_va_arg_not_pod)
9561         << TInfo->getType()
9562         << TInfo->getTypeLoc().getSourceRange();
9563     }
9564 
9565     // Check for va_arg where arguments of the given type will be promoted
9566     // (i.e. this va_arg is guaranteed to have undefined behavior).
9567     QualType PromoteType;
9568     if (TInfo->getType()->isPromotableIntegerType()) {
9569       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
9570       if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
9571         PromoteType = QualType();
9572     }
9573     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
9574       PromoteType = Context.DoubleTy;
9575     if (!PromoteType.isNull())
9576       Diag(TInfo->getTypeLoc().getBeginLoc(),
9577           diag::warn_second_parameter_to_va_arg_never_compatible)
9578         << TInfo->getType()
9579         << PromoteType
9580         << TInfo->getTypeLoc().getSourceRange();
9581   }
9582 
9583   QualType T = TInfo->getType().getNonLValueExprType(Context);
9584   return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
9585 }
9586 
9587 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
9588   // The type of __null will be int or long, depending on the size of
9589   // pointers on the target.
9590   QualType Ty;
9591   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
9592   if (pw == Context.getTargetInfo().getIntWidth())
9593     Ty = Context.IntTy;
9594   else if (pw == Context.getTargetInfo().getLongWidth())
9595     Ty = Context.LongTy;
9596   else if (pw == Context.getTargetInfo().getLongLongWidth())
9597     Ty = Context.LongLongTy;
9598   else {
9599     llvm_unreachable("I don't know size of pointer!");
9600   }
9601 
9602   return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
9603 }
9604 
9605 static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
9606                                            Expr *SrcExpr, FixItHint &Hint) {
9607   if (!SemaRef.getLangOpts().ObjC1)
9608     return;
9609 
9610   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
9611   if (!PT)
9612     return;
9613 
9614   // Check if the destination is of type 'id'.
9615   if (!PT->isObjCIdType()) {
9616     // Check if the destination is the 'NSString' interface.
9617     const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
9618     if (!ID || !ID->getIdentifier()->isStr("NSString"))
9619       return;
9620   }
9621 
9622   // Ignore any parens, implicit casts (should only be
9623   // array-to-pointer decays), and not-so-opaque values.  The last is
9624   // important for making this trigger for property assignments.
9625   SrcExpr = SrcExpr->IgnoreParenImpCasts();
9626   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
9627     if (OV->getSourceExpr())
9628       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
9629 
9630   StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
9631   if (!SL || !SL->isAscii())
9632     return;
9633 
9634   Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
9635 }
9636 
9637 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
9638                                     SourceLocation Loc,
9639                                     QualType DstType, QualType SrcType,
9640                                     Expr *SrcExpr, AssignmentAction Action,
9641                                     bool *Complained) {
9642   if (Complained)
9643     *Complained = false;
9644 
9645   // Decode the result (notice that AST's are still created for extensions).
9646   bool CheckInferredResultType = false;
9647   bool isInvalid = false;
9648   unsigned DiagKind = 0;
9649   FixItHint Hint;
9650   ConversionFixItGenerator ConvHints;
9651   bool MayHaveConvFixit = false;
9652   bool MayHaveFunctionDiff = false;
9653 
9654   switch (ConvTy) {
9655   case Compatible:
9656       DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
9657       return false;
9658 
9659   case PointerToInt:
9660     DiagKind = diag::ext_typecheck_convert_pointer_int;
9661     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9662     MayHaveConvFixit = true;
9663     break;
9664   case IntToPointer:
9665     DiagKind = diag::ext_typecheck_convert_int_pointer;
9666     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9667     MayHaveConvFixit = true;
9668     break;
9669   case IncompatiblePointer:
9670     MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
9671     DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
9672     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
9673       SrcType->isObjCObjectPointerType();
9674     if (Hint.isNull() && !CheckInferredResultType) {
9675       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9676     }
9677     MayHaveConvFixit = true;
9678     break;
9679   case IncompatiblePointerSign:
9680     DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
9681     break;
9682   case FunctionVoidPointer:
9683     DiagKind = diag::ext_typecheck_convert_pointer_void_func;
9684     break;
9685   case IncompatiblePointerDiscardsQualifiers: {
9686     // Perform array-to-pointer decay if necessary.
9687     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
9688 
9689     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
9690     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
9691     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
9692       DiagKind = diag::err_typecheck_incompatible_address_space;
9693       break;
9694 
9695 
9696     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
9697       DiagKind = diag::err_typecheck_incompatible_ownership;
9698       break;
9699     }
9700 
9701     llvm_unreachable("unknown error case for discarding qualifiers!");
9702     // fallthrough
9703   }
9704   case CompatiblePointerDiscardsQualifiers:
9705     // If the qualifiers lost were because we were applying the
9706     // (deprecated) C++ conversion from a string literal to a char*
9707     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
9708     // Ideally, this check would be performed in
9709     // checkPointerTypesForAssignment. However, that would require a
9710     // bit of refactoring (so that the second argument is an
9711     // expression, rather than a type), which should be done as part
9712     // of a larger effort to fix checkPointerTypesForAssignment for
9713     // C++ semantics.
9714     if (getLangOpts().CPlusPlus &&
9715         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
9716       return false;
9717     DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
9718     break;
9719   case IncompatibleNestedPointerQualifiers:
9720     DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
9721     break;
9722   case IntToBlockPointer:
9723     DiagKind = diag::err_int_to_block_pointer;
9724     break;
9725   case IncompatibleBlockPointer:
9726     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
9727     break;
9728   case IncompatibleObjCQualifiedId:
9729     // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
9730     // it can give a more specific diagnostic.
9731     DiagKind = diag::warn_incompatible_qualified_id;
9732     break;
9733   case IncompatibleVectors:
9734     DiagKind = diag::warn_incompatible_vectors;
9735     break;
9736   case IncompatibleObjCWeakRef:
9737     DiagKind = diag::err_arc_weak_unavailable_assign;
9738     break;
9739   case Incompatible:
9740     DiagKind = diag::err_typecheck_convert_incompatible;
9741     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9742     MayHaveConvFixit = true;
9743     isInvalid = true;
9744     MayHaveFunctionDiff = true;
9745     break;
9746   }
9747 
9748   QualType FirstType, SecondType;
9749   switch (Action) {
9750   case AA_Assigning:
9751   case AA_Initializing:
9752     // The destination type comes first.
9753     FirstType = DstType;
9754     SecondType = SrcType;
9755     break;
9756 
9757   case AA_Returning:
9758   case AA_Passing:
9759   case AA_Converting:
9760   case AA_Sending:
9761   case AA_Casting:
9762     // The source type comes first.
9763     FirstType = SrcType;
9764     SecondType = DstType;
9765     break;
9766   }
9767 
9768   PartialDiagnostic FDiag = PDiag(DiagKind);
9769   FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
9770 
9771   // If we can fix the conversion, suggest the FixIts.
9772   assert(ConvHints.isNull() || Hint.isNull());
9773   if (!ConvHints.isNull()) {
9774     for (std::vector<FixItHint>::iterator HI = ConvHints.Hints.begin(),
9775          HE = ConvHints.Hints.end(); HI != HE; ++HI)
9776       FDiag << *HI;
9777   } else {
9778     FDiag << Hint;
9779   }
9780   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
9781 
9782   if (MayHaveFunctionDiff)
9783     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
9784 
9785   Diag(Loc, FDiag);
9786 
9787   if (SecondType == Context.OverloadTy)
9788     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
9789                               FirstType);
9790 
9791   if (CheckInferredResultType)
9792     EmitRelatedResultTypeNote(SrcExpr);
9793 
9794   if (Complained)
9795     *Complained = true;
9796   return isInvalid;
9797 }
9798 
9799 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
9800                                                  llvm::APSInt *Result) {
9801   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
9802   public:
9803     virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
9804       S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
9805     }
9806   } Diagnoser;
9807 
9808   return VerifyIntegerConstantExpression(E, Result, Diagnoser);
9809 }
9810 
9811 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
9812                                                  llvm::APSInt *Result,
9813                                                  unsigned DiagID,
9814                                                  bool AllowFold) {
9815   class IDDiagnoser : public VerifyICEDiagnoser {
9816     unsigned DiagID;
9817 
9818   public:
9819     IDDiagnoser(unsigned DiagID)
9820       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
9821 
9822     virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
9823       S.Diag(Loc, DiagID) << SR;
9824     }
9825   } Diagnoser(DiagID);
9826 
9827   return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
9828 }
9829 
9830 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
9831                                             SourceRange SR) {
9832   S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
9833 }
9834 
9835 ExprResult
9836 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
9837                                       VerifyICEDiagnoser &Diagnoser,
9838                                       bool AllowFold) {
9839   SourceLocation DiagLoc = E->getLocStart();
9840 
9841   if (getLangOpts().CPlusPlus0x) {
9842     // C++11 [expr.const]p5:
9843     //   If an expression of literal class type is used in a context where an
9844     //   integral constant expression is required, then that class type shall
9845     //   have a single non-explicit conversion function to an integral or
9846     //   unscoped enumeration type
9847     ExprResult Converted;
9848     if (!Diagnoser.Suppress) {
9849       class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
9850       public:
9851         CXX11ConvertDiagnoser() : ICEConvertDiagnoser(false, true) { }
9852 
9853         virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
9854                                                  QualType T) {
9855           return S.Diag(Loc, diag::err_ice_not_integral) << T;
9856         }
9857 
9858         virtual DiagnosticBuilder diagnoseIncomplete(Sema &S,
9859                                                      SourceLocation Loc,
9860                                                      QualType T) {
9861           return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
9862         }
9863 
9864         virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S,
9865                                                        SourceLocation Loc,
9866                                                        QualType T,
9867                                                        QualType ConvTy) {
9868           return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
9869         }
9870 
9871         virtual DiagnosticBuilder noteExplicitConv(Sema &S,
9872                                                    CXXConversionDecl *Conv,
9873                                                    QualType ConvTy) {
9874           return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
9875                    << ConvTy->isEnumeralType() << ConvTy;
9876         }
9877 
9878         virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
9879                                                     QualType T) {
9880           return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
9881         }
9882 
9883         virtual DiagnosticBuilder noteAmbiguous(Sema &S,
9884                                                 CXXConversionDecl *Conv,
9885                                                 QualType ConvTy) {
9886           return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
9887                    << ConvTy->isEnumeralType() << ConvTy;
9888         }
9889 
9890         virtual DiagnosticBuilder diagnoseConversion(Sema &S,
9891                                                      SourceLocation Loc,
9892                                                      QualType T,
9893                                                      QualType ConvTy) {
9894           return DiagnosticBuilder::getEmpty();
9895         }
9896       } ConvertDiagnoser;
9897 
9898       Converted = ConvertToIntegralOrEnumerationType(DiagLoc, E,
9899                                                      ConvertDiagnoser,
9900                                              /*AllowScopedEnumerations*/ false);
9901     } else {
9902       // The caller wants to silently enquire whether this is an ICE. Don't
9903       // produce any diagnostics if it isn't.
9904       class SilentICEConvertDiagnoser : public ICEConvertDiagnoser {
9905       public:
9906         SilentICEConvertDiagnoser() : ICEConvertDiagnoser(true, true) { }
9907 
9908         virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
9909                                                  QualType T) {
9910           return DiagnosticBuilder::getEmpty();
9911         }
9912 
9913         virtual DiagnosticBuilder diagnoseIncomplete(Sema &S,
9914                                                      SourceLocation Loc,
9915                                                      QualType T) {
9916           return DiagnosticBuilder::getEmpty();
9917         }
9918 
9919         virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S,
9920                                                        SourceLocation Loc,
9921                                                        QualType T,
9922                                                        QualType ConvTy) {
9923           return DiagnosticBuilder::getEmpty();
9924         }
9925 
9926         virtual DiagnosticBuilder noteExplicitConv(Sema &S,
9927                                                    CXXConversionDecl *Conv,
9928                                                    QualType ConvTy) {
9929           return DiagnosticBuilder::getEmpty();
9930         }
9931 
9932         virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
9933                                                     QualType T) {
9934           return DiagnosticBuilder::getEmpty();
9935         }
9936 
9937         virtual DiagnosticBuilder noteAmbiguous(Sema &S,
9938                                                 CXXConversionDecl *Conv,
9939                                                 QualType ConvTy) {
9940           return DiagnosticBuilder::getEmpty();
9941         }
9942 
9943         virtual DiagnosticBuilder diagnoseConversion(Sema &S,
9944                                                      SourceLocation Loc,
9945                                                      QualType T,
9946                                                      QualType ConvTy) {
9947           return DiagnosticBuilder::getEmpty();
9948         }
9949       } ConvertDiagnoser;
9950 
9951       Converted = ConvertToIntegralOrEnumerationType(DiagLoc, E,
9952                                                      ConvertDiagnoser, false);
9953     }
9954     if (Converted.isInvalid())
9955       return Converted;
9956     E = Converted.take();
9957     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
9958       return ExprError();
9959   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
9960     // An ICE must be of integral or unscoped enumeration type.
9961     if (!Diagnoser.Suppress)
9962       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
9963     return ExprError();
9964   }
9965 
9966   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
9967   // in the non-ICE case.
9968   if (!getLangOpts().CPlusPlus0x && E->isIntegerConstantExpr(Context)) {
9969     if (Result)
9970       *Result = E->EvaluateKnownConstInt(Context);
9971     return Owned(E);
9972   }
9973 
9974   Expr::EvalResult EvalResult;
9975   llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
9976   EvalResult.Diag = &Notes;
9977 
9978   // Try to evaluate the expression, and produce diagnostics explaining why it's
9979   // not a constant expression as a side-effect.
9980   bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
9981                 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
9982 
9983   // In C++11, we can rely on diagnostics being produced for any expression
9984   // which is not a constant expression. If no diagnostics were produced, then
9985   // this is a constant expression.
9986   if (Folded && getLangOpts().CPlusPlus0x && Notes.empty()) {
9987     if (Result)
9988       *Result = EvalResult.Val.getInt();
9989     return Owned(E);
9990   }
9991 
9992   // If our only note is the usual "invalid subexpression" note, just point
9993   // the caret at its location rather than producing an essentially
9994   // redundant note.
9995   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
9996         diag::note_invalid_subexpr_in_const_expr) {
9997     DiagLoc = Notes[0].first;
9998     Notes.clear();
9999   }
10000 
10001   if (!Folded || !AllowFold) {
10002     if (!Diagnoser.Suppress) {
10003       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
10004       for (unsigned I = 0, N = Notes.size(); I != N; ++I)
10005         Diag(Notes[I].first, Notes[I].second);
10006     }
10007 
10008     return ExprError();
10009   }
10010 
10011   Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
10012   for (unsigned I = 0, N = Notes.size(); I != N; ++I)
10013     Diag(Notes[I].first, Notes[I].second);
10014 
10015   if (Result)
10016     *Result = EvalResult.Val.getInt();
10017   return Owned(E);
10018 }
10019 
10020 namespace {
10021   // Handle the case where we conclude a expression which we speculatively
10022   // considered to be unevaluated is actually evaluated.
10023   class TransformToPE : public TreeTransform<TransformToPE> {
10024     typedef TreeTransform<TransformToPE> BaseTransform;
10025 
10026   public:
10027     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
10028 
10029     // Make sure we redo semantic analysis
10030     bool AlwaysRebuild() { return true; }
10031 
10032     // Make sure we handle LabelStmts correctly.
10033     // FIXME: This does the right thing, but maybe we need a more general
10034     // fix to TreeTransform?
10035     StmtResult TransformLabelStmt(LabelStmt *S) {
10036       S->getDecl()->setStmt(0);
10037       return BaseTransform::TransformLabelStmt(S);
10038     }
10039 
10040     // We need to special-case DeclRefExprs referring to FieldDecls which
10041     // are not part of a member pointer formation; normal TreeTransforming
10042     // doesn't catch this case because of the way we represent them in the AST.
10043     // FIXME: This is a bit ugly; is it really the best way to handle this
10044     // case?
10045     //
10046     // Error on DeclRefExprs referring to FieldDecls.
10047     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
10048       if (isa<FieldDecl>(E->getDecl()) &&
10049           !SemaRef.isUnevaluatedContext())
10050         return SemaRef.Diag(E->getLocation(),
10051                             diag::err_invalid_non_static_member_use)
10052             << E->getDecl() << E->getSourceRange();
10053 
10054       return BaseTransform::TransformDeclRefExpr(E);
10055     }
10056 
10057     // Exception: filter out member pointer formation
10058     ExprResult TransformUnaryOperator(UnaryOperator *E) {
10059       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
10060         return E;
10061 
10062       return BaseTransform::TransformUnaryOperator(E);
10063     }
10064 
10065     ExprResult TransformLambdaExpr(LambdaExpr *E) {
10066       // Lambdas never need to be transformed.
10067       return E;
10068     }
10069   };
10070 }
10071 
10072 ExprResult Sema::TranformToPotentiallyEvaluated(Expr *E) {
10073   assert(ExprEvalContexts.back().Context == Unevaluated &&
10074          "Should only transform unevaluated expressions");
10075   ExprEvalContexts.back().Context =
10076       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
10077   if (ExprEvalContexts.back().Context == Unevaluated)
10078     return E;
10079   return TransformToPE(*this).TransformExpr(E);
10080 }
10081 
10082 void
10083 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
10084                                       Decl *LambdaContextDecl,
10085                                       bool IsDecltype) {
10086   ExprEvalContexts.push_back(
10087              ExpressionEvaluationContextRecord(NewContext,
10088                                                ExprCleanupObjects.size(),
10089                                                ExprNeedsCleanups,
10090                                                LambdaContextDecl,
10091                                                IsDecltype));
10092   ExprNeedsCleanups = false;
10093   if (!MaybeODRUseExprs.empty())
10094     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
10095 }
10096 
10097 void Sema::PopExpressionEvaluationContext() {
10098   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
10099 
10100   if (!Rec.Lambdas.empty()) {
10101     if (Rec.Context == Unevaluated) {
10102       // C++11 [expr.prim.lambda]p2:
10103       //   A lambda-expression shall not appear in an unevaluated operand
10104       //   (Clause 5).
10105       for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I)
10106         Diag(Rec.Lambdas[I]->getLocStart(),
10107              diag::err_lambda_unevaluated_operand);
10108     } else {
10109       // Mark the capture expressions odr-used. This was deferred
10110       // during lambda expression creation.
10111       for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I) {
10112         LambdaExpr *Lambda = Rec.Lambdas[I];
10113         for (LambdaExpr::capture_init_iterator
10114                   C = Lambda->capture_init_begin(),
10115                CEnd = Lambda->capture_init_end();
10116              C != CEnd; ++C) {
10117           MarkDeclarationsReferencedInExpr(*C);
10118         }
10119       }
10120     }
10121   }
10122 
10123   // When are coming out of an unevaluated context, clear out any
10124   // temporaries that we may have created as part of the evaluation of
10125   // the expression in that context: they aren't relevant because they
10126   // will never be constructed.
10127   if (Rec.Context == Unevaluated || Rec.Context == ConstantEvaluated) {
10128     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
10129                              ExprCleanupObjects.end());
10130     ExprNeedsCleanups = Rec.ParentNeedsCleanups;
10131     CleanupVarDeclMarking();
10132     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
10133   // Otherwise, merge the contexts together.
10134   } else {
10135     ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
10136     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
10137                             Rec.SavedMaybeODRUseExprs.end());
10138   }
10139 
10140   // Pop the current expression evaluation context off the stack.
10141   ExprEvalContexts.pop_back();
10142 }
10143 
10144 void Sema::DiscardCleanupsInEvaluationContext() {
10145   ExprCleanupObjects.erase(
10146          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
10147          ExprCleanupObjects.end());
10148   ExprNeedsCleanups = false;
10149   MaybeODRUseExprs.clear();
10150 }
10151 
10152 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
10153   if (!E->getType()->isVariablyModifiedType())
10154     return E;
10155   return TranformToPotentiallyEvaluated(E);
10156 }
10157 
10158 static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) {
10159   // Do not mark anything as "used" within a dependent context; wait for
10160   // an instantiation.
10161   if (SemaRef.CurContext->isDependentContext())
10162     return false;
10163 
10164   switch (SemaRef.ExprEvalContexts.back().Context) {
10165     case Sema::Unevaluated:
10166       // We are in an expression that is not potentially evaluated; do nothing.
10167       // (Depending on how you read the standard, we actually do need to do
10168       // something here for null pointer constants, but the standard's
10169       // definition of a null pointer constant is completely crazy.)
10170       return false;
10171 
10172     case Sema::ConstantEvaluated:
10173     case Sema::PotentiallyEvaluated:
10174       // We are in a potentially evaluated expression (or a constant-expression
10175       // in C++03); we need to do implicit template instantiation, implicitly
10176       // define class members, and mark most declarations as used.
10177       return true;
10178 
10179     case Sema::PotentiallyEvaluatedIfUsed:
10180       // Referenced declarations will only be used if the construct in the
10181       // containing expression is used.
10182       return false;
10183   }
10184   llvm_unreachable("Invalid context");
10185 }
10186 
10187 /// \brief Mark a function referenced, and check whether it is odr-used
10188 /// (C++ [basic.def.odr]p2, C99 6.9p3)
10189 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func) {
10190   assert(Func && "No function?");
10191 
10192   Func->setReferenced();
10193 
10194   // Don't mark this function as used multiple times, unless it's a constexpr
10195   // function which we need to instantiate.
10196   if (Func->isUsed(false) &&
10197       !(Func->isConstexpr() && !Func->getBody() &&
10198         Func->isImplicitlyInstantiable()))
10199     return;
10200 
10201   if (!IsPotentiallyEvaluatedContext(*this))
10202     return;
10203 
10204   // Note that this declaration has been used.
10205   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
10206     if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
10207       if (Constructor->isDefaultConstructor()) {
10208         if (Constructor->isTrivial())
10209           return;
10210         if (!Constructor->isUsed(false))
10211           DefineImplicitDefaultConstructor(Loc, Constructor);
10212       } else if (Constructor->isCopyConstructor()) {
10213         if (!Constructor->isUsed(false))
10214           DefineImplicitCopyConstructor(Loc, Constructor);
10215       } else if (Constructor->isMoveConstructor()) {
10216         if (!Constructor->isUsed(false))
10217           DefineImplicitMoveConstructor(Loc, Constructor);
10218       }
10219     }
10220 
10221     MarkVTableUsed(Loc, Constructor->getParent());
10222   } else if (CXXDestructorDecl *Destructor =
10223                  dyn_cast<CXXDestructorDecl>(Func)) {
10224     if (Destructor->isDefaulted() && !Destructor->isDeleted() &&
10225         !Destructor->isUsed(false))
10226       DefineImplicitDestructor(Loc, Destructor);
10227     if (Destructor->isVirtual())
10228       MarkVTableUsed(Loc, Destructor->getParent());
10229   } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
10230     if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted() &&
10231         MethodDecl->isOverloadedOperator() &&
10232         MethodDecl->getOverloadedOperator() == OO_Equal) {
10233       if (!MethodDecl->isUsed(false)) {
10234         if (MethodDecl->isCopyAssignmentOperator())
10235           DefineImplicitCopyAssignment(Loc, MethodDecl);
10236         else
10237           DefineImplicitMoveAssignment(Loc, MethodDecl);
10238       }
10239     } else if (isa<CXXConversionDecl>(MethodDecl) &&
10240                MethodDecl->getParent()->isLambda()) {
10241       CXXConversionDecl *Conversion = cast<CXXConversionDecl>(MethodDecl);
10242       if (Conversion->isLambdaToBlockPointerConversion())
10243         DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
10244       else
10245         DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
10246     } else if (MethodDecl->isVirtual())
10247       MarkVTableUsed(Loc, MethodDecl->getParent());
10248   }
10249 
10250   // Recursive functions should be marked when used from another function.
10251   // FIXME: Is this really right?
10252   if (CurContext == Func) return;
10253 
10254   // Resolve the exception specification for any function which is
10255   // used: CodeGen will need it.
10256   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
10257   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
10258     ResolveExceptionSpec(Loc, FPT);
10259 
10260   // Implicit instantiation of function templates and member functions of
10261   // class templates.
10262   if (Func->isImplicitlyInstantiable()) {
10263     bool AlreadyInstantiated = false;
10264     SourceLocation PointOfInstantiation = Loc;
10265     if (FunctionTemplateSpecializationInfo *SpecInfo
10266                               = Func->getTemplateSpecializationInfo()) {
10267       if (SpecInfo->getPointOfInstantiation().isInvalid())
10268         SpecInfo->setPointOfInstantiation(Loc);
10269       else if (SpecInfo->getTemplateSpecializationKind()
10270                  == TSK_ImplicitInstantiation) {
10271         AlreadyInstantiated = true;
10272         PointOfInstantiation = SpecInfo->getPointOfInstantiation();
10273       }
10274     } else if (MemberSpecializationInfo *MSInfo
10275                                 = Func->getMemberSpecializationInfo()) {
10276       if (MSInfo->getPointOfInstantiation().isInvalid())
10277         MSInfo->setPointOfInstantiation(Loc);
10278       else if (MSInfo->getTemplateSpecializationKind()
10279                  == TSK_ImplicitInstantiation) {
10280         AlreadyInstantiated = true;
10281         PointOfInstantiation = MSInfo->getPointOfInstantiation();
10282       }
10283     }
10284 
10285     if (!AlreadyInstantiated || Func->isConstexpr()) {
10286       if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
10287           cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass())
10288         PendingLocalImplicitInstantiations.push_back(
10289             std::make_pair(Func, PointOfInstantiation));
10290       else if (Func->isConstexpr())
10291         // Do not defer instantiations of constexpr functions, to avoid the
10292         // expression evaluator needing to call back into Sema if it sees a
10293         // call to such a function.
10294         InstantiateFunctionDefinition(PointOfInstantiation, Func);
10295       else {
10296         PendingInstantiations.push_back(std::make_pair(Func,
10297                                                        PointOfInstantiation));
10298         // Notify the consumer that a function was implicitly instantiated.
10299         Consumer.HandleCXXImplicitFunctionInstantiation(Func);
10300       }
10301     }
10302   } else {
10303     // Walk redefinitions, as some of them may be instantiable.
10304     for (FunctionDecl::redecl_iterator i(Func->redecls_begin()),
10305          e(Func->redecls_end()); i != e; ++i) {
10306       if (!i->isUsed(false) && i->isImplicitlyInstantiable())
10307         MarkFunctionReferenced(Loc, *i);
10308     }
10309   }
10310 
10311   // Keep track of used but undefined functions.
10312   if (!Func->isPure() && !Func->hasBody() &&
10313       Func->getLinkage() != ExternalLinkage) {
10314     SourceLocation &old = UndefinedInternals[Func->getCanonicalDecl()];
10315     if (old.isInvalid()) old = Loc;
10316   }
10317 
10318   Func->setUsed(true);
10319 }
10320 
10321 static void
10322 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
10323                                    VarDecl *var, DeclContext *DC) {
10324   DeclContext *VarDC = var->getDeclContext();
10325 
10326   //  If the parameter still belongs to the translation unit, then
10327   //  we're actually just using one parameter in the declaration of
10328   //  the next.
10329   if (isa<ParmVarDecl>(var) &&
10330       isa<TranslationUnitDecl>(VarDC))
10331     return;
10332 
10333   // For C code, don't diagnose about capture if we're not actually in code
10334   // right now; it's impossible to write a non-constant expression outside of
10335   // function context, so we'll get other (more useful) diagnostics later.
10336   //
10337   // For C++, things get a bit more nasty... it would be nice to suppress this
10338   // diagnostic for certain cases like using a local variable in an array bound
10339   // for a member of a local class, but the correct predicate is not obvious.
10340   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
10341     return;
10342 
10343   if (isa<CXXMethodDecl>(VarDC) &&
10344       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
10345     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda)
10346       << var->getIdentifier();
10347   } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) {
10348     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
10349       << var->getIdentifier() << fn->getDeclName();
10350   } else if (isa<BlockDecl>(VarDC)) {
10351     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block)
10352       << var->getIdentifier();
10353   } else {
10354     // FIXME: Is there any other context where a local variable can be
10355     // declared?
10356     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context)
10357       << var->getIdentifier();
10358   }
10359 
10360   S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
10361     << var->getIdentifier();
10362 
10363   // FIXME: Add additional diagnostic info about class etc. which prevents
10364   // capture.
10365 }
10366 
10367 /// \brief Capture the given variable in the given lambda expression.
10368 static ExprResult captureInLambda(Sema &S, LambdaScopeInfo *LSI,
10369                                   VarDecl *Var, QualType FieldType,
10370                                   QualType DeclRefType,
10371                                   SourceLocation Loc,
10372                                   bool RefersToEnclosingLocal) {
10373   CXXRecordDecl *Lambda = LSI->Lambda;
10374 
10375   // Build the non-static data member.
10376   FieldDecl *Field
10377     = FieldDecl::Create(S.Context, Lambda, Loc, Loc, 0, FieldType,
10378                         S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
10379                         0, false, ICIS_NoInit);
10380   Field->setImplicit(true);
10381   Field->setAccess(AS_private);
10382   Lambda->addDecl(Field);
10383 
10384   // C++11 [expr.prim.lambda]p21:
10385   //   When the lambda-expression is evaluated, the entities that
10386   //   are captured by copy are used to direct-initialize each
10387   //   corresponding non-static data member of the resulting closure
10388   //   object. (For array members, the array elements are
10389   //   direct-initialized in increasing subscript order.) These
10390   //   initializations are performed in the (unspecified) order in
10391   //   which the non-static data members are declared.
10392 
10393   // Introduce a new evaluation context for the initialization, so
10394   // that temporaries introduced as part of the capture are retained
10395   // to be re-"exported" from the lambda expression itself.
10396   S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
10397 
10398   // C++ [expr.prim.labda]p12:
10399   //   An entity captured by a lambda-expression is odr-used (3.2) in
10400   //   the scope containing the lambda-expression.
10401   Expr *Ref = new (S.Context) DeclRefExpr(Var, RefersToEnclosingLocal,
10402                                           DeclRefType, VK_LValue, Loc);
10403   Var->setReferenced(true);
10404   Var->setUsed(true);
10405 
10406   // When the field has array type, create index variables for each
10407   // dimension of the array. We use these index variables to subscript
10408   // the source array, and other clients (e.g., CodeGen) will perform
10409   // the necessary iteration with these index variables.
10410   SmallVector<VarDecl *, 4> IndexVariables;
10411   QualType BaseType = FieldType;
10412   QualType SizeType = S.Context.getSizeType();
10413   LSI->ArrayIndexStarts.push_back(LSI->ArrayIndexVars.size());
10414   while (const ConstantArrayType *Array
10415                         = S.Context.getAsConstantArrayType(BaseType)) {
10416     // Create the iteration variable for this array index.
10417     IdentifierInfo *IterationVarName = 0;
10418     {
10419       SmallString<8> Str;
10420       llvm::raw_svector_ostream OS(Str);
10421       OS << "__i" << IndexVariables.size();
10422       IterationVarName = &S.Context.Idents.get(OS.str());
10423     }
10424     VarDecl *IterationVar
10425       = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
10426                         IterationVarName, SizeType,
10427                         S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
10428                         SC_None, SC_None);
10429     IndexVariables.push_back(IterationVar);
10430     LSI->ArrayIndexVars.push_back(IterationVar);
10431 
10432     // Create a reference to the iteration variable.
10433     ExprResult IterationVarRef
10434       = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
10435     assert(!IterationVarRef.isInvalid() &&
10436            "Reference to invented variable cannot fail!");
10437     IterationVarRef = S.DefaultLvalueConversion(IterationVarRef.take());
10438     assert(!IterationVarRef.isInvalid() &&
10439            "Conversion of invented variable cannot fail!");
10440 
10441     // Subscript the array with this iteration variable.
10442     ExprResult Subscript = S.CreateBuiltinArraySubscriptExpr(
10443                              Ref, Loc, IterationVarRef.take(), Loc);
10444     if (Subscript.isInvalid()) {
10445       S.CleanupVarDeclMarking();
10446       S.DiscardCleanupsInEvaluationContext();
10447       S.PopExpressionEvaluationContext();
10448       return ExprError();
10449     }
10450 
10451     Ref = Subscript.take();
10452     BaseType = Array->getElementType();
10453   }
10454 
10455   // Construct the entity that we will be initializing. For an array, this
10456   // will be first element in the array, which may require several levels
10457   // of array-subscript entities.
10458   SmallVector<InitializedEntity, 4> Entities;
10459   Entities.reserve(1 + IndexVariables.size());
10460   Entities.push_back(
10461     InitializedEntity::InitializeLambdaCapture(Var, Field, Loc));
10462   for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
10463     Entities.push_back(InitializedEntity::InitializeElement(S.Context,
10464                                                             0,
10465                                                             Entities.back()));
10466 
10467   InitializationKind InitKind
10468     = InitializationKind::CreateDirect(Loc, Loc, Loc);
10469   InitializationSequence Init(S, Entities.back(), InitKind, &Ref, 1);
10470   ExprResult Result(true);
10471   if (!Init.Diagnose(S, Entities.back(), InitKind, &Ref, 1))
10472     Result = Init.Perform(S, Entities.back(), InitKind,
10473                           MultiExprArg(S, &Ref, 1));
10474 
10475   // If this initialization requires any cleanups (e.g., due to a
10476   // default argument to a copy constructor), note that for the
10477   // lambda.
10478   if (S.ExprNeedsCleanups)
10479     LSI->ExprNeedsCleanups = true;
10480 
10481   // Exit the expression evaluation context used for the capture.
10482   S.CleanupVarDeclMarking();
10483   S.DiscardCleanupsInEvaluationContext();
10484   S.PopExpressionEvaluationContext();
10485   return Result;
10486 }
10487 
10488 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
10489                               TryCaptureKind Kind, SourceLocation EllipsisLoc,
10490                               bool BuildAndDiagnose,
10491                               QualType &CaptureType,
10492                               QualType &DeclRefType) {
10493   bool Nested = false;
10494 
10495   DeclContext *DC = CurContext;
10496   if (Var->getDeclContext() == DC) return true;
10497   if (!Var->hasLocalStorage()) return true;
10498 
10499   bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
10500 
10501   // Walk up the stack to determine whether we can capture the variable,
10502   // performing the "simple" checks that don't depend on type. We stop when
10503   // we've either hit the declared scope of the variable or find an existing
10504   // capture of that variable.
10505   CaptureType = Var->getType();
10506   DeclRefType = CaptureType.getNonReferenceType();
10507   bool Explicit = (Kind != TryCapture_Implicit);
10508   unsigned FunctionScopesIndex = FunctionScopes.size() - 1;
10509   do {
10510     // Only block literals and lambda expressions can capture; other
10511     // scopes don't work.
10512     DeclContext *ParentDC;
10513     if (isa<BlockDecl>(DC))
10514       ParentDC = DC->getParent();
10515     else if (isa<CXXMethodDecl>(DC) &&
10516              cast<CXXMethodDecl>(DC)->getOverloadedOperator() == OO_Call &&
10517              cast<CXXRecordDecl>(DC->getParent())->isLambda())
10518       ParentDC = DC->getParent()->getParent();
10519     else {
10520       if (BuildAndDiagnose)
10521         diagnoseUncapturableValueReference(*this, Loc, Var, DC);
10522       return true;
10523     }
10524 
10525     CapturingScopeInfo *CSI =
10526       cast<CapturingScopeInfo>(FunctionScopes[FunctionScopesIndex]);
10527 
10528     // Check whether we've already captured it.
10529     if (CSI->CaptureMap.count(Var)) {
10530       // If we found a capture, any subcaptures are nested.
10531       Nested = true;
10532 
10533       // Retrieve the capture type for this variable.
10534       CaptureType = CSI->getCapture(Var).getCaptureType();
10535 
10536       // Compute the type of an expression that refers to this variable.
10537       DeclRefType = CaptureType.getNonReferenceType();
10538 
10539       const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var);
10540       if (Cap.isCopyCapture() &&
10541           !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable))
10542         DeclRefType.addConst();
10543       break;
10544     }
10545 
10546     bool IsBlock = isa<BlockScopeInfo>(CSI);
10547     bool IsLambda = !IsBlock;
10548 
10549     // Lambdas are not allowed to capture unnamed variables
10550     // (e.g. anonymous unions).
10551     // FIXME: The C++11 rule don't actually state this explicitly, but I'm
10552     // assuming that's the intent.
10553     if (IsLambda && !Var->getDeclName()) {
10554       if (BuildAndDiagnose) {
10555         Diag(Loc, diag::err_lambda_capture_anonymous_var);
10556         Diag(Var->getLocation(), diag::note_declared_at);
10557       }
10558       return true;
10559     }
10560 
10561     // Prohibit variably-modified types; they're difficult to deal with.
10562     if (Var->getType()->isVariablyModifiedType()) {
10563       if (BuildAndDiagnose) {
10564         if (IsBlock)
10565           Diag(Loc, diag::err_ref_vm_type);
10566         else
10567           Diag(Loc, diag::err_lambda_capture_vm_type) << Var->getDeclName();
10568         Diag(Var->getLocation(), diag::note_previous_decl)
10569           << Var->getDeclName();
10570       }
10571       return true;
10572     }
10573 
10574     // Lambdas are not allowed to capture __block variables; they don't
10575     // support the expected semantics.
10576     if (IsLambda && HasBlocksAttr) {
10577       if (BuildAndDiagnose) {
10578         Diag(Loc, diag::err_lambda_capture_block)
10579           << Var->getDeclName();
10580         Diag(Var->getLocation(), diag::note_previous_decl)
10581           << Var->getDeclName();
10582       }
10583       return true;
10584     }
10585 
10586     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
10587       // No capture-default
10588       if (BuildAndDiagnose) {
10589         Diag(Loc, diag::err_lambda_impcap) << Var->getDeclName();
10590         Diag(Var->getLocation(), diag::note_previous_decl)
10591           << Var->getDeclName();
10592         Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
10593              diag::note_lambda_decl);
10594       }
10595       return true;
10596     }
10597 
10598     FunctionScopesIndex--;
10599     DC = ParentDC;
10600     Explicit = false;
10601   } while (!Var->getDeclContext()->Equals(DC));
10602 
10603   // Walk back down the scope stack, computing the type of the capture at
10604   // each step, checking type-specific requirements, and adding captures if
10605   // requested.
10606   for (unsigned I = ++FunctionScopesIndex, N = FunctionScopes.size(); I != N;
10607        ++I) {
10608     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
10609 
10610     // Compute the type of the capture and of a reference to the capture within
10611     // this scope.
10612     if (isa<BlockScopeInfo>(CSI)) {
10613       Expr *CopyExpr = 0;
10614       bool ByRef = false;
10615 
10616       // Blocks are not allowed to capture arrays.
10617       if (CaptureType->isArrayType()) {
10618         if (BuildAndDiagnose) {
10619           Diag(Loc, diag::err_ref_array_type);
10620           Diag(Var->getLocation(), diag::note_previous_decl)
10621           << Var->getDeclName();
10622         }
10623         return true;
10624       }
10625 
10626       // Forbid the block-capture of autoreleasing variables.
10627       if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
10628         if (BuildAndDiagnose) {
10629           Diag(Loc, diag::err_arc_autoreleasing_capture)
10630             << /*block*/ 0;
10631           Diag(Var->getLocation(), diag::note_previous_decl)
10632             << Var->getDeclName();
10633         }
10634         return true;
10635       }
10636 
10637       if (HasBlocksAttr || CaptureType->isReferenceType()) {
10638         // Block capture by reference does not change the capture or
10639         // declaration reference types.
10640         ByRef = true;
10641       } else {
10642         // Block capture by copy introduces 'const'.
10643         CaptureType = CaptureType.getNonReferenceType().withConst();
10644         DeclRefType = CaptureType;
10645 
10646         if (getLangOpts().CPlusPlus && BuildAndDiagnose) {
10647           if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
10648             // The capture logic needs the destructor, so make sure we mark it.
10649             // Usually this is unnecessary because most local variables have
10650             // their destructors marked at declaration time, but parameters are
10651             // an exception because it's technically only the call site that
10652             // actually requires the destructor.
10653             if (isa<ParmVarDecl>(Var))
10654               FinalizeVarWithDestructor(Var, Record);
10655 
10656             // According to the blocks spec, the capture of a variable from
10657             // the stack requires a const copy constructor.  This is not true
10658             // of the copy/move done to move a __block variable to the heap.
10659             Expr *DeclRef = new (Context) DeclRefExpr(Var, false,
10660                                                       DeclRefType.withConst(),
10661                                                       VK_LValue, Loc);
10662             ExprResult Result
10663               = PerformCopyInitialization(
10664                   InitializedEntity::InitializeBlock(Var->getLocation(),
10665                                                      CaptureType, false),
10666                   Loc, Owned(DeclRef));
10667 
10668             // Build a full-expression copy expression if initialization
10669             // succeeded and used a non-trivial constructor.  Recover from
10670             // errors by pretending that the copy isn't necessary.
10671             if (!Result.isInvalid() &&
10672                 !cast<CXXConstructExpr>(Result.get())->getConstructor()
10673                    ->isTrivial()) {
10674               Result = MaybeCreateExprWithCleanups(Result);
10675               CopyExpr = Result.take();
10676             }
10677           }
10678         }
10679       }
10680 
10681       // Actually capture the variable.
10682       if (BuildAndDiagnose)
10683         CSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
10684                         SourceLocation(), CaptureType, CopyExpr);
10685       Nested = true;
10686       continue;
10687     }
10688 
10689     LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
10690 
10691     // Determine whether we are capturing by reference or by value.
10692     bool ByRef = false;
10693     if (I == N - 1 && Kind != TryCapture_Implicit) {
10694       ByRef = (Kind == TryCapture_ExplicitByRef);
10695     } else {
10696       ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
10697     }
10698 
10699     // Compute the type of the field that will capture this variable.
10700     if (ByRef) {
10701       // C++11 [expr.prim.lambda]p15:
10702       //   An entity is captured by reference if it is implicitly or
10703       //   explicitly captured but not captured by copy. It is
10704       //   unspecified whether additional unnamed non-static data
10705       //   members are declared in the closure type for entities
10706       //   captured by reference.
10707       //
10708       // FIXME: It is not clear whether we want to build an lvalue reference
10709       // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
10710       // to do the former, while EDG does the latter. Core issue 1249 will
10711       // clarify, but for now we follow GCC because it's a more permissive and
10712       // easily defensible position.
10713       CaptureType = Context.getLValueReferenceType(DeclRefType);
10714     } else {
10715       // C++11 [expr.prim.lambda]p14:
10716       //   For each entity captured by copy, an unnamed non-static
10717       //   data member is declared in the closure type. The
10718       //   declaration order of these members is unspecified. The type
10719       //   of such a data member is the type of the corresponding
10720       //   captured entity if the entity is not a reference to an
10721       //   object, or the referenced type otherwise. [Note: If the
10722       //   captured entity is a reference to a function, the
10723       //   corresponding data member is also a reference to a
10724       //   function. - end note ]
10725       if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
10726         if (!RefType->getPointeeType()->isFunctionType())
10727           CaptureType = RefType->getPointeeType();
10728       }
10729 
10730       // Forbid the lambda copy-capture of autoreleasing variables.
10731       if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
10732         if (BuildAndDiagnose) {
10733           Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
10734           Diag(Var->getLocation(), diag::note_previous_decl)
10735             << Var->getDeclName();
10736         }
10737         return true;
10738       }
10739     }
10740 
10741     // Capture this variable in the lambda.
10742     Expr *CopyExpr = 0;
10743     if (BuildAndDiagnose) {
10744       ExprResult Result = captureInLambda(*this, LSI, Var, CaptureType,
10745                                           DeclRefType, Loc,
10746                                           I == N-1);
10747       if (!Result.isInvalid())
10748         CopyExpr = Result.take();
10749     }
10750 
10751     // Compute the type of a reference to this captured variable.
10752     if (ByRef)
10753       DeclRefType = CaptureType.getNonReferenceType();
10754     else {
10755       // C++ [expr.prim.lambda]p5:
10756       //   The closure type for a lambda-expression has a public inline
10757       //   function call operator [...]. This function call operator is
10758       //   declared const (9.3.1) if and only if the lambda-expression’s
10759       //   parameter-declaration-clause is not followed by mutable.
10760       DeclRefType = CaptureType.getNonReferenceType();
10761       if (!LSI->Mutable && !CaptureType->isReferenceType())
10762         DeclRefType.addConst();
10763     }
10764 
10765     // Add the capture.
10766     if (BuildAndDiagnose)
10767       CSI->addCapture(Var, /*IsBlock=*/false, ByRef, Nested, Loc,
10768                       EllipsisLoc, CaptureType, CopyExpr);
10769     Nested = true;
10770   }
10771 
10772   return false;
10773 }
10774 
10775 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
10776                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {
10777   QualType CaptureType;
10778   QualType DeclRefType;
10779   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
10780                             /*BuildAndDiagnose=*/true, CaptureType,
10781                             DeclRefType);
10782 }
10783 
10784 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
10785   QualType CaptureType;
10786   QualType DeclRefType;
10787 
10788   // Determine whether we can capture this variable.
10789   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
10790                          /*BuildAndDiagnose=*/false, CaptureType, DeclRefType))
10791     return QualType();
10792 
10793   return DeclRefType;
10794 }
10795 
10796 static void MarkVarDeclODRUsed(Sema &SemaRef, VarDecl *Var,
10797                                SourceLocation Loc) {
10798   // Keep track of used but undefined variables.
10799   // FIXME: We shouldn't suppress this warning for static data members.
10800   if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
10801       Var->getLinkage() != ExternalLinkage &&
10802       !(Var->isStaticDataMember() && Var->hasInit())) {
10803     SourceLocation &old = SemaRef.UndefinedInternals[Var->getCanonicalDecl()];
10804     if (old.isInvalid()) old = Loc;
10805   }
10806 
10807   SemaRef.tryCaptureVariable(Var, Loc);
10808 
10809   Var->setUsed(true);
10810 }
10811 
10812 void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
10813   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
10814   // an object that satisfies the requirements for appearing in a
10815   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
10816   // is immediately applied."  This function handles the lvalue-to-rvalue
10817   // conversion part.
10818   MaybeODRUseExprs.erase(E->IgnoreParens());
10819 }
10820 
10821 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
10822   if (!Res.isUsable())
10823     return Res;
10824 
10825   // If a constant-expression is a reference to a variable where we delay
10826   // deciding whether it is an odr-use, just assume we will apply the
10827   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
10828   // (a non-type template argument), we have special handling anyway.
10829   UpdateMarkingForLValueToRValue(Res.get());
10830   return Res;
10831 }
10832 
10833 void Sema::CleanupVarDeclMarking() {
10834   for (llvm::SmallPtrSetIterator<Expr*> i = MaybeODRUseExprs.begin(),
10835                                         e = MaybeODRUseExprs.end();
10836        i != e; ++i) {
10837     VarDecl *Var;
10838     SourceLocation Loc;
10839     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(*i)) {
10840       Var = cast<VarDecl>(DRE->getDecl());
10841       Loc = DRE->getLocation();
10842     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(*i)) {
10843       Var = cast<VarDecl>(ME->getMemberDecl());
10844       Loc = ME->getMemberLoc();
10845     } else {
10846       llvm_unreachable("Unexpcted expression");
10847     }
10848 
10849     MarkVarDeclODRUsed(*this, Var, Loc);
10850   }
10851 
10852   MaybeODRUseExprs.clear();
10853 }
10854 
10855 // Mark a VarDecl referenced, and perform the necessary handling to compute
10856 // odr-uses.
10857 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
10858                                     VarDecl *Var, Expr *E) {
10859   Var->setReferenced();
10860 
10861   if (!IsPotentiallyEvaluatedContext(SemaRef))
10862     return;
10863 
10864   // Implicit instantiation of static data members of class templates.
10865   if (Var->isStaticDataMember() && Var->getInstantiatedFromStaticDataMember()) {
10866     MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
10867     assert(MSInfo && "Missing member specialization information?");
10868     bool AlreadyInstantiated = !MSInfo->getPointOfInstantiation().isInvalid();
10869     if (MSInfo->getTemplateSpecializationKind() == TSK_ImplicitInstantiation &&
10870         (!AlreadyInstantiated ||
10871          Var->isUsableInConstantExpressions(SemaRef.Context))) {
10872       if (!AlreadyInstantiated) {
10873         // This is a modification of an existing AST node. Notify listeners.
10874         if (ASTMutationListener *L = SemaRef.getASTMutationListener())
10875           L->StaticDataMemberInstantiated(Var);
10876         MSInfo->setPointOfInstantiation(Loc);
10877       }
10878       SourceLocation PointOfInstantiation = MSInfo->getPointOfInstantiation();
10879       if (Var->isUsableInConstantExpressions(SemaRef.Context))
10880         // Do not defer instantiations of variables which could be used in a
10881         // constant expression.
10882         SemaRef.InstantiateStaticDataMemberDefinition(PointOfInstantiation,Var);
10883       else
10884         SemaRef.PendingInstantiations.push_back(
10885             std::make_pair(Var, PointOfInstantiation));
10886     }
10887   }
10888 
10889   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
10890   // an object that satisfies the requirements for appearing in a
10891   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
10892   // is immediately applied."  We check the first part here, and
10893   // Sema::UpdateMarkingForLValueToRValue deals with the second part.
10894   // Note that we use the C++11 definition everywhere because nothing in
10895   // C++03 depends on whether we get the C++03 version correct. This does not
10896   // apply to references, since they are not objects.
10897   const VarDecl *DefVD;
10898   if (E && !isa<ParmVarDecl>(Var) && !Var->getType()->isReferenceType() &&
10899       Var->isUsableInConstantExpressions(SemaRef.Context) &&
10900       Var->getAnyInitializer(DefVD) && DefVD->checkInitIsICE())
10901     SemaRef.MaybeODRUseExprs.insert(E);
10902   else
10903     MarkVarDeclODRUsed(SemaRef, Var, Loc);
10904 }
10905 
10906 /// \brief Mark a variable referenced, and check whether it is odr-used
10907 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
10908 /// used directly for normal expressions referring to VarDecl.
10909 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
10910   DoMarkVarDeclReferenced(*this, Loc, Var, 0);
10911 }
10912 
10913 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
10914                                Decl *D, Expr *E) {
10915   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
10916     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
10917     return;
10918   }
10919 
10920   SemaRef.MarkAnyDeclReferenced(Loc, D);
10921 
10922   // If this is a call to a method via a cast, also mark the method in the
10923   // derived class used in case codegen can devirtualize the call.
10924   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
10925   if (!ME)
10926     return;
10927   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
10928   if (!MD)
10929     return;
10930   const Expr *Base = ME->getBase();
10931   const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
10932   if (!MostDerivedClassDecl)
10933     return;
10934   CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl);
10935   if (!DM)
10936     return;
10937   SemaRef.MarkAnyDeclReferenced(Loc, DM);
10938 }
10939 
10940 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
10941 void Sema::MarkDeclRefReferenced(DeclRefExpr *E) {
10942   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E);
10943 }
10944 
10945 /// \brief Perform reference-marking and odr-use handling for a MemberExpr.
10946 void Sema::MarkMemberReferenced(MemberExpr *E) {
10947   MarkExprReferenced(*this, E->getMemberLoc(), E->getMemberDecl(), E);
10948 }
10949 
10950 /// \brief Perform marking for a reference to an arbitrary declaration.  It
10951 /// marks the declaration referenced, and performs odr-use checking for functions
10952 /// and variables. This method should not be used when building an normal
10953 /// expression which refers to a variable.
10954 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D) {
10955   if (VarDecl *VD = dyn_cast<VarDecl>(D))
10956     MarkVariableReferenced(Loc, VD);
10957   else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
10958     MarkFunctionReferenced(Loc, FD);
10959   else
10960     D->setReferenced();
10961 }
10962 
10963 namespace {
10964   // Mark all of the declarations referenced
10965   // FIXME: Not fully implemented yet! We need to have a better understanding
10966   // of when we're entering
10967   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
10968     Sema &S;
10969     SourceLocation Loc;
10970 
10971   public:
10972     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
10973 
10974     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
10975 
10976     bool TraverseTemplateArgument(const TemplateArgument &Arg);
10977     bool TraverseRecordType(RecordType *T);
10978   };
10979 }
10980 
10981 bool MarkReferencedDecls::TraverseTemplateArgument(
10982   const TemplateArgument &Arg) {
10983   if (Arg.getKind() == TemplateArgument::Declaration) {
10984     if (Decl *D = Arg.getAsDecl())
10985       S.MarkAnyDeclReferenced(Loc, D);
10986   }
10987 
10988   return Inherited::TraverseTemplateArgument(Arg);
10989 }
10990 
10991 bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
10992   if (ClassTemplateSpecializationDecl *Spec
10993                   = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
10994     const TemplateArgumentList &Args = Spec->getTemplateArgs();
10995     return TraverseTemplateArguments(Args.data(), Args.size());
10996   }
10997 
10998   return true;
10999 }
11000 
11001 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
11002   MarkReferencedDecls Marker(*this, Loc);
11003   Marker.TraverseType(Context.getCanonicalType(T));
11004 }
11005 
11006 namespace {
11007   /// \brief Helper class that marks all of the declarations referenced by
11008   /// potentially-evaluated subexpressions as "referenced".
11009   class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
11010     Sema &S;
11011     bool SkipLocalVariables;
11012 
11013   public:
11014     typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
11015 
11016     EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
11017       : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
11018 
11019     void VisitDeclRefExpr(DeclRefExpr *E) {
11020       // If we were asked not to visit local variables, don't.
11021       if (SkipLocalVariables) {
11022         if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
11023           if (VD->hasLocalStorage())
11024             return;
11025       }
11026 
11027       S.MarkDeclRefReferenced(E);
11028     }
11029 
11030     void VisitMemberExpr(MemberExpr *E) {
11031       S.MarkMemberReferenced(E);
11032       Inherited::VisitMemberExpr(E);
11033     }
11034 
11035     void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
11036       S.MarkFunctionReferenced(E->getLocStart(),
11037             const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
11038       Visit(E->getSubExpr());
11039     }
11040 
11041     void VisitCXXNewExpr(CXXNewExpr *E) {
11042       if (E->getOperatorNew())
11043         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
11044       if (E->getOperatorDelete())
11045         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
11046       Inherited::VisitCXXNewExpr(E);
11047     }
11048 
11049     void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
11050       if (E->getOperatorDelete())
11051         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
11052       QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
11053       if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
11054         CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
11055         S.MarkFunctionReferenced(E->getLocStart(),
11056                                     S.LookupDestructor(Record));
11057       }
11058 
11059       Inherited::VisitCXXDeleteExpr(E);
11060     }
11061 
11062     void VisitCXXConstructExpr(CXXConstructExpr *E) {
11063       S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
11064       Inherited::VisitCXXConstructExpr(E);
11065     }
11066 
11067     void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
11068       Visit(E->getExpr());
11069     }
11070 
11071     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
11072       Inherited::VisitImplicitCastExpr(E);
11073 
11074       if (E->getCastKind() == CK_LValueToRValue)
11075         S.UpdateMarkingForLValueToRValue(E->getSubExpr());
11076     }
11077   };
11078 }
11079 
11080 /// \brief Mark any declarations that appear within this expression or any
11081 /// potentially-evaluated subexpressions as "referenced".
11082 ///
11083 /// \param SkipLocalVariables If true, don't mark local variables as
11084 /// 'referenced'.
11085 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
11086                                             bool SkipLocalVariables) {
11087   EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
11088 }
11089 
11090 /// \brief Emit a diagnostic that describes an effect on the run-time behavior
11091 /// of the program being compiled.
11092 ///
11093 /// This routine emits the given diagnostic when the code currently being
11094 /// type-checked is "potentially evaluated", meaning that there is a
11095 /// possibility that the code will actually be executable. Code in sizeof()
11096 /// expressions, code used only during overload resolution, etc., are not
11097 /// potentially evaluated. This routine will suppress such diagnostics or,
11098 /// in the absolutely nutty case of potentially potentially evaluated
11099 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
11100 /// later.
11101 ///
11102 /// This routine should be used for all diagnostics that describe the run-time
11103 /// behavior of a program, such as passing a non-POD value through an ellipsis.
11104 /// Failure to do so will likely result in spurious diagnostics or failures
11105 /// during overload resolution or within sizeof/alignof/typeof/typeid.
11106 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
11107                                const PartialDiagnostic &PD) {
11108   switch (ExprEvalContexts.back().Context) {
11109   case Unevaluated:
11110     // The argument will never be evaluated, so don't complain.
11111     break;
11112 
11113   case ConstantEvaluated:
11114     // Relevant diagnostics should be produced by constant evaluation.
11115     break;
11116 
11117   case PotentiallyEvaluated:
11118   case PotentiallyEvaluatedIfUsed:
11119     if (Statement && getCurFunctionOrMethodDecl()) {
11120       FunctionScopes.back()->PossiblyUnreachableDiags.
11121         push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
11122     }
11123     else
11124       Diag(Loc, PD);
11125 
11126     return true;
11127   }
11128 
11129   return false;
11130 }
11131 
11132 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
11133                                CallExpr *CE, FunctionDecl *FD) {
11134   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
11135     return false;
11136 
11137   // If we're inside a decltype's expression, don't check for a valid return
11138   // type or construct temporaries until we know whether this is the last call.
11139   if (ExprEvalContexts.back().IsDecltype) {
11140     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
11141     return false;
11142   }
11143 
11144   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
11145     FunctionDecl *FD;
11146     CallExpr *CE;
11147 
11148   public:
11149     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
11150       : FD(FD), CE(CE) { }
11151 
11152     virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
11153       if (!FD) {
11154         S.Diag(Loc, diag::err_call_incomplete_return)
11155           << T << CE->getSourceRange();
11156         return;
11157       }
11158 
11159       S.Diag(Loc, diag::err_call_function_incomplete_return)
11160         << CE->getSourceRange() << FD->getDeclName() << T;
11161       S.Diag(FD->getLocation(),
11162              diag::note_function_with_incomplete_return_type_declared_here)
11163         << FD->getDeclName();
11164     }
11165   } Diagnoser(FD, CE);
11166 
11167   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
11168     return true;
11169 
11170   return false;
11171 }
11172 
11173 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
11174 // will prevent this condition from triggering, which is what we want.
11175 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
11176   SourceLocation Loc;
11177 
11178   unsigned diagnostic = diag::warn_condition_is_assignment;
11179   bool IsOrAssign = false;
11180 
11181   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
11182     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
11183       return;
11184 
11185     IsOrAssign = Op->getOpcode() == BO_OrAssign;
11186 
11187     // Greylist some idioms by putting them into a warning subcategory.
11188     if (ObjCMessageExpr *ME
11189           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
11190       Selector Sel = ME->getSelector();
11191 
11192       // self = [<foo> init...]
11193       if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init"))
11194         diagnostic = diag::warn_condition_is_idiomatic_assignment;
11195 
11196       // <foo> = [<bar> nextObject]
11197       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
11198         diagnostic = diag::warn_condition_is_idiomatic_assignment;
11199     }
11200 
11201     Loc = Op->getOperatorLoc();
11202   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
11203     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
11204       return;
11205 
11206     IsOrAssign = Op->getOperator() == OO_PipeEqual;
11207     Loc = Op->getOperatorLoc();
11208   } else {
11209     // Not an assignment.
11210     return;
11211   }
11212 
11213   Diag(Loc, diagnostic) << E->getSourceRange();
11214 
11215   SourceLocation Open = E->getLocStart();
11216   SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
11217   Diag(Loc, diag::note_condition_assign_silence)
11218         << FixItHint::CreateInsertion(Open, "(")
11219         << FixItHint::CreateInsertion(Close, ")");
11220 
11221   if (IsOrAssign)
11222     Diag(Loc, diag::note_condition_or_assign_to_comparison)
11223       << FixItHint::CreateReplacement(Loc, "!=");
11224   else
11225     Diag(Loc, diag::note_condition_assign_to_comparison)
11226       << FixItHint::CreateReplacement(Loc, "==");
11227 }
11228 
11229 /// \brief Redundant parentheses over an equality comparison can indicate
11230 /// that the user intended an assignment used as condition.
11231 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
11232   // Don't warn if the parens came from a macro.
11233   SourceLocation parenLoc = ParenE->getLocStart();
11234   if (parenLoc.isInvalid() || parenLoc.isMacroID())
11235     return;
11236   // Don't warn for dependent expressions.
11237   if (ParenE->isTypeDependent())
11238     return;
11239 
11240   Expr *E = ParenE->IgnoreParens();
11241 
11242   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
11243     if (opE->getOpcode() == BO_EQ &&
11244         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
11245                                                            == Expr::MLV_Valid) {
11246       SourceLocation Loc = opE->getOperatorLoc();
11247 
11248       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
11249       SourceRange ParenERange = ParenE->getSourceRange();
11250       Diag(Loc, diag::note_equality_comparison_silence)
11251         << FixItHint::CreateRemoval(ParenERange.getBegin())
11252         << FixItHint::CreateRemoval(ParenERange.getEnd());
11253       Diag(Loc, diag::note_equality_comparison_to_assign)
11254         << FixItHint::CreateReplacement(Loc, "=");
11255     }
11256 }
11257 
11258 ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
11259   DiagnoseAssignmentAsCondition(E);
11260   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
11261     DiagnoseEqualityWithExtraParens(parenE);
11262 
11263   ExprResult result = CheckPlaceholderExpr(E);
11264   if (result.isInvalid()) return ExprError();
11265   E = result.take();
11266 
11267   if (!E->isTypeDependent()) {
11268     if (getLangOpts().CPlusPlus)
11269       return CheckCXXBooleanCondition(E); // C++ 6.4p4
11270 
11271     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
11272     if (ERes.isInvalid())
11273       return ExprError();
11274     E = ERes.take();
11275 
11276     QualType T = E->getType();
11277     if (!T->isScalarType()) { // C99 6.8.4.1p1
11278       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
11279         << T << E->getSourceRange();
11280       return ExprError();
11281     }
11282   }
11283 
11284   return Owned(E);
11285 }
11286 
11287 ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
11288                                        Expr *SubExpr) {
11289   if (!SubExpr)
11290     return ExprError();
11291 
11292   return CheckBooleanCondition(SubExpr, Loc);
11293 }
11294 
11295 namespace {
11296   /// A visitor for rebuilding a call to an __unknown_any expression
11297   /// to have an appropriate type.
11298   struct RebuildUnknownAnyFunction
11299     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
11300 
11301     Sema &S;
11302 
11303     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
11304 
11305     ExprResult VisitStmt(Stmt *S) {
11306       llvm_unreachable("unexpected statement!");
11307     }
11308 
11309     ExprResult VisitExpr(Expr *E) {
11310       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
11311         << E->getSourceRange();
11312       return ExprError();
11313     }
11314 
11315     /// Rebuild an expression which simply semantically wraps another
11316     /// expression which it shares the type and value kind of.
11317     template <class T> ExprResult rebuildSugarExpr(T *E) {
11318       ExprResult SubResult = Visit(E->getSubExpr());
11319       if (SubResult.isInvalid()) return ExprError();
11320 
11321       Expr *SubExpr = SubResult.take();
11322       E->setSubExpr(SubExpr);
11323       E->setType(SubExpr->getType());
11324       E->setValueKind(SubExpr->getValueKind());
11325       assert(E->getObjectKind() == OK_Ordinary);
11326       return E;
11327     }
11328 
11329     ExprResult VisitParenExpr(ParenExpr *E) {
11330       return rebuildSugarExpr(E);
11331     }
11332 
11333     ExprResult VisitUnaryExtension(UnaryOperator *E) {
11334       return rebuildSugarExpr(E);
11335     }
11336 
11337     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
11338       ExprResult SubResult = Visit(E->getSubExpr());
11339       if (SubResult.isInvalid()) return ExprError();
11340 
11341       Expr *SubExpr = SubResult.take();
11342       E->setSubExpr(SubExpr);
11343       E->setType(S.Context.getPointerType(SubExpr->getType()));
11344       assert(E->getValueKind() == VK_RValue);
11345       assert(E->getObjectKind() == OK_Ordinary);
11346       return E;
11347     }
11348 
11349     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
11350       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
11351 
11352       E->setType(VD->getType());
11353 
11354       assert(E->getValueKind() == VK_RValue);
11355       if (S.getLangOpts().CPlusPlus &&
11356           !(isa<CXXMethodDecl>(VD) &&
11357             cast<CXXMethodDecl>(VD)->isInstance()))
11358         E->setValueKind(VK_LValue);
11359 
11360       return E;
11361     }
11362 
11363     ExprResult VisitMemberExpr(MemberExpr *E) {
11364       return resolveDecl(E, E->getMemberDecl());
11365     }
11366 
11367     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
11368       return resolveDecl(E, E->getDecl());
11369     }
11370   };
11371 }
11372 
11373 /// Given a function expression of unknown-any type, try to rebuild it
11374 /// to have a function type.
11375 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
11376   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
11377   if (Result.isInvalid()) return ExprError();
11378   return S.DefaultFunctionArrayConversion(Result.take());
11379 }
11380 
11381 namespace {
11382   /// A visitor for rebuilding an expression of type __unknown_anytype
11383   /// into one which resolves the type directly on the referring
11384   /// expression.  Strict preservation of the original source
11385   /// structure is not a goal.
11386   struct RebuildUnknownAnyExpr
11387     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
11388 
11389     Sema &S;
11390 
11391     /// The current destination type.
11392     QualType DestType;
11393 
11394     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
11395       : S(S), DestType(CastType) {}
11396 
11397     ExprResult VisitStmt(Stmt *S) {
11398       llvm_unreachable("unexpected statement!");
11399     }
11400 
11401     ExprResult VisitExpr(Expr *E) {
11402       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
11403         << E->getSourceRange();
11404       return ExprError();
11405     }
11406 
11407     ExprResult VisitCallExpr(CallExpr *E);
11408     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
11409 
11410     /// Rebuild an expression which simply semantically wraps another
11411     /// expression which it shares the type and value kind of.
11412     template <class T> ExprResult rebuildSugarExpr(T *E) {
11413       ExprResult SubResult = Visit(E->getSubExpr());
11414       if (SubResult.isInvalid()) return ExprError();
11415       Expr *SubExpr = SubResult.take();
11416       E->setSubExpr(SubExpr);
11417       E->setType(SubExpr->getType());
11418       E->setValueKind(SubExpr->getValueKind());
11419       assert(E->getObjectKind() == OK_Ordinary);
11420       return E;
11421     }
11422 
11423     ExprResult VisitParenExpr(ParenExpr *E) {
11424       return rebuildSugarExpr(E);
11425     }
11426 
11427     ExprResult VisitUnaryExtension(UnaryOperator *E) {
11428       return rebuildSugarExpr(E);
11429     }
11430 
11431     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
11432       const PointerType *Ptr = DestType->getAs<PointerType>();
11433       if (!Ptr) {
11434         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
11435           << E->getSourceRange();
11436         return ExprError();
11437       }
11438       assert(E->getValueKind() == VK_RValue);
11439       assert(E->getObjectKind() == OK_Ordinary);
11440       E->setType(DestType);
11441 
11442       // Build the sub-expression as if it were an object of the pointee type.
11443       DestType = Ptr->getPointeeType();
11444       ExprResult SubResult = Visit(E->getSubExpr());
11445       if (SubResult.isInvalid()) return ExprError();
11446       E->setSubExpr(SubResult.take());
11447       return E;
11448     }
11449 
11450     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
11451 
11452     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
11453 
11454     ExprResult VisitMemberExpr(MemberExpr *E) {
11455       return resolveDecl(E, E->getMemberDecl());
11456     }
11457 
11458     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
11459       return resolveDecl(E, E->getDecl());
11460     }
11461   };
11462 }
11463 
11464 /// Rebuilds a call expression which yielded __unknown_anytype.
11465 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
11466   Expr *CalleeExpr = E->getCallee();
11467 
11468   enum FnKind {
11469     FK_MemberFunction,
11470     FK_FunctionPointer,
11471     FK_BlockPointer
11472   };
11473 
11474   FnKind Kind;
11475   QualType CalleeType = CalleeExpr->getType();
11476   if (CalleeType == S.Context.BoundMemberTy) {
11477     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
11478     Kind = FK_MemberFunction;
11479     CalleeType = Expr::findBoundMemberType(CalleeExpr);
11480   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
11481     CalleeType = Ptr->getPointeeType();
11482     Kind = FK_FunctionPointer;
11483   } else {
11484     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
11485     Kind = FK_BlockPointer;
11486   }
11487   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
11488 
11489   // Verify that this is a legal result type of a function.
11490   if (DestType->isArrayType() || DestType->isFunctionType()) {
11491     unsigned diagID = diag::err_func_returning_array_function;
11492     if (Kind == FK_BlockPointer)
11493       diagID = diag::err_block_returning_array_function;
11494 
11495     S.Diag(E->getExprLoc(), diagID)
11496       << DestType->isFunctionType() << DestType;
11497     return ExprError();
11498   }
11499 
11500   // Otherwise, go ahead and set DestType as the call's result.
11501   E->setType(DestType.getNonLValueExprType(S.Context));
11502   E->setValueKind(Expr::getValueKindForType(DestType));
11503   assert(E->getObjectKind() == OK_Ordinary);
11504 
11505   // Rebuild the function type, replacing the result type with DestType.
11506   if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType))
11507     DestType = S.Context.getFunctionType(DestType,
11508                                          Proto->arg_type_begin(),
11509                                          Proto->getNumArgs(),
11510                                          Proto->getExtProtoInfo());
11511   else
11512     DestType = S.Context.getFunctionNoProtoType(DestType,
11513                                                 FnType->getExtInfo());
11514 
11515   // Rebuild the appropriate pointer-to-function type.
11516   switch (Kind) {
11517   case FK_MemberFunction:
11518     // Nothing to do.
11519     break;
11520 
11521   case FK_FunctionPointer:
11522     DestType = S.Context.getPointerType(DestType);
11523     break;
11524 
11525   case FK_BlockPointer:
11526     DestType = S.Context.getBlockPointerType(DestType);
11527     break;
11528   }
11529 
11530   // Finally, we can recurse.
11531   ExprResult CalleeResult = Visit(CalleeExpr);
11532   if (!CalleeResult.isUsable()) return ExprError();
11533   E->setCallee(CalleeResult.take());
11534 
11535   // Bind a temporary if necessary.
11536   return S.MaybeBindToTemporary(E);
11537 }
11538 
11539 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
11540   // Verify that this is a legal result type of a call.
11541   if (DestType->isArrayType() || DestType->isFunctionType()) {
11542     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
11543       << DestType->isFunctionType() << DestType;
11544     return ExprError();
11545   }
11546 
11547   // Rewrite the method result type if available.
11548   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
11549     assert(Method->getResultType() == S.Context.UnknownAnyTy);
11550     Method->setResultType(DestType);
11551   }
11552 
11553   // Change the type of the message.
11554   E->setType(DestType.getNonReferenceType());
11555   E->setValueKind(Expr::getValueKindForType(DestType));
11556 
11557   return S.MaybeBindToTemporary(E);
11558 }
11559 
11560 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
11561   // The only case we should ever see here is a function-to-pointer decay.
11562   if (E->getCastKind() == CK_FunctionToPointerDecay) {
11563     assert(E->getValueKind() == VK_RValue);
11564     assert(E->getObjectKind() == OK_Ordinary);
11565 
11566     E->setType(DestType);
11567 
11568     // Rebuild the sub-expression as the pointee (function) type.
11569     DestType = DestType->castAs<PointerType>()->getPointeeType();
11570 
11571     ExprResult Result = Visit(E->getSubExpr());
11572     if (!Result.isUsable()) return ExprError();
11573 
11574     E->setSubExpr(Result.take());
11575     return S.Owned(E);
11576   } else if (E->getCastKind() == CK_LValueToRValue) {
11577     assert(E->getValueKind() == VK_RValue);
11578     assert(E->getObjectKind() == OK_Ordinary);
11579 
11580     assert(isa<BlockPointerType>(E->getType()));
11581 
11582     E->setType(DestType);
11583 
11584     // The sub-expression has to be a lvalue reference, so rebuild it as such.
11585     DestType = S.Context.getLValueReferenceType(DestType);
11586 
11587     ExprResult Result = Visit(E->getSubExpr());
11588     if (!Result.isUsable()) return ExprError();
11589 
11590     E->setSubExpr(Result.take());
11591     return S.Owned(E);
11592   } else {
11593     llvm_unreachable("Unhandled cast type!");
11594   }
11595 }
11596 
11597 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
11598   ExprValueKind ValueKind = VK_LValue;
11599   QualType Type = DestType;
11600 
11601   // We know how to make this work for certain kinds of decls:
11602 
11603   //  - functions
11604   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
11605     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
11606       DestType = Ptr->getPointeeType();
11607       ExprResult Result = resolveDecl(E, VD);
11608       if (Result.isInvalid()) return ExprError();
11609       return S.ImpCastExprToType(Result.take(), Type,
11610                                  CK_FunctionToPointerDecay, VK_RValue);
11611     }
11612 
11613     if (!Type->isFunctionType()) {
11614       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
11615         << VD << E->getSourceRange();
11616       return ExprError();
11617     }
11618 
11619     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
11620       if (MD->isInstance()) {
11621         ValueKind = VK_RValue;
11622         Type = S.Context.BoundMemberTy;
11623       }
11624 
11625     // Function references aren't l-values in C.
11626     if (!S.getLangOpts().CPlusPlus)
11627       ValueKind = VK_RValue;
11628 
11629   //  - variables
11630   } else if (isa<VarDecl>(VD)) {
11631     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
11632       Type = RefTy->getPointeeType();
11633     } else if (Type->isFunctionType()) {
11634       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
11635         << VD << E->getSourceRange();
11636       return ExprError();
11637     }
11638 
11639   //  - nothing else
11640   } else {
11641     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
11642       << VD << E->getSourceRange();
11643     return ExprError();
11644   }
11645 
11646   VD->setType(DestType);
11647   E->setType(Type);
11648   E->setValueKind(ValueKind);
11649   return S.Owned(E);
11650 }
11651 
11652 /// Check a cast of an unknown-any type.  We intentionally only
11653 /// trigger this for C-style casts.
11654 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
11655                                      Expr *CastExpr, CastKind &CastKind,
11656                                      ExprValueKind &VK, CXXCastPath &Path) {
11657   // Rewrite the casted expression from scratch.
11658   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
11659   if (!result.isUsable()) return ExprError();
11660 
11661   CastExpr = result.take();
11662   VK = CastExpr->getValueKind();
11663   CastKind = CK_NoOp;
11664 
11665   return CastExpr;
11666 }
11667 
11668 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
11669   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
11670 }
11671 
11672 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
11673   Expr *orig = E;
11674   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
11675   while (true) {
11676     E = E->IgnoreParenImpCasts();
11677     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
11678       E = call->getCallee();
11679       diagID = diag::err_uncasted_call_of_unknown_any;
11680     } else {
11681       break;
11682     }
11683   }
11684 
11685   SourceLocation loc;
11686   NamedDecl *d;
11687   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
11688     loc = ref->getLocation();
11689     d = ref->getDecl();
11690   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
11691     loc = mem->getMemberLoc();
11692     d = mem->getMemberDecl();
11693   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
11694     diagID = diag::err_uncasted_call_of_unknown_any;
11695     loc = msg->getSelectorStartLoc();
11696     d = msg->getMethodDecl();
11697     if (!d) {
11698       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
11699         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
11700         << orig->getSourceRange();
11701       return ExprError();
11702     }
11703   } else {
11704     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
11705       << E->getSourceRange();
11706     return ExprError();
11707   }
11708 
11709   S.Diag(loc, diagID) << d << orig->getSourceRange();
11710 
11711   // Never recoverable.
11712   return ExprError();
11713 }
11714 
11715 /// Check for operands with placeholder types and complain if found.
11716 /// Returns true if there was an error and no recovery was possible.
11717 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
11718   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
11719   if (!placeholderType) return Owned(E);
11720 
11721   switch (placeholderType->getKind()) {
11722 
11723   // Overloaded expressions.
11724   case BuiltinType::Overload: {
11725     // Try to resolve a single function template specialization.
11726     // This is obligatory.
11727     ExprResult result = Owned(E);
11728     if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) {
11729       return result;
11730 
11731     // If that failed, try to recover with a call.
11732     } else {
11733       tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable),
11734                            /*complain*/ true);
11735       return result;
11736     }
11737   }
11738 
11739   // Bound member functions.
11740   case BuiltinType::BoundMember: {
11741     ExprResult result = Owned(E);
11742     tryToRecoverWithCall(result, PDiag(diag::err_bound_member_function),
11743                          /*complain*/ true);
11744     return result;
11745   }
11746 
11747   // ARC unbridged casts.
11748   case BuiltinType::ARCUnbridgedCast: {
11749     Expr *realCast = stripARCUnbridgedCast(E);
11750     diagnoseARCUnbridgedCast(realCast);
11751     return Owned(realCast);
11752   }
11753 
11754   // Expressions of unknown type.
11755   case BuiltinType::UnknownAny:
11756     return diagnoseUnknownAnyExpr(*this, E);
11757 
11758   // Pseudo-objects.
11759   case BuiltinType::PseudoObject:
11760     return checkPseudoObjectRValue(E);
11761 
11762   // Everything else should be impossible.
11763 #define BUILTIN_TYPE(Id, SingletonId) \
11764   case BuiltinType::Id:
11765 #define PLACEHOLDER_TYPE(Id, SingletonId)
11766 #include "clang/AST/BuiltinTypes.def"
11767     break;
11768   }
11769 
11770   llvm_unreachable("invalid placeholder type!");
11771 }
11772 
11773 bool Sema::CheckCaseExpression(Expr *E) {
11774   if (E->isTypeDependent())
11775     return true;
11776   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
11777     return E->getType()->isIntegralOrEnumerationType();
11778   return false;
11779 }
11780 
11781 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
11782 ExprResult
11783 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
11784   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
11785          "Unknown Objective-C Boolean value!");
11786   return Owned(new (Context) ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes,
11787                                         Context.ObjCBuiltinBoolTy, OpLoc));
11788 }
11789