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 void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
70   // Warn if this is used but marked unused.
71   if (D->hasAttr<UnusedAttr>()) {
72     const Decl *DC = cast<Decl>(S.getCurObjCLexicalContext());
73     if (!DC->hasAttr<UnusedAttr>())
74       S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
75   }
76 }
77 
78 static AvailabilityResult DiagnoseAvailabilityOfDecl(Sema &S,
79                               NamedDecl *D, SourceLocation Loc,
80                               const ObjCInterfaceDecl *UnknownObjCClass) {
81   // See if this declaration is unavailable or deprecated.
82   std::string Message;
83   AvailabilityResult Result = D->getAvailability(&Message);
84   if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D))
85     if (Result == AR_Available) {
86       const DeclContext *DC = ECD->getDeclContext();
87       if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC))
88         Result = TheEnumDecl->getAvailability(&Message);
89     }
90   const ObjCPropertyDecl *ObjCPDecl = 0;
91   if (Result == AR_Deprecated || Result == AR_Unavailable)
92     if (ObjCPropertyDecl *ND = S.PropertyIfSetterOrGetter(D)) {
93       AvailabilityResult PDeclResult = ND->getAvailability(0);
94       if (PDeclResult == Result)
95         ObjCPDecl = ND;
96     }
97 
98   switch (Result) {
99     case AR_Available:
100     case AR_NotYetIntroduced:
101       break;
102 
103     case AR_Deprecated:
104       S.EmitDeprecationWarning(D, Message, Loc, UnknownObjCClass, ObjCPDecl);
105       break;
106 
107     case AR_Unavailable:
108       if (S.getCurContextAvailability() != AR_Unavailable) {
109         if (Message.empty()) {
110           if (!UnknownObjCClass) {
111             S.Diag(Loc, diag::err_unavailable) << D->getDeclName();
112             if (ObjCPDecl)
113               S.Diag(ObjCPDecl->getLocation(), diag::note_property_attribute)
114                 << ObjCPDecl->getDeclName() << 1;
115           }
116           else
117             S.Diag(Loc, diag::warn_unavailable_fwdclass_message)
118               << D->getDeclName();
119         }
120         else
121           S.Diag(Loc, diag::err_unavailable_message)
122             << D->getDeclName() << Message;
123         S.Diag(D->getLocation(), diag::note_unavailable_here)
124                   << isa<FunctionDecl>(D) << false;
125         if (ObjCPDecl)
126           S.Diag(ObjCPDecl->getLocation(), diag::note_property_attribute)
127           << ObjCPDecl->getDeclName() << 1;
128       }
129       break;
130     }
131     return Result;
132 }
133 
134 /// \brief Emit a note explaining that this function is deleted or unavailable.
135 void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
136   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
137 
138   if (Method && Method->isDeleted() && !Method->isDeletedAsWritten()) {
139     // If the method was explicitly defaulted, point at that declaration.
140     if (!Method->isImplicit())
141       Diag(Decl->getLocation(), diag::note_implicitly_deleted);
142 
143     // Try to diagnose why this special member function was implicitly
144     // deleted. This might fail, if that reason no longer applies.
145     CXXSpecialMember CSM = getSpecialMember(Method);
146     if (CSM != CXXInvalid)
147       ShouldDeleteSpecialMember(Method, CSM, /*Diagnose=*/true);
148 
149     return;
150   }
151 
152   Diag(Decl->getLocation(), diag::note_unavailable_here)
153     << 1 << Decl->isDeleted();
154 }
155 
156 /// \brief Determine whether a FunctionDecl was ever declared with an
157 /// explicit storage class.
158 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
159   for (FunctionDecl::redecl_iterator I = D->redecls_begin(),
160                                      E = D->redecls_end();
161        I != E; ++I) {
162     if (I->getStorageClassAsWritten() != SC_None)
163       return true;
164   }
165   return false;
166 }
167 
168 /// \brief Check whether we're in an extern inline function and referring to a
169 /// variable or function with internal linkage (C11 6.7.4p3).
170 ///
171 /// This is only a warning because we used to silently accept this code, but
172 /// in many cases it will not behave correctly. This is not enabled in C++ mode
173 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
174 /// and so while there may still be user mistakes, most of the time we can't
175 /// prove that there are errors.
176 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
177                                                       const NamedDecl *D,
178                                                       SourceLocation Loc) {
179   // This is disabled under C++; there are too many ways for this to fire in
180   // contexts where the warning is a false positive, or where it is technically
181   // correct but benign.
182   if (S.getLangOpts().CPlusPlus)
183     return;
184 
185   // Check if this is an inlined function or method.
186   FunctionDecl *Current = S.getCurFunctionDecl();
187   if (!Current)
188     return;
189   if (!Current->isInlined())
190     return;
191   if (Current->getLinkage() != ExternalLinkage)
192     return;
193 
194   // Check if the decl has internal linkage.
195   if (D->getLinkage() != InternalLinkage)
196     return;
197 
198   // Downgrade from ExtWarn to Extension if
199   //  (1) the supposedly external inline function is in the main file,
200   //      and probably won't be included anywhere else.
201   //  (2) the thing we're referencing is a pure function.
202   //  (3) the thing we're referencing is another inline function.
203   // This last can give us false negatives, but it's better than warning on
204   // wrappers for simple C library functions.
205   const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
206   bool DowngradeWarning = S.getSourceManager().isFromMainFile(Loc);
207   if (!DowngradeWarning && UsedFn)
208     DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
209 
210   S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline
211                                : diag::warn_internal_in_extern_inline)
212     << /*IsVar=*/!UsedFn << D;
213 
214   // Suggest "static" on the inline function, if possible.
215   if (!hasAnyExplicitStorageClass(Current)) {
216     const FunctionDecl *FirstDecl = Current->getCanonicalDecl();
217     SourceLocation DeclBegin = FirstDecl->getSourceRange().getBegin();
218     S.Diag(DeclBegin, diag::note_convert_inline_to_static)
219       << Current << FixItHint::CreateInsertion(DeclBegin, "static ");
220   }
221 
222   S.Diag(D->getCanonicalDecl()->getLocation(),
223          diag::note_internal_decl_declared_here)
224     << D;
225 }
226 
227 /// \brief Determine whether the use of this declaration is valid, and
228 /// emit any corresponding diagnostics.
229 ///
230 /// This routine diagnoses various problems with referencing
231 /// declarations that can occur when using a declaration. For example,
232 /// it might warn if a deprecated or unavailable declaration is being
233 /// used, or produce an error (and return true) if a C++0x deleted
234 /// function is being used.
235 ///
236 /// \returns true if there was an error (this declaration cannot be
237 /// referenced), false otherwise.
238 ///
239 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
240                              const ObjCInterfaceDecl *UnknownObjCClass) {
241   if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
242     // If there were any diagnostics suppressed by template argument deduction,
243     // emit them now.
244     llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >::iterator
245       Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
246     if (Pos != SuppressedDiagnostics.end()) {
247       SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second;
248       for (unsigned I = 0, N = Suppressed.size(); I != N; ++I)
249         Diag(Suppressed[I].first, Suppressed[I].second);
250 
251       // Clear out the list of suppressed diagnostics, so that we don't emit
252       // them again for this specialization. However, we don't obsolete this
253       // entry from the table, because we want to avoid ever emitting these
254       // diagnostics again.
255       Suppressed.clear();
256     }
257   }
258 
259   // See if this is an auto-typed variable whose initializer we are parsing.
260   if (ParsingInitForAutoVars.count(D)) {
261     Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
262       << D->getDeclName();
263     return true;
264   }
265 
266   // See if this is a deleted function.
267   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
268     if (FD->isDeleted()) {
269       Diag(Loc, diag::err_deleted_function_use);
270       NoteDeletedFunction(FD);
271       return true;
272     }
273   }
274   DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass);
275 
276   DiagnoseUnusedOfDecl(*this, D, Loc);
277 
278   diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
279 
280   return false;
281 }
282 
283 /// \brief Retrieve the message suffix that should be added to a
284 /// diagnostic complaining about the given function being deleted or
285 /// unavailable.
286 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
287   // FIXME: C++0x implicitly-deleted special member functions could be
288   // detected here so that we could improve diagnostics to say, e.g.,
289   // "base class 'A' had a deleted copy constructor".
290   if (FD->isDeleted())
291     return std::string();
292 
293   std::string Message;
294   if (FD->getAvailability(&Message))
295     return ": " + Message;
296 
297   return std::string();
298 }
299 
300 /// DiagnoseSentinelCalls - This routine checks whether a call or
301 /// message-send is to a declaration with the sentinel attribute, and
302 /// if so, it checks that the requirements of the sentinel are
303 /// satisfied.
304 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
305                                  Expr **args, unsigned numArgs) {
306   const SentinelAttr *attr = D->getAttr<SentinelAttr>();
307   if (!attr)
308     return;
309 
310   // The number of formal parameters of the declaration.
311   unsigned numFormalParams;
312 
313   // The kind of declaration.  This is also an index into a %select in
314   // the diagnostic.
315   enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
316 
317   if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
318     numFormalParams = MD->param_size();
319     calleeType = CT_Method;
320   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
321     numFormalParams = FD->param_size();
322     calleeType = CT_Function;
323   } else if (isa<VarDecl>(D)) {
324     QualType type = cast<ValueDecl>(D)->getType();
325     const FunctionType *fn = 0;
326     if (const PointerType *ptr = type->getAs<PointerType>()) {
327       fn = ptr->getPointeeType()->getAs<FunctionType>();
328       if (!fn) return;
329       calleeType = CT_Function;
330     } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
331       fn = ptr->getPointeeType()->castAs<FunctionType>();
332       calleeType = CT_Block;
333     } else {
334       return;
335     }
336 
337     if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
338       numFormalParams = proto->getNumArgs();
339     } else {
340       numFormalParams = 0;
341     }
342   } else {
343     return;
344   }
345 
346   // "nullPos" is the number of formal parameters at the end which
347   // effectively count as part of the variadic arguments.  This is
348   // useful if you would prefer to not have *any* formal parameters,
349   // but the language forces you to have at least one.
350   unsigned nullPos = attr->getNullPos();
351   assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
352   numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
353 
354   // The number of arguments which should follow the sentinel.
355   unsigned numArgsAfterSentinel = attr->getSentinel();
356 
357   // If there aren't enough arguments for all the formal parameters,
358   // the sentinel, and the args after the sentinel, complain.
359   if (numArgs < numFormalParams + numArgsAfterSentinel + 1) {
360     Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
361     Diag(D->getLocation(), diag::note_sentinel_here) << calleeType;
362     return;
363   }
364 
365   // Otherwise, find the sentinel expression.
366   Expr *sentinelExpr = args[numArgs - numArgsAfterSentinel - 1];
367   if (!sentinelExpr) return;
368   if (sentinelExpr->isValueDependent()) return;
369   if (Context.isSentinelNullExpr(sentinelExpr)) return;
370 
371   // Pick a reasonable string to insert.  Optimistically use 'nil' or
372   // 'NULL' if those are actually defined in the context.  Only use
373   // 'nil' for ObjC methods, where it's much more likely that the
374   // variadic arguments form a list of object pointers.
375   SourceLocation MissingNilLoc
376     = PP.getLocForEndOfToken(sentinelExpr->getLocEnd());
377   std::string NullValue;
378   if (calleeType == CT_Method &&
379       PP.getIdentifierInfo("nil")->hasMacroDefinition())
380     NullValue = "nil";
381   else if (PP.getIdentifierInfo("NULL")->hasMacroDefinition())
382     NullValue = "NULL";
383   else
384     NullValue = "(void*) 0";
385 
386   if (MissingNilLoc.isInvalid())
387     Diag(Loc, diag::warn_missing_sentinel) << calleeType;
388   else
389     Diag(MissingNilLoc, diag::warn_missing_sentinel)
390       << calleeType
391       << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
392   Diag(D->getLocation(), diag::note_sentinel_here) << calleeType;
393 }
394 
395 SourceRange Sema::getExprRange(Expr *E) const {
396   return E ? E->getSourceRange() : SourceRange();
397 }
398 
399 //===----------------------------------------------------------------------===//
400 //  Standard Promotions and Conversions
401 //===----------------------------------------------------------------------===//
402 
403 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
404 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) {
405   // Handle any placeholder expressions which made it here.
406   if (E->getType()->isPlaceholderType()) {
407     ExprResult result = CheckPlaceholderExpr(E);
408     if (result.isInvalid()) return ExprError();
409     E = result.take();
410   }
411 
412   QualType Ty = E->getType();
413   assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
414 
415   if (Ty->isFunctionType())
416     E = ImpCastExprToType(E, Context.getPointerType(Ty),
417                           CK_FunctionToPointerDecay).take();
418   else if (Ty->isArrayType()) {
419     // In C90 mode, arrays only promote to pointers if the array expression is
420     // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
421     // type 'array of type' is converted to an expression that has type 'pointer
422     // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
423     // that has type 'array of type' ...".  The relevant change is "an lvalue"
424     // (C90) to "an expression" (C99).
425     //
426     // C++ 4.2p1:
427     // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
428     // T" can be converted to an rvalue of type "pointer to T".
429     //
430     if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
431       E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
432                             CK_ArrayToPointerDecay).take();
433   }
434   return Owned(E);
435 }
436 
437 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
438   // Check to see if we are dereferencing a null pointer.  If so,
439   // and if not volatile-qualified, this is undefined behavior that the
440   // optimizer will delete, so warn about it.  People sometimes try to use this
441   // to get a deterministic trap and are surprised by clang's behavior.  This
442   // only handles the pattern "*null", which is a very syntactic check.
443   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
444     if (UO->getOpcode() == UO_Deref &&
445         UO->getSubExpr()->IgnoreParenCasts()->
446           isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
447         !UO->getType().isVolatileQualified()) {
448     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
449                           S.PDiag(diag::warn_indirection_through_null)
450                             << UO->getSubExpr()->getSourceRange());
451     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
452                         S.PDiag(diag::note_indirection_through_null));
453   }
454 }
455 
456 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
457   // Handle any placeholder expressions which made it here.
458   if (E->getType()->isPlaceholderType()) {
459     ExprResult result = CheckPlaceholderExpr(E);
460     if (result.isInvalid()) return ExprError();
461     E = result.take();
462   }
463 
464   // C++ [conv.lval]p1:
465   //   A glvalue of a non-function, non-array type T can be
466   //   converted to a prvalue.
467   if (!E->isGLValue()) return Owned(E);
468 
469   QualType T = E->getType();
470   assert(!T.isNull() && "r-value conversion on typeless expression?");
471 
472   // We don't want to throw lvalue-to-rvalue casts on top of
473   // expressions of certain types in C++.
474   if (getLangOpts().CPlusPlus &&
475       (E->getType() == Context.OverloadTy ||
476        T->isDependentType() ||
477        T->isRecordType()))
478     return Owned(E);
479 
480   // The C standard is actually really unclear on this point, and
481   // DR106 tells us what the result should be but not why.  It's
482   // generally best to say that void types just doesn't undergo
483   // lvalue-to-rvalue at all.  Note that expressions of unqualified
484   // 'void' type are never l-values, but qualified void can be.
485   if (T->isVoidType())
486     return Owned(E);
487 
488   CheckForNullPointerDereference(*this, E);
489 
490   // C++ [conv.lval]p1:
491   //   [...] If T is a non-class type, the type of the prvalue is the
492   //   cv-unqualified version of T. Otherwise, the type of the
493   //   rvalue is T.
494   //
495   // C99 6.3.2.1p2:
496   //   If the lvalue has qualified type, the value has the unqualified
497   //   version of the type of the lvalue; otherwise, the value has the
498   //   type of the lvalue.
499   if (T.hasQualifiers())
500     T = T.getUnqualifiedType();
501 
502   UpdateMarkingForLValueToRValue(E);
503 
504   ExprResult Res = Owned(ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
505                                                   E, 0, VK_RValue));
506 
507   // C11 6.3.2.1p2:
508   //   ... if the lvalue has atomic type, the value has the non-atomic version
509   //   of the type of the lvalue ...
510   if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
511     T = Atomic->getValueType().getUnqualifiedType();
512     Res = Owned(ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic,
513                                          Res.get(), 0, VK_RValue));
514   }
515 
516   return Res;
517 }
518 
519 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) {
520   ExprResult Res = DefaultFunctionArrayConversion(E);
521   if (Res.isInvalid())
522     return ExprError();
523   Res = DefaultLvalueConversion(Res.take());
524   if (Res.isInvalid())
525     return ExprError();
526   return Res;
527 }
528 
529 
530 /// UsualUnaryConversions - Performs various conversions that are common to most
531 /// operators (C99 6.3). The conversions of array and function types are
532 /// sometimes suppressed. For example, the array->pointer conversion doesn't
533 /// apply if the array is an argument to the sizeof or address (&) operators.
534 /// In these instances, this routine should *not* be called.
535 ExprResult Sema::UsualUnaryConversions(Expr *E) {
536   // First, convert to an r-value.
537   ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
538   if (Res.isInvalid())
539     return Owned(E);
540   E = Res.take();
541 
542   QualType Ty = E->getType();
543   assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
544 
545   // Half FP is a bit different: it's a storage-only type, meaning that any
546   // "use" of it should be promoted to float.
547   if (Ty->isHalfType())
548     return ImpCastExprToType(Res.take(), Context.FloatTy, CK_FloatingCast);
549 
550   // Try to perform integral promotions if the object has a theoretically
551   // promotable type.
552   if (Ty->isIntegralOrUnscopedEnumerationType()) {
553     // C99 6.3.1.1p2:
554     //
555     //   The following may be used in an expression wherever an int or
556     //   unsigned int may be used:
557     //     - an object or expression with an integer type whose integer
558     //       conversion rank is less than or equal to the rank of int
559     //       and unsigned int.
560     //     - A bit-field of type _Bool, int, signed int, or unsigned int.
561     //
562     //   If an int can represent all values of the original type, the
563     //   value is converted to an int; otherwise, it is converted to an
564     //   unsigned int. These are called the integer promotions. All
565     //   other types are unchanged by the integer promotions.
566 
567     QualType PTy = Context.isPromotableBitField(E);
568     if (!PTy.isNull()) {
569       E = ImpCastExprToType(E, PTy, CK_IntegralCast).take();
570       return Owned(E);
571     }
572     if (Ty->isPromotableIntegerType()) {
573       QualType PT = Context.getPromotedIntegerType(Ty);
574       E = ImpCastExprToType(E, PT, CK_IntegralCast).take();
575       return Owned(E);
576     }
577   }
578   return Owned(E);
579 }
580 
581 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
582 /// do not have a prototype. Arguments that have type float are promoted to
583 /// double. All other argument types are converted by UsualUnaryConversions().
584 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
585   QualType Ty = E->getType();
586   assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
587 
588   ExprResult Res = UsualUnaryConversions(E);
589   if (Res.isInvalid())
590     return Owned(E);
591   E = Res.take();
592 
593   // If this is a 'float' (CVR qualified or typedef) promote to double.
594   if (Ty->isSpecificBuiltinType(BuiltinType::Float))
595     E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).take();
596 
597   // C++ performs lvalue-to-rvalue conversion as a default argument
598   // promotion, even on class types, but note:
599   //   C++11 [conv.lval]p2:
600   //     When an lvalue-to-rvalue conversion occurs in an unevaluated
601   //     operand or a subexpression thereof the value contained in the
602   //     referenced object is not accessed. Otherwise, if the glvalue
603   //     has a class type, the conversion copy-initializes a temporary
604   //     of type T from the glvalue and the result of the conversion
605   //     is a prvalue for the temporary.
606   // FIXME: add some way to gate this entire thing for correctness in
607   // potentially potentially evaluated contexts.
608   if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
609     ExprResult Temp = PerformCopyInitialization(
610                        InitializedEntity::InitializeTemporary(E->getType()),
611                                                 E->getExprLoc(),
612                                                 Owned(E));
613     if (Temp.isInvalid())
614       return ExprError();
615     E = Temp.get();
616   }
617 
618   return Owned(E);
619 }
620 
621 /// Determine the degree of POD-ness for an expression.
622 /// Incomplete types are considered POD, since this check can be performed
623 /// when we're in an unevaluated context.
624 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
625   if (Ty->isIncompleteType()) {
626     if (Ty->isObjCObjectType())
627       return VAK_Invalid;
628     return VAK_Valid;
629   }
630 
631   if (Ty.isCXX98PODType(Context))
632     return VAK_Valid;
633 
634   // C++0x [expr.call]p7:
635   //   Passing a potentially-evaluated argument of class type (Clause 9)
636   //   having a non-trivial copy constructor, a non-trivial move constructor,
637   //   or a non-trivial destructor, with no corresponding parameter,
638   //   is conditionally-supported with implementation-defined semantics.
639   if (getLangOpts().CPlusPlus0x && !Ty->isDependentType())
640     if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
641       if (Record->hasTrivialCopyConstructor() &&
642           Record->hasTrivialMoveConstructor() &&
643           Record->hasTrivialDestructor())
644         return VAK_ValidInCXX11;
645 
646   if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
647     return VAK_Valid;
648   return VAK_Invalid;
649 }
650 
651 bool Sema::variadicArgumentPODCheck(const Expr *E, VariadicCallType CT) {
652   // Don't allow one to pass an Objective-C interface to a vararg.
653   const QualType & Ty = E->getType();
654 
655   // Complain about passing non-POD types through varargs.
656   switch (isValidVarArgType(Ty)) {
657   case VAK_Valid:
658     break;
659   case VAK_ValidInCXX11:
660     DiagRuntimeBehavior(E->getLocStart(), 0,
661         PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
662         << E->getType() << CT);
663     break;
664   case VAK_Invalid: {
665     if (Ty->isObjCObjectType())
666       return DiagRuntimeBehavior(E->getLocStart(), 0,
667                           PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
668                             << Ty << CT);
669 
670     return DiagRuntimeBehavior(E->getLocStart(), 0,
671                    PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
672                    << getLangOpts().CPlusPlus0x << Ty << CT);
673   }
674   }
675   // c++ rules are enforced elsewhere.
676   return false;
677 }
678 
679 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
680 /// will create a trap if the resulting type is not a POD type.
681 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
682                                                   FunctionDecl *FDecl) {
683   if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
684     // Strip the unbridged-cast placeholder expression off, if applicable.
685     if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
686         (CT == VariadicMethod ||
687          (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
688       E = stripARCUnbridgedCast(E);
689 
690     // Otherwise, do normal placeholder checking.
691     } else {
692       ExprResult ExprRes = CheckPlaceholderExpr(E);
693       if (ExprRes.isInvalid())
694         return ExprError();
695       E = ExprRes.take();
696     }
697   }
698 
699   ExprResult ExprRes = DefaultArgumentPromotion(E);
700   if (ExprRes.isInvalid())
701     return ExprError();
702   E = ExprRes.take();
703 
704   // Diagnostics regarding non-POD argument types are
705   // emitted along with format string checking in Sema::CheckFunctionCall().
706   if (isValidVarArgType(E->getType()) == VAK_Invalid) {
707     // Turn this into a trap.
708     CXXScopeSpec SS;
709     SourceLocation TemplateKWLoc;
710     UnqualifiedId Name;
711     Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
712                        E->getLocStart());
713     ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
714                                           Name, true, false);
715     if (TrapFn.isInvalid())
716       return ExprError();
717 
718     ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(),
719                                     E->getLocStart(), MultiExprArg(),
720                                     E->getLocEnd());
721     if (Call.isInvalid())
722       return ExprError();
723 
724     ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
725                                   Call.get(), E);
726     if (Comma.isInvalid())
727       return ExprError();
728     return Comma.get();
729   }
730 
731   if (!getLangOpts().CPlusPlus &&
732       RequireCompleteType(E->getExprLoc(), E->getType(),
733                           diag::err_call_incomplete_argument))
734     return ExprError();
735 
736   return Owned(E);
737 }
738 
739 /// \brief Converts an integer to complex float type.  Helper function of
740 /// UsualArithmeticConversions()
741 ///
742 /// \return false if the integer expression is an integer type and is
743 /// successfully converted to the complex type.
744 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
745                                                   ExprResult &ComplexExpr,
746                                                   QualType IntTy,
747                                                   QualType ComplexTy,
748                                                   bool SkipCast) {
749   if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
750   if (SkipCast) return false;
751   if (IntTy->isIntegerType()) {
752     QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
753     IntExpr = S.ImpCastExprToType(IntExpr.take(), fpTy, CK_IntegralToFloating);
754     IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
755                                   CK_FloatingRealToComplex);
756   } else {
757     assert(IntTy->isComplexIntegerType());
758     IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
759                                   CK_IntegralComplexToFloatingComplex);
760   }
761   return false;
762 }
763 
764 /// \brief Takes two complex float types and converts them to the same type.
765 /// Helper function of UsualArithmeticConversions()
766 static QualType
767 handleComplexFloatToComplexFloatConverstion(Sema &S, ExprResult &LHS,
768                                             ExprResult &RHS, QualType LHSType,
769                                             QualType RHSType,
770                                             bool IsCompAssign) {
771   int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
772 
773   if (order < 0) {
774     // _Complex float -> _Complex double
775     if (!IsCompAssign)
776       LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingComplexCast);
777     return RHSType;
778   }
779   if (order > 0)
780     // _Complex float -> _Complex double
781     RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingComplexCast);
782   return LHSType;
783 }
784 
785 /// \brief Converts otherExpr to complex float and promotes complexExpr if
786 /// necessary.  Helper function of UsualArithmeticConversions()
787 static QualType handleOtherComplexFloatConversion(Sema &S,
788                                                   ExprResult &ComplexExpr,
789                                                   ExprResult &OtherExpr,
790                                                   QualType ComplexTy,
791                                                   QualType OtherTy,
792                                                   bool ConvertComplexExpr,
793                                                   bool ConvertOtherExpr) {
794   int order = S.Context.getFloatingTypeOrder(ComplexTy, OtherTy);
795 
796   // If just the complexExpr is complex, the otherExpr needs to be converted,
797   // and the complexExpr might need to be promoted.
798   if (order > 0) { // complexExpr is wider
799     // float -> _Complex double
800     if (ConvertOtherExpr) {
801       QualType fp = cast<ComplexType>(ComplexTy)->getElementType();
802       OtherExpr = S.ImpCastExprToType(OtherExpr.take(), fp, CK_FloatingCast);
803       OtherExpr = S.ImpCastExprToType(OtherExpr.take(), ComplexTy,
804                                       CK_FloatingRealToComplex);
805     }
806     return ComplexTy;
807   }
808 
809   // otherTy is at least as wide.  Find its corresponding complex type.
810   QualType result = (order == 0 ? ComplexTy :
811                                   S.Context.getComplexType(OtherTy));
812 
813   // double -> _Complex double
814   if (ConvertOtherExpr)
815     OtherExpr = S.ImpCastExprToType(OtherExpr.take(), result,
816                                     CK_FloatingRealToComplex);
817 
818   // _Complex float -> _Complex double
819   if (ConvertComplexExpr && order < 0)
820     ComplexExpr = S.ImpCastExprToType(ComplexExpr.take(), result,
821                                       CK_FloatingComplexCast);
822 
823   return result;
824 }
825 
826 /// \brief Handle arithmetic conversion with complex types.  Helper function of
827 /// UsualArithmeticConversions()
828 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
829                                              ExprResult &RHS, QualType LHSType,
830                                              QualType RHSType,
831                                              bool IsCompAssign) {
832   // if we have an integer operand, the result is the complex type.
833   if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
834                                              /*skipCast*/false))
835     return LHSType;
836   if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
837                                              /*skipCast*/IsCompAssign))
838     return RHSType;
839 
840   // This handles complex/complex, complex/float, or float/complex.
841   // When both operands are complex, the shorter operand is converted to the
842   // type of the longer, and that is the type of the result. This corresponds
843   // to what is done when combining two real floating-point operands.
844   // The fun begins when size promotion occur across type domains.
845   // From H&S 6.3.4: When one operand is complex and the other is a real
846   // floating-point type, the less precise type is converted, within it's
847   // real or complex domain, to the precision of the other type. For example,
848   // when combining a "long double" with a "double _Complex", the
849   // "double _Complex" is promoted to "long double _Complex".
850 
851   bool LHSComplexFloat = LHSType->isComplexType();
852   bool RHSComplexFloat = RHSType->isComplexType();
853 
854   // If both are complex, just cast to the more precise type.
855   if (LHSComplexFloat && RHSComplexFloat)
856     return handleComplexFloatToComplexFloatConverstion(S, LHS, RHS,
857                                                        LHSType, RHSType,
858                                                        IsCompAssign);
859 
860   // If only one operand is complex, promote it if necessary and convert the
861   // other operand to complex.
862   if (LHSComplexFloat)
863     return handleOtherComplexFloatConversion(
864         S, LHS, RHS, LHSType, RHSType, /*convertComplexExpr*/!IsCompAssign,
865         /*convertOtherExpr*/ true);
866 
867   assert(RHSComplexFloat);
868   return handleOtherComplexFloatConversion(
869       S, RHS, LHS, RHSType, LHSType, /*convertComplexExpr*/true,
870       /*convertOtherExpr*/ !IsCompAssign);
871 }
872 
873 /// \brief Hande arithmetic conversion from integer to float.  Helper function
874 /// of UsualArithmeticConversions()
875 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
876                                            ExprResult &IntExpr,
877                                            QualType FloatTy, QualType IntTy,
878                                            bool ConvertFloat, bool ConvertInt) {
879   if (IntTy->isIntegerType()) {
880     if (ConvertInt)
881       // Convert intExpr to the lhs floating point type.
882       IntExpr = S.ImpCastExprToType(IntExpr.take(), FloatTy,
883                                     CK_IntegralToFloating);
884     return FloatTy;
885   }
886 
887   // Convert both sides to the appropriate complex float.
888   assert(IntTy->isComplexIntegerType());
889   QualType result = S.Context.getComplexType(FloatTy);
890 
891   // _Complex int -> _Complex float
892   if (ConvertInt)
893     IntExpr = S.ImpCastExprToType(IntExpr.take(), result,
894                                   CK_IntegralComplexToFloatingComplex);
895 
896   // float -> _Complex float
897   if (ConvertFloat)
898     FloatExpr = S.ImpCastExprToType(FloatExpr.take(), result,
899                                     CK_FloatingRealToComplex);
900 
901   return result;
902 }
903 
904 /// \brief Handle arithmethic conversion with floating point types.  Helper
905 /// function of UsualArithmeticConversions()
906 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
907                                       ExprResult &RHS, QualType LHSType,
908                                       QualType RHSType, bool IsCompAssign) {
909   bool LHSFloat = LHSType->isRealFloatingType();
910   bool RHSFloat = RHSType->isRealFloatingType();
911 
912   // If we have two real floating types, convert the smaller operand
913   // to the bigger result.
914   if (LHSFloat && RHSFloat) {
915     int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
916     if (order > 0) {
917       RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingCast);
918       return LHSType;
919     }
920 
921     assert(order < 0 && "illegal float comparison");
922     if (!IsCompAssign)
923       LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingCast);
924     return RHSType;
925   }
926 
927   if (LHSFloat)
928     return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
929                                       /*convertFloat=*/!IsCompAssign,
930                                       /*convertInt=*/ true);
931   assert(RHSFloat);
932   return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
933                                     /*convertInt=*/ true,
934                                     /*convertFloat=*/!IsCompAssign);
935 }
936 
937 /// \brief Handle conversions with GCC complex int extension.  Helper function
938 /// of UsualArithmeticConversions()
939 // FIXME: if the operands are (int, _Complex long), we currently
940 // don't promote the complex.  Also, signedness?
941 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
942                                            ExprResult &RHS, QualType LHSType,
943                                            QualType RHSType,
944                                            bool IsCompAssign) {
945   const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
946   const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
947 
948   if (LHSComplexInt && RHSComplexInt) {
949     int order = S.Context.getIntegerTypeOrder(LHSComplexInt->getElementType(),
950                                               RHSComplexInt->getElementType());
951     assert(order && "inequal types with equal element ordering");
952     if (order > 0) {
953       // _Complex int -> _Complex long
954       RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralComplexCast);
955       return LHSType;
956     }
957 
958     if (!IsCompAssign)
959       LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralComplexCast);
960     return RHSType;
961   }
962 
963   if (LHSComplexInt) {
964     // int -> _Complex int
965     // FIXME: This needs to take integer ranks into account
966     RHS = S.ImpCastExprToType(RHS.take(), LHSComplexInt->getElementType(),
967                               CK_IntegralCast);
968     RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralRealToComplex);
969     return LHSType;
970   }
971 
972   assert(RHSComplexInt);
973   // int -> _Complex int
974   // FIXME: This needs to take integer ranks into account
975   if (!IsCompAssign) {
976     LHS = S.ImpCastExprToType(LHS.take(), RHSComplexInt->getElementType(),
977                               CK_IntegralCast);
978     LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralRealToComplex);
979   }
980   return RHSType;
981 }
982 
983 /// \brief Handle integer arithmetic conversions.  Helper function of
984 /// UsualArithmeticConversions()
985 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
986                                         ExprResult &RHS, QualType LHSType,
987                                         QualType RHSType, bool IsCompAssign) {
988   // The rules for this case are in C99 6.3.1.8
989   int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
990   bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
991   bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
992   if (LHSSigned == RHSSigned) {
993     // Same signedness; use the higher-ranked type
994     if (order >= 0) {
995       RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
996       return LHSType;
997     } else if (!IsCompAssign)
998       LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
999     return RHSType;
1000   } else if (order != (LHSSigned ? 1 : -1)) {
1001     // The unsigned type has greater than or equal rank to the
1002     // signed type, so use the unsigned type
1003     if (RHSSigned) {
1004       RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
1005       return LHSType;
1006     } else if (!IsCompAssign)
1007       LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
1008     return RHSType;
1009   } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1010     // The two types are different widths; if we are here, that
1011     // means the signed type is larger than the unsigned type, so
1012     // use the signed type.
1013     if (LHSSigned) {
1014       RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
1015       return LHSType;
1016     } else if (!IsCompAssign)
1017       LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
1018     return RHSType;
1019   } else {
1020     // The signed type is higher-ranked than the unsigned type,
1021     // but isn't actually any bigger (like unsigned int and long
1022     // on most 32-bit systems).  Use the unsigned type corresponding
1023     // to the signed type.
1024     QualType result =
1025       S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1026     RHS = S.ImpCastExprToType(RHS.take(), result, CK_IntegralCast);
1027     if (!IsCompAssign)
1028       LHS = S.ImpCastExprToType(LHS.take(), result, CK_IntegralCast);
1029     return result;
1030   }
1031 }
1032 
1033 /// UsualArithmeticConversions - Performs various conversions that are common to
1034 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1035 /// routine returns the first non-arithmetic type found. The client is
1036 /// responsible for emitting appropriate error diagnostics.
1037 /// FIXME: verify the conversion rules for "complex int" are consistent with
1038 /// GCC.
1039 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1040                                           bool IsCompAssign) {
1041   if (!IsCompAssign) {
1042     LHS = UsualUnaryConversions(LHS.take());
1043     if (LHS.isInvalid())
1044       return QualType();
1045   }
1046 
1047   RHS = UsualUnaryConversions(RHS.take());
1048   if (RHS.isInvalid())
1049     return QualType();
1050 
1051   // For conversion purposes, we ignore any qualifiers.
1052   // For example, "const float" and "float" are equivalent.
1053   QualType LHSType =
1054     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1055   QualType RHSType =
1056     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1057 
1058   // For conversion purposes, we ignore any atomic qualifier on the LHS.
1059   if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1060     LHSType = AtomicLHS->getValueType();
1061 
1062   // If both types are identical, no conversion is needed.
1063   if (LHSType == RHSType)
1064     return LHSType;
1065 
1066   // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1067   // The caller can deal with this (e.g. pointer + int).
1068   if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1069     return QualType();
1070 
1071   // Apply unary and bitfield promotions to the LHS's type.
1072   QualType LHSUnpromotedType = LHSType;
1073   if (LHSType->isPromotableIntegerType())
1074     LHSType = Context.getPromotedIntegerType(LHSType);
1075   QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1076   if (!LHSBitfieldPromoteTy.isNull())
1077     LHSType = LHSBitfieldPromoteTy;
1078   if (LHSType != LHSUnpromotedType && !IsCompAssign)
1079     LHS = ImpCastExprToType(LHS.take(), LHSType, CK_IntegralCast);
1080 
1081   // If both types are identical, no conversion is needed.
1082   if (LHSType == RHSType)
1083     return LHSType;
1084 
1085   // At this point, we have two different arithmetic types.
1086 
1087   // Handle complex types first (C99 6.3.1.8p1).
1088   if (LHSType->isComplexType() || RHSType->isComplexType())
1089     return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1090                                         IsCompAssign);
1091 
1092   // Now handle "real" floating types (i.e. float, double, long double).
1093   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1094     return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1095                                  IsCompAssign);
1096 
1097   // Handle GCC complex int extension.
1098   if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1099     return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1100                                       IsCompAssign);
1101 
1102   // Finally, we have two differing integer types.
1103   return handleIntegerConversion(*this, LHS, RHS, LHSType, RHSType,
1104                                  IsCompAssign);
1105 }
1106 
1107 //===----------------------------------------------------------------------===//
1108 //  Semantic Analysis for various Expression Types
1109 //===----------------------------------------------------------------------===//
1110 
1111 
1112 ExprResult
1113 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1114                                 SourceLocation DefaultLoc,
1115                                 SourceLocation RParenLoc,
1116                                 Expr *ControllingExpr,
1117                                 MultiTypeArg ArgTypes,
1118                                 MultiExprArg ArgExprs) {
1119   unsigned NumAssocs = ArgTypes.size();
1120   assert(NumAssocs == ArgExprs.size());
1121 
1122   ParsedType *ParsedTypes = ArgTypes.data();
1123   Expr **Exprs = ArgExprs.data();
1124 
1125   TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1126   for (unsigned i = 0; i < NumAssocs; ++i) {
1127     if (ParsedTypes[i])
1128       (void) GetTypeFromParser(ParsedTypes[i], &Types[i]);
1129     else
1130       Types[i] = 0;
1131   }
1132 
1133   ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1134                                              ControllingExpr, Types, Exprs,
1135                                              NumAssocs);
1136   delete [] Types;
1137   return ER;
1138 }
1139 
1140 ExprResult
1141 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1142                                  SourceLocation DefaultLoc,
1143                                  SourceLocation RParenLoc,
1144                                  Expr *ControllingExpr,
1145                                  TypeSourceInfo **Types,
1146                                  Expr **Exprs,
1147                                  unsigned NumAssocs) {
1148   bool TypeErrorFound = false,
1149        IsResultDependent = ControllingExpr->isTypeDependent(),
1150        ContainsUnexpandedParameterPack
1151          = ControllingExpr->containsUnexpandedParameterPack();
1152 
1153   for (unsigned i = 0; i < NumAssocs; ++i) {
1154     if (Exprs[i]->containsUnexpandedParameterPack())
1155       ContainsUnexpandedParameterPack = true;
1156 
1157     if (Types[i]) {
1158       if (Types[i]->getType()->containsUnexpandedParameterPack())
1159         ContainsUnexpandedParameterPack = true;
1160 
1161       if (Types[i]->getType()->isDependentType()) {
1162         IsResultDependent = true;
1163       } else {
1164         // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1165         // complete object type other than a variably modified type."
1166         unsigned D = 0;
1167         if (Types[i]->getType()->isIncompleteType())
1168           D = diag::err_assoc_type_incomplete;
1169         else if (!Types[i]->getType()->isObjectType())
1170           D = diag::err_assoc_type_nonobject;
1171         else if (Types[i]->getType()->isVariablyModifiedType())
1172           D = diag::err_assoc_type_variably_modified;
1173 
1174         if (D != 0) {
1175           Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1176             << Types[i]->getTypeLoc().getSourceRange()
1177             << Types[i]->getType();
1178           TypeErrorFound = true;
1179         }
1180 
1181         // C11 6.5.1.1p2 "No two generic associations in the same generic
1182         // selection shall specify compatible types."
1183         for (unsigned j = i+1; j < NumAssocs; ++j)
1184           if (Types[j] && !Types[j]->getType()->isDependentType() &&
1185               Context.typesAreCompatible(Types[i]->getType(),
1186                                          Types[j]->getType())) {
1187             Diag(Types[j]->getTypeLoc().getBeginLoc(),
1188                  diag::err_assoc_compatible_types)
1189               << Types[j]->getTypeLoc().getSourceRange()
1190               << Types[j]->getType()
1191               << Types[i]->getType();
1192             Diag(Types[i]->getTypeLoc().getBeginLoc(),
1193                  diag::note_compat_assoc)
1194               << Types[i]->getTypeLoc().getSourceRange()
1195               << Types[i]->getType();
1196             TypeErrorFound = true;
1197           }
1198       }
1199     }
1200   }
1201   if (TypeErrorFound)
1202     return ExprError();
1203 
1204   // If we determined that the generic selection is result-dependent, don't
1205   // try to compute the result expression.
1206   if (IsResultDependent)
1207     return Owned(new (Context) GenericSelectionExpr(
1208                    Context, KeyLoc, ControllingExpr,
1209                    llvm::makeArrayRef(Types, NumAssocs),
1210                    llvm::makeArrayRef(Exprs, NumAssocs),
1211                    DefaultLoc, RParenLoc, ContainsUnexpandedParameterPack));
1212 
1213   SmallVector<unsigned, 1> CompatIndices;
1214   unsigned DefaultIndex = -1U;
1215   for (unsigned i = 0; i < NumAssocs; ++i) {
1216     if (!Types[i])
1217       DefaultIndex = i;
1218     else if (Context.typesAreCompatible(ControllingExpr->getType(),
1219                                         Types[i]->getType()))
1220       CompatIndices.push_back(i);
1221   }
1222 
1223   // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1224   // type compatible with at most one of the types named in its generic
1225   // association list."
1226   if (CompatIndices.size() > 1) {
1227     // We strip parens here because the controlling expression is typically
1228     // parenthesized in macro definitions.
1229     ControllingExpr = ControllingExpr->IgnoreParens();
1230     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1231       << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1232       << (unsigned) CompatIndices.size();
1233     for (SmallVector<unsigned, 1>::iterator I = CompatIndices.begin(),
1234          E = CompatIndices.end(); I != E; ++I) {
1235       Diag(Types[*I]->getTypeLoc().getBeginLoc(),
1236            diag::note_compat_assoc)
1237         << Types[*I]->getTypeLoc().getSourceRange()
1238         << Types[*I]->getType();
1239     }
1240     return ExprError();
1241   }
1242 
1243   // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1244   // its controlling expression shall have type compatible with exactly one of
1245   // the types named in its generic association list."
1246   if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1247     // We strip parens here because the controlling expression is typically
1248     // parenthesized in macro definitions.
1249     ControllingExpr = ControllingExpr->IgnoreParens();
1250     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1251       << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1252     return ExprError();
1253   }
1254 
1255   // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1256   // type name that is compatible with the type of the controlling expression,
1257   // then the result expression of the generic selection is the expression
1258   // in that generic association. Otherwise, the result expression of the
1259   // generic selection is the expression in the default generic association."
1260   unsigned ResultIndex =
1261     CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1262 
1263   return Owned(new (Context) GenericSelectionExpr(
1264                  Context, KeyLoc, ControllingExpr,
1265                  llvm::makeArrayRef(Types, NumAssocs),
1266                  llvm::makeArrayRef(Exprs, NumAssocs),
1267                  DefaultLoc, RParenLoc, ContainsUnexpandedParameterPack,
1268                  ResultIndex));
1269 }
1270 
1271 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1272 /// location of the token and the offset of the ud-suffix within it.
1273 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1274                                      unsigned Offset) {
1275   return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1276                                         S.getLangOpts());
1277 }
1278 
1279 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1280 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1281 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1282                                                  IdentifierInfo *UDSuffix,
1283                                                  SourceLocation UDSuffixLoc,
1284                                                  ArrayRef<Expr*> Args,
1285                                                  SourceLocation LitEndLoc) {
1286   assert(Args.size() <= 2 && "too many arguments for literal operator");
1287 
1288   QualType ArgTy[2];
1289   for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1290     ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1291     if (ArgTy[ArgIdx]->isArrayType())
1292       ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1293   }
1294 
1295   DeclarationName OpName =
1296     S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1297   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1298   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1299 
1300   LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1301   if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1302                               /*AllowRawAndTemplate*/false) == Sema::LOLR_Error)
1303     return ExprError();
1304 
1305   return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1306 }
1307 
1308 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1309 /// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
1310 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1311 /// multiple tokens.  However, the common case is that StringToks points to one
1312 /// string.
1313 ///
1314 ExprResult
1315 Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks,
1316                          Scope *UDLScope) {
1317   assert(NumStringToks && "Must have at least one string!");
1318 
1319   StringLiteralParser Literal(StringToks, NumStringToks, PP);
1320   if (Literal.hadError)
1321     return ExprError();
1322 
1323   SmallVector<SourceLocation, 4> StringTokLocs;
1324   for (unsigned i = 0; i != NumStringToks; ++i)
1325     StringTokLocs.push_back(StringToks[i].getLocation());
1326 
1327   QualType StrTy = Context.CharTy;
1328   if (Literal.isWide())
1329     StrTy = Context.getWCharType();
1330   else if (Literal.isUTF16())
1331     StrTy = Context.Char16Ty;
1332   else if (Literal.isUTF32())
1333     StrTy = Context.Char32Ty;
1334   else if (Literal.isPascal())
1335     StrTy = Context.UnsignedCharTy;
1336 
1337   StringLiteral::StringKind Kind = StringLiteral::Ascii;
1338   if (Literal.isWide())
1339     Kind = StringLiteral::Wide;
1340   else if (Literal.isUTF8())
1341     Kind = StringLiteral::UTF8;
1342   else if (Literal.isUTF16())
1343     Kind = StringLiteral::UTF16;
1344   else if (Literal.isUTF32())
1345     Kind = StringLiteral::UTF32;
1346 
1347   // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
1348   if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
1349     StrTy.addConst();
1350 
1351   // Get an array type for the string, according to C99 6.4.5.  This includes
1352   // the nul terminator character as well as the string length for pascal
1353   // strings.
1354   StrTy = Context.getConstantArrayType(StrTy,
1355                                  llvm::APInt(32, Literal.GetNumStringChars()+1),
1356                                        ArrayType::Normal, 0);
1357 
1358   // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1359   StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1360                                              Kind, Literal.Pascal, StrTy,
1361                                              &StringTokLocs[0],
1362                                              StringTokLocs.size());
1363   if (Literal.getUDSuffix().empty())
1364     return Owned(Lit);
1365 
1366   // We're building a user-defined literal.
1367   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1368   SourceLocation UDSuffixLoc =
1369     getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1370                    Literal.getUDSuffixOffset());
1371 
1372   // Make sure we're allowed user-defined literals here.
1373   if (!UDLScope)
1374     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1375 
1376   // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1377   //   operator "" X (str, len)
1378   QualType SizeType = Context.getSizeType();
1379   llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1380   IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1381                                                   StringTokLocs[0]);
1382   Expr *Args[] = { Lit, LenArg };
1383   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
1384                                         Args, StringTokLocs.back());
1385 }
1386 
1387 ExprResult
1388 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1389                        SourceLocation Loc,
1390                        const CXXScopeSpec *SS) {
1391   DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1392   return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1393 }
1394 
1395 /// BuildDeclRefExpr - Build an expression that references a
1396 /// declaration that does not require a closure capture.
1397 ExprResult
1398 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1399                        const DeclarationNameInfo &NameInfo,
1400                        const CXXScopeSpec *SS) {
1401   if (getLangOpts().CUDA)
1402     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
1403       if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) {
1404         CUDAFunctionTarget CallerTarget = IdentifyCUDATarget(Caller),
1405                            CalleeTarget = IdentifyCUDATarget(Callee);
1406         if (CheckCUDATarget(CallerTarget, CalleeTarget)) {
1407           Diag(NameInfo.getLoc(), diag::err_ref_bad_target)
1408             << CalleeTarget << D->getIdentifier() << CallerTarget;
1409           Diag(D->getLocation(), diag::note_previous_decl)
1410             << D->getIdentifier();
1411           return ExprError();
1412         }
1413       }
1414 
1415   bool refersToEnclosingScope =
1416     (CurContext != D->getDeclContext() &&
1417      D->getDeclContext()->isFunctionOrMethod());
1418 
1419   DeclRefExpr *E = DeclRefExpr::Create(Context,
1420                                        SS ? SS->getWithLocInContext(Context)
1421                                               : NestedNameSpecifierLoc(),
1422                                        SourceLocation(),
1423                                        D, refersToEnclosingScope,
1424                                        NameInfo, Ty, VK);
1425 
1426   MarkDeclRefReferenced(E);
1427 
1428   if (getLangOpts().ObjCARCWeak && isa<VarDecl>(D) &&
1429       Ty.getObjCLifetime() == Qualifiers::OCL_Weak) {
1430     DiagnosticsEngine::Level Level =
1431       Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
1432                                E->getLocStart());
1433     if (Level != DiagnosticsEngine::Ignored)
1434       getCurFunction()->recordUseOfWeak(E);
1435   }
1436 
1437   // Just in case we're building an illegal pointer-to-member.
1438   FieldDecl *FD = dyn_cast<FieldDecl>(D);
1439   if (FD && FD->isBitField())
1440     E->setObjectKind(OK_BitField);
1441 
1442   return Owned(E);
1443 }
1444 
1445 /// Decomposes the given name into a DeclarationNameInfo, its location, and
1446 /// possibly a list of template arguments.
1447 ///
1448 /// If this produces template arguments, it is permitted to call
1449 /// DecomposeTemplateName.
1450 ///
1451 /// This actually loses a lot of source location information for
1452 /// non-standard name kinds; we should consider preserving that in
1453 /// some way.
1454 void
1455 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1456                              TemplateArgumentListInfo &Buffer,
1457                              DeclarationNameInfo &NameInfo,
1458                              const TemplateArgumentListInfo *&TemplateArgs) {
1459   if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1460     Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1461     Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1462 
1463     ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
1464                                        Id.TemplateId->NumArgs);
1465     translateTemplateArguments(TemplateArgsPtr, Buffer);
1466 
1467     TemplateName TName = Id.TemplateId->Template.get();
1468     SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1469     NameInfo = Context.getNameForTemplate(TName, TNameLoc);
1470     TemplateArgs = &Buffer;
1471   } else {
1472     NameInfo = GetNameFromUnqualifiedId(Id);
1473     TemplateArgs = 0;
1474   }
1475 }
1476 
1477 /// Diagnose an empty lookup.
1478 ///
1479 /// \return false if new lookup candidates were found
1480 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1481                                CorrectionCandidateCallback &CCC,
1482                                TemplateArgumentListInfo *ExplicitTemplateArgs,
1483                                llvm::ArrayRef<Expr *> Args) {
1484   DeclarationName Name = R.getLookupName();
1485 
1486   unsigned diagnostic = diag::err_undeclared_var_use;
1487   unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
1488   if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1489       Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
1490       Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
1491     diagnostic = diag::err_undeclared_use;
1492     diagnostic_suggest = diag::err_undeclared_use_suggest;
1493   }
1494 
1495   // If the original lookup was an unqualified lookup, fake an
1496   // unqualified lookup.  This is useful when (for example) the
1497   // original lookup would not have found something because it was a
1498   // dependent name.
1499   DeclContext *DC = (SS.isEmpty() && !CallsUndergoingInstantiation.empty())
1500     ? CurContext : 0;
1501   while (DC) {
1502     if (isa<CXXRecordDecl>(DC)) {
1503       LookupQualifiedName(R, DC);
1504 
1505       if (!R.empty()) {
1506         // Don't give errors about ambiguities in this lookup.
1507         R.suppressDiagnostics();
1508 
1509         // During a default argument instantiation the CurContext points
1510         // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1511         // function parameter list, hence add an explicit check.
1512         bool isDefaultArgument = !ActiveTemplateInstantiations.empty() &&
1513                               ActiveTemplateInstantiations.back().Kind ==
1514             ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
1515         CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1516         bool isInstance = CurMethod &&
1517                           CurMethod->isInstance() &&
1518                           DC == CurMethod->getParent() && !isDefaultArgument;
1519 
1520 
1521         // Give a code modification hint to insert 'this->'.
1522         // TODO: fixit for inserting 'Base<T>::' in the other cases.
1523         // Actually quite difficult!
1524         if (getLangOpts().MicrosoftMode)
1525           diagnostic = diag::warn_found_via_dependent_bases_lookup;
1526         if (isInstance) {
1527           Diag(R.getNameLoc(), diagnostic) << Name
1528             << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1529           UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1530               CallsUndergoingInstantiation.back()->getCallee());
1531 
1532 
1533           CXXMethodDecl *DepMethod;
1534           if (CurMethod->getTemplatedKind() ==
1535               FunctionDecl::TK_FunctionTemplateSpecialization)
1536             DepMethod = cast<CXXMethodDecl>(CurMethod->getPrimaryTemplate()->
1537                 getInstantiatedFromMemberTemplate()->getTemplatedDecl());
1538           else
1539             DepMethod = cast<CXXMethodDecl>(
1540                 CurMethod->getInstantiatedFromMemberFunction());
1541           assert(DepMethod && "No template pattern found");
1542 
1543           QualType DepThisType = DepMethod->getThisType(Context);
1544           CheckCXXThisCapture(R.getNameLoc());
1545           CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1546                                      R.getNameLoc(), DepThisType, false);
1547           TemplateArgumentListInfo TList;
1548           if (ULE->hasExplicitTemplateArgs())
1549             ULE->copyTemplateArgumentsInto(TList);
1550 
1551           CXXScopeSpec SS;
1552           SS.Adopt(ULE->getQualifierLoc());
1553           CXXDependentScopeMemberExpr *DepExpr =
1554               CXXDependentScopeMemberExpr::Create(
1555                   Context, DepThis, DepThisType, true, SourceLocation(),
1556                   SS.getWithLocInContext(Context),
1557                   ULE->getTemplateKeywordLoc(), 0,
1558                   R.getLookupNameInfo(),
1559                   ULE->hasExplicitTemplateArgs() ? &TList : 0);
1560           CallsUndergoingInstantiation.back()->setCallee(DepExpr);
1561         } else {
1562           Diag(R.getNameLoc(), diagnostic) << Name;
1563         }
1564 
1565         // Do we really want to note all of these?
1566         for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1567           Diag((*I)->getLocation(), diag::note_dependent_var_use);
1568 
1569         // Return true if we are inside a default argument instantiation
1570         // and the found name refers to an instance member function, otherwise
1571         // the function calling DiagnoseEmptyLookup will try to create an
1572         // implicit member call and this is wrong for default argument.
1573         if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1574           Diag(R.getNameLoc(), diag::err_member_call_without_object);
1575           return true;
1576         }
1577 
1578         // Tell the callee to try to recover.
1579         return false;
1580       }
1581 
1582       R.clear();
1583     }
1584 
1585     // In Microsoft mode, if we are performing lookup from within a friend
1586     // function definition declared at class scope then we must set
1587     // DC to the lexical parent to be able to search into the parent
1588     // class.
1589     if (getLangOpts().MicrosoftMode && isa<FunctionDecl>(DC) &&
1590         cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1591         DC->getLexicalParent()->isRecord())
1592       DC = DC->getLexicalParent();
1593     else
1594       DC = DC->getParent();
1595   }
1596 
1597   // We didn't find anything, so try to correct for a typo.
1598   TypoCorrection Corrected;
1599   if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
1600                                     S, &SS, CCC))) {
1601     std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1602     std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOpts()));
1603     R.setLookupName(Corrected.getCorrection());
1604 
1605     if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
1606       if (Corrected.isOverloaded()) {
1607         OverloadCandidateSet OCS(R.getNameLoc());
1608         OverloadCandidateSet::iterator Best;
1609         for (TypoCorrection::decl_iterator CD = Corrected.begin(),
1610                                         CDEnd = Corrected.end();
1611              CD != CDEnd; ++CD) {
1612           if (FunctionTemplateDecl *FTD =
1613                    dyn_cast<FunctionTemplateDecl>(*CD))
1614             AddTemplateOverloadCandidate(
1615                 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
1616                 Args, OCS);
1617           else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
1618             if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1619               AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
1620                                    Args, OCS);
1621         }
1622         switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1623           case OR_Success:
1624             ND = Best->Function;
1625             break;
1626           default:
1627             break;
1628         }
1629       }
1630       R.addDecl(ND);
1631       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
1632         if (SS.isEmpty())
1633           Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr
1634             << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1635         else
1636           Diag(R.getNameLoc(), diag::err_no_member_suggest)
1637             << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
1638             << SS.getRange()
1639             << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1640         if (ND)
1641           Diag(ND->getLocation(), diag::note_previous_decl)
1642             << CorrectedQuotedStr;
1643 
1644         // Tell the callee to try to recover.
1645         return false;
1646       }
1647 
1648       if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) {
1649         // FIXME: If we ended up with a typo for a type name or
1650         // Objective-C class name, we're in trouble because the parser
1651         // is in the wrong place to recover. Suggest the typo
1652         // correction, but don't make it a fix-it since we're not going
1653         // to recover well anyway.
1654         if (SS.isEmpty())
1655           Diag(R.getNameLoc(), diagnostic_suggest)
1656             << Name << CorrectedQuotedStr;
1657         else
1658           Diag(R.getNameLoc(), diag::err_no_member_suggest)
1659             << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
1660             << SS.getRange();
1661 
1662         // Don't try to recover; it won't work.
1663         return true;
1664       }
1665     } else {
1666       // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
1667       // because we aren't able to recover.
1668       if (SS.isEmpty())
1669         Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr;
1670       else
1671         Diag(R.getNameLoc(), diag::err_no_member_suggest)
1672         << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
1673         << SS.getRange();
1674       return true;
1675     }
1676   }
1677   R.clear();
1678 
1679   // Emit a special diagnostic for failed member lookups.
1680   // FIXME: computing the declaration context might fail here (?)
1681   if (!SS.isEmpty()) {
1682     Diag(R.getNameLoc(), diag::err_no_member)
1683       << Name << computeDeclContext(SS, false)
1684       << SS.getRange();
1685     return true;
1686   }
1687 
1688   // Give up, we can't recover.
1689   Diag(R.getNameLoc(), diagnostic) << Name;
1690   return true;
1691 }
1692 
1693 ExprResult Sema::ActOnIdExpression(Scope *S,
1694                                    CXXScopeSpec &SS,
1695                                    SourceLocation TemplateKWLoc,
1696                                    UnqualifiedId &Id,
1697                                    bool HasTrailingLParen,
1698                                    bool IsAddressOfOperand,
1699                                    CorrectionCandidateCallback *CCC) {
1700   assert(!(IsAddressOfOperand && HasTrailingLParen) &&
1701          "cannot be direct & operand and have a trailing lparen");
1702 
1703   if (SS.isInvalid())
1704     return ExprError();
1705 
1706   TemplateArgumentListInfo TemplateArgsBuffer;
1707 
1708   // Decompose the UnqualifiedId into the following data.
1709   DeclarationNameInfo NameInfo;
1710   const TemplateArgumentListInfo *TemplateArgs;
1711   DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
1712 
1713   DeclarationName Name = NameInfo.getName();
1714   IdentifierInfo *II = Name.getAsIdentifierInfo();
1715   SourceLocation NameLoc = NameInfo.getLoc();
1716 
1717   // C++ [temp.dep.expr]p3:
1718   //   An id-expression is type-dependent if it contains:
1719   //     -- an identifier that was declared with a dependent type,
1720   //        (note: handled after lookup)
1721   //     -- a template-id that is dependent,
1722   //        (note: handled in BuildTemplateIdExpr)
1723   //     -- a conversion-function-id that specifies a dependent type,
1724   //     -- a nested-name-specifier that contains a class-name that
1725   //        names a dependent type.
1726   // Determine whether this is a member of an unknown specialization;
1727   // we need to handle these differently.
1728   bool DependentID = false;
1729   if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1730       Name.getCXXNameType()->isDependentType()) {
1731     DependentID = true;
1732   } else if (SS.isSet()) {
1733     if (DeclContext *DC = computeDeclContext(SS, false)) {
1734       if (RequireCompleteDeclContext(SS, DC))
1735         return ExprError();
1736     } else {
1737       DependentID = true;
1738     }
1739   }
1740 
1741   if (DependentID)
1742     return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1743                                       IsAddressOfOperand, TemplateArgs);
1744 
1745   // Perform the required lookup.
1746   LookupResult R(*this, NameInfo,
1747                  (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
1748                   ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
1749   if (TemplateArgs) {
1750     // Lookup the template name again to correctly establish the context in
1751     // which it was found. This is really unfortunate as we already did the
1752     // lookup to determine that it was a template name in the first place. If
1753     // this becomes a performance hit, we can work harder to preserve those
1754     // results until we get here but it's likely not worth it.
1755     bool MemberOfUnknownSpecialization;
1756     LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1757                        MemberOfUnknownSpecialization);
1758 
1759     if (MemberOfUnknownSpecialization ||
1760         (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
1761       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1762                                         IsAddressOfOperand, TemplateArgs);
1763   } else {
1764     bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
1765     LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
1766 
1767     // If the result might be in a dependent base class, this is a dependent
1768     // id-expression.
1769     if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
1770       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1771                                         IsAddressOfOperand, TemplateArgs);
1772 
1773     // If this reference is in an Objective-C method, then we need to do
1774     // some special Objective-C lookup, too.
1775     if (IvarLookupFollowUp) {
1776       ExprResult E(LookupInObjCMethod(R, S, II, true));
1777       if (E.isInvalid())
1778         return ExprError();
1779 
1780       if (Expr *Ex = E.takeAs<Expr>())
1781         return Owned(Ex);
1782     }
1783   }
1784 
1785   if (R.isAmbiguous())
1786     return ExprError();
1787 
1788   // Determine whether this name might be a candidate for
1789   // argument-dependent lookup.
1790   bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
1791 
1792   if (R.empty() && !ADL) {
1793     // Otherwise, this could be an implicitly declared function reference (legal
1794     // in C90, extension in C99, forbidden in C++).
1795     if (HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
1796       NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1797       if (D) R.addDecl(D);
1798     }
1799 
1800     // If this name wasn't predeclared and if this is not a function
1801     // call, diagnose the problem.
1802     if (R.empty()) {
1803 
1804       // In Microsoft mode, if we are inside a template class member function
1805       // and we can't resolve an identifier then assume the identifier is type
1806       // dependent. The goal is to postpone name lookup to instantiation time
1807       // to be able to search into type dependent base classes.
1808       if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
1809           isa<CXXMethodDecl>(CurContext))
1810         return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1811                                           IsAddressOfOperand, TemplateArgs);
1812 
1813       CorrectionCandidateCallback DefaultValidator;
1814       if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator))
1815         return ExprError();
1816 
1817       assert(!R.empty() &&
1818              "DiagnoseEmptyLookup returned false but added no results");
1819 
1820       // If we found an Objective-C instance variable, let
1821       // LookupInObjCMethod build the appropriate expression to
1822       // reference the ivar.
1823       if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1824         R.clear();
1825         ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
1826         // In a hopelessly buggy code, Objective-C instance variable
1827         // lookup fails and no expression will be built to reference it.
1828         if (!E.isInvalid() && !E.get())
1829           return ExprError();
1830         return E;
1831       }
1832     }
1833   }
1834 
1835   // This is guaranteed from this point on.
1836   assert(!R.empty() || ADL);
1837 
1838   // Check whether this might be a C++ implicit instance member access.
1839   // C++ [class.mfct.non-static]p3:
1840   //   When an id-expression that is not part of a class member access
1841   //   syntax and not used to form a pointer to member is used in the
1842   //   body of a non-static member function of class X, if name lookup
1843   //   resolves the name in the id-expression to a non-static non-type
1844   //   member of some class C, the id-expression is transformed into a
1845   //   class member access expression using (*this) as the
1846   //   postfix-expression to the left of the . operator.
1847   //
1848   // But we don't actually need to do this for '&' operands if R
1849   // resolved to a function or overloaded function set, because the
1850   // expression is ill-formed if it actually works out to be a
1851   // non-static member function:
1852   //
1853   // C++ [expr.ref]p4:
1854   //   Otherwise, if E1.E2 refers to a non-static member function. . .
1855   //   [t]he expression can be used only as the left-hand operand of a
1856   //   member function call.
1857   //
1858   // There are other safeguards against such uses, but it's important
1859   // to get this right here so that we don't end up making a
1860   // spuriously dependent expression if we're inside a dependent
1861   // instance method.
1862   if (!R.empty() && (*R.begin())->isCXXClassMember()) {
1863     bool MightBeImplicitMember;
1864     if (!IsAddressOfOperand)
1865       MightBeImplicitMember = true;
1866     else if (!SS.isEmpty())
1867       MightBeImplicitMember = false;
1868     else if (R.isOverloadedResult())
1869       MightBeImplicitMember = false;
1870     else if (R.isUnresolvableResult())
1871       MightBeImplicitMember = true;
1872     else
1873       MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
1874                               isa<IndirectFieldDecl>(R.getFoundDecl());
1875 
1876     if (MightBeImplicitMember)
1877       return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
1878                                              R, TemplateArgs);
1879   }
1880 
1881   if (TemplateArgs || TemplateKWLoc.isValid())
1882     return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
1883 
1884   return BuildDeclarationNameExpr(SS, R, ADL);
1885 }
1886 
1887 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1888 /// declaration name, generally during template instantiation.
1889 /// There's a large number of things which don't need to be done along
1890 /// this path.
1891 ExprResult
1892 Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
1893                                         const DeclarationNameInfo &NameInfo) {
1894   DeclContext *DC;
1895   if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
1896     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
1897                                      NameInfo, /*TemplateArgs=*/0);
1898 
1899   if (RequireCompleteDeclContext(SS, DC))
1900     return ExprError();
1901 
1902   LookupResult R(*this, NameInfo, LookupOrdinaryName);
1903   LookupQualifiedName(R, DC);
1904 
1905   if (R.isAmbiguous())
1906     return ExprError();
1907 
1908   if (R.empty()) {
1909     Diag(NameInfo.getLoc(), diag::err_no_member)
1910       << NameInfo.getName() << DC << SS.getRange();
1911     return ExprError();
1912   }
1913 
1914   return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1915 }
1916 
1917 /// LookupInObjCMethod - The parser has read a name in, and Sema has
1918 /// detected that we're currently inside an ObjC method.  Perform some
1919 /// additional lookup.
1920 ///
1921 /// Ideally, most of this would be done by lookup, but there's
1922 /// actually quite a lot of extra work involved.
1923 ///
1924 /// Returns a null sentinel to indicate trivial success.
1925 ExprResult
1926 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
1927                          IdentifierInfo *II, bool AllowBuiltinCreation) {
1928   SourceLocation Loc = Lookup.getNameLoc();
1929   ObjCMethodDecl *CurMethod = getCurMethodDecl();
1930 
1931   // There are two cases to handle here.  1) scoped lookup could have failed,
1932   // in which case we should look for an ivar.  2) scoped lookup could have
1933   // found a decl, but that decl is outside the current instance method (i.e.
1934   // a global variable).  In these two cases, we do a lookup for an ivar with
1935   // this name, if the lookup sucedes, we replace it our current decl.
1936 
1937   // If we're in a class method, we don't normally want to look for
1938   // ivars.  But if we don't find anything else, and there's an
1939   // ivar, that's an error.
1940   bool IsClassMethod = CurMethod->isClassMethod();
1941 
1942   bool LookForIvars;
1943   if (Lookup.empty())
1944     LookForIvars = true;
1945   else if (IsClassMethod)
1946     LookForIvars = false;
1947   else
1948     LookForIvars = (Lookup.isSingleResult() &&
1949                     Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
1950   ObjCInterfaceDecl *IFace = 0;
1951   if (LookForIvars) {
1952     IFace = CurMethod->getClassInterface();
1953     ObjCInterfaceDecl *ClassDeclared;
1954     ObjCIvarDecl *IV = 0;
1955     if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
1956       // Diagnose using an ivar in a class method.
1957       if (IsClassMethod)
1958         return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1959                          << IV->getDeclName());
1960 
1961       // If we're referencing an invalid decl, just return this as a silent
1962       // error node.  The error diagnostic was already emitted on the decl.
1963       if (IV->isInvalidDecl())
1964         return ExprError();
1965 
1966       // Check if referencing a field with __attribute__((deprecated)).
1967       if (DiagnoseUseOfDecl(IV, Loc))
1968         return ExprError();
1969 
1970       // Diagnose the use of an ivar outside of the declaring class.
1971       if (IV->getAccessControl() == ObjCIvarDecl::Private &&
1972           !declaresSameEntity(ClassDeclared, IFace) &&
1973           !getLangOpts().DebuggerSupport)
1974         Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1975 
1976       // FIXME: This should use a new expr for a direct reference, don't
1977       // turn this into Self->ivar, just return a BareIVarExpr or something.
1978       IdentifierInfo &II = Context.Idents.get("self");
1979       UnqualifiedId SelfName;
1980       SelfName.setIdentifier(&II, SourceLocation());
1981       SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
1982       CXXScopeSpec SelfScopeSpec;
1983       SourceLocation TemplateKWLoc;
1984       ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
1985                                               SelfName, false, false);
1986       if (SelfExpr.isInvalid())
1987         return ExprError();
1988 
1989       SelfExpr = DefaultLvalueConversion(SelfExpr.take());
1990       if (SelfExpr.isInvalid())
1991         return ExprError();
1992 
1993       MarkAnyDeclReferenced(Loc, IV);
1994 
1995       ObjCMethodFamily MF = CurMethod->getMethodFamily();
1996       if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize)
1997         Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
1998 
1999       ObjCIvarRefExpr *Result = new (Context) ObjCIvarRefExpr(IV, IV->getType(),
2000                                                               Loc,
2001                                                               SelfExpr.take(),
2002                                                               true, true);
2003 
2004       if (getLangOpts().ObjCAutoRefCount) {
2005         if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2006           DiagnosticsEngine::Level Level =
2007             Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, Loc);
2008           if (Level != DiagnosticsEngine::Ignored)
2009             getCurFunction()->recordUseOfWeak(Result);
2010         }
2011       }
2012 
2013       return Owned(Result);
2014     }
2015   } else if (CurMethod->isInstanceMethod()) {
2016     // We should warn if a local variable hides an ivar.
2017     if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2018       ObjCInterfaceDecl *ClassDeclared;
2019       if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2020         if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2021             declaresSameEntity(IFace, ClassDeclared))
2022           Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2023       }
2024     }
2025   } else if (Lookup.isSingleResult() &&
2026              Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2027     // If accessing a stand-alone ivar in a class method, this is an error.
2028     if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
2029       return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
2030                        << IV->getDeclName());
2031   }
2032 
2033   if (Lookup.empty() && II && AllowBuiltinCreation) {
2034     // FIXME. Consolidate this with similar code in LookupName.
2035     if (unsigned BuiltinID = II->getBuiltinID()) {
2036       if (!(getLangOpts().CPlusPlus &&
2037             Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2038         NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2039                                            S, Lookup.isForRedeclaration(),
2040                                            Lookup.getNameLoc());
2041         if (D) Lookup.addDecl(D);
2042       }
2043     }
2044   }
2045   // Sentinel value saying that we didn't do anything special.
2046   return Owned((Expr*) 0);
2047 }
2048 
2049 /// \brief Cast a base object to a member's actual type.
2050 ///
2051 /// Logically this happens in three phases:
2052 ///
2053 /// * First we cast from the base type to the naming class.
2054 ///   The naming class is the class into which we were looking
2055 ///   when we found the member;  it's the qualifier type if a
2056 ///   qualifier was provided, and otherwise it's the base type.
2057 ///
2058 /// * Next we cast from the naming class to the declaring class.
2059 ///   If the member we found was brought into a class's scope by
2060 ///   a using declaration, this is that class;  otherwise it's
2061 ///   the class declaring the member.
2062 ///
2063 /// * Finally we cast from the declaring class to the "true"
2064 ///   declaring class of the member.  This conversion does not
2065 ///   obey access control.
2066 ExprResult
2067 Sema::PerformObjectMemberConversion(Expr *From,
2068                                     NestedNameSpecifier *Qualifier,
2069                                     NamedDecl *FoundDecl,
2070                                     NamedDecl *Member) {
2071   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2072   if (!RD)
2073     return Owned(From);
2074 
2075   QualType DestRecordType;
2076   QualType DestType;
2077   QualType FromRecordType;
2078   QualType FromType = From->getType();
2079   bool PointerConversions = false;
2080   if (isa<FieldDecl>(Member)) {
2081     DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2082 
2083     if (FromType->getAs<PointerType>()) {
2084       DestType = Context.getPointerType(DestRecordType);
2085       FromRecordType = FromType->getPointeeType();
2086       PointerConversions = true;
2087     } else {
2088       DestType = DestRecordType;
2089       FromRecordType = FromType;
2090     }
2091   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2092     if (Method->isStatic())
2093       return Owned(From);
2094 
2095     DestType = Method->getThisType(Context);
2096     DestRecordType = DestType->getPointeeType();
2097 
2098     if (FromType->getAs<PointerType>()) {
2099       FromRecordType = FromType->getPointeeType();
2100       PointerConversions = true;
2101     } else {
2102       FromRecordType = FromType;
2103       DestType = DestRecordType;
2104     }
2105   } else {
2106     // No conversion necessary.
2107     return Owned(From);
2108   }
2109 
2110   if (DestType->isDependentType() || FromType->isDependentType())
2111     return Owned(From);
2112 
2113   // If the unqualified types are the same, no conversion is necessary.
2114   if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2115     return Owned(From);
2116 
2117   SourceRange FromRange = From->getSourceRange();
2118   SourceLocation FromLoc = FromRange.getBegin();
2119 
2120   ExprValueKind VK = From->getValueKind();
2121 
2122   // C++ [class.member.lookup]p8:
2123   //   [...] Ambiguities can often be resolved by qualifying a name with its
2124   //   class name.
2125   //
2126   // If the member was a qualified name and the qualified referred to a
2127   // specific base subobject type, we'll cast to that intermediate type
2128   // first and then to the object in which the member is declared. That allows
2129   // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2130   //
2131   //   class Base { public: int x; };
2132   //   class Derived1 : public Base { };
2133   //   class Derived2 : public Base { };
2134   //   class VeryDerived : public Derived1, public Derived2 { void f(); };
2135   //
2136   //   void VeryDerived::f() {
2137   //     x = 17; // error: ambiguous base subobjects
2138   //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
2139   //   }
2140   if (Qualifier) {
2141     QualType QType = QualType(Qualifier->getAsType(), 0);
2142     assert(!QType.isNull() && "lookup done with dependent qualifier?");
2143     assert(QType->isRecordType() && "lookup done with non-record type");
2144 
2145     QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2146 
2147     // In C++98, the qualifier type doesn't actually have to be a base
2148     // type of the object type, in which case we just ignore it.
2149     // Otherwise build the appropriate casts.
2150     if (IsDerivedFrom(FromRecordType, QRecordType)) {
2151       CXXCastPath BasePath;
2152       if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2153                                        FromLoc, FromRange, &BasePath))
2154         return ExprError();
2155 
2156       if (PointerConversions)
2157         QType = Context.getPointerType(QType);
2158       From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2159                                VK, &BasePath).take();
2160 
2161       FromType = QType;
2162       FromRecordType = QRecordType;
2163 
2164       // If the qualifier type was the same as the destination type,
2165       // we're done.
2166       if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2167         return Owned(From);
2168     }
2169   }
2170 
2171   bool IgnoreAccess = false;
2172 
2173   // If we actually found the member through a using declaration, cast
2174   // down to the using declaration's type.
2175   //
2176   // Pointer equality is fine here because only one declaration of a
2177   // class ever has member declarations.
2178   if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2179     assert(isa<UsingShadowDecl>(FoundDecl));
2180     QualType URecordType = Context.getTypeDeclType(
2181                            cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2182 
2183     // We only need to do this if the naming-class to declaring-class
2184     // conversion is non-trivial.
2185     if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2186       assert(IsDerivedFrom(FromRecordType, URecordType));
2187       CXXCastPath BasePath;
2188       if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2189                                        FromLoc, FromRange, &BasePath))
2190         return ExprError();
2191 
2192       QualType UType = URecordType;
2193       if (PointerConversions)
2194         UType = Context.getPointerType(UType);
2195       From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2196                                VK, &BasePath).take();
2197       FromType = UType;
2198       FromRecordType = URecordType;
2199     }
2200 
2201     // We don't do access control for the conversion from the
2202     // declaring class to the true declaring class.
2203     IgnoreAccess = true;
2204   }
2205 
2206   CXXCastPath BasePath;
2207   if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2208                                    FromLoc, FromRange, &BasePath,
2209                                    IgnoreAccess))
2210     return ExprError();
2211 
2212   return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2213                            VK, &BasePath);
2214 }
2215 
2216 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2217                                       const LookupResult &R,
2218                                       bool HasTrailingLParen) {
2219   // Only when used directly as the postfix-expression of a call.
2220   if (!HasTrailingLParen)
2221     return false;
2222 
2223   // Never if a scope specifier was provided.
2224   if (SS.isSet())
2225     return false;
2226 
2227   // Only in C++ or ObjC++.
2228   if (!getLangOpts().CPlusPlus)
2229     return false;
2230 
2231   // Turn off ADL when we find certain kinds of declarations during
2232   // normal lookup:
2233   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2234     NamedDecl *D = *I;
2235 
2236     // C++0x [basic.lookup.argdep]p3:
2237     //     -- a declaration of a class member
2238     // Since using decls preserve this property, we check this on the
2239     // original decl.
2240     if (D->isCXXClassMember())
2241       return false;
2242 
2243     // C++0x [basic.lookup.argdep]p3:
2244     //     -- a block-scope function declaration that is not a
2245     //        using-declaration
2246     // NOTE: we also trigger this for function templates (in fact, we
2247     // don't check the decl type at all, since all other decl types
2248     // turn off ADL anyway).
2249     if (isa<UsingShadowDecl>(D))
2250       D = cast<UsingShadowDecl>(D)->getTargetDecl();
2251     else if (D->getDeclContext()->isFunctionOrMethod())
2252       return false;
2253 
2254     // C++0x [basic.lookup.argdep]p3:
2255     //     -- a declaration that is neither a function or a function
2256     //        template
2257     // And also for builtin functions.
2258     if (isa<FunctionDecl>(D)) {
2259       FunctionDecl *FDecl = cast<FunctionDecl>(D);
2260 
2261       // But also builtin functions.
2262       if (FDecl->getBuiltinID() && FDecl->isImplicit())
2263         return false;
2264     } else if (!isa<FunctionTemplateDecl>(D))
2265       return false;
2266   }
2267 
2268   return true;
2269 }
2270 
2271 
2272 /// Diagnoses obvious problems with the use of the given declaration
2273 /// as an expression.  This is only actually called for lookups that
2274 /// were not overloaded, and it doesn't promise that the declaration
2275 /// will in fact be used.
2276 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2277   if (isa<TypedefNameDecl>(D)) {
2278     S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2279     return true;
2280   }
2281 
2282   if (isa<ObjCInterfaceDecl>(D)) {
2283     S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2284     return true;
2285   }
2286 
2287   if (isa<NamespaceDecl>(D)) {
2288     S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2289     return true;
2290   }
2291 
2292   return false;
2293 }
2294 
2295 ExprResult
2296 Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2297                                LookupResult &R,
2298                                bool NeedsADL) {
2299   // If this is a single, fully-resolved result and we don't need ADL,
2300   // just build an ordinary singleton decl ref.
2301   if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
2302     return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
2303                                     R.getFoundDecl());
2304 
2305   // We only need to check the declaration if there's exactly one
2306   // result, because in the overloaded case the results can only be
2307   // functions and function templates.
2308   if (R.isSingleResult() &&
2309       CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
2310     return ExprError();
2311 
2312   // Otherwise, just build an unresolved lookup expression.  Suppress
2313   // any lookup-related diagnostics; we'll hash these out later, when
2314   // we've picked a target.
2315   R.suppressDiagnostics();
2316 
2317   UnresolvedLookupExpr *ULE
2318     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2319                                    SS.getWithLocInContext(Context),
2320                                    R.getLookupNameInfo(),
2321                                    NeedsADL, R.isOverloadedResult(),
2322                                    R.begin(), R.end());
2323 
2324   return Owned(ULE);
2325 }
2326 
2327 /// \brief Complete semantic analysis for a reference to the given declaration.
2328 ExprResult
2329 Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2330                                const DeclarationNameInfo &NameInfo,
2331                                NamedDecl *D) {
2332   assert(D && "Cannot refer to a NULL declaration");
2333   assert(!isa<FunctionTemplateDecl>(D) &&
2334          "Cannot refer unambiguously to a function template");
2335 
2336   SourceLocation Loc = NameInfo.getLoc();
2337   if (CheckDeclInExpr(*this, Loc, D))
2338     return ExprError();
2339 
2340   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2341     // Specifically diagnose references to class templates that are missing
2342     // a template argument list.
2343     Diag(Loc, diag::err_template_decl_ref)
2344       << Template << SS.getRange();
2345     Diag(Template->getLocation(), diag::note_template_decl_here);
2346     return ExprError();
2347   }
2348 
2349   // Make sure that we're referring to a value.
2350   ValueDecl *VD = dyn_cast<ValueDecl>(D);
2351   if (!VD) {
2352     Diag(Loc, diag::err_ref_non_value)
2353       << D << SS.getRange();
2354     Diag(D->getLocation(), diag::note_declared_at);
2355     return ExprError();
2356   }
2357 
2358   // Check whether this declaration can be used. Note that we suppress
2359   // this check when we're going to perform argument-dependent lookup
2360   // on this function name, because this might not be the function
2361   // that overload resolution actually selects.
2362   if (DiagnoseUseOfDecl(VD, Loc))
2363     return ExprError();
2364 
2365   // Only create DeclRefExpr's for valid Decl's.
2366   if (VD->isInvalidDecl())
2367     return ExprError();
2368 
2369   // Handle members of anonymous structs and unions.  If we got here,
2370   // and the reference is to a class member indirect field, then this
2371   // must be the subject of a pointer-to-member expression.
2372   if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2373     if (!indirectField->isCXXClassMember())
2374       return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2375                                                       indirectField);
2376 
2377   {
2378     QualType type = VD->getType();
2379     ExprValueKind valueKind = VK_RValue;
2380 
2381     switch (D->getKind()) {
2382     // Ignore all the non-ValueDecl kinds.
2383 #define ABSTRACT_DECL(kind)
2384 #define VALUE(type, base)
2385 #define DECL(type, base) \
2386     case Decl::type:
2387 #include "clang/AST/DeclNodes.inc"
2388       llvm_unreachable("invalid value decl kind");
2389 
2390     // These shouldn't make it here.
2391     case Decl::ObjCAtDefsField:
2392     case Decl::ObjCIvar:
2393       llvm_unreachable("forming non-member reference to ivar?");
2394 
2395     // Enum constants are always r-values and never references.
2396     // Unresolved using declarations are dependent.
2397     case Decl::EnumConstant:
2398     case Decl::UnresolvedUsingValue:
2399       valueKind = VK_RValue;
2400       break;
2401 
2402     // Fields and indirect fields that got here must be for
2403     // pointer-to-member expressions; we just call them l-values for
2404     // internal consistency, because this subexpression doesn't really
2405     // exist in the high-level semantics.
2406     case Decl::Field:
2407     case Decl::IndirectField:
2408       assert(getLangOpts().CPlusPlus &&
2409              "building reference to field in C?");
2410 
2411       // These can't have reference type in well-formed programs, but
2412       // for internal consistency we do this anyway.
2413       type = type.getNonReferenceType();
2414       valueKind = VK_LValue;
2415       break;
2416 
2417     // Non-type template parameters are either l-values or r-values
2418     // depending on the type.
2419     case Decl::NonTypeTemplateParm: {
2420       if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2421         type = reftype->getPointeeType();
2422         valueKind = VK_LValue; // even if the parameter is an r-value reference
2423         break;
2424       }
2425 
2426       // For non-references, we need to strip qualifiers just in case
2427       // the template parameter was declared as 'const int' or whatever.
2428       valueKind = VK_RValue;
2429       type = type.getUnqualifiedType();
2430       break;
2431     }
2432 
2433     case Decl::Var:
2434       // In C, "extern void blah;" is valid and is an r-value.
2435       if (!getLangOpts().CPlusPlus &&
2436           !type.hasQualifiers() &&
2437           type->isVoidType()) {
2438         valueKind = VK_RValue;
2439         break;
2440       }
2441       // fallthrough
2442 
2443     case Decl::ImplicitParam:
2444     case Decl::ParmVar: {
2445       // These are always l-values.
2446       valueKind = VK_LValue;
2447       type = type.getNonReferenceType();
2448 
2449       // FIXME: Does the addition of const really only apply in
2450       // potentially-evaluated contexts? Since the variable isn't actually
2451       // captured in an unevaluated context, it seems that the answer is no.
2452       if (!isUnevaluatedContext()) {
2453         QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
2454         if (!CapturedType.isNull())
2455           type = CapturedType;
2456       }
2457 
2458       break;
2459     }
2460 
2461     case Decl::Function: {
2462       if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
2463         if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
2464           type = Context.BuiltinFnTy;
2465           valueKind = VK_RValue;
2466           break;
2467         }
2468       }
2469 
2470       const FunctionType *fty = type->castAs<FunctionType>();
2471 
2472       // If we're referring to a function with an __unknown_anytype
2473       // result type, make the entire expression __unknown_anytype.
2474       if (fty->getResultType() == Context.UnknownAnyTy) {
2475         type = Context.UnknownAnyTy;
2476         valueKind = VK_RValue;
2477         break;
2478       }
2479 
2480       // Functions are l-values in C++.
2481       if (getLangOpts().CPlusPlus) {
2482         valueKind = VK_LValue;
2483         break;
2484       }
2485 
2486       // C99 DR 316 says that, if a function type comes from a
2487       // function definition (without a prototype), that type is only
2488       // used for checking compatibility. Therefore, when referencing
2489       // the function, we pretend that we don't have the full function
2490       // type.
2491       if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2492           isa<FunctionProtoType>(fty))
2493         type = Context.getFunctionNoProtoType(fty->getResultType(),
2494                                               fty->getExtInfo());
2495 
2496       // Functions are r-values in C.
2497       valueKind = VK_RValue;
2498       break;
2499     }
2500 
2501     case Decl::CXXMethod:
2502       // If we're referring to a method with an __unknown_anytype
2503       // result type, make the entire expression __unknown_anytype.
2504       // This should only be possible with a type written directly.
2505       if (const FunctionProtoType *proto
2506             = dyn_cast<FunctionProtoType>(VD->getType()))
2507         if (proto->getResultType() == Context.UnknownAnyTy) {
2508           type = Context.UnknownAnyTy;
2509           valueKind = VK_RValue;
2510           break;
2511         }
2512 
2513       // C++ methods are l-values if static, r-values if non-static.
2514       if (cast<CXXMethodDecl>(VD)->isStatic()) {
2515         valueKind = VK_LValue;
2516         break;
2517       }
2518       // fallthrough
2519 
2520     case Decl::CXXConversion:
2521     case Decl::CXXDestructor:
2522     case Decl::CXXConstructor:
2523       valueKind = VK_RValue;
2524       break;
2525     }
2526 
2527     return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS);
2528   }
2529 }
2530 
2531 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
2532   PredefinedExpr::IdentType IT;
2533 
2534   switch (Kind) {
2535   default: llvm_unreachable("Unknown simple primary expr!");
2536   case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2537   case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
2538   case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break;
2539   case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
2540   }
2541 
2542   // Pre-defined identifiers are of type char[x], where x is the length of the
2543   // string.
2544 
2545   Decl *currentDecl = getCurFunctionOrMethodDecl();
2546   if (!currentDecl && getCurBlock())
2547     currentDecl = getCurBlock()->TheDecl;
2548   if (!currentDecl) {
2549     Diag(Loc, diag::ext_predef_outside_function);
2550     currentDecl = Context.getTranslationUnitDecl();
2551   }
2552 
2553   QualType ResTy;
2554   if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2555     ResTy = Context.DependentTy;
2556   } else {
2557     unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
2558 
2559     llvm::APInt LengthI(32, Length + 1);
2560     if (IT == PredefinedExpr::LFunction)
2561       ResTy = Context.WCharTy.withConst();
2562     else
2563       ResTy = Context.CharTy.withConst();
2564     ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2565   }
2566   return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
2567 }
2568 
2569 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
2570   SmallString<16> CharBuffer;
2571   bool Invalid = false;
2572   StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
2573   if (Invalid)
2574     return ExprError();
2575 
2576   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
2577                             PP, Tok.getKind());
2578   if (Literal.hadError())
2579     return ExprError();
2580 
2581   QualType Ty;
2582   if (Literal.isWide())
2583     Ty = Context.WCharTy; // L'x' -> wchar_t in C and C++.
2584   else if (Literal.isUTF16())
2585     Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
2586   else if (Literal.isUTF32())
2587     Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
2588   else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
2589     Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
2590   else
2591     Ty = Context.CharTy;  // 'x' -> char in C++
2592 
2593   CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
2594   if (Literal.isWide())
2595     Kind = CharacterLiteral::Wide;
2596   else if (Literal.isUTF16())
2597     Kind = CharacterLiteral::UTF16;
2598   else if (Literal.isUTF32())
2599     Kind = CharacterLiteral::UTF32;
2600 
2601   Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
2602                                              Tok.getLocation());
2603 
2604   if (Literal.getUDSuffix().empty())
2605     return Owned(Lit);
2606 
2607   // We're building a user-defined literal.
2608   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2609   SourceLocation UDSuffixLoc =
2610     getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
2611 
2612   // Make sure we're allowed user-defined literals here.
2613   if (!UDLScope)
2614     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
2615 
2616   // C++11 [lex.ext]p6: The literal L is treated as a call of the form
2617   //   operator "" X (ch)
2618   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
2619                                         llvm::makeArrayRef(&Lit, 1),
2620                                         Tok.getLocation());
2621 }
2622 
2623 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
2624   unsigned IntSize = Context.getTargetInfo().getIntWidth();
2625   return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
2626                                       Context.IntTy, Loc));
2627 }
2628 
2629 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
2630                                   QualType Ty, SourceLocation Loc) {
2631   const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
2632 
2633   using llvm::APFloat;
2634   APFloat Val(Format);
2635 
2636   APFloat::opStatus result = Literal.GetFloatValue(Val);
2637 
2638   // Overflow is always an error, but underflow is only an error if
2639   // we underflowed to zero (APFloat reports denormals as underflow).
2640   if ((result & APFloat::opOverflow) ||
2641       ((result & APFloat::opUnderflow) && Val.isZero())) {
2642     unsigned diagnostic;
2643     SmallString<20> buffer;
2644     if (result & APFloat::opOverflow) {
2645       diagnostic = diag::warn_float_overflow;
2646       APFloat::getLargest(Format).toString(buffer);
2647     } else {
2648       diagnostic = diag::warn_float_underflow;
2649       APFloat::getSmallest(Format).toString(buffer);
2650     }
2651 
2652     S.Diag(Loc, diagnostic)
2653       << Ty
2654       << StringRef(buffer.data(), buffer.size());
2655   }
2656 
2657   bool isExact = (result == APFloat::opOK);
2658   return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
2659 }
2660 
2661 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
2662   // Fast path for a single digit (which is quite common).  A single digit
2663   // cannot have a trigraph, escaped newline, radix prefix, or suffix.
2664   if (Tok.getLength() == 1) {
2665     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
2666     return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
2667   }
2668 
2669   SmallString<128> SpellingBuffer;
2670   // NumericLiteralParser wants to overread by one character.  Add padding to
2671   // the buffer in case the token is copied to the buffer.  If getSpelling()
2672   // returns a StringRef to the memory buffer, it should have a null char at
2673   // the EOF, so it is also safe.
2674   SpellingBuffer.resize(Tok.getLength() + 1);
2675 
2676   // Get the spelling of the token, which eliminates trigraphs, etc.
2677   bool Invalid = false;
2678   StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
2679   if (Invalid)
2680     return ExprError();
2681 
2682   NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
2683   if (Literal.hadError)
2684     return ExprError();
2685 
2686   if (Literal.hasUDSuffix()) {
2687     // We're building a user-defined literal.
2688     IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2689     SourceLocation UDSuffixLoc =
2690       getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
2691 
2692     // Make sure we're allowed user-defined literals here.
2693     if (!UDLScope)
2694       return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
2695 
2696     QualType CookedTy;
2697     if (Literal.isFloatingLiteral()) {
2698       // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
2699       // long double, the literal is treated as a call of the form
2700       //   operator "" X (f L)
2701       CookedTy = Context.LongDoubleTy;
2702     } else {
2703       // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
2704       // unsigned long long, the literal is treated as a call of the form
2705       //   operator "" X (n ULL)
2706       CookedTy = Context.UnsignedLongLongTy;
2707     }
2708 
2709     DeclarationName OpName =
2710       Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
2711     DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
2712     OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
2713 
2714     // Perform literal operator lookup to determine if we're building a raw
2715     // literal or a cooked one.
2716     LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
2717     switch (LookupLiteralOperator(UDLScope, R, llvm::makeArrayRef(&CookedTy, 1),
2718                                   /*AllowRawAndTemplate*/true)) {
2719     case LOLR_Error:
2720       return ExprError();
2721 
2722     case LOLR_Cooked: {
2723       Expr *Lit;
2724       if (Literal.isFloatingLiteral()) {
2725         Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
2726       } else {
2727         llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
2728         if (Literal.GetIntegerValue(ResultVal))
2729           Diag(Tok.getLocation(), diag::warn_integer_too_large);
2730         Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
2731                                      Tok.getLocation());
2732       }
2733       return BuildLiteralOperatorCall(R, OpNameInfo,
2734                                       llvm::makeArrayRef(&Lit, 1),
2735                                       Tok.getLocation());
2736     }
2737 
2738     case LOLR_Raw: {
2739       // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
2740       // literal is treated as a call of the form
2741       //   operator "" X ("n")
2742       SourceLocation TokLoc = Tok.getLocation();
2743       unsigned Length = Literal.getUDSuffixOffset();
2744       QualType StrTy = Context.getConstantArrayType(
2745           Context.CharTy, llvm::APInt(32, Length + 1),
2746           ArrayType::Normal, 0);
2747       Expr *Lit = StringLiteral::Create(
2748           Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
2749           /*Pascal*/false, StrTy, &TokLoc, 1);
2750       return BuildLiteralOperatorCall(R, OpNameInfo,
2751                                       llvm::makeArrayRef(&Lit, 1), TokLoc);
2752     }
2753 
2754     case LOLR_Template:
2755       // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
2756       // template), L is treated as a call fo the form
2757       //   operator "" X <'c1', 'c2', ... 'ck'>()
2758       // where n is the source character sequence c1 c2 ... ck.
2759       TemplateArgumentListInfo ExplicitArgs;
2760       unsigned CharBits = Context.getIntWidth(Context.CharTy);
2761       bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
2762       llvm::APSInt Value(CharBits, CharIsUnsigned);
2763       for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
2764         Value = TokSpelling[I];
2765         TemplateArgument Arg(Context, Value, Context.CharTy);
2766         TemplateArgumentLocInfo ArgInfo;
2767         ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
2768       }
2769       return BuildLiteralOperatorCall(R, OpNameInfo, ArrayRef<Expr*>(),
2770                                       Tok.getLocation(), &ExplicitArgs);
2771     }
2772 
2773     llvm_unreachable("unexpected literal operator lookup result");
2774   }
2775 
2776   Expr *Res;
2777 
2778   if (Literal.isFloatingLiteral()) {
2779     QualType Ty;
2780     if (Literal.isFloat)
2781       Ty = Context.FloatTy;
2782     else if (!Literal.isLong)
2783       Ty = Context.DoubleTy;
2784     else
2785       Ty = Context.LongDoubleTy;
2786 
2787     Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
2788 
2789     if (Ty == Context.DoubleTy) {
2790       if (getLangOpts().SinglePrecisionConstants) {
2791         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
2792       } else if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
2793         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
2794         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
2795       }
2796     }
2797   } else if (!Literal.isIntegerLiteral()) {
2798     return ExprError();
2799   } else {
2800     QualType Ty;
2801 
2802     // 'long long' is a C99 or C++11 feature.
2803     if (!getLangOpts().C99 && Literal.isLongLong) {
2804       if (getLangOpts().CPlusPlus)
2805         Diag(Tok.getLocation(),
2806              getLangOpts().CPlusPlus0x ?
2807              diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
2808       else
2809         Diag(Tok.getLocation(), diag::ext_c99_longlong);
2810     }
2811 
2812     // Get the value in the widest-possible width.
2813     unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
2814     // The microsoft literal suffix extensions support 128-bit literals, which
2815     // may be wider than [u]intmax_t.
2816     if (Literal.isMicrosoftInteger && MaxWidth < 128)
2817       MaxWidth = 128;
2818     llvm::APInt ResultVal(MaxWidth, 0);
2819 
2820     if (Literal.GetIntegerValue(ResultVal)) {
2821       // If this value didn't fit into uintmax_t, warn and force to ull.
2822       Diag(Tok.getLocation(), diag::warn_integer_too_large);
2823       Ty = Context.UnsignedLongLongTy;
2824       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
2825              "long long is not intmax_t?");
2826     } else {
2827       // If this value fits into a ULL, try to figure out what else it fits into
2828       // according to the rules of C99 6.4.4.1p5.
2829 
2830       // Octal, Hexadecimal, and integers with a U suffix are allowed to
2831       // be an unsigned int.
2832       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2833 
2834       // Check from smallest to largest, picking the smallest type we can.
2835       unsigned Width = 0;
2836       if (!Literal.isLong && !Literal.isLongLong) {
2837         // Are int/unsigned possibilities?
2838         unsigned IntSize = Context.getTargetInfo().getIntWidth();
2839 
2840         // Does it fit in a unsigned int?
2841         if (ResultVal.isIntN(IntSize)) {
2842           // Does it fit in a signed int?
2843           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
2844             Ty = Context.IntTy;
2845           else if (AllowUnsigned)
2846             Ty = Context.UnsignedIntTy;
2847           Width = IntSize;
2848         }
2849       }
2850 
2851       // Are long/unsigned long possibilities?
2852       if (Ty.isNull() && !Literal.isLongLong) {
2853         unsigned LongSize = Context.getTargetInfo().getLongWidth();
2854 
2855         // Does it fit in a unsigned long?
2856         if (ResultVal.isIntN(LongSize)) {
2857           // Does it fit in a signed long?
2858           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
2859             Ty = Context.LongTy;
2860           else if (AllowUnsigned)
2861             Ty = Context.UnsignedLongTy;
2862           Width = LongSize;
2863         }
2864       }
2865 
2866       // Check long long if needed.
2867       if (Ty.isNull()) {
2868         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
2869 
2870         // Does it fit in a unsigned long long?
2871         if (ResultVal.isIntN(LongLongSize)) {
2872           // Does it fit in a signed long long?
2873           // To be compatible with MSVC, hex integer literals ending with the
2874           // LL or i64 suffix are always signed in Microsoft mode.
2875           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
2876               (getLangOpts().MicrosoftExt && Literal.isLongLong)))
2877             Ty = Context.LongLongTy;
2878           else if (AllowUnsigned)
2879             Ty = Context.UnsignedLongLongTy;
2880           Width = LongLongSize;
2881         }
2882       }
2883 
2884       // If it doesn't fit in unsigned long long, and we're using Microsoft
2885       // extensions, then its a 128-bit integer literal.
2886       if (Ty.isNull() && Literal.isMicrosoftInteger) {
2887         if (Literal.isUnsigned)
2888           Ty = Context.UnsignedInt128Ty;
2889         else
2890           Ty = Context.Int128Ty;
2891         Width = 128;
2892       }
2893 
2894       // If we still couldn't decide a type, we probably have something that
2895       // does not fit in a signed long long, but has no U suffix.
2896       if (Ty.isNull()) {
2897         Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
2898         Ty = Context.UnsignedLongLongTy;
2899         Width = Context.getTargetInfo().getLongLongWidth();
2900       }
2901 
2902       if (ResultVal.getBitWidth() != Width)
2903         ResultVal = ResultVal.trunc(Width);
2904     }
2905     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
2906   }
2907 
2908   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
2909   if (Literal.isImaginary)
2910     Res = new (Context) ImaginaryLiteral(Res,
2911                                         Context.getComplexType(Res->getType()));
2912 
2913   return Owned(Res);
2914 }
2915 
2916 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
2917   assert((E != 0) && "ActOnParenExpr() missing expr");
2918   return Owned(new (Context) ParenExpr(L, R, E));
2919 }
2920 
2921 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
2922                                          SourceLocation Loc,
2923                                          SourceRange ArgRange) {
2924   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
2925   // scalar or vector data type argument..."
2926   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
2927   // type (C99 6.2.5p18) or void.
2928   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
2929     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
2930       << T << ArgRange;
2931     return true;
2932   }
2933 
2934   assert((T->isVoidType() || !T->isIncompleteType()) &&
2935          "Scalar types should always be complete");
2936   return false;
2937 }
2938 
2939 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
2940                                            SourceLocation Loc,
2941                                            SourceRange ArgRange,
2942                                            UnaryExprOrTypeTrait TraitKind) {
2943   // C99 6.5.3.4p1:
2944   if (T->isFunctionType()) {
2945     // alignof(function) is allowed as an extension.
2946     if (TraitKind == UETT_SizeOf)
2947       S.Diag(Loc, diag::ext_sizeof_function_type) << ArgRange;
2948     return false;
2949   }
2950 
2951   // Allow sizeof(void)/alignof(void) as an extension.
2952   if (T->isVoidType()) {
2953     S.Diag(Loc, diag::ext_sizeof_void_type) << TraitKind << ArgRange;
2954     return false;
2955   }
2956 
2957   return true;
2958 }
2959 
2960 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
2961                                              SourceLocation Loc,
2962                                              SourceRange ArgRange,
2963                                              UnaryExprOrTypeTrait TraitKind) {
2964   // Reject sizeof(interface) and sizeof(interface<proto>) if the
2965   // runtime doesn't allow it.
2966   if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
2967     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
2968       << T << (TraitKind == UETT_SizeOf)
2969       << ArgRange;
2970     return true;
2971   }
2972 
2973   return false;
2974 }
2975 
2976 /// \brief Check the constrains on expression operands to unary type expression
2977 /// and type traits.
2978 ///
2979 /// Completes any types necessary and validates the constraints on the operand
2980 /// expression. The logic mostly mirrors the type-based overload, but may modify
2981 /// the expression as it completes the type for that expression through template
2982 /// instantiation, etc.
2983 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
2984                                             UnaryExprOrTypeTrait ExprKind) {
2985   QualType ExprTy = E->getType();
2986 
2987   // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2988   //   the result is the size of the referenced type."
2989   // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2990   //   result shall be the alignment of the referenced type."
2991   if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2992     ExprTy = Ref->getPointeeType();
2993 
2994   if (ExprKind == UETT_VecStep)
2995     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
2996                                         E->getSourceRange());
2997 
2998   // Whitelist some types as extensions
2999   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
3000                                       E->getSourceRange(), ExprKind))
3001     return false;
3002 
3003   if (RequireCompleteExprType(E,
3004                               diag::err_sizeof_alignof_incomplete_type,
3005                               ExprKind, E->getSourceRange()))
3006     return true;
3007 
3008   // Completeing the expression's type may have changed it.
3009   ExprTy = E->getType();
3010   if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
3011     ExprTy = Ref->getPointeeType();
3012 
3013   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
3014                                        E->getSourceRange(), ExprKind))
3015     return true;
3016 
3017   if (ExprKind == UETT_SizeOf) {
3018     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
3019       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
3020         QualType OType = PVD->getOriginalType();
3021         QualType Type = PVD->getType();
3022         if (Type->isPointerType() && OType->isArrayType()) {
3023           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
3024             << Type << OType;
3025           Diag(PVD->getLocation(), diag::note_declared_at);
3026         }
3027       }
3028     }
3029   }
3030 
3031   return false;
3032 }
3033 
3034 /// \brief Check the constraints on operands to unary expression and type
3035 /// traits.
3036 ///
3037 /// This will complete any types necessary, and validate the various constraints
3038 /// on those operands.
3039 ///
3040 /// The UsualUnaryConversions() function is *not* called by this routine.
3041 /// C99 6.3.2.1p[2-4] all state:
3042 ///   Except when it is the operand of the sizeof operator ...
3043 ///
3044 /// C++ [expr.sizeof]p4
3045 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3046 ///   standard conversions are not applied to the operand of sizeof.
3047 ///
3048 /// This policy is followed for all of the unary trait expressions.
3049 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
3050                                             SourceLocation OpLoc,
3051                                             SourceRange ExprRange,
3052                                             UnaryExprOrTypeTrait ExprKind) {
3053   if (ExprType->isDependentType())
3054     return false;
3055 
3056   // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
3057   //   the result is the size of the referenced type."
3058   // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
3059   //   result shall be the alignment of the referenced type."
3060   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3061     ExprType = Ref->getPointeeType();
3062 
3063   if (ExprKind == UETT_VecStep)
3064     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
3065 
3066   // Whitelist some types as extensions
3067   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
3068                                       ExprKind))
3069     return false;
3070 
3071   if (RequireCompleteType(OpLoc, ExprType,
3072                           diag::err_sizeof_alignof_incomplete_type,
3073                           ExprKind, ExprRange))
3074     return true;
3075 
3076   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
3077                                        ExprKind))
3078     return true;
3079 
3080   return false;
3081 }
3082 
3083 static bool CheckAlignOfExpr(Sema &S, Expr *E) {
3084   E = E->IgnoreParens();
3085 
3086   // alignof decl is always ok.
3087   if (isa<DeclRefExpr>(E))
3088     return false;
3089 
3090   // Cannot know anything else if the expression is dependent.
3091   if (E->isTypeDependent())
3092     return false;
3093 
3094   if (E->getBitField()) {
3095     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield)
3096        << 1 << E->getSourceRange();
3097     return true;
3098   }
3099 
3100   // Alignment of a field access is always okay, so long as it isn't a
3101   // bit-field.
3102   if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
3103     if (isa<FieldDecl>(ME->getMemberDecl()))
3104       return false;
3105 
3106   return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
3107 }
3108 
3109 bool Sema::CheckVecStepExpr(Expr *E) {
3110   E = E->IgnoreParens();
3111 
3112   // Cannot know anything else if the expression is dependent.
3113   if (E->isTypeDependent())
3114     return false;
3115 
3116   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
3117 }
3118 
3119 /// \brief Build a sizeof or alignof expression given a type operand.
3120 ExprResult
3121 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3122                                      SourceLocation OpLoc,
3123                                      UnaryExprOrTypeTrait ExprKind,
3124                                      SourceRange R) {
3125   if (!TInfo)
3126     return ExprError();
3127 
3128   QualType T = TInfo->getType();
3129 
3130   if (!T->isDependentType() &&
3131       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
3132     return ExprError();
3133 
3134   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
3135   return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo,
3136                                                       Context.getSizeType(),
3137                                                       OpLoc, R.getEnd()));
3138 }
3139 
3140 /// \brief Build a sizeof or alignof expression given an expression
3141 /// operand.
3142 ExprResult
3143 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
3144                                      UnaryExprOrTypeTrait ExprKind) {
3145   ExprResult PE = CheckPlaceholderExpr(E);
3146   if (PE.isInvalid())
3147     return ExprError();
3148 
3149   E = PE.get();
3150 
3151   // Verify that the operand is valid.
3152   bool isInvalid = false;
3153   if (E->isTypeDependent()) {
3154     // Delay type-checking for type-dependent expressions.
3155   } else if (ExprKind == UETT_AlignOf) {
3156     isInvalid = CheckAlignOfExpr(*this, E);
3157   } else if (ExprKind == UETT_VecStep) {
3158     isInvalid = CheckVecStepExpr(E);
3159   } else if (E->getBitField()) {  // C99 6.5.3.4p1.
3160     Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0;
3161     isInvalid = true;
3162   } else {
3163     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
3164   }
3165 
3166   if (isInvalid)
3167     return ExprError();
3168 
3169   if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
3170     PE = TranformToPotentiallyEvaluated(E);
3171     if (PE.isInvalid()) return ExprError();
3172     E = PE.take();
3173   }
3174 
3175   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
3176   return Owned(new (Context) UnaryExprOrTypeTraitExpr(
3177       ExprKind, E, Context.getSizeType(), OpLoc,
3178       E->getSourceRange().getEnd()));
3179 }
3180 
3181 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
3182 /// expr and the same for @c alignof and @c __alignof
3183 /// Note that the ArgRange is invalid if isType is false.
3184 ExprResult
3185 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
3186                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
3187                                     void *TyOrEx, const SourceRange &ArgRange) {
3188   // If error parsing type, ignore.
3189   if (TyOrEx == 0) return ExprError();
3190 
3191   if (IsType) {
3192     TypeSourceInfo *TInfo;
3193     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
3194     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
3195   }
3196 
3197   Expr *ArgEx = (Expr *)TyOrEx;
3198   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
3199   return Result;
3200 }
3201 
3202 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
3203                                      bool IsReal) {
3204   if (V.get()->isTypeDependent())
3205     return S.Context.DependentTy;
3206 
3207   // _Real and _Imag are only l-values for normal l-values.
3208   if (V.get()->getObjectKind() != OK_Ordinary) {
3209     V = S.DefaultLvalueConversion(V.take());
3210     if (V.isInvalid())
3211       return QualType();
3212   }
3213 
3214   // These operators return the element type of a complex type.
3215   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
3216     return CT->getElementType();
3217 
3218   // Otherwise they pass through real integer and floating point types here.
3219   if (V.get()->getType()->isArithmeticType())
3220     return V.get()->getType();
3221 
3222   // Test for placeholders.
3223   ExprResult PR = S.CheckPlaceholderExpr(V.get());
3224   if (PR.isInvalid()) return QualType();
3225   if (PR.get() != V.get()) {
3226     V = PR;
3227     return CheckRealImagOperand(S, V, Loc, IsReal);
3228   }
3229 
3230   // Reject anything else.
3231   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
3232     << (IsReal ? "__real" : "__imag");
3233   return QualType();
3234 }
3235 
3236 
3237 
3238 ExprResult
3239 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
3240                           tok::TokenKind Kind, Expr *Input) {
3241   UnaryOperatorKind Opc;
3242   switch (Kind) {
3243   default: llvm_unreachable("Unknown unary op!");
3244   case tok::plusplus:   Opc = UO_PostInc; break;
3245   case tok::minusminus: Opc = UO_PostDec; break;
3246   }
3247 
3248   // Since this might is a postfix expression, get rid of ParenListExprs.
3249   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
3250   if (Result.isInvalid()) return ExprError();
3251   Input = Result.take();
3252 
3253   return BuildUnaryOp(S, OpLoc, Opc, Input);
3254 }
3255 
3256 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal.
3257 ///
3258 /// \return true on error
3259 static bool checkArithmeticOnObjCPointer(Sema &S,
3260                                          SourceLocation opLoc,
3261                                          Expr *op) {
3262   assert(op->getType()->isObjCObjectPointerType());
3263   if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic())
3264     return false;
3265 
3266   S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
3267     << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
3268     << op->getSourceRange();
3269   return true;
3270 }
3271 
3272 ExprResult
3273 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
3274                               Expr *Idx, SourceLocation RLoc) {
3275   // Since this might be a postfix expression, get rid of ParenListExprs.
3276   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
3277   if (Result.isInvalid()) return ExprError();
3278   Base = Result.take();
3279 
3280   Expr *LHSExp = Base, *RHSExp = Idx;
3281 
3282   if (getLangOpts().CPlusPlus &&
3283       (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
3284     return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
3285                                                   Context.DependentTy,
3286                                                   VK_LValue, OK_Ordinary,
3287                                                   RLoc));
3288   }
3289 
3290   if (getLangOpts().CPlusPlus &&
3291       (LHSExp->getType()->isRecordType() ||
3292        LHSExp->getType()->isEnumeralType() ||
3293        RHSExp->getType()->isRecordType() ||
3294        RHSExp->getType()->isEnumeralType()) &&
3295       !LHSExp->getType()->isObjCObjectPointerType()) {
3296     return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
3297   }
3298 
3299   return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
3300 }
3301 
3302 ExprResult
3303 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
3304                                       Expr *Idx, SourceLocation RLoc) {
3305   Expr *LHSExp = Base;
3306   Expr *RHSExp = Idx;
3307 
3308   // Perform default conversions.
3309   if (!LHSExp->getType()->getAs<VectorType>()) {
3310     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
3311     if (Result.isInvalid())
3312       return ExprError();
3313     LHSExp = Result.take();
3314   }
3315   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
3316   if (Result.isInvalid())
3317     return ExprError();
3318   RHSExp = Result.take();
3319 
3320   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
3321   ExprValueKind VK = VK_LValue;
3322   ExprObjectKind OK = OK_Ordinary;
3323 
3324   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
3325   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
3326   // in the subscript position. As a result, we need to derive the array base
3327   // and index from the expression types.
3328   Expr *BaseExpr, *IndexExpr;
3329   QualType ResultType;
3330   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3331     BaseExpr = LHSExp;
3332     IndexExpr = RHSExp;
3333     ResultType = Context.DependentTy;
3334   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
3335     BaseExpr = LHSExp;
3336     IndexExpr = RHSExp;
3337     ResultType = PTy->getPointeeType();
3338   } else if (const ObjCObjectPointerType *PTy =
3339                LHSTy->getAs<ObjCObjectPointerType>()) {
3340     BaseExpr = LHSExp;
3341     IndexExpr = RHSExp;
3342 
3343     // Use custom logic if this should be the pseudo-object subscript
3344     // expression.
3345     if (!LangOpts.ObjCRuntime.isSubscriptPointerArithmetic())
3346       return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, 0, 0);
3347 
3348     ResultType = PTy->getPointeeType();
3349     if (!LangOpts.ObjCRuntime.allowsPointerArithmetic()) {
3350       Diag(LLoc, diag::err_subscript_nonfragile_interface)
3351         << ResultType << BaseExpr->getSourceRange();
3352       return ExprError();
3353     }
3354   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
3355      // Handle the uncommon case of "123[Ptr]".
3356     BaseExpr = RHSExp;
3357     IndexExpr = LHSExp;
3358     ResultType = PTy->getPointeeType();
3359   } else if (const ObjCObjectPointerType *PTy =
3360                RHSTy->getAs<ObjCObjectPointerType>()) {
3361      // Handle the uncommon case of "123[Ptr]".
3362     BaseExpr = RHSExp;
3363     IndexExpr = LHSExp;
3364     ResultType = PTy->getPointeeType();
3365     if (!LangOpts.ObjCRuntime.allowsPointerArithmetic()) {
3366       Diag(LLoc, diag::err_subscript_nonfragile_interface)
3367         << ResultType << BaseExpr->getSourceRange();
3368       return ExprError();
3369     }
3370   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
3371     BaseExpr = LHSExp;    // vectors: V[123]
3372     IndexExpr = RHSExp;
3373     VK = LHSExp->getValueKind();
3374     if (VK != VK_RValue)
3375       OK = OK_VectorComponent;
3376 
3377     // FIXME: need to deal with const...
3378     ResultType = VTy->getElementType();
3379   } else if (LHSTy->isArrayType()) {
3380     // If we see an array that wasn't promoted by
3381     // DefaultFunctionArrayLvalueConversion, it must be an array that
3382     // wasn't promoted because of the C90 rule that doesn't
3383     // allow promoting non-lvalue arrays.  Warn, then
3384     // force the promotion here.
3385     Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3386         LHSExp->getSourceRange();
3387     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
3388                                CK_ArrayToPointerDecay).take();
3389     LHSTy = LHSExp->getType();
3390 
3391     BaseExpr = LHSExp;
3392     IndexExpr = RHSExp;
3393     ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
3394   } else if (RHSTy->isArrayType()) {
3395     // Same as previous, except for 123[f().a] case
3396     Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3397         RHSExp->getSourceRange();
3398     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
3399                                CK_ArrayToPointerDecay).take();
3400     RHSTy = RHSExp->getType();
3401 
3402     BaseExpr = RHSExp;
3403     IndexExpr = LHSExp;
3404     ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
3405   } else {
3406     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3407        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
3408   }
3409   // C99 6.5.2.1p1
3410   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
3411     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3412                      << IndexExpr->getSourceRange());
3413 
3414   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
3415        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3416          && !IndexExpr->isTypeDependent())
3417     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3418 
3419   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
3420   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3421   // type. Note that Functions are not objects, and that (in C99 parlance)
3422   // incomplete types are not object types.
3423   if (ResultType->isFunctionType()) {
3424     Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3425       << ResultType << BaseExpr->getSourceRange();
3426     return ExprError();
3427   }
3428 
3429   if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
3430     // GNU extension: subscripting on pointer to void
3431     Diag(LLoc, diag::ext_gnu_subscript_void_type)
3432       << BaseExpr->getSourceRange();
3433 
3434     // C forbids expressions of unqualified void type from being l-values.
3435     // See IsCForbiddenLValueType.
3436     if (!ResultType.hasQualifiers()) VK = VK_RValue;
3437   } else if (!ResultType->isDependentType() &&
3438       RequireCompleteType(LLoc, ResultType,
3439                           diag::err_subscript_incomplete_type, BaseExpr))
3440     return ExprError();
3441 
3442   assert(VK == VK_RValue || LangOpts.CPlusPlus ||
3443          !ResultType.isCForbiddenLValueType());
3444 
3445   return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
3446                                                 ResultType, VK, OK, RLoc));
3447 }
3448 
3449 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
3450                                         FunctionDecl *FD,
3451                                         ParmVarDecl *Param) {
3452   if (Param->hasUnparsedDefaultArg()) {
3453     Diag(CallLoc,
3454          diag::err_use_of_default_argument_to_function_declared_later) <<
3455       FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
3456     Diag(UnparsedDefaultArgLocs[Param],
3457          diag::note_default_argument_declared_here);
3458     return ExprError();
3459   }
3460 
3461   if (Param->hasUninstantiatedDefaultArg()) {
3462     Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
3463 
3464     EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated,
3465                                                  Param);
3466 
3467     // Instantiate the expression.
3468     MultiLevelTemplateArgumentList ArgList
3469       = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
3470 
3471     std::pair<const TemplateArgument *, unsigned> Innermost
3472       = ArgList.getInnermost();
3473     InstantiatingTemplate Inst(*this, CallLoc, Param,
3474                                ArrayRef<TemplateArgument>(Innermost.first,
3475                                                           Innermost.second));
3476     if (Inst)
3477       return ExprError();
3478 
3479     ExprResult Result;
3480     {
3481       // C++ [dcl.fct.default]p5:
3482       //   The names in the [default argument] expression are bound, and
3483       //   the semantic constraints are checked, at the point where the
3484       //   default argument expression appears.
3485       ContextRAII SavedContext(*this, FD);
3486       LocalInstantiationScope Local(*this);
3487       Result = SubstExpr(UninstExpr, ArgList);
3488     }
3489     if (Result.isInvalid())
3490       return ExprError();
3491 
3492     // Check the expression as an initializer for the parameter.
3493     InitializedEntity Entity
3494       = InitializedEntity::InitializeParameter(Context, Param);
3495     InitializationKind Kind
3496       = InitializationKind::CreateCopy(Param->getLocation(),
3497              /*FIXME:EqualLoc*/UninstExpr->getLocStart());
3498     Expr *ResultE = Result.takeAs<Expr>();
3499 
3500     InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
3501     Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
3502     if (Result.isInvalid())
3503       return ExprError();
3504 
3505     Expr *Arg = Result.takeAs<Expr>();
3506     CheckImplicitConversions(Arg, Param->getOuterLocStart());
3507     // Build the default argument expression.
3508     return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param, Arg));
3509   }
3510 
3511   // If the default expression creates temporaries, we need to
3512   // push them to the current stack of expression temporaries so they'll
3513   // be properly destroyed.
3514   // FIXME: We should really be rebuilding the default argument with new
3515   // bound temporaries; see the comment in PR5810.
3516   // We don't need to do that with block decls, though, because
3517   // blocks in default argument expression can never capture anything.
3518   if (isa<ExprWithCleanups>(Param->getInit())) {
3519     // Set the "needs cleanups" bit regardless of whether there are
3520     // any explicit objects.
3521     ExprNeedsCleanups = true;
3522 
3523     // Append all the objects to the cleanup list.  Right now, this
3524     // should always be a no-op, because blocks in default argument
3525     // expressions should never be able to capture anything.
3526     assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() &&
3527            "default argument expression has capturing blocks?");
3528   }
3529 
3530   // We already type-checked the argument, so we know it works.
3531   // Just mark all of the declarations in this potentially-evaluated expression
3532   // as being "referenced".
3533   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
3534                                    /*SkipLocalVariables=*/true);
3535   return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
3536 }
3537 
3538 
3539 Sema::VariadicCallType
3540 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
3541                           Expr *Fn) {
3542   if (Proto && Proto->isVariadic()) {
3543     if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
3544       return VariadicConstructor;
3545     else if (Fn && Fn->getType()->isBlockPointerType())
3546       return VariadicBlock;
3547     else if (FDecl) {
3548       if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3549         if (Method->isInstance())
3550           return VariadicMethod;
3551     }
3552     return VariadicFunction;
3553   }
3554   return VariadicDoesNotApply;
3555 }
3556 
3557 /// ConvertArgumentsForCall - Converts the arguments specified in
3558 /// Args/NumArgs to the parameter types of the function FDecl with
3559 /// function prototype Proto. Call is the call expression itself, and
3560 /// Fn is the function expression. For a C++ member function, this
3561 /// routine does not attempt to convert the object argument. Returns
3562 /// true if the call is ill-formed.
3563 bool
3564 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
3565                               FunctionDecl *FDecl,
3566                               const FunctionProtoType *Proto,
3567                               Expr **Args, unsigned NumArgs,
3568                               SourceLocation RParenLoc,
3569                               bool IsExecConfig) {
3570   // Bail out early if calling a builtin with custom typechecking.
3571   // We don't need to do this in the
3572   if (FDecl)
3573     if (unsigned ID = FDecl->getBuiltinID())
3574       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
3575         return false;
3576 
3577   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
3578   // assignment, to the types of the corresponding parameter, ...
3579   unsigned NumArgsInProto = Proto->getNumArgs();
3580   bool Invalid = false;
3581   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumArgsInProto;
3582   unsigned FnKind = Fn->getType()->isBlockPointerType()
3583                        ? 1 /* block */
3584                        : (IsExecConfig ? 3 /* kernel function (exec config) */
3585                                        : 0 /* function */);
3586 
3587   // If too few arguments are available (and we don't have default
3588   // arguments for the remaining parameters), don't make the call.
3589   if (NumArgs < NumArgsInProto) {
3590     if (NumArgs < MinArgs) {
3591       if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
3592         Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic()
3593                           ? diag::err_typecheck_call_too_few_args_one
3594                           : diag::err_typecheck_call_too_few_args_at_least_one)
3595           << FnKind
3596           << FDecl->getParamDecl(0) << Fn->getSourceRange();
3597       else
3598         Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic()
3599                           ? diag::err_typecheck_call_too_few_args
3600                           : diag::err_typecheck_call_too_few_args_at_least)
3601           << FnKind
3602           << MinArgs << NumArgs << Fn->getSourceRange();
3603 
3604       // Emit the location of the prototype.
3605       if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
3606         Diag(FDecl->getLocStart(), diag::note_callee_decl)
3607           << FDecl;
3608 
3609       return true;
3610     }
3611     Call->setNumArgs(Context, NumArgsInProto);
3612   }
3613 
3614   // If too many are passed and not variadic, error on the extras and drop
3615   // them.
3616   if (NumArgs > NumArgsInProto) {
3617     if (!Proto->isVariadic()) {
3618       if (NumArgsInProto == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
3619         Diag(Args[NumArgsInProto]->getLocStart(),
3620              MinArgs == NumArgsInProto
3621                ? diag::err_typecheck_call_too_many_args_one
3622                : diag::err_typecheck_call_too_many_args_at_most_one)
3623           << FnKind
3624           << FDecl->getParamDecl(0) << NumArgs << Fn->getSourceRange()
3625           << SourceRange(Args[NumArgsInProto]->getLocStart(),
3626                          Args[NumArgs-1]->getLocEnd());
3627       else
3628         Diag(Args[NumArgsInProto]->getLocStart(),
3629              MinArgs == NumArgsInProto
3630                ? diag::err_typecheck_call_too_many_args
3631                : diag::err_typecheck_call_too_many_args_at_most)
3632           << FnKind
3633           << NumArgsInProto << NumArgs << Fn->getSourceRange()
3634           << SourceRange(Args[NumArgsInProto]->getLocStart(),
3635                          Args[NumArgs-1]->getLocEnd());
3636 
3637       // Emit the location of the prototype.
3638       if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
3639         Diag(FDecl->getLocStart(), diag::note_callee_decl)
3640           << FDecl;
3641 
3642       // This deletes the extra arguments.
3643       Call->setNumArgs(Context, NumArgsInProto);
3644       return true;
3645     }
3646   }
3647   SmallVector<Expr *, 8> AllArgs;
3648   VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
3649 
3650   Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
3651                                    Proto, 0, Args, NumArgs, AllArgs, CallType);
3652   if (Invalid)
3653     return true;
3654   unsigned TotalNumArgs = AllArgs.size();
3655   for (unsigned i = 0; i < TotalNumArgs; ++i)
3656     Call->setArg(i, AllArgs[i]);
3657 
3658   return false;
3659 }
3660 
3661 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
3662                                   FunctionDecl *FDecl,
3663                                   const FunctionProtoType *Proto,
3664                                   unsigned FirstProtoArg,
3665                                   Expr **Args, unsigned NumArgs,
3666                                   SmallVector<Expr *, 8> &AllArgs,
3667                                   VariadicCallType CallType,
3668                                   bool AllowExplicit) {
3669   unsigned NumArgsInProto = Proto->getNumArgs();
3670   unsigned NumArgsToCheck = NumArgs;
3671   bool Invalid = false;
3672   if (NumArgs != NumArgsInProto)
3673     // Use default arguments for missing arguments
3674     NumArgsToCheck = NumArgsInProto;
3675   unsigned ArgIx = 0;
3676   // Continue to check argument types (even if we have too few/many args).
3677   for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
3678     QualType ProtoArgType = Proto->getArgType(i);
3679 
3680     Expr *Arg;
3681     ParmVarDecl *Param;
3682     if (ArgIx < NumArgs) {
3683       Arg = Args[ArgIx++];
3684 
3685       if (RequireCompleteType(Arg->getLocStart(),
3686                               ProtoArgType,
3687                               diag::err_call_incomplete_argument, Arg))
3688         return true;
3689 
3690       // Pass the argument
3691       Param = 0;
3692       if (FDecl && i < FDecl->getNumParams())
3693         Param = FDecl->getParamDecl(i);
3694 
3695       // Strip the unbridged-cast placeholder expression off, if applicable.
3696       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
3697           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
3698           (!Param || !Param->hasAttr<CFConsumedAttr>()))
3699         Arg = stripARCUnbridgedCast(Arg);
3700 
3701       InitializedEntity Entity =
3702         Param? InitializedEntity::InitializeParameter(Context, Param)
3703              : InitializedEntity::InitializeParameter(Context, ProtoArgType,
3704                                                       Proto->isArgConsumed(i));
3705       ExprResult ArgE = PerformCopyInitialization(Entity,
3706                                                   SourceLocation(),
3707                                                   Owned(Arg),
3708                                                   /*TopLevelOfInitList=*/false,
3709                                                   AllowExplicit);
3710       if (ArgE.isInvalid())
3711         return true;
3712 
3713       Arg = ArgE.takeAs<Expr>();
3714     } else {
3715       Param = FDecl->getParamDecl(i);
3716 
3717       ExprResult ArgExpr =
3718         BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
3719       if (ArgExpr.isInvalid())
3720         return true;
3721 
3722       Arg = ArgExpr.takeAs<Expr>();
3723     }
3724 
3725     // Check for array bounds violations for each argument to the call. This
3726     // check only triggers warnings when the argument isn't a more complex Expr
3727     // with its own checking, such as a BinaryOperator.
3728     CheckArrayAccess(Arg);
3729 
3730     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
3731     CheckStaticArrayArgument(CallLoc, Param, Arg);
3732 
3733     AllArgs.push_back(Arg);
3734   }
3735 
3736   // If this is a variadic call, handle args passed through "...".
3737   if (CallType != VariadicDoesNotApply) {
3738     // Assume that extern "C" functions with variadic arguments that
3739     // return __unknown_anytype aren't *really* variadic.
3740     if (Proto->getResultType() == Context.UnknownAnyTy &&
3741         FDecl && FDecl->isExternC()) {
3742       for (unsigned i = ArgIx; i != NumArgs; ++i) {
3743         ExprResult arg;
3744         if (isa<ExplicitCastExpr>(Args[i]->IgnoreParens()))
3745           arg = DefaultFunctionArrayLvalueConversion(Args[i]);
3746         else
3747           arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl);
3748         Invalid |= arg.isInvalid();
3749         AllArgs.push_back(arg.take());
3750       }
3751 
3752     // Otherwise do argument promotion, (C99 6.5.2.2p7).
3753     } else {
3754       for (unsigned i = ArgIx; i != NumArgs; ++i) {
3755         ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType,
3756                                                           FDecl);
3757         Invalid |= Arg.isInvalid();
3758         AllArgs.push_back(Arg.take());
3759       }
3760     }
3761 
3762     // Check for array bounds violations.
3763     for (unsigned i = ArgIx; i != NumArgs; ++i)
3764       CheckArrayAccess(Args[i]);
3765   }
3766   return Invalid;
3767 }
3768 
3769 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
3770   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
3771   if (ArrayTypeLoc *ATL = dyn_cast<ArrayTypeLoc>(&TL))
3772     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
3773       << ATL->getLocalSourceRange();
3774 }
3775 
3776 /// CheckStaticArrayArgument - If the given argument corresponds to a static
3777 /// array parameter, check that it is non-null, and that if it is formed by
3778 /// array-to-pointer decay, the underlying array is sufficiently large.
3779 ///
3780 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
3781 /// array type derivation, then for each call to the function, the value of the
3782 /// corresponding actual argument shall provide access to the first element of
3783 /// an array with at least as many elements as specified by the size expression.
3784 void
3785 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
3786                                ParmVarDecl *Param,
3787                                const Expr *ArgExpr) {
3788   // Static array parameters are not supported in C++.
3789   if (!Param || getLangOpts().CPlusPlus)
3790     return;
3791 
3792   QualType OrigTy = Param->getOriginalType();
3793 
3794   const ArrayType *AT = Context.getAsArrayType(OrigTy);
3795   if (!AT || AT->getSizeModifier() != ArrayType::Static)
3796     return;
3797 
3798   if (ArgExpr->isNullPointerConstant(Context,
3799                                      Expr::NPC_NeverValueDependent)) {
3800     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
3801     DiagnoseCalleeStaticArrayParam(*this, Param);
3802     return;
3803   }
3804 
3805   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
3806   if (!CAT)
3807     return;
3808 
3809   const ConstantArrayType *ArgCAT =
3810     Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
3811   if (!ArgCAT)
3812     return;
3813 
3814   if (ArgCAT->getSize().ult(CAT->getSize())) {
3815     Diag(CallLoc, diag::warn_static_array_too_small)
3816       << ArgExpr->getSourceRange()
3817       << (unsigned) ArgCAT->getSize().getZExtValue()
3818       << (unsigned) CAT->getSize().getZExtValue();
3819     DiagnoseCalleeStaticArrayParam(*this, Param);
3820   }
3821 }
3822 
3823 /// Given a function expression of unknown-any type, try to rebuild it
3824 /// to have a function type.
3825 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
3826 
3827 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
3828 /// This provides the location of the left/right parens and a list of comma
3829 /// locations.
3830 ExprResult
3831 Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
3832                     MultiExprArg ArgExprs, SourceLocation RParenLoc,
3833                     Expr *ExecConfig, bool IsExecConfig) {
3834   // Since this might be a postfix expression, get rid of ParenListExprs.
3835   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
3836   if (Result.isInvalid()) return ExprError();
3837   Fn = Result.take();
3838 
3839   if (getLangOpts().CPlusPlus) {
3840     // If this is a pseudo-destructor expression, build the call immediately.
3841     if (isa<CXXPseudoDestructorExpr>(Fn)) {
3842       if (!ArgExprs.empty()) {
3843         // Pseudo-destructor calls should not have any arguments.
3844         Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
3845           << FixItHint::CreateRemoval(
3846                                     SourceRange(ArgExprs[0]->getLocStart(),
3847                                                 ArgExprs.back()->getLocEnd()));
3848       }
3849 
3850       return Owned(new (Context) CallExpr(Context, Fn, MultiExprArg(),
3851                                           Context.VoidTy, VK_RValue,
3852                                           RParenLoc));
3853     }
3854 
3855     // Determine whether this is a dependent call inside a C++ template,
3856     // in which case we won't do any semantic analysis now.
3857     // FIXME: Will need to cache the results of name lookup (including ADL) in
3858     // Fn.
3859     bool Dependent = false;
3860     if (Fn->isTypeDependent())
3861       Dependent = true;
3862     else if (Expr::hasAnyTypeDependentArguments(ArgExprs))
3863       Dependent = true;
3864 
3865     if (Dependent) {
3866       if (ExecConfig) {
3867         return Owned(new (Context) CUDAKernelCallExpr(
3868             Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
3869             Context.DependentTy, VK_RValue, RParenLoc));
3870       } else {
3871         return Owned(new (Context) CallExpr(Context, Fn, ArgExprs,
3872                                             Context.DependentTy, VK_RValue,
3873                                             RParenLoc));
3874       }
3875     }
3876 
3877     // Determine whether this is a call to an object (C++ [over.call.object]).
3878     if (Fn->getType()->isRecordType())
3879       return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc,
3880                                                 ArgExprs.data(),
3881                                                 ArgExprs.size(), RParenLoc));
3882 
3883     if (Fn->getType() == Context.UnknownAnyTy) {
3884       ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
3885       if (result.isInvalid()) return ExprError();
3886       Fn = result.take();
3887     }
3888 
3889     if (Fn->getType() == Context.BoundMemberTy) {
3890       return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs.data(),
3891                                        ArgExprs.size(), RParenLoc);
3892     }
3893   }
3894 
3895   // Check for overloaded calls.  This can happen even in C due to extensions.
3896   if (Fn->getType() == Context.OverloadTy) {
3897     OverloadExpr::FindResult find = OverloadExpr::find(Fn);
3898 
3899     // We aren't supposed to apply this logic for if there's an '&' involved.
3900     if (!find.HasFormOfMemberPointer) {
3901       OverloadExpr *ovl = find.Expression;
3902       if (isa<UnresolvedLookupExpr>(ovl)) {
3903         UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
3904         return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, ArgExprs.data(),
3905                                        ArgExprs.size(), RParenLoc, ExecConfig);
3906       } else {
3907         return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs.data(),
3908                                          ArgExprs.size(), RParenLoc);
3909       }
3910     }
3911   }
3912 
3913   // If we're directly calling a function, get the appropriate declaration.
3914   if (Fn->getType() == Context.UnknownAnyTy) {
3915     ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
3916     if (result.isInvalid()) return ExprError();
3917     Fn = result.take();
3918   }
3919 
3920   Expr *NakedFn = Fn->IgnoreParens();
3921 
3922   NamedDecl *NDecl = 0;
3923   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
3924     if (UnOp->getOpcode() == UO_AddrOf)
3925       NakedFn = UnOp->getSubExpr()->IgnoreParens();
3926 
3927   if (isa<DeclRefExpr>(NakedFn))
3928     NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
3929   else if (isa<MemberExpr>(NakedFn))
3930     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
3931 
3932   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs.data(),
3933                                ArgExprs.size(), RParenLoc, ExecConfig,
3934                                IsExecConfig);
3935 }
3936 
3937 ExprResult
3938 Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
3939                               MultiExprArg ExecConfig, SourceLocation GGGLoc) {
3940   FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
3941   if (!ConfigDecl)
3942     return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
3943                           << "cudaConfigureCall");
3944   QualType ConfigQTy = ConfigDecl->getType();
3945 
3946   DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
3947       ConfigDecl, false, ConfigQTy, VK_LValue, LLLLoc);
3948   MarkFunctionReferenced(LLLLoc, ConfigDecl);
3949 
3950   return ActOnCallExpr(S, ConfigDR, LLLLoc, ExecConfig, GGGLoc, 0,
3951                        /*IsExecConfig=*/true);
3952 }
3953 
3954 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
3955 ///
3956 /// __builtin_astype( value, dst type )
3957 ///
3958 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
3959                                  SourceLocation BuiltinLoc,
3960                                  SourceLocation RParenLoc) {
3961   ExprValueKind VK = VK_RValue;
3962   ExprObjectKind OK = OK_Ordinary;
3963   QualType DstTy = GetTypeFromParser(ParsedDestTy);
3964   QualType SrcTy = E->getType();
3965   if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
3966     return ExprError(Diag(BuiltinLoc,
3967                           diag::err_invalid_astype_of_different_size)
3968                      << DstTy
3969                      << SrcTy
3970                      << E->getSourceRange());
3971   return Owned(new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc,
3972                RParenLoc));
3973 }
3974 
3975 /// BuildResolvedCallExpr - Build a call to a resolved expression,
3976 /// i.e. an expression not of \p OverloadTy.  The expression should
3977 /// unary-convert to an expression of function-pointer or
3978 /// block-pointer type.
3979 ///
3980 /// \param NDecl the declaration being called, if available
3981 ExprResult
3982 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
3983                             SourceLocation LParenLoc,
3984                             Expr **Args, unsigned NumArgs,
3985                             SourceLocation RParenLoc,
3986                             Expr *Config, bool IsExecConfig) {
3987   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
3988   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
3989 
3990   // Promote the function operand.
3991   // We special-case function promotion here because we only allow promoting
3992   // builtin functions to function pointers in the callee of a call.
3993   ExprResult Result;
3994   if (BuiltinID &&
3995       Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
3996     Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()),
3997                                CK_BuiltinFnToFnPtr).take();
3998   } else {
3999     Result = UsualUnaryConversions(Fn);
4000   }
4001   if (Result.isInvalid())
4002     return ExprError();
4003   Fn = Result.take();
4004 
4005   // Make the call expr early, before semantic checks.  This guarantees cleanup
4006   // of arguments and function on error.
4007   CallExpr *TheCall;
4008   if (Config)
4009     TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
4010                                                cast<CallExpr>(Config),
4011                                                llvm::makeArrayRef(Args,NumArgs),
4012                                                Context.BoolTy,
4013                                                VK_RValue,
4014                                                RParenLoc);
4015   else
4016     TheCall = new (Context) CallExpr(Context, Fn,
4017                                      llvm::makeArrayRef(Args, NumArgs),
4018                                      Context.BoolTy,
4019                                      VK_RValue,
4020                                      RParenLoc);
4021 
4022   // Bail out early if calling a builtin with custom typechecking.
4023   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
4024     return CheckBuiltinFunctionCall(BuiltinID, TheCall);
4025 
4026  retry:
4027   const FunctionType *FuncT;
4028   if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
4029     // C99 6.5.2.2p1 - "The expression that denotes the called function shall
4030     // have type pointer to function".
4031     FuncT = PT->getPointeeType()->getAs<FunctionType>();
4032     if (FuncT == 0)
4033       return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4034                          << Fn->getType() << Fn->getSourceRange());
4035   } else if (const BlockPointerType *BPT =
4036                Fn->getType()->getAs<BlockPointerType>()) {
4037     FuncT = BPT->getPointeeType()->castAs<FunctionType>();
4038   } else {
4039     // Handle calls to expressions of unknown-any type.
4040     if (Fn->getType() == Context.UnknownAnyTy) {
4041       ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
4042       if (rewrite.isInvalid()) return ExprError();
4043       Fn = rewrite.take();
4044       TheCall->setCallee(Fn);
4045       goto retry;
4046     }
4047 
4048     return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4049       << Fn->getType() << Fn->getSourceRange());
4050   }
4051 
4052   if (getLangOpts().CUDA) {
4053     if (Config) {
4054       // CUDA: Kernel calls must be to global functions
4055       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
4056         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
4057             << FDecl->getName() << Fn->getSourceRange());
4058 
4059       // CUDA: Kernel function must have 'void' return type
4060       if (!FuncT->getResultType()->isVoidType())
4061         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
4062             << Fn->getType() << Fn->getSourceRange());
4063     } else {
4064       // CUDA: Calls to global functions must be configured
4065       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
4066         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
4067             << FDecl->getName() << Fn->getSourceRange());
4068     }
4069   }
4070 
4071   // Check for a valid return type
4072   if (CheckCallReturnType(FuncT->getResultType(),
4073                           Fn->getLocStart(), TheCall,
4074                           FDecl))
4075     return ExprError();
4076 
4077   // We know the result type of the call, set it.
4078   TheCall->setType(FuncT->getCallResultType(Context));
4079   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
4080 
4081   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
4082   if (Proto) {
4083     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
4084                                 RParenLoc, IsExecConfig))
4085       return ExprError();
4086   } else {
4087     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
4088 
4089     if (FDecl) {
4090       // Check if we have too few/too many template arguments, based
4091       // on our knowledge of the function definition.
4092       const FunctionDecl *Def = 0;
4093       if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
4094         Proto = Def->getType()->getAs<FunctionProtoType>();
4095         if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
4096           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
4097             << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
4098       }
4099 
4100       // If the function we're calling isn't a function prototype, but we have
4101       // a function prototype from a prior declaratiom, use that prototype.
4102       if (!FDecl->hasPrototype())
4103         Proto = FDecl->getType()->getAs<FunctionProtoType>();
4104     }
4105 
4106     // Promote the arguments (C99 6.5.2.2p6).
4107     for (unsigned i = 0; i != NumArgs; i++) {
4108       Expr *Arg = Args[i];
4109 
4110       if (Proto && i < Proto->getNumArgs()) {
4111         InitializedEntity Entity
4112           = InitializedEntity::InitializeParameter(Context,
4113                                                    Proto->getArgType(i),
4114                                                    Proto->isArgConsumed(i));
4115         ExprResult ArgE = PerformCopyInitialization(Entity,
4116                                                     SourceLocation(),
4117                                                     Owned(Arg));
4118         if (ArgE.isInvalid())
4119           return true;
4120 
4121         Arg = ArgE.takeAs<Expr>();
4122 
4123       } else {
4124         ExprResult ArgE = DefaultArgumentPromotion(Arg);
4125 
4126         if (ArgE.isInvalid())
4127           return true;
4128 
4129         Arg = ArgE.takeAs<Expr>();
4130       }
4131 
4132       if (RequireCompleteType(Arg->getLocStart(),
4133                               Arg->getType(),
4134                               diag::err_call_incomplete_argument, Arg))
4135         return ExprError();
4136 
4137       TheCall->setArg(i, Arg);
4138     }
4139   }
4140 
4141   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4142     if (!Method->isStatic())
4143       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
4144         << Fn->getSourceRange());
4145 
4146   // Check for sentinels
4147   if (NDecl)
4148     DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
4149 
4150   // Do special checking on direct calls to functions.
4151   if (FDecl) {
4152     if (CheckFunctionCall(FDecl, TheCall, Proto))
4153       return ExprError();
4154 
4155     if (BuiltinID)
4156       return CheckBuiltinFunctionCall(BuiltinID, TheCall);
4157   } else if (NDecl) {
4158     if (CheckBlockCall(NDecl, TheCall, Proto))
4159       return ExprError();
4160   }
4161 
4162   return MaybeBindToTemporary(TheCall);
4163 }
4164 
4165 ExprResult
4166 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
4167                            SourceLocation RParenLoc, Expr *InitExpr) {
4168   assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
4169   // FIXME: put back this assert when initializers are worked out.
4170   //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
4171 
4172   TypeSourceInfo *TInfo;
4173   QualType literalType = GetTypeFromParser(Ty, &TInfo);
4174   if (!TInfo)
4175     TInfo = Context.getTrivialTypeSourceInfo(literalType);
4176 
4177   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
4178 }
4179 
4180 ExprResult
4181 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
4182                                SourceLocation RParenLoc, Expr *LiteralExpr) {
4183   QualType literalType = TInfo->getType();
4184 
4185   if (literalType->isArrayType()) {
4186     if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
4187           diag::err_illegal_decl_array_incomplete_type,
4188           SourceRange(LParenLoc,
4189                       LiteralExpr->getSourceRange().getEnd())))
4190       return ExprError();
4191     if (literalType->isVariableArrayType())
4192       return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
4193         << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
4194   } else if (!literalType->isDependentType() &&
4195              RequireCompleteType(LParenLoc, literalType,
4196                diag::err_typecheck_decl_incomplete_type,
4197                SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
4198     return ExprError();
4199 
4200   InitializedEntity Entity
4201     = InitializedEntity::InitializeTemporary(literalType);
4202   InitializationKind Kind
4203     = InitializationKind::CreateCStyleCast(LParenLoc,
4204                                            SourceRange(LParenLoc, RParenLoc),
4205                                            /*InitList=*/true);
4206   InitializationSequence InitSeq(*this, Entity, Kind, &LiteralExpr, 1);
4207   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
4208                                       &literalType);
4209   if (Result.isInvalid())
4210     return ExprError();
4211   LiteralExpr = Result.get();
4212 
4213   bool isFileScope = getCurFunctionOrMethodDecl() == 0;
4214   if (isFileScope) { // 6.5.2.5p3
4215     if (CheckForConstantInitializer(LiteralExpr, literalType))
4216       return ExprError();
4217   }
4218 
4219   // In C, compound literals are l-values for some reason.
4220   ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue;
4221 
4222   return MaybeBindToTemporary(
4223            new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
4224                                              VK, LiteralExpr, isFileScope));
4225 }
4226 
4227 ExprResult
4228 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
4229                     SourceLocation RBraceLoc) {
4230   // Immediately handle non-overload placeholders.  Overloads can be
4231   // resolved contextually, but everything else here can't.
4232   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
4233     if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
4234       ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
4235 
4236       // Ignore failures; dropping the entire initializer list because
4237       // of one failure would be terrible for indexing/etc.
4238       if (result.isInvalid()) continue;
4239 
4240       InitArgList[I] = result.take();
4241     }
4242   }
4243 
4244   // Semantic analysis for initializers is done by ActOnDeclarator() and
4245   // CheckInitializer() - it requires knowledge of the object being intialized.
4246 
4247   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
4248                                                RBraceLoc);
4249   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
4250   return Owned(E);
4251 }
4252 
4253 /// Do an explicit extend of the given block pointer if we're in ARC.
4254 static void maybeExtendBlockObject(Sema &S, ExprResult &E) {
4255   assert(E.get()->getType()->isBlockPointerType());
4256   assert(E.get()->isRValue());
4257 
4258   // Only do this in an r-value context.
4259   if (!S.getLangOpts().ObjCAutoRefCount) return;
4260 
4261   E = ImplicitCastExpr::Create(S.Context, E.get()->getType(),
4262                                CK_ARCExtendBlockObject, E.get(),
4263                                /*base path*/ 0, VK_RValue);
4264   S.ExprNeedsCleanups = true;
4265 }
4266 
4267 /// Prepare a conversion of the given expression to an ObjC object
4268 /// pointer type.
4269 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
4270   QualType type = E.get()->getType();
4271   if (type->isObjCObjectPointerType()) {
4272     return CK_BitCast;
4273   } else if (type->isBlockPointerType()) {
4274     maybeExtendBlockObject(*this, E);
4275     return CK_BlockPointerToObjCPointerCast;
4276   } else {
4277     assert(type->isPointerType());
4278     return CK_CPointerToObjCPointerCast;
4279   }
4280 }
4281 
4282 /// Prepares for a scalar cast, performing all the necessary stages
4283 /// except the final cast and returning the kind required.
4284 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
4285   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
4286   // Also, callers should have filtered out the invalid cases with
4287   // pointers.  Everything else should be possible.
4288 
4289   QualType SrcTy = Src.get()->getType();
4290   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
4291     return CK_NoOp;
4292 
4293   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
4294   case Type::STK_MemberPointer:
4295     llvm_unreachable("member pointer type in C");
4296 
4297   case Type::STK_CPointer:
4298   case Type::STK_BlockPointer:
4299   case Type::STK_ObjCObjectPointer:
4300     switch (DestTy->getScalarTypeKind()) {
4301     case Type::STK_CPointer:
4302       return CK_BitCast;
4303     case Type::STK_BlockPointer:
4304       return (SrcKind == Type::STK_BlockPointer
4305                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
4306     case Type::STK_ObjCObjectPointer:
4307       if (SrcKind == Type::STK_ObjCObjectPointer)
4308         return CK_BitCast;
4309       if (SrcKind == Type::STK_CPointer)
4310         return CK_CPointerToObjCPointerCast;
4311       maybeExtendBlockObject(*this, Src);
4312       return CK_BlockPointerToObjCPointerCast;
4313     case Type::STK_Bool:
4314       return CK_PointerToBoolean;
4315     case Type::STK_Integral:
4316       return CK_PointerToIntegral;
4317     case Type::STK_Floating:
4318     case Type::STK_FloatingComplex:
4319     case Type::STK_IntegralComplex:
4320     case Type::STK_MemberPointer:
4321       llvm_unreachable("illegal cast from pointer");
4322     }
4323     llvm_unreachable("Should have returned before this");
4324 
4325   case Type::STK_Bool: // casting from bool is like casting from an integer
4326   case Type::STK_Integral:
4327     switch (DestTy->getScalarTypeKind()) {
4328     case Type::STK_CPointer:
4329     case Type::STK_ObjCObjectPointer:
4330     case Type::STK_BlockPointer:
4331       if (Src.get()->isNullPointerConstant(Context,
4332                                            Expr::NPC_ValueDependentIsNull))
4333         return CK_NullToPointer;
4334       return CK_IntegralToPointer;
4335     case Type::STK_Bool:
4336       return CK_IntegralToBoolean;
4337     case Type::STK_Integral:
4338       return CK_IntegralCast;
4339     case Type::STK_Floating:
4340       return CK_IntegralToFloating;
4341     case Type::STK_IntegralComplex:
4342       Src = ImpCastExprToType(Src.take(),
4343                               DestTy->castAs<ComplexType>()->getElementType(),
4344                               CK_IntegralCast);
4345       return CK_IntegralRealToComplex;
4346     case Type::STK_FloatingComplex:
4347       Src = ImpCastExprToType(Src.take(),
4348                               DestTy->castAs<ComplexType>()->getElementType(),
4349                               CK_IntegralToFloating);
4350       return CK_FloatingRealToComplex;
4351     case Type::STK_MemberPointer:
4352       llvm_unreachable("member pointer type in C");
4353     }
4354     llvm_unreachable("Should have returned before this");
4355 
4356   case Type::STK_Floating:
4357     switch (DestTy->getScalarTypeKind()) {
4358     case Type::STK_Floating:
4359       return CK_FloatingCast;
4360     case Type::STK_Bool:
4361       return CK_FloatingToBoolean;
4362     case Type::STK_Integral:
4363       return CK_FloatingToIntegral;
4364     case Type::STK_FloatingComplex:
4365       Src = ImpCastExprToType(Src.take(),
4366                               DestTy->castAs<ComplexType>()->getElementType(),
4367                               CK_FloatingCast);
4368       return CK_FloatingRealToComplex;
4369     case Type::STK_IntegralComplex:
4370       Src = ImpCastExprToType(Src.take(),
4371                               DestTy->castAs<ComplexType>()->getElementType(),
4372                               CK_FloatingToIntegral);
4373       return CK_IntegralRealToComplex;
4374     case Type::STK_CPointer:
4375     case Type::STK_ObjCObjectPointer:
4376     case Type::STK_BlockPointer:
4377       llvm_unreachable("valid float->pointer cast?");
4378     case Type::STK_MemberPointer:
4379       llvm_unreachable("member pointer type in C");
4380     }
4381     llvm_unreachable("Should have returned before this");
4382 
4383   case Type::STK_FloatingComplex:
4384     switch (DestTy->getScalarTypeKind()) {
4385     case Type::STK_FloatingComplex:
4386       return CK_FloatingComplexCast;
4387     case Type::STK_IntegralComplex:
4388       return CK_FloatingComplexToIntegralComplex;
4389     case Type::STK_Floating: {
4390       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
4391       if (Context.hasSameType(ET, DestTy))
4392         return CK_FloatingComplexToReal;
4393       Src = ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal);
4394       return CK_FloatingCast;
4395     }
4396     case Type::STK_Bool:
4397       return CK_FloatingComplexToBoolean;
4398     case Type::STK_Integral:
4399       Src = ImpCastExprToType(Src.take(),
4400                               SrcTy->castAs<ComplexType>()->getElementType(),
4401                               CK_FloatingComplexToReal);
4402       return CK_FloatingToIntegral;
4403     case Type::STK_CPointer:
4404     case Type::STK_ObjCObjectPointer:
4405     case Type::STK_BlockPointer:
4406       llvm_unreachable("valid complex float->pointer cast?");
4407     case Type::STK_MemberPointer:
4408       llvm_unreachable("member pointer type in C");
4409     }
4410     llvm_unreachable("Should have returned before this");
4411 
4412   case Type::STK_IntegralComplex:
4413     switch (DestTy->getScalarTypeKind()) {
4414     case Type::STK_FloatingComplex:
4415       return CK_IntegralComplexToFloatingComplex;
4416     case Type::STK_IntegralComplex:
4417       return CK_IntegralComplexCast;
4418     case Type::STK_Integral: {
4419       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
4420       if (Context.hasSameType(ET, DestTy))
4421         return CK_IntegralComplexToReal;
4422       Src = ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal);
4423       return CK_IntegralCast;
4424     }
4425     case Type::STK_Bool:
4426       return CK_IntegralComplexToBoolean;
4427     case Type::STK_Floating:
4428       Src = ImpCastExprToType(Src.take(),
4429                               SrcTy->castAs<ComplexType>()->getElementType(),
4430                               CK_IntegralComplexToReal);
4431       return CK_IntegralToFloating;
4432     case Type::STK_CPointer:
4433     case Type::STK_ObjCObjectPointer:
4434     case Type::STK_BlockPointer:
4435       llvm_unreachable("valid complex int->pointer cast?");
4436     case Type::STK_MemberPointer:
4437       llvm_unreachable("member pointer type in C");
4438     }
4439     llvm_unreachable("Should have returned before this");
4440   }
4441 
4442   llvm_unreachable("Unhandled scalar cast");
4443 }
4444 
4445 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
4446                            CastKind &Kind) {
4447   assert(VectorTy->isVectorType() && "Not a vector type!");
4448 
4449   if (Ty->isVectorType() || Ty->isIntegerType()) {
4450     if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
4451       return Diag(R.getBegin(),
4452                   Ty->isVectorType() ?
4453                   diag::err_invalid_conversion_between_vectors :
4454                   diag::err_invalid_conversion_between_vector_and_integer)
4455         << VectorTy << Ty << R;
4456   } else
4457     return Diag(R.getBegin(),
4458                 diag::err_invalid_conversion_between_vector_and_scalar)
4459       << VectorTy << Ty << R;
4460 
4461   Kind = CK_BitCast;
4462   return false;
4463 }
4464 
4465 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
4466                                     Expr *CastExpr, CastKind &Kind) {
4467   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
4468 
4469   QualType SrcTy = CastExpr->getType();
4470 
4471   // If SrcTy is a VectorType, the total size must match to explicitly cast to
4472   // an ExtVectorType.
4473   // In OpenCL, casts between vectors of different types are not allowed.
4474   // (See OpenCL 6.2).
4475   if (SrcTy->isVectorType()) {
4476     if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)
4477         || (getLangOpts().OpenCL &&
4478             (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
4479       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
4480         << DestTy << SrcTy << R;
4481       return ExprError();
4482     }
4483     Kind = CK_BitCast;
4484     return Owned(CastExpr);
4485   }
4486 
4487   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
4488   // conversion will take place first from scalar to elt type, and then
4489   // splat from elt type to vector.
4490   if (SrcTy->isPointerType())
4491     return Diag(R.getBegin(),
4492                 diag::err_invalid_conversion_between_vector_and_scalar)
4493       << DestTy << SrcTy << R;
4494 
4495   QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
4496   ExprResult CastExprRes = Owned(CastExpr);
4497   CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy);
4498   if (CastExprRes.isInvalid())
4499     return ExprError();
4500   CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take();
4501 
4502   Kind = CK_VectorSplat;
4503   return Owned(CastExpr);
4504 }
4505 
4506 ExprResult
4507 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
4508                     Declarator &D, ParsedType &Ty,
4509                     SourceLocation RParenLoc, Expr *CastExpr) {
4510   assert(!D.isInvalidType() && (CastExpr != 0) &&
4511          "ActOnCastExpr(): missing type or expr");
4512 
4513   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
4514   if (D.isInvalidType())
4515     return ExprError();
4516 
4517   if (getLangOpts().CPlusPlus) {
4518     // Check that there are no default arguments (C++ only).
4519     CheckExtraCXXDefaultArguments(D);
4520   }
4521 
4522   checkUnusedDeclAttributes(D);
4523 
4524   QualType castType = castTInfo->getType();
4525   Ty = CreateParsedType(castType, castTInfo);
4526 
4527   bool isVectorLiteral = false;
4528 
4529   // Check for an altivec or OpenCL literal,
4530   // i.e. all the elements are integer constants.
4531   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
4532   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
4533   if ((getLangOpts().AltiVec || getLangOpts().OpenCL)
4534        && castType->isVectorType() && (PE || PLE)) {
4535     if (PLE && PLE->getNumExprs() == 0) {
4536       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
4537       return ExprError();
4538     }
4539     if (PE || PLE->getNumExprs() == 1) {
4540       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
4541       if (!E->getType()->isVectorType())
4542         isVectorLiteral = true;
4543     }
4544     else
4545       isVectorLiteral = true;
4546   }
4547 
4548   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
4549   // then handle it as such.
4550   if (isVectorLiteral)
4551     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
4552 
4553   // If the Expr being casted is a ParenListExpr, handle it specially.
4554   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
4555   // sequence of BinOp comma operators.
4556   if (isa<ParenListExpr>(CastExpr)) {
4557     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
4558     if (Result.isInvalid()) return ExprError();
4559     CastExpr = Result.take();
4560   }
4561 
4562   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
4563 }
4564 
4565 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
4566                                     SourceLocation RParenLoc, Expr *E,
4567                                     TypeSourceInfo *TInfo) {
4568   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
4569          "Expected paren or paren list expression");
4570 
4571   Expr **exprs;
4572   unsigned numExprs;
4573   Expr *subExpr;
4574   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
4575     exprs = PE->getExprs();
4576     numExprs = PE->getNumExprs();
4577   } else {
4578     subExpr = cast<ParenExpr>(E)->getSubExpr();
4579     exprs = &subExpr;
4580     numExprs = 1;
4581   }
4582 
4583   QualType Ty = TInfo->getType();
4584   assert(Ty->isVectorType() && "Expected vector type");
4585 
4586   SmallVector<Expr *, 8> initExprs;
4587   const VectorType *VTy = Ty->getAs<VectorType>();
4588   unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
4589 
4590   // '(...)' form of vector initialization in AltiVec: the number of
4591   // initializers must be one or must match the size of the vector.
4592   // If a single value is specified in the initializer then it will be
4593   // replicated to all the components of the vector
4594   if (VTy->getVectorKind() == VectorType::AltiVecVector) {
4595     // The number of initializers must be one or must match the size of the
4596     // vector. If a single value is specified in the initializer then it will
4597     // be replicated to all the components of the vector
4598     if (numExprs == 1) {
4599       QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
4600       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
4601       if (Literal.isInvalid())
4602         return ExprError();
4603       Literal = ImpCastExprToType(Literal.take(), ElemTy,
4604                                   PrepareScalarCast(Literal, ElemTy));
4605       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4606     }
4607     else if (numExprs < numElems) {
4608       Diag(E->getExprLoc(),
4609            diag::err_incorrect_number_of_vector_initializers);
4610       return ExprError();
4611     }
4612     else
4613       initExprs.append(exprs, exprs + numExprs);
4614   }
4615   else {
4616     // For OpenCL, when the number of initializers is a single value,
4617     // it will be replicated to all components of the vector.
4618     if (getLangOpts().OpenCL &&
4619         VTy->getVectorKind() == VectorType::GenericVector &&
4620         numExprs == 1) {
4621         QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
4622         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
4623         if (Literal.isInvalid())
4624           return ExprError();
4625         Literal = ImpCastExprToType(Literal.take(), ElemTy,
4626                                     PrepareScalarCast(Literal, ElemTy));
4627         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4628     }
4629 
4630     initExprs.append(exprs, exprs + numExprs);
4631   }
4632   // FIXME: This means that pretty-printing the final AST will produce curly
4633   // braces instead of the original commas.
4634   InitListExpr *initE = new (Context) InitListExpr(Context, LParenLoc,
4635                                                    initExprs, RParenLoc);
4636   initE->setType(Ty);
4637   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
4638 }
4639 
4640 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
4641 /// the ParenListExpr into a sequence of comma binary operators.
4642 ExprResult
4643 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
4644   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
4645   if (!E)
4646     return Owned(OrigExpr);
4647 
4648   ExprResult Result(E->getExpr(0));
4649 
4650   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
4651     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
4652                         E->getExpr(i));
4653 
4654   if (Result.isInvalid()) return ExprError();
4655 
4656   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
4657 }
4658 
4659 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
4660                                     SourceLocation R,
4661                                     MultiExprArg Val) {
4662   assert(Val.data() != 0 && "ActOnParenOrParenListExpr() missing expr list");
4663   Expr *expr = new (Context) ParenListExpr(Context, L, Val, R);
4664   return Owned(expr);
4665 }
4666 
4667 /// \brief Emit a specialized diagnostic when one expression is a null pointer
4668 /// constant and the other is not a pointer.  Returns true if a diagnostic is
4669 /// emitted.
4670 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
4671                                       SourceLocation QuestionLoc) {
4672   Expr *NullExpr = LHSExpr;
4673   Expr *NonPointerExpr = RHSExpr;
4674   Expr::NullPointerConstantKind NullKind =
4675       NullExpr->isNullPointerConstant(Context,
4676                                       Expr::NPC_ValueDependentIsNotNull);
4677 
4678   if (NullKind == Expr::NPCK_NotNull) {
4679     NullExpr = RHSExpr;
4680     NonPointerExpr = LHSExpr;
4681     NullKind =
4682         NullExpr->isNullPointerConstant(Context,
4683                                         Expr::NPC_ValueDependentIsNotNull);
4684   }
4685 
4686   if (NullKind == Expr::NPCK_NotNull)
4687     return false;
4688 
4689   if (NullKind == Expr::NPCK_ZeroExpression)
4690     return false;
4691 
4692   if (NullKind == Expr::NPCK_ZeroLiteral) {
4693     // In this case, check to make sure that we got here from a "NULL"
4694     // string in the source code.
4695     NullExpr = NullExpr->IgnoreParenImpCasts();
4696     SourceLocation loc = NullExpr->getExprLoc();
4697     if (!findMacroSpelling(loc, "NULL"))
4698       return false;
4699   }
4700 
4701   int DiagType = (NullKind == Expr::NPCK_CXX0X_nullptr);
4702   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
4703       << NonPointerExpr->getType() << DiagType
4704       << NonPointerExpr->getSourceRange();
4705   return true;
4706 }
4707 
4708 /// \brief Return false if the condition expression is valid, true otherwise.
4709 static bool checkCondition(Sema &S, Expr *Cond) {
4710   QualType CondTy = Cond->getType();
4711 
4712   // C99 6.5.15p2
4713   if (CondTy->isScalarType()) return false;
4714 
4715   // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
4716   if (S.getLangOpts().OpenCL && CondTy->isVectorType())
4717     return false;
4718 
4719   // Emit the proper error message.
4720   S.Diag(Cond->getLocStart(), S.getLangOpts().OpenCL ?
4721                               diag::err_typecheck_cond_expect_scalar :
4722                               diag::err_typecheck_cond_expect_scalar_or_vector)
4723     << CondTy;
4724   return true;
4725 }
4726 
4727 /// \brief Return false if the two expressions can be converted to a vector,
4728 /// true otherwise
4729 static bool checkConditionalConvertScalarsToVectors(Sema &S, ExprResult &LHS,
4730                                                     ExprResult &RHS,
4731                                                     QualType CondTy) {
4732   // Both operands should be of scalar type.
4733   if (!LHS.get()->getType()->isScalarType()) {
4734     S.Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4735       << CondTy;
4736     return true;
4737   }
4738   if (!RHS.get()->getType()->isScalarType()) {
4739     S.Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4740       << CondTy;
4741     return true;
4742   }
4743 
4744   // Implicity convert these scalars to the type of the condition.
4745   LHS = S.ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast);
4746   RHS = S.ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast);
4747   return false;
4748 }
4749 
4750 /// \brief Handle when one or both operands are void type.
4751 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
4752                                          ExprResult &RHS) {
4753     Expr *LHSExpr = LHS.get();
4754     Expr *RHSExpr = RHS.get();
4755 
4756     if (!LHSExpr->getType()->isVoidType())
4757       S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4758         << RHSExpr->getSourceRange();
4759     if (!RHSExpr->getType()->isVoidType())
4760       S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4761         << LHSExpr->getSourceRange();
4762     LHS = S.ImpCastExprToType(LHS.take(), S.Context.VoidTy, CK_ToVoid);
4763     RHS = S.ImpCastExprToType(RHS.take(), S.Context.VoidTy, CK_ToVoid);
4764     return S.Context.VoidTy;
4765 }
4766 
4767 /// \brief Return false if the NullExpr can be promoted to PointerTy,
4768 /// true otherwise.
4769 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
4770                                         QualType PointerTy) {
4771   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
4772       !NullExpr.get()->isNullPointerConstant(S.Context,
4773                                             Expr::NPC_ValueDependentIsNull))
4774     return true;
4775 
4776   NullExpr = S.ImpCastExprToType(NullExpr.take(), PointerTy, CK_NullToPointer);
4777   return false;
4778 }
4779 
4780 /// \brief Checks compatibility between two pointers and return the resulting
4781 /// type.
4782 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
4783                                                      ExprResult &RHS,
4784                                                      SourceLocation Loc) {
4785   QualType LHSTy = LHS.get()->getType();
4786   QualType RHSTy = RHS.get()->getType();
4787 
4788   if (S.Context.hasSameType(LHSTy, RHSTy)) {
4789     // Two identical pointers types are always compatible.
4790     return LHSTy;
4791   }
4792 
4793   QualType lhptee, rhptee;
4794 
4795   // Get the pointee types.
4796   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
4797     lhptee = LHSBTy->getPointeeType();
4798     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
4799   } else {
4800     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
4801     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
4802   }
4803 
4804   // C99 6.5.15p6: If both operands are pointers to compatible types or to
4805   // differently qualified versions of compatible types, the result type is
4806   // a pointer to an appropriately qualified version of the composite
4807   // type.
4808 
4809   // Only CVR-qualifiers exist in the standard, and the differently-qualified
4810   // clause doesn't make sense for our extensions. E.g. address space 2 should
4811   // be incompatible with address space 3: they may live on different devices or
4812   // anything.
4813   Qualifiers lhQual = lhptee.getQualifiers();
4814   Qualifiers rhQual = rhptee.getQualifiers();
4815 
4816   unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
4817   lhQual.removeCVRQualifiers();
4818   rhQual.removeCVRQualifiers();
4819 
4820   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
4821   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
4822 
4823   QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
4824 
4825   if (CompositeTy.isNull()) {
4826     S.Diag(Loc, diag::warn_typecheck_cond_incompatible_pointers)
4827       << LHSTy << RHSTy << LHS.get()->getSourceRange()
4828       << RHS.get()->getSourceRange();
4829     // In this situation, we assume void* type. No especially good
4830     // reason, but this is what gcc does, and we do have to pick
4831     // to get a consistent AST.
4832     QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy);
4833     LHS = S.ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4834     RHS = S.ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
4835     return incompatTy;
4836   }
4837 
4838   // The pointer types are compatible.
4839   QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual);
4840   ResultTy = S.Context.getPointerType(ResultTy);
4841 
4842   LHS = S.ImpCastExprToType(LHS.take(), ResultTy, CK_BitCast);
4843   RHS = S.ImpCastExprToType(RHS.take(), ResultTy, CK_BitCast);
4844   return ResultTy;
4845 }
4846 
4847 /// \brief Return the resulting type when the operands are both block pointers.
4848 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
4849                                                           ExprResult &LHS,
4850                                                           ExprResult &RHS,
4851                                                           SourceLocation Loc) {
4852   QualType LHSTy = LHS.get()->getType();
4853   QualType RHSTy = RHS.get()->getType();
4854 
4855   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
4856     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
4857       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
4858       LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4859       RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4860       return destType;
4861     }
4862     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
4863       << LHSTy << RHSTy << LHS.get()->getSourceRange()
4864       << RHS.get()->getSourceRange();
4865     return QualType();
4866   }
4867 
4868   // We have 2 block pointer types.
4869   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
4870 }
4871 
4872 /// \brief Return the resulting type when the operands are both pointers.
4873 static QualType
4874 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
4875                                             ExprResult &RHS,
4876                                             SourceLocation Loc) {
4877   // get the pointer types
4878   QualType LHSTy = LHS.get()->getType();
4879   QualType RHSTy = RHS.get()->getType();
4880 
4881   // get the "pointed to" types
4882   QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4883   QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4884 
4885   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
4886   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
4887     // Figure out necessary qualifiers (C99 6.5.15p6)
4888     QualType destPointee
4889       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4890     QualType destType = S.Context.getPointerType(destPointee);
4891     // Add qualifiers if necessary.
4892     LHS = S.ImpCastExprToType(LHS.take(), destType, CK_NoOp);
4893     // Promote to void*.
4894     RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4895     return destType;
4896   }
4897   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
4898     QualType destPointee
4899       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4900     QualType destType = S.Context.getPointerType(destPointee);
4901     // Add qualifiers if necessary.
4902     RHS = S.ImpCastExprToType(RHS.take(), destType, CK_NoOp);
4903     // Promote to void*.
4904     LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4905     return destType;
4906   }
4907 
4908   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
4909 }
4910 
4911 /// \brief Return false if the first expression is not an integer and the second
4912 /// expression is not a pointer, true otherwise.
4913 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
4914                                         Expr* PointerExpr, SourceLocation Loc,
4915                                         bool IsIntFirstExpr) {
4916   if (!PointerExpr->getType()->isPointerType() ||
4917       !Int.get()->getType()->isIntegerType())
4918     return false;
4919 
4920   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
4921   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
4922 
4923   S.Diag(Loc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4924     << Expr1->getType() << Expr2->getType()
4925     << Expr1->getSourceRange() << Expr2->getSourceRange();
4926   Int = S.ImpCastExprToType(Int.take(), PointerExpr->getType(),
4927                             CK_IntegralToPointer);
4928   return true;
4929 }
4930 
4931 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
4932 /// In that case, LHS = cond.
4933 /// C99 6.5.15
4934 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
4935                                         ExprResult &RHS, ExprValueKind &VK,
4936                                         ExprObjectKind &OK,
4937                                         SourceLocation QuestionLoc) {
4938 
4939   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
4940   if (!LHSResult.isUsable()) return QualType();
4941   LHS = LHSResult;
4942 
4943   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
4944   if (!RHSResult.isUsable()) return QualType();
4945   RHS = RHSResult;
4946 
4947   // C++ is sufficiently different to merit its own checker.
4948   if (getLangOpts().CPlusPlus)
4949     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
4950 
4951   VK = VK_RValue;
4952   OK = OK_Ordinary;
4953 
4954   Cond = UsualUnaryConversions(Cond.take());
4955   if (Cond.isInvalid())
4956     return QualType();
4957   LHS = UsualUnaryConversions(LHS.take());
4958   if (LHS.isInvalid())
4959     return QualType();
4960   RHS = UsualUnaryConversions(RHS.take());
4961   if (RHS.isInvalid())
4962     return QualType();
4963 
4964   QualType CondTy = Cond.get()->getType();
4965   QualType LHSTy = LHS.get()->getType();
4966   QualType RHSTy = RHS.get()->getType();
4967 
4968   // first, check the condition.
4969   if (checkCondition(*this, Cond.get()))
4970     return QualType();
4971 
4972   // Now check the two expressions.
4973   if (LHSTy->isVectorType() || RHSTy->isVectorType())
4974     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
4975 
4976   // OpenCL: If the condition is a vector, and both operands are scalar,
4977   // attempt to implicity convert them to the vector type to act like the
4978   // built in select.
4979   if (getLangOpts().OpenCL && CondTy->isVectorType())
4980     if (checkConditionalConvertScalarsToVectors(*this, LHS, RHS, CondTy))
4981       return QualType();
4982 
4983   // If both operands have arithmetic type, do the usual arithmetic conversions
4984   // to find a common type: C99 6.5.15p3,5.
4985   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
4986     UsualArithmeticConversions(LHS, RHS);
4987     if (LHS.isInvalid() || RHS.isInvalid())
4988       return QualType();
4989     return LHS.get()->getType();
4990   }
4991 
4992   // If both operands are the same structure or union type, the result is that
4993   // type.
4994   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
4995     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
4996       if (LHSRT->getDecl() == RHSRT->getDecl())
4997         // "If both the operands have structure or union type, the result has
4998         // that type."  This implies that CV qualifiers are dropped.
4999         return LHSTy.getUnqualifiedType();
5000     // FIXME: Type of conditional expression must be complete in C mode.
5001   }
5002 
5003   // C99 6.5.15p5: "If both operands have void type, the result has void type."
5004   // The following || allows only one side to be void (a GCC-ism).
5005   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
5006     return checkConditionalVoidType(*this, LHS, RHS);
5007   }
5008 
5009   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
5010   // the type of the other operand."
5011   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
5012   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
5013 
5014   // All objective-c pointer type analysis is done here.
5015   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
5016                                                         QuestionLoc);
5017   if (LHS.isInvalid() || RHS.isInvalid())
5018     return QualType();
5019   if (!compositeType.isNull())
5020     return compositeType;
5021 
5022 
5023   // Handle block pointer types.
5024   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
5025     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
5026                                                      QuestionLoc);
5027 
5028   // Check constraints for C object pointers types (C99 6.5.15p3,6).
5029   if (LHSTy->isPointerType() && RHSTy->isPointerType())
5030     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
5031                                                        QuestionLoc);
5032 
5033   // GCC compatibility: soften pointer/integer mismatch.  Note that
5034   // null pointers have been filtered out by this point.
5035   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
5036       /*isIntFirstExpr=*/true))
5037     return RHSTy;
5038   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
5039       /*isIntFirstExpr=*/false))
5040     return LHSTy;
5041 
5042   // Emit a better diagnostic if one of the expressions is a null pointer
5043   // constant and the other is not a pointer type. In this case, the user most
5044   // likely forgot to take the address of the other expression.
5045   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
5046     return QualType();
5047 
5048   // Otherwise, the operands are not compatible.
5049   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
5050     << LHSTy << RHSTy << LHS.get()->getSourceRange()
5051     << RHS.get()->getSourceRange();
5052   return QualType();
5053 }
5054 
5055 /// FindCompositeObjCPointerType - Helper method to find composite type of
5056 /// two objective-c pointer types of the two input expressions.
5057 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
5058                                             SourceLocation QuestionLoc) {
5059   QualType LHSTy = LHS.get()->getType();
5060   QualType RHSTy = RHS.get()->getType();
5061 
5062   // Handle things like Class and struct objc_class*.  Here we case the result
5063   // to the pseudo-builtin, because that will be implicitly cast back to the
5064   // redefinition type if an attempt is made to access its fields.
5065   if (LHSTy->isObjCClassType() &&
5066       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
5067     RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
5068     return LHSTy;
5069   }
5070   if (RHSTy->isObjCClassType() &&
5071       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
5072     LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
5073     return RHSTy;
5074   }
5075   // And the same for struct objc_object* / id
5076   if (LHSTy->isObjCIdType() &&
5077       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
5078     RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
5079     return LHSTy;
5080   }
5081   if (RHSTy->isObjCIdType() &&
5082       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
5083     LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
5084     return RHSTy;
5085   }
5086   // And the same for struct objc_selector* / SEL
5087   if (Context.isObjCSelType(LHSTy) &&
5088       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
5089     RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
5090     return LHSTy;
5091   }
5092   if (Context.isObjCSelType(RHSTy) &&
5093       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
5094     LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
5095     return RHSTy;
5096   }
5097   // Check constraints for Objective-C object pointers types.
5098   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
5099 
5100     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5101       // Two identical object pointer types are always compatible.
5102       return LHSTy;
5103     }
5104     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
5105     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
5106     QualType compositeType = LHSTy;
5107 
5108     // If both operands are interfaces and either operand can be
5109     // assigned to the other, use that type as the composite
5110     // type. This allows
5111     //   xxx ? (A*) a : (B*) b
5112     // where B is a subclass of A.
5113     //
5114     // Additionally, as for assignment, if either type is 'id'
5115     // allow silent coercion. Finally, if the types are
5116     // incompatible then make sure to use 'id' as the composite
5117     // type so the result is acceptable for sending messages to.
5118 
5119     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
5120     // It could return the composite type.
5121     if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
5122       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
5123     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
5124       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
5125     } else if ((LHSTy->isObjCQualifiedIdType() ||
5126                 RHSTy->isObjCQualifiedIdType()) &&
5127                Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
5128       // Need to handle "id<xx>" explicitly.
5129       // GCC allows qualified id and any Objective-C type to devolve to
5130       // id. Currently localizing to here until clear this should be
5131       // part of ObjCQualifiedIdTypesAreCompatible.
5132       compositeType = Context.getObjCIdType();
5133     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
5134       compositeType = Context.getObjCIdType();
5135     } else if (!(compositeType =
5136                  Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
5137       ;
5138     else {
5139       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
5140       << LHSTy << RHSTy
5141       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5142       QualType incompatTy = Context.getObjCIdType();
5143       LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
5144       RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
5145       return incompatTy;
5146     }
5147     // The object pointer types are compatible.
5148     LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast);
5149     RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast);
5150     return compositeType;
5151   }
5152   // Check Objective-C object pointer types and 'void *'
5153   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
5154     if (getLangOpts().ObjCAutoRefCount) {
5155       // ARC forbids the implicit conversion of object pointers to 'void *',
5156       // so these types are not compatible.
5157       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
5158           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5159       LHS = RHS = true;
5160       return QualType();
5161     }
5162     QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5163     QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5164     QualType destPointee
5165     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
5166     QualType destType = Context.getPointerType(destPointee);
5167     // Add qualifiers if necessary.
5168     LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
5169     // Promote to void*.
5170     RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
5171     return destType;
5172   }
5173   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
5174     if (getLangOpts().ObjCAutoRefCount) {
5175       // ARC forbids the implicit conversion of object pointers to 'void *',
5176       // so these types are not compatible.
5177       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
5178           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5179       LHS = RHS = true;
5180       return QualType();
5181     }
5182     QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5183     QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
5184     QualType destPointee
5185     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
5186     QualType destType = Context.getPointerType(destPointee);
5187     // Add qualifiers if necessary.
5188     RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
5189     // Promote to void*.
5190     LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
5191     return destType;
5192   }
5193   return QualType();
5194 }
5195 
5196 /// SuggestParentheses - Emit a note with a fixit hint that wraps
5197 /// ParenRange in parentheses.
5198 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
5199                                const PartialDiagnostic &Note,
5200                                SourceRange ParenRange) {
5201   SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
5202   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
5203       EndLoc.isValid()) {
5204     Self.Diag(Loc, Note)
5205       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
5206       << FixItHint::CreateInsertion(EndLoc, ")");
5207   } else {
5208     // We can't display the parentheses, so just show the bare note.
5209     Self.Diag(Loc, Note) << ParenRange;
5210   }
5211 }
5212 
5213 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
5214   return Opc >= BO_Mul && Opc <= BO_Shr;
5215 }
5216 
5217 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
5218 /// expression, either using a built-in or overloaded operator,
5219 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
5220 /// expression.
5221 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
5222                                    Expr **RHSExprs) {
5223   // Don't strip parenthesis: we should not warn if E is in parenthesis.
5224   E = E->IgnoreImpCasts();
5225   E = E->IgnoreConversionOperator();
5226   E = E->IgnoreImpCasts();
5227 
5228   // Built-in binary operator.
5229   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
5230     if (IsArithmeticOp(OP->getOpcode())) {
5231       *Opcode = OP->getOpcode();
5232       *RHSExprs = OP->getRHS();
5233       return true;
5234     }
5235   }
5236 
5237   // Overloaded operator.
5238   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
5239     if (Call->getNumArgs() != 2)
5240       return false;
5241 
5242     // Make sure this is really a binary operator that is safe to pass into
5243     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
5244     OverloadedOperatorKind OO = Call->getOperator();
5245     if (OO < OO_Plus || OO > OO_Arrow)
5246       return false;
5247 
5248     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
5249     if (IsArithmeticOp(OpKind)) {
5250       *Opcode = OpKind;
5251       *RHSExprs = Call->getArg(1);
5252       return true;
5253     }
5254   }
5255 
5256   return false;
5257 }
5258 
5259 static bool IsLogicOp(BinaryOperatorKind Opc) {
5260   return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
5261 }
5262 
5263 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
5264 /// or is a logical expression such as (x==y) which has int type, but is
5265 /// commonly interpreted as boolean.
5266 static bool ExprLooksBoolean(Expr *E) {
5267   E = E->IgnoreParenImpCasts();
5268 
5269   if (E->getType()->isBooleanType())
5270     return true;
5271   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
5272     return IsLogicOp(OP->getOpcode());
5273   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
5274     return OP->getOpcode() == UO_LNot;
5275 
5276   return false;
5277 }
5278 
5279 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
5280 /// and binary operator are mixed in a way that suggests the programmer assumed
5281 /// the conditional operator has higher precedence, for example:
5282 /// "int x = a + someBinaryCondition ? 1 : 2".
5283 static void DiagnoseConditionalPrecedence(Sema &Self,
5284                                           SourceLocation OpLoc,
5285                                           Expr *Condition,
5286                                           Expr *LHSExpr,
5287                                           Expr *RHSExpr) {
5288   BinaryOperatorKind CondOpcode;
5289   Expr *CondRHS;
5290 
5291   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
5292     return;
5293   if (!ExprLooksBoolean(CondRHS))
5294     return;
5295 
5296   // The condition is an arithmetic binary expression, with a right-
5297   // hand side that looks boolean, so warn.
5298 
5299   Self.Diag(OpLoc, diag::warn_precedence_conditional)
5300       << Condition->getSourceRange()
5301       << BinaryOperator::getOpcodeStr(CondOpcode);
5302 
5303   SuggestParentheses(Self, OpLoc,
5304     Self.PDiag(diag::note_precedence_conditional_silence)
5305       << BinaryOperator::getOpcodeStr(CondOpcode),
5306     SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
5307 
5308   SuggestParentheses(Self, OpLoc,
5309     Self.PDiag(diag::note_precedence_conditional_first),
5310     SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
5311 }
5312 
5313 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
5314 /// in the case of a the GNU conditional expr extension.
5315 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
5316                                     SourceLocation ColonLoc,
5317                                     Expr *CondExpr, Expr *LHSExpr,
5318                                     Expr *RHSExpr) {
5319   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
5320   // was the condition.
5321   OpaqueValueExpr *opaqueValue = 0;
5322   Expr *commonExpr = 0;
5323   if (LHSExpr == 0) {
5324     commonExpr = CondExpr;
5325 
5326     // We usually want to apply unary conversions *before* saving, except
5327     // in the special case of a C++ l-value conditional.
5328     if (!(getLangOpts().CPlusPlus
5329           && !commonExpr->isTypeDependent()
5330           && commonExpr->getValueKind() == RHSExpr->getValueKind()
5331           && commonExpr->isGLValue()
5332           && commonExpr->isOrdinaryOrBitFieldObject()
5333           && RHSExpr->isOrdinaryOrBitFieldObject()
5334           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
5335       ExprResult commonRes = UsualUnaryConversions(commonExpr);
5336       if (commonRes.isInvalid())
5337         return ExprError();
5338       commonExpr = commonRes.take();
5339     }
5340 
5341     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
5342                                                 commonExpr->getType(),
5343                                                 commonExpr->getValueKind(),
5344                                                 commonExpr->getObjectKind(),
5345                                                 commonExpr);
5346     LHSExpr = CondExpr = opaqueValue;
5347   }
5348 
5349   ExprValueKind VK = VK_RValue;
5350   ExprObjectKind OK = OK_Ordinary;
5351   ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
5352   QualType result = CheckConditionalOperands(Cond, LHS, RHS,
5353                                              VK, OK, QuestionLoc);
5354   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
5355       RHS.isInvalid())
5356     return ExprError();
5357 
5358   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
5359                                 RHS.get());
5360 
5361   if (!commonExpr)
5362     return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc,
5363                                                    LHS.take(), ColonLoc,
5364                                                    RHS.take(), result, VK, OK));
5365 
5366   return Owned(new (Context)
5367     BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(),
5368                               RHS.take(), QuestionLoc, ColonLoc, result, VK,
5369                               OK));
5370 }
5371 
5372 // checkPointerTypesForAssignment - This is a very tricky routine (despite
5373 // being closely modeled after the C99 spec:-). The odd characteristic of this
5374 // routine is it effectively iqnores the qualifiers on the top level pointee.
5375 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
5376 // FIXME: add a couple examples in this comment.
5377 static Sema::AssignConvertType
5378 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
5379   assert(LHSType.isCanonical() && "LHS not canonicalized!");
5380   assert(RHSType.isCanonical() && "RHS not canonicalized!");
5381 
5382   // get the "pointed to" type (ignoring qualifiers at the top level)
5383   const Type *lhptee, *rhptee;
5384   Qualifiers lhq, rhq;
5385   llvm::tie(lhptee, lhq) = cast<PointerType>(LHSType)->getPointeeType().split();
5386   llvm::tie(rhptee, rhq) = cast<PointerType>(RHSType)->getPointeeType().split();
5387 
5388   Sema::AssignConvertType ConvTy = Sema::Compatible;
5389 
5390   // C99 6.5.16.1p1: This following citation is common to constraints
5391   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
5392   // qualifiers of the type *pointed to* by the right;
5393   Qualifiers lq;
5394 
5395   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
5396   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
5397       lhq.compatiblyIncludesObjCLifetime(rhq)) {
5398     // Ignore lifetime for further calculation.
5399     lhq.removeObjCLifetime();
5400     rhq.removeObjCLifetime();
5401   }
5402 
5403   if (!lhq.compatiblyIncludes(rhq)) {
5404     // Treat address-space mismatches as fatal.  TODO: address subspaces
5405     if (lhq.getAddressSpace() != rhq.getAddressSpace())
5406       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5407 
5408     // It's okay to add or remove GC or lifetime qualifiers when converting to
5409     // and from void*.
5410     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
5411                         .compatiblyIncludes(
5412                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
5413              && (lhptee->isVoidType() || rhptee->isVoidType()))
5414       ; // keep old
5415 
5416     // Treat lifetime mismatches as fatal.
5417     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
5418       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5419 
5420     // For GCC compatibility, other qualifier mismatches are treated
5421     // as still compatible in C.
5422     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
5423   }
5424 
5425   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
5426   // incomplete type and the other is a pointer to a qualified or unqualified
5427   // version of void...
5428   if (lhptee->isVoidType()) {
5429     if (rhptee->isIncompleteOrObjectType())
5430       return ConvTy;
5431 
5432     // As an extension, we allow cast to/from void* to function pointer.
5433     assert(rhptee->isFunctionType());
5434     return Sema::FunctionVoidPointer;
5435   }
5436 
5437   if (rhptee->isVoidType()) {
5438     if (lhptee->isIncompleteOrObjectType())
5439       return ConvTy;
5440 
5441     // As an extension, we allow cast to/from void* to function pointer.
5442     assert(lhptee->isFunctionType());
5443     return Sema::FunctionVoidPointer;
5444   }
5445 
5446   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
5447   // unqualified versions of compatible types, ...
5448   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
5449   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
5450     // Check if the pointee types are compatible ignoring the sign.
5451     // We explicitly check for char so that we catch "char" vs
5452     // "unsigned char" on systems where "char" is unsigned.
5453     if (lhptee->isCharType())
5454       ltrans = S.Context.UnsignedCharTy;
5455     else if (lhptee->hasSignedIntegerRepresentation())
5456       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
5457 
5458     if (rhptee->isCharType())
5459       rtrans = S.Context.UnsignedCharTy;
5460     else if (rhptee->hasSignedIntegerRepresentation())
5461       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
5462 
5463     if (ltrans == rtrans) {
5464       // Types are compatible ignoring the sign. Qualifier incompatibility
5465       // takes priority over sign incompatibility because the sign
5466       // warning can be disabled.
5467       if (ConvTy != Sema::Compatible)
5468         return ConvTy;
5469 
5470       return Sema::IncompatiblePointerSign;
5471     }
5472 
5473     // If we are a multi-level pointer, it's possible that our issue is simply
5474     // one of qualification - e.g. char ** -> const char ** is not allowed. If
5475     // the eventual target type is the same and the pointers have the same
5476     // level of indirection, this must be the issue.
5477     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
5478       do {
5479         lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
5480         rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
5481       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
5482 
5483       if (lhptee == rhptee)
5484         return Sema::IncompatibleNestedPointerQualifiers;
5485     }
5486 
5487     // General pointer incompatibility takes priority over qualifiers.
5488     return Sema::IncompatiblePointer;
5489   }
5490   if (!S.getLangOpts().CPlusPlus &&
5491       S.IsNoReturnConversion(ltrans, rtrans, ltrans))
5492     return Sema::IncompatiblePointer;
5493   return ConvTy;
5494 }
5495 
5496 /// checkBlockPointerTypesForAssignment - This routine determines whether two
5497 /// block pointer types are compatible or whether a block and normal pointer
5498 /// are compatible. It is more restrict than comparing two function pointer
5499 // types.
5500 static Sema::AssignConvertType
5501 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
5502                                     QualType RHSType) {
5503   assert(LHSType.isCanonical() && "LHS not canonicalized!");
5504   assert(RHSType.isCanonical() && "RHS not canonicalized!");
5505 
5506   QualType lhptee, rhptee;
5507 
5508   // get the "pointed to" type (ignoring qualifiers at the top level)
5509   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
5510   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
5511 
5512   // In C++, the types have to match exactly.
5513   if (S.getLangOpts().CPlusPlus)
5514     return Sema::IncompatibleBlockPointer;
5515 
5516   Sema::AssignConvertType ConvTy = Sema::Compatible;
5517 
5518   // For blocks we enforce that qualifiers are identical.
5519   if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
5520     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
5521 
5522   if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
5523     return Sema::IncompatibleBlockPointer;
5524 
5525   return ConvTy;
5526 }
5527 
5528 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
5529 /// for assignment compatibility.
5530 static Sema::AssignConvertType
5531 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
5532                                    QualType RHSType) {
5533   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
5534   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
5535 
5536   if (LHSType->isObjCBuiltinType()) {
5537     // Class is not compatible with ObjC object pointers.
5538     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
5539         !RHSType->isObjCQualifiedClassType())
5540       return Sema::IncompatiblePointer;
5541     return Sema::Compatible;
5542   }
5543   if (RHSType->isObjCBuiltinType()) {
5544     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
5545         !LHSType->isObjCQualifiedClassType())
5546       return Sema::IncompatiblePointer;
5547     return Sema::Compatible;
5548   }
5549   QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
5550   QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
5551 
5552   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
5553       // make an exception for id<P>
5554       !LHSType->isObjCQualifiedIdType())
5555     return Sema::CompatiblePointerDiscardsQualifiers;
5556 
5557   if (S.Context.typesAreCompatible(LHSType, RHSType))
5558     return Sema::Compatible;
5559   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
5560     return Sema::IncompatibleObjCQualifiedId;
5561   return Sema::IncompatiblePointer;
5562 }
5563 
5564 Sema::AssignConvertType
5565 Sema::CheckAssignmentConstraints(SourceLocation Loc,
5566                                  QualType LHSType, QualType RHSType) {
5567   // Fake up an opaque expression.  We don't actually care about what
5568   // cast operations are required, so if CheckAssignmentConstraints
5569   // adds casts to this they'll be wasted, but fortunately that doesn't
5570   // usually happen on valid code.
5571   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
5572   ExprResult RHSPtr = &RHSExpr;
5573   CastKind K = CK_Invalid;
5574 
5575   return CheckAssignmentConstraints(LHSType, RHSPtr, K);
5576 }
5577 
5578 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
5579 /// has code to accommodate several GCC extensions when type checking
5580 /// pointers. Here are some objectionable examples that GCC considers warnings:
5581 ///
5582 ///  int a, *pint;
5583 ///  short *pshort;
5584 ///  struct foo *pfoo;
5585 ///
5586 ///  pint = pshort; // warning: assignment from incompatible pointer type
5587 ///  a = pint; // warning: assignment makes integer from pointer without a cast
5588 ///  pint = a; // warning: assignment makes pointer from integer without a cast
5589 ///  pint = pfoo; // warning: assignment from incompatible pointer type
5590 ///
5591 /// As a result, the code for dealing with pointers is more complex than the
5592 /// C99 spec dictates.
5593 ///
5594 /// Sets 'Kind' for any result kind except Incompatible.
5595 Sema::AssignConvertType
5596 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
5597                                  CastKind &Kind) {
5598   QualType RHSType = RHS.get()->getType();
5599   QualType OrigLHSType = LHSType;
5600 
5601   // Get canonical types.  We're not formatting these types, just comparing
5602   // them.
5603   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
5604   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
5605 
5606 
5607   // Common case: no conversion required.
5608   if (LHSType == RHSType) {
5609     Kind = CK_NoOp;
5610     return Compatible;
5611   }
5612 
5613   // If we have an atomic type, try a non-atomic assignment, then just add an
5614   // atomic qualification step.
5615   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
5616     Sema::AssignConvertType result =
5617       CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
5618     if (result != Compatible)
5619       return result;
5620     if (Kind != CK_NoOp)
5621       RHS = ImpCastExprToType(RHS.take(), AtomicTy->getValueType(), Kind);
5622     Kind = CK_NonAtomicToAtomic;
5623     return Compatible;
5624   }
5625 
5626   // If the left-hand side is a reference type, then we are in a
5627   // (rare!) case where we've allowed the use of references in C,
5628   // e.g., as a parameter type in a built-in function. In this case,
5629   // just make sure that the type referenced is compatible with the
5630   // right-hand side type. The caller is responsible for adjusting
5631   // LHSType so that the resulting expression does not have reference
5632   // type.
5633   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
5634     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
5635       Kind = CK_LValueBitCast;
5636       return Compatible;
5637     }
5638     return Incompatible;
5639   }
5640 
5641   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
5642   // to the same ExtVector type.
5643   if (LHSType->isExtVectorType()) {
5644     if (RHSType->isExtVectorType())
5645       return Incompatible;
5646     if (RHSType->isArithmeticType()) {
5647       // CK_VectorSplat does T -> vector T, so first cast to the
5648       // element type.
5649       QualType elType = cast<ExtVectorType>(LHSType)->getElementType();
5650       if (elType != RHSType) {
5651         Kind = PrepareScalarCast(RHS, elType);
5652         RHS = ImpCastExprToType(RHS.take(), elType, Kind);
5653       }
5654       Kind = CK_VectorSplat;
5655       return Compatible;
5656     }
5657   }
5658 
5659   // Conversions to or from vector type.
5660   if (LHSType->isVectorType() || RHSType->isVectorType()) {
5661     if (LHSType->isVectorType() && RHSType->isVectorType()) {
5662       // Allow assignments of an AltiVec vector type to an equivalent GCC
5663       // vector type and vice versa
5664       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
5665         Kind = CK_BitCast;
5666         return Compatible;
5667       }
5668 
5669       // If we are allowing lax vector conversions, and LHS and RHS are both
5670       // vectors, the total size only needs to be the same. This is a bitcast;
5671       // no bits are changed but the result type is different.
5672       if (getLangOpts().LaxVectorConversions &&
5673           (Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType))) {
5674         Kind = CK_BitCast;
5675         return IncompatibleVectors;
5676       }
5677     }
5678     return Incompatible;
5679   }
5680 
5681   // Arithmetic conversions.
5682   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
5683       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
5684     Kind = PrepareScalarCast(RHS, LHSType);
5685     return Compatible;
5686   }
5687 
5688   // Conversions to normal pointers.
5689   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
5690     // U* -> T*
5691     if (isa<PointerType>(RHSType)) {
5692       Kind = CK_BitCast;
5693       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
5694     }
5695 
5696     // int -> T*
5697     if (RHSType->isIntegerType()) {
5698       Kind = CK_IntegralToPointer; // FIXME: null?
5699       return IntToPointer;
5700     }
5701 
5702     // C pointers are not compatible with ObjC object pointers,
5703     // with two exceptions:
5704     if (isa<ObjCObjectPointerType>(RHSType)) {
5705       //  - conversions to void*
5706       if (LHSPointer->getPointeeType()->isVoidType()) {
5707         Kind = CK_BitCast;
5708         return Compatible;
5709       }
5710 
5711       //  - conversions from 'Class' to the redefinition type
5712       if (RHSType->isObjCClassType() &&
5713           Context.hasSameType(LHSType,
5714                               Context.getObjCClassRedefinitionType())) {
5715         Kind = CK_BitCast;
5716         return Compatible;
5717       }
5718 
5719       Kind = CK_BitCast;
5720       return IncompatiblePointer;
5721     }
5722 
5723     // U^ -> void*
5724     if (RHSType->getAs<BlockPointerType>()) {
5725       if (LHSPointer->getPointeeType()->isVoidType()) {
5726         Kind = CK_BitCast;
5727         return Compatible;
5728       }
5729     }
5730 
5731     return Incompatible;
5732   }
5733 
5734   // Conversions to block pointers.
5735   if (isa<BlockPointerType>(LHSType)) {
5736     // U^ -> T^
5737     if (RHSType->isBlockPointerType()) {
5738       Kind = CK_BitCast;
5739       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
5740     }
5741 
5742     // int or null -> T^
5743     if (RHSType->isIntegerType()) {
5744       Kind = CK_IntegralToPointer; // FIXME: null
5745       return IntToBlockPointer;
5746     }
5747 
5748     // id -> T^
5749     if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
5750       Kind = CK_AnyPointerToBlockPointerCast;
5751       return Compatible;
5752     }
5753 
5754     // void* -> T^
5755     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
5756       if (RHSPT->getPointeeType()->isVoidType()) {
5757         Kind = CK_AnyPointerToBlockPointerCast;
5758         return Compatible;
5759       }
5760 
5761     return Incompatible;
5762   }
5763 
5764   // Conversions to Objective-C pointers.
5765   if (isa<ObjCObjectPointerType>(LHSType)) {
5766     // A* -> B*
5767     if (RHSType->isObjCObjectPointerType()) {
5768       Kind = CK_BitCast;
5769       Sema::AssignConvertType result =
5770         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
5771       if (getLangOpts().ObjCAutoRefCount &&
5772           result == Compatible &&
5773           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
5774         result = IncompatibleObjCWeakRef;
5775       return result;
5776     }
5777 
5778     // int or null -> A*
5779     if (RHSType->isIntegerType()) {
5780       Kind = CK_IntegralToPointer; // FIXME: null
5781       return IntToPointer;
5782     }
5783 
5784     // In general, C pointers are not compatible with ObjC object pointers,
5785     // with two exceptions:
5786     if (isa<PointerType>(RHSType)) {
5787       Kind = CK_CPointerToObjCPointerCast;
5788 
5789       //  - conversions from 'void*'
5790       if (RHSType->isVoidPointerType()) {
5791         return Compatible;
5792       }
5793 
5794       //  - conversions to 'Class' from its redefinition type
5795       if (LHSType->isObjCClassType() &&
5796           Context.hasSameType(RHSType,
5797                               Context.getObjCClassRedefinitionType())) {
5798         return Compatible;
5799       }
5800 
5801       return IncompatiblePointer;
5802     }
5803 
5804     // T^ -> A*
5805     if (RHSType->isBlockPointerType()) {
5806       maybeExtendBlockObject(*this, RHS);
5807       Kind = CK_BlockPointerToObjCPointerCast;
5808       return Compatible;
5809     }
5810 
5811     return Incompatible;
5812   }
5813 
5814   // Conversions from pointers that are not covered by the above.
5815   if (isa<PointerType>(RHSType)) {
5816     // T* -> _Bool
5817     if (LHSType == Context.BoolTy) {
5818       Kind = CK_PointerToBoolean;
5819       return Compatible;
5820     }
5821 
5822     // T* -> int
5823     if (LHSType->isIntegerType()) {
5824       Kind = CK_PointerToIntegral;
5825       return PointerToInt;
5826     }
5827 
5828     return Incompatible;
5829   }
5830 
5831   // Conversions from Objective-C pointers that are not covered by the above.
5832   if (isa<ObjCObjectPointerType>(RHSType)) {
5833     // T* -> _Bool
5834     if (LHSType == Context.BoolTy) {
5835       Kind = CK_PointerToBoolean;
5836       return Compatible;
5837     }
5838 
5839     // T* -> int
5840     if (LHSType->isIntegerType()) {
5841       Kind = CK_PointerToIntegral;
5842       return PointerToInt;
5843     }
5844 
5845     return Incompatible;
5846   }
5847 
5848   // struct A -> struct B
5849   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
5850     if (Context.typesAreCompatible(LHSType, RHSType)) {
5851       Kind = CK_NoOp;
5852       return Compatible;
5853     }
5854   }
5855 
5856   return Incompatible;
5857 }
5858 
5859 /// \brief Constructs a transparent union from an expression that is
5860 /// used to initialize the transparent union.
5861 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
5862                                       ExprResult &EResult, QualType UnionType,
5863                                       FieldDecl *Field) {
5864   // Build an initializer list that designates the appropriate member
5865   // of the transparent union.
5866   Expr *E = EResult.take();
5867   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
5868                                                    E, SourceLocation());
5869   Initializer->setType(UnionType);
5870   Initializer->setInitializedFieldInUnion(Field);
5871 
5872   // Build a compound literal constructing a value of the transparent
5873   // union type from this initializer list.
5874   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
5875   EResult = S.Owned(
5876     new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
5877                                 VK_RValue, Initializer, false));
5878 }
5879 
5880 Sema::AssignConvertType
5881 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
5882                                                ExprResult &RHS) {
5883   QualType RHSType = RHS.get()->getType();
5884 
5885   // If the ArgType is a Union type, we want to handle a potential
5886   // transparent_union GCC extension.
5887   const RecordType *UT = ArgType->getAsUnionType();
5888   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
5889     return Incompatible;
5890 
5891   // The field to initialize within the transparent union.
5892   RecordDecl *UD = UT->getDecl();
5893   FieldDecl *InitField = 0;
5894   // It's compatible if the expression matches any of the fields.
5895   for (RecordDecl::field_iterator it = UD->field_begin(),
5896          itend = UD->field_end();
5897        it != itend; ++it) {
5898     if (it->getType()->isPointerType()) {
5899       // If the transparent union contains a pointer type, we allow:
5900       // 1) void pointer
5901       // 2) null pointer constant
5902       if (RHSType->isPointerType())
5903         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
5904           RHS = ImpCastExprToType(RHS.take(), it->getType(), CK_BitCast);
5905           InitField = *it;
5906           break;
5907         }
5908 
5909       if (RHS.get()->isNullPointerConstant(Context,
5910                                            Expr::NPC_ValueDependentIsNull)) {
5911         RHS = ImpCastExprToType(RHS.take(), it->getType(),
5912                                 CK_NullToPointer);
5913         InitField = *it;
5914         break;
5915       }
5916     }
5917 
5918     CastKind Kind = CK_Invalid;
5919     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
5920           == Compatible) {
5921       RHS = ImpCastExprToType(RHS.take(), it->getType(), Kind);
5922       InitField = *it;
5923       break;
5924     }
5925   }
5926 
5927   if (!InitField)
5928     return Incompatible;
5929 
5930   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
5931   return Compatible;
5932 }
5933 
5934 Sema::AssignConvertType
5935 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS,
5936                                        bool Diagnose) {
5937   if (getLangOpts().CPlusPlus) {
5938     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
5939       // C++ 5.17p3: If the left operand is not of class type, the
5940       // expression is implicitly converted (C++ 4) to the
5941       // cv-unqualified type of the left operand.
5942       ExprResult Res;
5943       if (Diagnose) {
5944         Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5945                                         AA_Assigning);
5946       } else {
5947         ImplicitConversionSequence ICS =
5948             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5949                                   /*SuppressUserConversions=*/false,
5950                                   /*AllowExplicit=*/false,
5951                                   /*InOverloadResolution=*/false,
5952                                   /*CStyle=*/false,
5953                                   /*AllowObjCWritebackConversion=*/false);
5954         if (ICS.isFailure())
5955           return Incompatible;
5956         Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5957                                         ICS, AA_Assigning);
5958       }
5959       if (Res.isInvalid())
5960         return Incompatible;
5961       Sema::AssignConvertType result = Compatible;
5962       if (getLangOpts().ObjCAutoRefCount &&
5963           !CheckObjCARCUnavailableWeakConversion(LHSType,
5964                                                  RHS.get()->getType()))
5965         result = IncompatibleObjCWeakRef;
5966       RHS = Res;
5967       return result;
5968     }
5969 
5970     // FIXME: Currently, we fall through and treat C++ classes like C
5971     // structures.
5972     // FIXME: We also fall through for atomics; not sure what should
5973     // happen there, though.
5974   }
5975 
5976   // C99 6.5.16.1p1: the left operand is a pointer and the right is
5977   // a null pointer constant.
5978   if ((LHSType->isPointerType() ||
5979        LHSType->isObjCObjectPointerType() ||
5980        LHSType->isBlockPointerType())
5981       && RHS.get()->isNullPointerConstant(Context,
5982                                           Expr::NPC_ValueDependentIsNull)) {
5983     RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
5984     return Compatible;
5985   }
5986 
5987   // This check seems unnatural, however it is necessary to ensure the proper
5988   // conversion of functions/arrays. If the conversion were done for all
5989   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
5990   // expressions that suppress this implicit conversion (&, sizeof).
5991   //
5992   // Suppress this for references: C++ 8.5.3p5.
5993   if (!LHSType->isReferenceType()) {
5994     RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
5995     if (RHS.isInvalid())
5996       return Incompatible;
5997   }
5998 
5999   CastKind Kind = CK_Invalid;
6000   Sema::AssignConvertType result =
6001     CheckAssignmentConstraints(LHSType, RHS, Kind);
6002 
6003   // C99 6.5.16.1p2: The value of the right operand is converted to the
6004   // type of the assignment expression.
6005   // CheckAssignmentConstraints allows the left-hand side to be a reference,
6006   // so that we can use references in built-in functions even in C.
6007   // The getNonReferenceType() call makes sure that the resulting expression
6008   // does not have reference type.
6009   if (result != Incompatible && RHS.get()->getType() != LHSType)
6010     RHS = ImpCastExprToType(RHS.take(),
6011                             LHSType.getNonLValueExprType(Context), Kind);
6012   return result;
6013 }
6014 
6015 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
6016                                ExprResult &RHS) {
6017   Diag(Loc, diag::err_typecheck_invalid_operands)
6018     << LHS.get()->getType() << RHS.get()->getType()
6019     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6020   return QualType();
6021 }
6022 
6023 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
6024                                    SourceLocation Loc, bool IsCompAssign) {
6025   if (!IsCompAssign) {
6026     LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
6027     if (LHS.isInvalid())
6028       return QualType();
6029   }
6030   RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
6031   if (RHS.isInvalid())
6032     return QualType();
6033 
6034   // For conversion purposes, we ignore any qualifiers.
6035   // For example, "const float" and "float" are equivalent.
6036   QualType LHSType =
6037     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
6038   QualType RHSType =
6039     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
6040 
6041   // If the vector types are identical, return.
6042   if (LHSType == RHSType)
6043     return LHSType;
6044 
6045   // Handle the case of equivalent AltiVec and GCC vector types
6046   if (LHSType->isVectorType() && RHSType->isVectorType() &&
6047       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
6048     if (LHSType->isExtVectorType()) {
6049       RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
6050       return LHSType;
6051     }
6052 
6053     if (!IsCompAssign)
6054       LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
6055     return RHSType;
6056   }
6057 
6058   if (getLangOpts().LaxVectorConversions &&
6059       Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType)) {
6060     // If we are allowing lax vector conversions, and LHS and RHS are both
6061     // vectors, the total size only needs to be the same. This is a
6062     // bitcast; no bits are changed but the result type is different.
6063     // FIXME: Should we really be allowing this?
6064     RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
6065     return LHSType;
6066   }
6067 
6068   // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
6069   // swap back (so that we don't reverse the inputs to a subtract, for instance.
6070   bool swapped = false;
6071   if (RHSType->isExtVectorType() && !IsCompAssign) {
6072     swapped = true;
6073     std::swap(RHS, LHS);
6074     std::swap(RHSType, LHSType);
6075   }
6076 
6077   // Handle the case of an ext vector and scalar.
6078   if (const ExtVectorType *LV = LHSType->getAs<ExtVectorType>()) {
6079     QualType EltTy = LV->getElementType();
6080     if (EltTy->isIntegralType(Context) && RHSType->isIntegralType(Context)) {
6081       int order = Context.getIntegerTypeOrder(EltTy, RHSType);
6082       if (order > 0)
6083         RHS = ImpCastExprToType(RHS.take(), EltTy, CK_IntegralCast);
6084       if (order >= 0) {
6085         RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
6086         if (swapped) std::swap(RHS, LHS);
6087         return LHSType;
6088       }
6089     }
6090     if (EltTy->isRealFloatingType() && RHSType->isScalarType() &&
6091         RHSType->isRealFloatingType()) {
6092       int order = Context.getFloatingTypeOrder(EltTy, RHSType);
6093       if (order > 0)
6094         RHS = ImpCastExprToType(RHS.take(), EltTy, CK_FloatingCast);
6095       if (order >= 0) {
6096         RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
6097         if (swapped) std::swap(RHS, LHS);
6098         return LHSType;
6099       }
6100     }
6101   }
6102 
6103   // Vectors of different size or scalar and non-ext-vector are errors.
6104   if (swapped) std::swap(RHS, LHS);
6105   Diag(Loc, diag::err_typecheck_vector_not_convertable)
6106     << LHS.get()->getType() << RHS.get()->getType()
6107     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6108   return QualType();
6109 }
6110 
6111 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
6112 // expression.  These are mainly cases where the null pointer is used as an
6113 // integer instead of a pointer.
6114 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
6115                                 SourceLocation Loc, bool IsCompare) {
6116   // The canonical way to check for a GNU null is with isNullPointerConstant,
6117   // but we use a bit of a hack here for speed; this is a relatively
6118   // hot path, and isNullPointerConstant is slow.
6119   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
6120   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
6121 
6122   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
6123 
6124   // Avoid analyzing cases where the result will either be invalid (and
6125   // diagnosed as such) or entirely valid and not something to warn about.
6126   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
6127       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
6128     return;
6129 
6130   // Comparison operations would not make sense with a null pointer no matter
6131   // what the other expression is.
6132   if (!IsCompare) {
6133     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
6134         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
6135         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
6136     return;
6137   }
6138 
6139   // The rest of the operations only make sense with a null pointer
6140   // if the other expression is a pointer.
6141   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
6142       NonNullType->canDecayToPointerType())
6143     return;
6144 
6145   S.Diag(Loc, diag::warn_null_in_comparison_operation)
6146       << LHSNull /* LHS is NULL */ << NonNullType
6147       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6148 }
6149 
6150 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
6151                                            SourceLocation Loc,
6152                                            bool IsCompAssign, bool IsDiv) {
6153   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6154 
6155   if (LHS.get()->getType()->isVectorType() ||
6156       RHS.get()->getType()->isVectorType())
6157     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
6158 
6159   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
6160   if (LHS.isInvalid() || RHS.isInvalid())
6161     return QualType();
6162 
6163 
6164   if (compType.isNull() || !compType->isArithmeticType())
6165     return InvalidOperands(Loc, LHS, RHS);
6166 
6167   // Check for division by zero.
6168   if (IsDiv &&
6169       RHS.get()->isNullPointerConstant(Context,
6170                                        Expr::NPC_ValueDependentIsNotNull))
6171     DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_division_by_zero)
6172                                           << RHS.get()->getSourceRange());
6173 
6174   return compType;
6175 }
6176 
6177 QualType Sema::CheckRemainderOperands(
6178   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
6179   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6180 
6181   if (LHS.get()->getType()->isVectorType() ||
6182       RHS.get()->getType()->isVectorType()) {
6183     if (LHS.get()->getType()->hasIntegerRepresentation() &&
6184         RHS.get()->getType()->hasIntegerRepresentation())
6185       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
6186     return InvalidOperands(Loc, LHS, RHS);
6187   }
6188 
6189   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
6190   if (LHS.isInvalid() || RHS.isInvalid())
6191     return QualType();
6192 
6193   if (compType.isNull() || !compType->isIntegerType())
6194     return InvalidOperands(Loc, LHS, RHS);
6195 
6196   // Check for remainder by zero.
6197   if (RHS.get()->isNullPointerConstant(Context,
6198                                        Expr::NPC_ValueDependentIsNotNull))
6199     DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_remainder_by_zero)
6200                                  << RHS.get()->getSourceRange());
6201 
6202   return compType;
6203 }
6204 
6205 /// \brief Diagnose invalid arithmetic on two void pointers.
6206 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
6207                                                 Expr *LHSExpr, Expr *RHSExpr) {
6208   S.Diag(Loc, S.getLangOpts().CPlusPlus
6209                 ? diag::err_typecheck_pointer_arith_void_type
6210                 : diag::ext_gnu_void_ptr)
6211     << 1 /* two pointers */ << LHSExpr->getSourceRange()
6212                             << RHSExpr->getSourceRange();
6213 }
6214 
6215 /// \brief Diagnose invalid arithmetic on a void pointer.
6216 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
6217                                             Expr *Pointer) {
6218   S.Diag(Loc, S.getLangOpts().CPlusPlus
6219                 ? diag::err_typecheck_pointer_arith_void_type
6220                 : diag::ext_gnu_void_ptr)
6221     << 0 /* one pointer */ << Pointer->getSourceRange();
6222 }
6223 
6224 /// \brief Diagnose invalid arithmetic on two function pointers.
6225 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
6226                                                     Expr *LHS, Expr *RHS) {
6227   assert(LHS->getType()->isAnyPointerType());
6228   assert(RHS->getType()->isAnyPointerType());
6229   S.Diag(Loc, S.getLangOpts().CPlusPlus
6230                 ? diag::err_typecheck_pointer_arith_function_type
6231                 : diag::ext_gnu_ptr_func_arith)
6232     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
6233     // We only show the second type if it differs from the first.
6234     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
6235                                                    RHS->getType())
6236     << RHS->getType()->getPointeeType()
6237     << LHS->getSourceRange() << RHS->getSourceRange();
6238 }
6239 
6240 /// \brief Diagnose invalid arithmetic on a function pointer.
6241 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
6242                                                 Expr *Pointer) {
6243   assert(Pointer->getType()->isAnyPointerType());
6244   S.Diag(Loc, S.getLangOpts().CPlusPlus
6245                 ? diag::err_typecheck_pointer_arith_function_type
6246                 : diag::ext_gnu_ptr_func_arith)
6247     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
6248     << 0 /* one pointer, so only one type */
6249     << Pointer->getSourceRange();
6250 }
6251 
6252 /// \brief Emit error if Operand is incomplete pointer type
6253 ///
6254 /// \returns True if pointer has incomplete type
6255 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
6256                                                  Expr *Operand) {
6257   assert(Operand->getType()->isAnyPointerType() &&
6258          !Operand->getType()->isDependentType());
6259   QualType PointeeTy = Operand->getType()->getPointeeType();
6260   return S.RequireCompleteType(Loc, PointeeTy,
6261                                diag::err_typecheck_arithmetic_incomplete_type,
6262                                PointeeTy, Operand->getSourceRange());
6263 }
6264 
6265 /// \brief Check the validity of an arithmetic pointer operand.
6266 ///
6267 /// If the operand has pointer type, this code will check for pointer types
6268 /// which are invalid in arithmetic operations. These will be diagnosed
6269 /// appropriately, including whether or not the use is supported as an
6270 /// extension.
6271 ///
6272 /// \returns True when the operand is valid to use (even if as an extension).
6273 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
6274                                             Expr *Operand) {
6275   if (!Operand->getType()->isAnyPointerType()) return true;
6276 
6277   QualType PointeeTy = Operand->getType()->getPointeeType();
6278   if (PointeeTy->isVoidType()) {
6279     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
6280     return !S.getLangOpts().CPlusPlus;
6281   }
6282   if (PointeeTy->isFunctionType()) {
6283     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
6284     return !S.getLangOpts().CPlusPlus;
6285   }
6286 
6287   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
6288 
6289   return true;
6290 }
6291 
6292 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
6293 /// operands.
6294 ///
6295 /// This routine will diagnose any invalid arithmetic on pointer operands much
6296 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
6297 /// for emitting a single diagnostic even for operations where both LHS and RHS
6298 /// are (potentially problematic) pointers.
6299 ///
6300 /// \returns True when the operand is valid to use (even if as an extension).
6301 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
6302                                                 Expr *LHSExpr, Expr *RHSExpr) {
6303   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
6304   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
6305   if (!isLHSPointer && !isRHSPointer) return true;
6306 
6307   QualType LHSPointeeTy, RHSPointeeTy;
6308   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
6309   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
6310 
6311   // Check for arithmetic on pointers to incomplete types.
6312   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
6313   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
6314   if (isLHSVoidPtr || isRHSVoidPtr) {
6315     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
6316     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
6317     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
6318 
6319     return !S.getLangOpts().CPlusPlus;
6320   }
6321 
6322   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
6323   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
6324   if (isLHSFuncPtr || isRHSFuncPtr) {
6325     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
6326     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
6327                                                                 RHSExpr);
6328     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
6329 
6330     return !S.getLangOpts().CPlusPlus;
6331   }
6332 
6333   if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
6334     return false;
6335   if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
6336     return false;
6337 
6338   return true;
6339 }
6340 
6341 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
6342 /// literal.
6343 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
6344                                   Expr *LHSExpr, Expr *RHSExpr) {
6345   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
6346   Expr* IndexExpr = RHSExpr;
6347   if (!StrExpr) {
6348     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
6349     IndexExpr = LHSExpr;
6350   }
6351 
6352   bool IsStringPlusInt = StrExpr &&
6353       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
6354   if (!IsStringPlusInt)
6355     return;
6356 
6357   llvm::APSInt index;
6358   if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
6359     unsigned StrLenWithNull = StrExpr->getLength() + 1;
6360     if (index.isNonNegative() &&
6361         index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
6362                               index.isUnsigned()))
6363       return;
6364   }
6365 
6366   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
6367   Self.Diag(OpLoc, diag::warn_string_plus_int)
6368       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
6369 
6370   // Only print a fixit for "str" + int, not for int + "str".
6371   if (IndexExpr == RHSExpr) {
6372     SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd());
6373     Self.Diag(OpLoc, diag::note_string_plus_int_silence)
6374         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
6375         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
6376         << FixItHint::CreateInsertion(EndLoc, "]");
6377   } else
6378     Self.Diag(OpLoc, diag::note_string_plus_int_silence);
6379 }
6380 
6381 /// \brief Emit error when two pointers are incompatible.
6382 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
6383                                            Expr *LHSExpr, Expr *RHSExpr) {
6384   assert(LHSExpr->getType()->isAnyPointerType());
6385   assert(RHSExpr->getType()->isAnyPointerType());
6386   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
6387     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
6388     << RHSExpr->getSourceRange();
6389 }
6390 
6391 QualType Sema::CheckAdditionOperands( // C99 6.5.6
6392     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc,
6393     QualType* CompLHSTy) {
6394   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6395 
6396   if (LHS.get()->getType()->isVectorType() ||
6397       RHS.get()->getType()->isVectorType()) {
6398     QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
6399     if (CompLHSTy) *CompLHSTy = compType;
6400     return compType;
6401   }
6402 
6403   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6404   if (LHS.isInvalid() || RHS.isInvalid())
6405     return QualType();
6406 
6407   // Diagnose "string literal" '+' int.
6408   if (Opc == BO_Add)
6409     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
6410 
6411   // handle the common case first (both operands are arithmetic).
6412   if (!compType.isNull() && compType->isArithmeticType()) {
6413     if (CompLHSTy) *CompLHSTy = compType;
6414     return compType;
6415   }
6416 
6417   // Type-checking.  Ultimately the pointer's going to be in PExp;
6418   // note that we bias towards the LHS being the pointer.
6419   Expr *PExp = LHS.get(), *IExp = RHS.get();
6420 
6421   bool isObjCPointer;
6422   if (PExp->getType()->isPointerType()) {
6423     isObjCPointer = false;
6424   } else if (PExp->getType()->isObjCObjectPointerType()) {
6425     isObjCPointer = true;
6426   } else {
6427     std::swap(PExp, IExp);
6428     if (PExp->getType()->isPointerType()) {
6429       isObjCPointer = false;
6430     } else if (PExp->getType()->isObjCObjectPointerType()) {
6431       isObjCPointer = true;
6432     } else {
6433       return InvalidOperands(Loc, LHS, RHS);
6434     }
6435   }
6436   assert(PExp->getType()->isAnyPointerType());
6437 
6438   if (!IExp->getType()->isIntegerType())
6439     return InvalidOperands(Loc, LHS, RHS);
6440 
6441   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
6442     return QualType();
6443 
6444   if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
6445     return QualType();
6446 
6447   // Check array bounds for pointer arithemtic
6448   CheckArrayAccess(PExp, IExp);
6449 
6450   if (CompLHSTy) {
6451     QualType LHSTy = Context.isPromotableBitField(LHS.get());
6452     if (LHSTy.isNull()) {
6453       LHSTy = LHS.get()->getType();
6454       if (LHSTy->isPromotableIntegerType())
6455         LHSTy = Context.getPromotedIntegerType(LHSTy);
6456     }
6457     *CompLHSTy = LHSTy;
6458   }
6459 
6460   return PExp->getType();
6461 }
6462 
6463 // C99 6.5.6
6464 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
6465                                         SourceLocation Loc,
6466                                         QualType* CompLHSTy) {
6467   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6468 
6469   if (LHS.get()->getType()->isVectorType() ||
6470       RHS.get()->getType()->isVectorType()) {
6471     QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
6472     if (CompLHSTy) *CompLHSTy = compType;
6473     return compType;
6474   }
6475 
6476   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6477   if (LHS.isInvalid() || RHS.isInvalid())
6478     return QualType();
6479 
6480   // Enforce type constraints: C99 6.5.6p3.
6481 
6482   // Handle the common case first (both operands are arithmetic).
6483   if (!compType.isNull() && compType->isArithmeticType()) {
6484     if (CompLHSTy) *CompLHSTy = compType;
6485     return compType;
6486   }
6487 
6488   // Either ptr - int   or   ptr - ptr.
6489   if (LHS.get()->getType()->isAnyPointerType()) {
6490     QualType lpointee = LHS.get()->getType()->getPointeeType();
6491 
6492     // Diagnose bad cases where we step over interface counts.
6493     if (LHS.get()->getType()->isObjCObjectPointerType() &&
6494         checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
6495       return QualType();
6496 
6497     // The result type of a pointer-int computation is the pointer type.
6498     if (RHS.get()->getType()->isIntegerType()) {
6499       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
6500         return QualType();
6501 
6502       // Check array bounds for pointer arithemtic
6503       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/0,
6504                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
6505 
6506       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
6507       return LHS.get()->getType();
6508     }
6509 
6510     // Handle pointer-pointer subtractions.
6511     if (const PointerType *RHSPTy
6512           = RHS.get()->getType()->getAs<PointerType>()) {
6513       QualType rpointee = RHSPTy->getPointeeType();
6514 
6515       if (getLangOpts().CPlusPlus) {
6516         // Pointee types must be the same: C++ [expr.add]
6517         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
6518           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
6519         }
6520       } else {
6521         // Pointee types must be compatible C99 6.5.6p3
6522         if (!Context.typesAreCompatible(
6523                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
6524                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
6525           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
6526           return QualType();
6527         }
6528       }
6529 
6530       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
6531                                                LHS.get(), RHS.get()))
6532         return QualType();
6533 
6534       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
6535       return Context.getPointerDiffType();
6536     }
6537   }
6538 
6539   return InvalidOperands(Loc, LHS, RHS);
6540 }
6541 
6542 static bool isScopedEnumerationType(QualType T) {
6543   if (const EnumType *ET = dyn_cast<EnumType>(T))
6544     return ET->getDecl()->isScoped();
6545   return false;
6546 }
6547 
6548 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
6549                                    SourceLocation Loc, unsigned Opc,
6550                                    QualType LHSType) {
6551   llvm::APSInt Right;
6552   // Check right/shifter operand
6553   if (RHS.get()->isValueDependent() ||
6554       !RHS.get()->isIntegerConstantExpr(Right, S.Context))
6555     return;
6556 
6557   if (Right.isNegative()) {
6558     S.DiagRuntimeBehavior(Loc, RHS.get(),
6559                           S.PDiag(diag::warn_shift_negative)
6560                             << RHS.get()->getSourceRange());
6561     return;
6562   }
6563   llvm::APInt LeftBits(Right.getBitWidth(),
6564                        S.Context.getTypeSize(LHS.get()->getType()));
6565   if (Right.uge(LeftBits)) {
6566     S.DiagRuntimeBehavior(Loc, RHS.get(),
6567                           S.PDiag(diag::warn_shift_gt_typewidth)
6568                             << RHS.get()->getSourceRange());
6569     return;
6570   }
6571   if (Opc != BO_Shl)
6572     return;
6573 
6574   // When left shifting an ICE which is signed, we can check for overflow which
6575   // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
6576   // integers have defined behavior modulo one more than the maximum value
6577   // representable in the result type, so never warn for those.
6578   llvm::APSInt Left;
6579   if (LHS.get()->isValueDependent() ||
6580       !LHS.get()->isIntegerConstantExpr(Left, S.Context) ||
6581       LHSType->hasUnsignedIntegerRepresentation())
6582     return;
6583   llvm::APInt ResultBits =
6584       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
6585   if (LeftBits.uge(ResultBits))
6586     return;
6587   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
6588   Result = Result.shl(Right);
6589 
6590   // Print the bit representation of the signed integer as an unsigned
6591   // hexadecimal number.
6592   SmallString<40> HexResult;
6593   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
6594 
6595   // If we are only missing a sign bit, this is less likely to result in actual
6596   // bugs -- if the result is cast back to an unsigned type, it will have the
6597   // expected value. Thus we place this behind a different warning that can be
6598   // turned off separately if needed.
6599   if (LeftBits == ResultBits - 1) {
6600     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
6601         << HexResult.str() << LHSType
6602         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6603     return;
6604   }
6605 
6606   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
6607     << HexResult.str() << Result.getMinSignedBits() << LHSType
6608     << Left.getBitWidth() << LHS.get()->getSourceRange()
6609     << RHS.get()->getSourceRange();
6610 }
6611 
6612 // C99 6.5.7
6613 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
6614                                   SourceLocation Loc, unsigned Opc,
6615                                   bool IsCompAssign) {
6616   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6617 
6618   // C99 6.5.7p2: Each of the operands shall have integer type.
6619   if (!LHS.get()->getType()->hasIntegerRepresentation() ||
6620       !RHS.get()->getType()->hasIntegerRepresentation())
6621     return InvalidOperands(Loc, LHS, RHS);
6622 
6623   // C++0x: Don't allow scoped enums. FIXME: Use something better than
6624   // hasIntegerRepresentation() above instead of this.
6625   if (isScopedEnumerationType(LHS.get()->getType()) ||
6626       isScopedEnumerationType(RHS.get()->getType())) {
6627     return InvalidOperands(Loc, LHS, RHS);
6628   }
6629 
6630   // Vector shifts promote their scalar inputs to vector type.
6631   if (LHS.get()->getType()->isVectorType() ||
6632       RHS.get()->getType()->isVectorType())
6633     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
6634 
6635   // Shifts don't perform usual arithmetic conversions, they just do integer
6636   // promotions on each operand. C99 6.5.7p3
6637 
6638   // For the LHS, do usual unary conversions, but then reset them away
6639   // if this is a compound assignment.
6640   ExprResult OldLHS = LHS;
6641   LHS = UsualUnaryConversions(LHS.take());
6642   if (LHS.isInvalid())
6643     return QualType();
6644   QualType LHSType = LHS.get()->getType();
6645   if (IsCompAssign) LHS = OldLHS;
6646 
6647   // The RHS is simpler.
6648   RHS = UsualUnaryConversions(RHS.take());
6649   if (RHS.isInvalid())
6650     return QualType();
6651 
6652   // Sanity-check shift operands
6653   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
6654 
6655   // "The type of the result is that of the promoted left operand."
6656   return LHSType;
6657 }
6658 
6659 static bool IsWithinTemplateSpecialization(Decl *D) {
6660   if (DeclContext *DC = D->getDeclContext()) {
6661     if (isa<ClassTemplateSpecializationDecl>(DC))
6662       return true;
6663     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
6664       return FD->isFunctionTemplateSpecialization();
6665   }
6666   return false;
6667 }
6668 
6669 /// If two different enums are compared, raise a warning.
6670 static void checkEnumComparison(Sema &S, SourceLocation Loc, ExprResult &LHS,
6671                                 ExprResult &RHS) {
6672   QualType LHSStrippedType = LHS.get()->IgnoreParenImpCasts()->getType();
6673   QualType RHSStrippedType = RHS.get()->IgnoreParenImpCasts()->getType();
6674 
6675   const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
6676   if (!LHSEnumType)
6677     return;
6678   const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
6679   if (!RHSEnumType)
6680     return;
6681 
6682   // Ignore anonymous enums.
6683   if (!LHSEnumType->getDecl()->getIdentifier())
6684     return;
6685   if (!RHSEnumType->getDecl()->getIdentifier())
6686     return;
6687 
6688   if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
6689     return;
6690 
6691   S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
6692       << LHSStrippedType << RHSStrippedType
6693       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6694 }
6695 
6696 /// \brief Diagnose bad pointer comparisons.
6697 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
6698                                               ExprResult &LHS, ExprResult &RHS,
6699                                               bool IsError) {
6700   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
6701                       : diag::ext_typecheck_comparison_of_distinct_pointers)
6702     << LHS.get()->getType() << RHS.get()->getType()
6703     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6704 }
6705 
6706 /// \brief Returns false if the pointers are converted to a composite type,
6707 /// true otherwise.
6708 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
6709                                            ExprResult &LHS, ExprResult &RHS) {
6710   // C++ [expr.rel]p2:
6711   //   [...] Pointer conversions (4.10) and qualification
6712   //   conversions (4.4) are performed on pointer operands (or on
6713   //   a pointer operand and a null pointer constant) to bring
6714   //   them to their composite pointer type. [...]
6715   //
6716   // C++ [expr.eq]p1 uses the same notion for (in)equality
6717   // comparisons of pointers.
6718 
6719   // C++ [expr.eq]p2:
6720   //   In addition, pointers to members can be compared, or a pointer to
6721   //   member and a null pointer constant. Pointer to member conversions
6722   //   (4.11) and qualification conversions (4.4) are performed to bring
6723   //   them to a common type. If one operand is a null pointer constant,
6724   //   the common type is the type of the other operand. Otherwise, the
6725   //   common type is a pointer to member type similar (4.4) to the type
6726   //   of one of the operands, with a cv-qualification signature (4.4)
6727   //   that is the union of the cv-qualification signatures of the operand
6728   //   types.
6729 
6730   QualType LHSType = LHS.get()->getType();
6731   QualType RHSType = RHS.get()->getType();
6732   assert((LHSType->isPointerType() && RHSType->isPointerType()) ||
6733          (LHSType->isMemberPointerType() && RHSType->isMemberPointerType()));
6734 
6735   bool NonStandardCompositeType = false;
6736   bool *BoolPtr = S.isSFINAEContext() ? 0 : &NonStandardCompositeType;
6737   QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr);
6738   if (T.isNull()) {
6739     diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
6740     return true;
6741   }
6742 
6743   if (NonStandardCompositeType)
6744     S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
6745       << LHSType << RHSType << T << LHS.get()->getSourceRange()
6746       << RHS.get()->getSourceRange();
6747 
6748   LHS = S.ImpCastExprToType(LHS.take(), T, CK_BitCast);
6749   RHS = S.ImpCastExprToType(RHS.take(), T, CK_BitCast);
6750   return false;
6751 }
6752 
6753 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
6754                                                     ExprResult &LHS,
6755                                                     ExprResult &RHS,
6756                                                     bool IsError) {
6757   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
6758                       : diag::ext_typecheck_comparison_of_fptr_to_void)
6759     << LHS.get()->getType() << RHS.get()->getType()
6760     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6761 }
6762 
6763 static bool isObjCObjectLiteral(ExprResult &E) {
6764   switch (E.get()->getStmtClass()) {
6765   case Stmt::ObjCArrayLiteralClass:
6766   case Stmt::ObjCDictionaryLiteralClass:
6767   case Stmt::ObjCStringLiteralClass:
6768   case Stmt::ObjCBoxedExprClass:
6769     return true;
6770   default:
6771     // Note that ObjCBoolLiteral is NOT an object literal!
6772     return false;
6773   }
6774 }
6775 
6776 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
6777   // Get the LHS object's interface type.
6778   QualType Type = LHS->getType();
6779   QualType InterfaceType;
6780   if (const ObjCObjectPointerType *PTy = Type->getAs<ObjCObjectPointerType>()) {
6781     InterfaceType = PTy->getPointeeType();
6782     if (const ObjCObjectType *iQFaceTy =
6783         InterfaceType->getAsObjCQualifiedInterfaceType())
6784       InterfaceType = iQFaceTy->getBaseType();
6785   } else {
6786     // If this is not actually an Objective-C object, bail out.
6787     return false;
6788   }
6789 
6790   // If the RHS isn't an Objective-C object, bail out.
6791   if (!RHS->getType()->isObjCObjectPointerType())
6792     return false;
6793 
6794   // Try to find the -isEqual: method.
6795   Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
6796   ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
6797                                                       InterfaceType,
6798                                                       /*instance=*/true);
6799   if (!Method) {
6800     if (Type->isObjCIdType()) {
6801       // For 'id', just check the global pool.
6802       Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
6803                                                   /*receiverId=*/true,
6804                                                   /*warn=*/false);
6805     } else {
6806       // Check protocols.
6807       Method = S.LookupMethodInQualifiedType(IsEqualSel,
6808                                              cast<ObjCObjectPointerType>(Type),
6809                                              /*instance=*/true);
6810     }
6811   }
6812 
6813   if (!Method)
6814     return false;
6815 
6816   QualType T = Method->param_begin()[0]->getType();
6817   if (!T->isObjCObjectPointerType())
6818     return false;
6819 
6820   QualType R = Method->getResultType();
6821   if (!R->isScalarType())
6822     return false;
6823 
6824   return true;
6825 }
6826 
6827 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
6828                                           ExprResult &LHS, ExprResult &RHS,
6829                                           BinaryOperator::Opcode Opc){
6830   Expr *Literal;
6831   Expr *Other;
6832   if (isObjCObjectLiteral(LHS)) {
6833     Literal = LHS.get();
6834     Other = RHS.get();
6835   } else {
6836     Literal = RHS.get();
6837     Other = LHS.get();
6838   }
6839 
6840   // Don't warn on comparisons against nil.
6841   Other = Other->IgnoreParenCasts();
6842   if (Other->isNullPointerConstant(S.getASTContext(),
6843                                    Expr::NPC_ValueDependentIsNotNull))
6844     return;
6845 
6846   // This should be kept in sync with warn_objc_literal_comparison.
6847   // LK_String should always be last, since it has its own warning flag.
6848   enum {
6849     LK_Array,
6850     LK_Dictionary,
6851     LK_Numeric,
6852     LK_Boxed,
6853     LK_String
6854   } LiteralKind;
6855 
6856   switch (Literal->getStmtClass()) {
6857   case Stmt::ObjCStringLiteralClass:
6858     // "string literal"
6859     LiteralKind = LK_String;
6860     break;
6861   case Stmt::ObjCArrayLiteralClass:
6862     // "array literal"
6863     LiteralKind = LK_Array;
6864     break;
6865   case Stmt::ObjCDictionaryLiteralClass:
6866     // "dictionary literal"
6867     LiteralKind = LK_Dictionary;
6868     break;
6869   case Stmt::ObjCBoxedExprClass: {
6870     Expr *Inner = cast<ObjCBoxedExpr>(Literal)->getSubExpr();
6871     switch (Inner->getStmtClass()) {
6872     case Stmt::IntegerLiteralClass:
6873     case Stmt::FloatingLiteralClass:
6874     case Stmt::CharacterLiteralClass:
6875     case Stmt::ObjCBoolLiteralExprClass:
6876     case Stmt::CXXBoolLiteralExprClass:
6877       // "numeric literal"
6878       LiteralKind = LK_Numeric;
6879       break;
6880     case Stmt::ImplicitCastExprClass: {
6881       CastKind CK = cast<CastExpr>(Inner)->getCastKind();
6882       // Boolean literals can be represented by implicit casts.
6883       if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) {
6884         LiteralKind = LK_Numeric;
6885         break;
6886       }
6887       // FALLTHROUGH
6888     }
6889     default:
6890       // "boxed expression"
6891       LiteralKind = LK_Boxed;
6892       break;
6893     }
6894     break;
6895   }
6896   default:
6897     llvm_unreachable("Unknown Objective-C object literal kind");
6898   }
6899 
6900   if (LiteralKind == LK_String)
6901     S.Diag(Loc, diag::warn_objc_string_literal_comparison)
6902       << Literal->getSourceRange();
6903   else
6904     S.Diag(Loc, diag::warn_objc_literal_comparison)
6905       << LiteralKind << Literal->getSourceRange();
6906 
6907   if (BinaryOperator::isEqualityOp(Opc) &&
6908       hasIsEqualMethod(S, LHS.get(), RHS.get())) {
6909     SourceLocation Start = LHS.get()->getLocStart();
6910     SourceLocation End = S.PP.getLocForEndOfToken(RHS.get()->getLocEnd());
6911     SourceRange OpRange(Loc, S.PP.getLocForEndOfToken(Loc));
6912 
6913     S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
6914       << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
6915       << FixItHint::CreateReplacement(OpRange, "isEqual:")
6916       << FixItHint::CreateInsertion(End, "]");
6917   }
6918 }
6919 
6920 // C99 6.5.8, C++ [expr.rel]
6921 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
6922                                     SourceLocation Loc, unsigned OpaqueOpc,
6923                                     bool IsRelational) {
6924   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
6925 
6926   BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
6927 
6928   // Handle vector comparisons separately.
6929   if (LHS.get()->getType()->isVectorType() ||
6930       RHS.get()->getType()->isVectorType())
6931     return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
6932 
6933   QualType LHSType = LHS.get()->getType();
6934   QualType RHSType = RHS.get()->getType();
6935 
6936   Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
6937   Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
6938 
6939   checkEnumComparison(*this, Loc, LHS, RHS);
6940 
6941   if (!LHSType->hasFloatingRepresentation() &&
6942       !(LHSType->isBlockPointerType() && IsRelational) &&
6943       !LHS.get()->getLocStart().isMacroID() &&
6944       !RHS.get()->getLocStart().isMacroID()) {
6945     // For non-floating point types, check for self-comparisons of the form
6946     // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
6947     // often indicate logic errors in the program.
6948     //
6949     // NOTE: Don't warn about comparison expressions resulting from macro
6950     // expansion. Also don't warn about comparisons which are only self
6951     // comparisons within a template specialization. The warnings should catch
6952     // obvious cases in the definition of the template anyways. The idea is to
6953     // warn when the typed comparison operator will always evaluate to the same
6954     // result.
6955     if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
6956       if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
6957         if (DRL->getDecl() == DRR->getDecl() &&
6958             !IsWithinTemplateSpecialization(DRL->getDecl())) {
6959           DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
6960                               << 0 // self-
6961                               << (Opc == BO_EQ
6962                                   || Opc == BO_LE
6963                                   || Opc == BO_GE));
6964         } else if (LHSType->isArrayType() && RHSType->isArrayType() &&
6965                    !DRL->getDecl()->getType()->isReferenceType() &&
6966                    !DRR->getDecl()->getType()->isReferenceType()) {
6967             // what is it always going to eval to?
6968             char always_evals_to;
6969             switch(Opc) {
6970             case BO_EQ: // e.g. array1 == array2
6971               always_evals_to = 0; // false
6972               break;
6973             case BO_NE: // e.g. array1 != array2
6974               always_evals_to = 1; // true
6975               break;
6976             default:
6977               // best we can say is 'a constant'
6978               always_evals_to = 2; // e.g. array1 <= array2
6979               break;
6980             }
6981             DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
6982                                 << 1 // array
6983                                 << always_evals_to);
6984         }
6985       }
6986     }
6987 
6988     if (isa<CastExpr>(LHSStripped))
6989       LHSStripped = LHSStripped->IgnoreParenCasts();
6990     if (isa<CastExpr>(RHSStripped))
6991       RHSStripped = RHSStripped->IgnoreParenCasts();
6992 
6993     // Warn about comparisons against a string constant (unless the other
6994     // operand is null), the user probably wants strcmp.
6995     Expr *literalString = 0;
6996     Expr *literalStringStripped = 0;
6997     if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
6998         !RHSStripped->isNullPointerConstant(Context,
6999                                             Expr::NPC_ValueDependentIsNull)) {
7000       literalString = LHS.get();
7001       literalStringStripped = LHSStripped;
7002     } else if ((isa<StringLiteral>(RHSStripped) ||
7003                 isa<ObjCEncodeExpr>(RHSStripped)) &&
7004                !LHSStripped->isNullPointerConstant(Context,
7005                                             Expr::NPC_ValueDependentIsNull)) {
7006       literalString = RHS.get();
7007       literalStringStripped = RHSStripped;
7008     }
7009 
7010     if (literalString) {
7011       std::string resultComparison;
7012       switch (Opc) {
7013       case BO_LT: resultComparison = ") < 0"; break;
7014       case BO_GT: resultComparison = ") > 0"; break;
7015       case BO_LE: resultComparison = ") <= 0"; break;
7016       case BO_GE: resultComparison = ") >= 0"; break;
7017       case BO_EQ: resultComparison = ") == 0"; break;
7018       case BO_NE: resultComparison = ") != 0"; break;
7019       default: llvm_unreachable("Invalid comparison operator");
7020       }
7021 
7022       DiagRuntimeBehavior(Loc, 0,
7023         PDiag(diag::warn_stringcompare)
7024           << isa<ObjCEncodeExpr>(literalStringStripped)
7025           << literalString->getSourceRange());
7026     }
7027   }
7028 
7029   // C99 6.5.8p3 / C99 6.5.9p4
7030   if (LHS.get()->getType()->isArithmeticType() &&
7031       RHS.get()->getType()->isArithmeticType()) {
7032     UsualArithmeticConversions(LHS, RHS);
7033     if (LHS.isInvalid() || RHS.isInvalid())
7034       return QualType();
7035   }
7036   else {
7037     LHS = UsualUnaryConversions(LHS.take());
7038     if (LHS.isInvalid())
7039       return QualType();
7040 
7041     RHS = UsualUnaryConversions(RHS.take());
7042     if (RHS.isInvalid())
7043       return QualType();
7044   }
7045 
7046   LHSType = LHS.get()->getType();
7047   RHSType = RHS.get()->getType();
7048 
7049   // The result of comparisons is 'bool' in C++, 'int' in C.
7050   QualType ResultTy = Context.getLogicalOperationType();
7051 
7052   if (IsRelational) {
7053     if (LHSType->isRealType() && RHSType->isRealType())
7054       return ResultTy;
7055   } else {
7056     // Check for comparisons of floating point operands using != and ==.
7057     if (LHSType->hasFloatingRepresentation())
7058       CheckFloatComparison(Loc, LHS.get(), RHS.get());
7059 
7060     if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
7061       return ResultTy;
7062   }
7063 
7064   bool LHSIsNull = LHS.get()->isNullPointerConstant(Context,
7065                                               Expr::NPC_ValueDependentIsNull);
7066   bool RHSIsNull = RHS.get()->isNullPointerConstant(Context,
7067                                               Expr::NPC_ValueDependentIsNull);
7068 
7069   // All of the following pointer-related warnings are GCC extensions, except
7070   // when handling null pointer constants.
7071   if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2
7072     QualType LCanPointeeTy =
7073       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
7074     QualType RCanPointeeTy =
7075       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
7076 
7077     if (getLangOpts().CPlusPlus) {
7078       if (LCanPointeeTy == RCanPointeeTy)
7079         return ResultTy;
7080       if (!IsRelational &&
7081           (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7082         // Valid unless comparison between non-null pointer and function pointer
7083         // This is a gcc extension compatibility comparison.
7084         // In a SFINAE context, we treat this as a hard error to maintain
7085         // conformance with the C++ standard.
7086         if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
7087             && !LHSIsNull && !RHSIsNull) {
7088           diagnoseFunctionPointerToVoidComparison(
7089               *this, Loc, LHS, RHS, /*isError*/ isSFINAEContext());
7090 
7091           if (isSFINAEContext())
7092             return QualType();
7093 
7094           RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
7095           return ResultTy;
7096         }
7097       }
7098 
7099       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
7100         return QualType();
7101       else
7102         return ResultTy;
7103     }
7104     // C99 6.5.9p2 and C99 6.5.8p2
7105     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
7106                                    RCanPointeeTy.getUnqualifiedType())) {
7107       // Valid unless a relational comparison of function pointers
7108       if (IsRelational && LCanPointeeTy->isFunctionType()) {
7109         Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
7110           << LHSType << RHSType << LHS.get()->getSourceRange()
7111           << RHS.get()->getSourceRange();
7112       }
7113     } else if (!IsRelational &&
7114                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7115       // Valid unless comparison between non-null pointer and function pointer
7116       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
7117           && !LHSIsNull && !RHSIsNull)
7118         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
7119                                                 /*isError*/false);
7120     } else {
7121       // Invalid
7122       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
7123     }
7124     if (LCanPointeeTy != RCanPointeeTy) {
7125       if (LHSIsNull && !RHSIsNull)
7126         LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
7127       else
7128         RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
7129     }
7130     return ResultTy;
7131   }
7132 
7133   if (getLangOpts().CPlusPlus) {
7134     // Comparison of nullptr_t with itself.
7135     if (LHSType->isNullPtrType() && RHSType->isNullPtrType())
7136       return ResultTy;
7137 
7138     // Comparison of pointers with null pointer constants and equality
7139     // comparisons of member pointers to null pointer constants.
7140     if (RHSIsNull &&
7141         ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) ||
7142          (!IsRelational &&
7143           (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) {
7144       RHS = ImpCastExprToType(RHS.take(), LHSType,
7145                         LHSType->isMemberPointerType()
7146                           ? CK_NullToMemberPointer
7147                           : CK_NullToPointer);
7148       return ResultTy;
7149     }
7150     if (LHSIsNull &&
7151         ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) ||
7152          (!IsRelational &&
7153           (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) {
7154       LHS = ImpCastExprToType(LHS.take(), RHSType,
7155                         RHSType->isMemberPointerType()
7156                           ? CK_NullToMemberPointer
7157                           : CK_NullToPointer);
7158       return ResultTy;
7159     }
7160 
7161     // Comparison of member pointers.
7162     if (!IsRelational &&
7163         LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) {
7164       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
7165         return QualType();
7166       else
7167         return ResultTy;
7168     }
7169 
7170     // Handle scoped enumeration types specifically, since they don't promote
7171     // to integers.
7172     if (LHS.get()->getType()->isEnumeralType() &&
7173         Context.hasSameUnqualifiedType(LHS.get()->getType(),
7174                                        RHS.get()->getType()))
7175       return ResultTy;
7176   }
7177 
7178   // Handle block pointer types.
7179   if (!IsRelational && LHSType->isBlockPointerType() &&
7180       RHSType->isBlockPointerType()) {
7181     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
7182     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
7183 
7184     if (!LHSIsNull && !RHSIsNull &&
7185         !Context.typesAreCompatible(lpointee, rpointee)) {
7186       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
7187         << LHSType << RHSType << LHS.get()->getSourceRange()
7188         << RHS.get()->getSourceRange();
7189     }
7190     RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
7191     return ResultTy;
7192   }
7193 
7194   // Allow block pointers to be compared with null pointer constants.
7195   if (!IsRelational
7196       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
7197           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
7198     if (!LHSIsNull && !RHSIsNull) {
7199       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
7200              ->getPointeeType()->isVoidType())
7201             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
7202                 ->getPointeeType()->isVoidType())))
7203         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
7204           << LHSType << RHSType << LHS.get()->getSourceRange()
7205           << RHS.get()->getSourceRange();
7206     }
7207     if (LHSIsNull && !RHSIsNull)
7208       LHS = ImpCastExprToType(LHS.take(), RHSType,
7209                               RHSType->isPointerType() ? CK_BitCast
7210                                 : CK_AnyPointerToBlockPointerCast);
7211     else
7212       RHS = ImpCastExprToType(RHS.take(), LHSType,
7213                               LHSType->isPointerType() ? CK_BitCast
7214                                 : CK_AnyPointerToBlockPointerCast);
7215     return ResultTy;
7216   }
7217 
7218   if (LHSType->isObjCObjectPointerType() ||
7219       RHSType->isObjCObjectPointerType()) {
7220     const PointerType *LPT = LHSType->getAs<PointerType>();
7221     const PointerType *RPT = RHSType->getAs<PointerType>();
7222     if (LPT || RPT) {
7223       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
7224       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
7225 
7226       if (!LPtrToVoid && !RPtrToVoid &&
7227           !Context.typesAreCompatible(LHSType, RHSType)) {
7228         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
7229                                           /*isError*/false);
7230       }
7231       if (LHSIsNull && !RHSIsNull)
7232         LHS = ImpCastExprToType(LHS.take(), RHSType,
7233                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
7234       else
7235         RHS = ImpCastExprToType(RHS.take(), LHSType,
7236                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
7237       return ResultTy;
7238     }
7239     if (LHSType->isObjCObjectPointerType() &&
7240         RHSType->isObjCObjectPointerType()) {
7241       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
7242         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
7243                                           /*isError*/false);
7244       if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
7245         diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
7246 
7247       if (LHSIsNull && !RHSIsNull)
7248         LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
7249       else
7250         RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
7251       return ResultTy;
7252     }
7253   }
7254   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
7255       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
7256     unsigned DiagID = 0;
7257     bool isError = false;
7258     if (LangOpts.DebuggerSupport) {
7259       // Under a debugger, allow the comparison of pointers to integers,
7260       // since users tend to want to compare addresses.
7261     } else if ((LHSIsNull && LHSType->isIntegerType()) ||
7262         (RHSIsNull && RHSType->isIntegerType())) {
7263       if (IsRelational && !getLangOpts().CPlusPlus)
7264         DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
7265     } else if (IsRelational && !getLangOpts().CPlusPlus)
7266       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
7267     else if (getLangOpts().CPlusPlus) {
7268       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
7269       isError = true;
7270     } else
7271       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
7272 
7273     if (DiagID) {
7274       Diag(Loc, DiagID)
7275         << LHSType << RHSType << LHS.get()->getSourceRange()
7276         << RHS.get()->getSourceRange();
7277       if (isError)
7278         return QualType();
7279     }
7280 
7281     if (LHSType->isIntegerType())
7282       LHS = ImpCastExprToType(LHS.take(), RHSType,
7283                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
7284     else
7285       RHS = ImpCastExprToType(RHS.take(), LHSType,
7286                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
7287     return ResultTy;
7288   }
7289 
7290   // Handle block pointers.
7291   if (!IsRelational && RHSIsNull
7292       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
7293     RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
7294     return ResultTy;
7295   }
7296   if (!IsRelational && LHSIsNull
7297       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
7298     LHS = ImpCastExprToType(LHS.take(), RHSType, CK_NullToPointer);
7299     return ResultTy;
7300   }
7301 
7302   return InvalidOperands(Loc, LHS, RHS);
7303 }
7304 
7305 
7306 // Return a signed type that is of identical size and number of elements.
7307 // For floating point vectors, return an integer type of identical size
7308 // and number of elements.
7309 QualType Sema::GetSignedVectorType(QualType V) {
7310   const VectorType *VTy = V->getAs<VectorType>();
7311   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
7312   if (TypeSize == Context.getTypeSize(Context.CharTy))
7313     return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
7314   else if (TypeSize == Context.getTypeSize(Context.ShortTy))
7315     return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
7316   else if (TypeSize == Context.getTypeSize(Context.IntTy))
7317     return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
7318   else if (TypeSize == Context.getTypeSize(Context.LongTy))
7319     return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
7320   assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
7321          "Unhandled vector element size in vector compare");
7322   return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
7323 }
7324 
7325 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
7326 /// operates on extended vector types.  Instead of producing an IntTy result,
7327 /// like a scalar comparison, a vector comparison produces a vector of integer
7328 /// types.
7329 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
7330                                           SourceLocation Loc,
7331                                           bool IsRelational) {
7332   // Check to make sure we're operating on vectors of the same type and width,
7333   // Allowing one side to be a scalar of element type.
7334   QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false);
7335   if (vType.isNull())
7336     return vType;
7337 
7338   QualType LHSType = LHS.get()->getType();
7339 
7340   // If AltiVec, the comparison results in a numeric type, i.e.
7341   // bool for C++, int for C
7342   if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
7343     return Context.getLogicalOperationType();
7344 
7345   // For non-floating point types, check for self-comparisons of the form
7346   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
7347   // often indicate logic errors in the program.
7348   if (!LHSType->hasFloatingRepresentation()) {
7349     if (DeclRefExpr* DRL
7350           = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
7351       if (DeclRefExpr* DRR
7352             = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
7353         if (DRL->getDecl() == DRR->getDecl())
7354           DiagRuntimeBehavior(Loc, 0,
7355                               PDiag(diag::warn_comparison_always)
7356                                 << 0 // self-
7357                                 << 2 // "a constant"
7358                               );
7359   }
7360 
7361   // Check for comparisons of floating point operands using != and ==.
7362   if (!IsRelational && LHSType->hasFloatingRepresentation()) {
7363     assert (RHS.get()->getType()->hasFloatingRepresentation());
7364     CheckFloatComparison(Loc, LHS.get(), RHS.get());
7365   }
7366 
7367   // Return a signed type for the vector.
7368   return GetSignedVectorType(LHSType);
7369 }
7370 
7371 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
7372                                           SourceLocation Loc) {
7373   // Ensure that either both operands are of the same vector type, or
7374   // one operand is of a vector type and the other is of its element type.
7375   QualType vType = CheckVectorOperands(LHS, RHS, Loc, false);
7376   if (vType.isNull() || vType->isFloatingType())
7377     return InvalidOperands(Loc, LHS, RHS);
7378 
7379   return GetSignedVectorType(LHS.get()->getType());
7380 }
7381 
7382 inline QualType Sema::CheckBitwiseOperands(
7383   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
7384   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7385 
7386   if (LHS.get()->getType()->isVectorType() ||
7387       RHS.get()->getType()->isVectorType()) {
7388     if (LHS.get()->getType()->hasIntegerRepresentation() &&
7389         RHS.get()->getType()->hasIntegerRepresentation())
7390       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
7391 
7392     return InvalidOperands(Loc, LHS, RHS);
7393   }
7394 
7395   ExprResult LHSResult = Owned(LHS), RHSResult = Owned(RHS);
7396   QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
7397                                                  IsCompAssign);
7398   if (LHSResult.isInvalid() || RHSResult.isInvalid())
7399     return QualType();
7400   LHS = LHSResult.take();
7401   RHS = RHSResult.take();
7402 
7403   if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
7404     return compType;
7405   return InvalidOperands(Loc, LHS, RHS);
7406 }
7407 
7408 inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
7409   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) {
7410 
7411   // Check vector operands differently.
7412   if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
7413     return CheckVectorLogicalOperands(LHS, RHS, Loc);
7414 
7415   // Diagnose cases where the user write a logical and/or but probably meant a
7416   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
7417   // is a constant.
7418   if (LHS.get()->getType()->isIntegerType() &&
7419       !LHS.get()->getType()->isBooleanType() &&
7420       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
7421       // Don't warn in macros or template instantiations.
7422       !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
7423     // If the RHS can be constant folded, and if it constant folds to something
7424     // that isn't 0 or 1 (which indicate a potential logical operation that
7425     // happened to fold to true/false) then warn.
7426     // Parens on the RHS are ignored.
7427     llvm::APSInt Result;
7428     if (RHS.get()->EvaluateAsInt(Result, Context))
7429       if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType()) ||
7430           (Result != 0 && Result != 1)) {
7431         Diag(Loc, diag::warn_logical_instead_of_bitwise)
7432           << RHS.get()->getSourceRange()
7433           << (Opc == BO_LAnd ? "&&" : "||");
7434         // Suggest replacing the logical operator with the bitwise version
7435         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
7436             << (Opc == BO_LAnd ? "&" : "|")
7437             << FixItHint::CreateReplacement(SourceRange(
7438                 Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(),
7439                                                 getLangOpts())),
7440                                             Opc == BO_LAnd ? "&" : "|");
7441         if (Opc == BO_LAnd)
7442           // Suggest replacing "Foo() && kNonZero" with "Foo()"
7443           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
7444               << FixItHint::CreateRemoval(
7445                   SourceRange(
7446                       Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(),
7447                                                  0, getSourceManager(),
7448                                                  getLangOpts()),
7449                       RHS.get()->getLocEnd()));
7450       }
7451   }
7452 
7453   if (!Context.getLangOpts().CPlusPlus) {
7454     LHS = UsualUnaryConversions(LHS.take());
7455     if (LHS.isInvalid())
7456       return QualType();
7457 
7458     RHS = UsualUnaryConversions(RHS.take());
7459     if (RHS.isInvalid())
7460       return QualType();
7461 
7462     if (!LHS.get()->getType()->isScalarType() ||
7463         !RHS.get()->getType()->isScalarType())
7464       return InvalidOperands(Loc, LHS, RHS);
7465 
7466     return Context.IntTy;
7467   }
7468 
7469   // The following is safe because we only use this method for
7470   // non-overloadable operands.
7471 
7472   // C++ [expr.log.and]p1
7473   // C++ [expr.log.or]p1
7474   // The operands are both contextually converted to type bool.
7475   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
7476   if (LHSRes.isInvalid())
7477     return InvalidOperands(Loc, LHS, RHS);
7478   LHS = LHSRes;
7479 
7480   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
7481   if (RHSRes.isInvalid())
7482     return InvalidOperands(Loc, LHS, RHS);
7483   RHS = RHSRes;
7484 
7485   // C++ [expr.log.and]p2
7486   // C++ [expr.log.or]p2
7487   // The result is a bool.
7488   return Context.BoolTy;
7489 }
7490 
7491 /// IsReadonlyProperty - Verify that otherwise a valid l-value expression
7492 /// is a read-only property; return true if so. A readonly property expression
7493 /// depends on various declarations and thus must be treated specially.
7494 ///
7495 static bool IsReadonlyProperty(Expr *E, Sema &S) {
7496   const ObjCPropertyRefExpr *PropExpr = dyn_cast<ObjCPropertyRefExpr>(E);
7497   if (!PropExpr) return false;
7498   if (PropExpr->isImplicitProperty()) return false;
7499 
7500   ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
7501   QualType BaseType = PropExpr->isSuperReceiver() ?
7502                             PropExpr->getSuperReceiverType() :
7503                             PropExpr->getBase()->getType();
7504 
7505   if (const ObjCObjectPointerType *OPT =
7506       BaseType->getAsObjCInterfacePointerType())
7507     if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
7508       if (S.isPropertyReadonly(PDecl, IFace))
7509         return true;
7510   return false;
7511 }
7512 
7513 static bool IsReadonlyMessage(Expr *E, Sema &S) {
7514   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
7515   if (!ME) return false;
7516   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
7517   ObjCMessageExpr *Base =
7518     dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts());
7519   if (!Base) return false;
7520   return Base->getMethodDecl() != 0;
7521 }
7522 
7523 /// Is the given expression (which must be 'const') a reference to a
7524 /// variable which was originally non-const, but which has become
7525 /// 'const' due to being captured within a block?
7526 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
7527 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
7528   assert(E->isLValue() && E->getType().isConstQualified());
7529   E = E->IgnoreParens();
7530 
7531   // Must be a reference to a declaration from an enclosing scope.
7532   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
7533   if (!DRE) return NCCK_None;
7534   if (!DRE->refersToEnclosingLocal()) return NCCK_None;
7535 
7536   // The declaration must be a variable which is not declared 'const'.
7537   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
7538   if (!var) return NCCK_None;
7539   if (var->getType().isConstQualified()) return NCCK_None;
7540   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
7541 
7542   // Decide whether the first capture was for a block or a lambda.
7543   DeclContext *DC = S.CurContext;
7544   while (DC->getParent() != var->getDeclContext())
7545     DC = DC->getParent();
7546   return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
7547 }
7548 
7549 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
7550 /// emit an error and return true.  If so, return false.
7551 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
7552   assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
7553   SourceLocation OrigLoc = Loc;
7554   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
7555                                                               &Loc);
7556   if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
7557     IsLV = Expr::MLV_ReadonlyProperty;
7558   else if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
7559     IsLV = Expr::MLV_InvalidMessageExpression;
7560   if (IsLV == Expr::MLV_Valid)
7561     return false;
7562 
7563   unsigned Diag = 0;
7564   bool NeedType = false;
7565   switch (IsLV) { // C99 6.5.16p2
7566   case Expr::MLV_ConstQualified:
7567     Diag = diag::err_typecheck_assign_const;
7568 
7569     // Use a specialized diagnostic when we're assigning to an object
7570     // from an enclosing function or block.
7571     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
7572       if (NCCK == NCCK_Block)
7573         Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
7574       else
7575         Diag = diag::err_lambda_decl_ref_not_modifiable_lvalue;
7576       break;
7577     }
7578 
7579     // In ARC, use some specialized diagnostics for occasions where we
7580     // infer 'const'.  These are always pseudo-strong variables.
7581     if (S.getLangOpts().ObjCAutoRefCount) {
7582       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
7583       if (declRef && isa<VarDecl>(declRef->getDecl())) {
7584         VarDecl *var = cast<VarDecl>(declRef->getDecl());
7585 
7586         // Use the normal diagnostic if it's pseudo-__strong but the
7587         // user actually wrote 'const'.
7588         if (var->isARCPseudoStrong() &&
7589             (!var->getTypeSourceInfo() ||
7590              !var->getTypeSourceInfo()->getType().isConstQualified())) {
7591           // There are two pseudo-strong cases:
7592           //  - self
7593           ObjCMethodDecl *method = S.getCurMethodDecl();
7594           if (method && var == method->getSelfDecl())
7595             Diag = method->isClassMethod()
7596               ? diag::err_typecheck_arc_assign_self_class_method
7597               : diag::err_typecheck_arc_assign_self;
7598 
7599           //  - fast enumeration variables
7600           else
7601             Diag = diag::err_typecheck_arr_assign_enumeration;
7602 
7603           SourceRange Assign;
7604           if (Loc != OrigLoc)
7605             Assign = SourceRange(OrigLoc, OrigLoc);
7606           S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
7607           // We need to preserve the AST regardless, so migration tool
7608           // can do its job.
7609           return false;
7610         }
7611       }
7612     }
7613 
7614     break;
7615   case Expr::MLV_ArrayType:
7616   case Expr::MLV_ArrayTemporary:
7617     Diag = diag::err_typecheck_array_not_modifiable_lvalue;
7618     NeedType = true;
7619     break;
7620   case Expr::MLV_NotObjectType:
7621     Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
7622     NeedType = true;
7623     break;
7624   case Expr::MLV_LValueCast:
7625     Diag = diag::err_typecheck_lvalue_casts_not_supported;
7626     break;
7627   case Expr::MLV_Valid:
7628     llvm_unreachable("did not take early return for MLV_Valid");
7629   case Expr::MLV_InvalidExpression:
7630   case Expr::MLV_MemberFunction:
7631   case Expr::MLV_ClassTemporary:
7632     Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
7633     break;
7634   case Expr::MLV_IncompleteType:
7635   case Expr::MLV_IncompleteVoidType:
7636     return S.RequireCompleteType(Loc, E->getType(),
7637              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
7638   case Expr::MLV_DuplicateVectorComponents:
7639     Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
7640     break;
7641   case Expr::MLV_ReadonlyProperty:
7642   case Expr::MLV_NoSetterProperty:
7643     llvm_unreachable("readonly properties should be processed differently");
7644   case Expr::MLV_InvalidMessageExpression:
7645     Diag = diag::error_readonly_message_assignment;
7646     break;
7647   case Expr::MLV_SubObjCPropertySetting:
7648     Diag = diag::error_no_subobject_property_setting;
7649     break;
7650   }
7651 
7652   SourceRange Assign;
7653   if (Loc != OrigLoc)
7654     Assign = SourceRange(OrigLoc, OrigLoc);
7655   if (NeedType)
7656     S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
7657   else
7658     S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
7659   return true;
7660 }
7661 
7662 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
7663                                          SourceLocation Loc,
7664                                          Sema &Sema) {
7665   // C / C++ fields
7666   MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
7667   MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
7668   if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) {
7669     if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))
7670       Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
7671   }
7672 
7673   // Objective-C instance variables
7674   ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
7675   ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
7676   if (OL && OR && OL->getDecl() == OR->getDecl()) {
7677     DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
7678     DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
7679     if (RL && RR && RL->getDecl() == RR->getDecl())
7680       Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
7681   }
7682 }
7683 
7684 // C99 6.5.16.1
7685 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
7686                                        SourceLocation Loc,
7687                                        QualType CompoundType) {
7688   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
7689 
7690   // Verify that LHS is a modifiable lvalue, and emit error if not.
7691   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
7692     return QualType();
7693 
7694   QualType LHSType = LHSExpr->getType();
7695   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
7696                                              CompoundType;
7697   AssignConvertType ConvTy;
7698   if (CompoundType.isNull()) {
7699     Expr *RHSCheck = RHS.get();
7700 
7701     CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
7702 
7703     QualType LHSTy(LHSType);
7704     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
7705     if (RHS.isInvalid())
7706       return QualType();
7707     // Special case of NSObject attributes on c-style pointer types.
7708     if (ConvTy == IncompatiblePointer &&
7709         ((Context.isObjCNSObjectType(LHSType) &&
7710           RHSType->isObjCObjectPointerType()) ||
7711          (Context.isObjCNSObjectType(RHSType) &&
7712           LHSType->isObjCObjectPointerType())))
7713       ConvTy = Compatible;
7714 
7715     if (ConvTy == Compatible &&
7716         LHSType->isObjCObjectType())
7717         Diag(Loc, diag::err_objc_object_assignment)
7718           << LHSType;
7719 
7720     // If the RHS is a unary plus or minus, check to see if they = and + are
7721     // right next to each other.  If so, the user may have typo'd "x =+ 4"
7722     // instead of "x += 4".
7723     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
7724       RHSCheck = ICE->getSubExpr();
7725     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
7726       if ((UO->getOpcode() == UO_Plus ||
7727            UO->getOpcode() == UO_Minus) &&
7728           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
7729           // Only if the two operators are exactly adjacent.
7730           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
7731           // And there is a space or other character before the subexpr of the
7732           // unary +/-.  We don't want to warn on "x=-1".
7733           Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
7734           UO->getSubExpr()->getLocStart().isFileID()) {
7735         Diag(Loc, diag::warn_not_compound_assign)
7736           << (UO->getOpcode() == UO_Plus ? "+" : "-")
7737           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
7738       }
7739     }
7740 
7741     if (ConvTy == Compatible) {
7742       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
7743         // Warn about retain cycles where a block captures the LHS, but
7744         // not if the LHS is a simple variable into which the block is
7745         // being stored...unless that variable can be captured by reference!
7746         const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
7747         const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
7748         if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
7749           checkRetainCycles(LHSExpr, RHS.get());
7750 
7751         // It is safe to assign a weak reference into a strong variable.
7752         // Although this code can still have problems:
7753         //   id x = self.weakProp;
7754         //   id y = self.weakProp;
7755         // we do not warn to warn spuriously when 'x' and 'y' are on separate
7756         // paths through the function. This should be revisited if
7757         // -Wrepeated-use-of-weak is made flow-sensitive.
7758         DiagnosticsEngine::Level Level =
7759           Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
7760                                    RHS.get()->getLocStart());
7761         if (Level != DiagnosticsEngine::Ignored)
7762           getCurFunction()->markSafeWeakUse(RHS.get());
7763 
7764       } else if (getLangOpts().ObjCAutoRefCount) {
7765         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
7766       }
7767     }
7768   } else {
7769     // Compound assignment "x += y"
7770     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
7771   }
7772 
7773   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
7774                                RHS.get(), AA_Assigning))
7775     return QualType();
7776 
7777   CheckForNullPointerDereference(*this, LHSExpr);
7778 
7779   // C99 6.5.16p3: The type of an assignment expression is the type of the
7780   // left operand unless the left operand has qualified type, in which case
7781   // it is the unqualified version of the type of the left operand.
7782   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
7783   // is converted to the type of the assignment expression (above).
7784   // C++ 5.17p1: the type of the assignment expression is that of its left
7785   // operand.
7786   return (getLangOpts().CPlusPlus
7787           ? LHSType : LHSType.getUnqualifiedType());
7788 }
7789 
7790 // C99 6.5.17
7791 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
7792                                    SourceLocation Loc) {
7793   LHS = S.CheckPlaceholderExpr(LHS.take());
7794   RHS = S.CheckPlaceholderExpr(RHS.take());
7795   if (LHS.isInvalid() || RHS.isInvalid())
7796     return QualType();
7797 
7798   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
7799   // operands, but not unary promotions.
7800   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
7801 
7802   // So we treat the LHS as a ignored value, and in C++ we allow the
7803   // containing site to determine what should be done with the RHS.
7804   LHS = S.IgnoredValueConversions(LHS.take());
7805   if (LHS.isInvalid())
7806     return QualType();
7807 
7808   S.DiagnoseUnusedExprResult(LHS.get());
7809 
7810   if (!S.getLangOpts().CPlusPlus) {
7811     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take());
7812     if (RHS.isInvalid())
7813       return QualType();
7814     if (!RHS.get()->getType()->isVoidType())
7815       S.RequireCompleteType(Loc, RHS.get()->getType(),
7816                             diag::err_incomplete_type);
7817   }
7818 
7819   return RHS.get()->getType();
7820 }
7821 
7822 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
7823 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
7824 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
7825                                                ExprValueKind &VK,
7826                                                SourceLocation OpLoc,
7827                                                bool IsInc, bool IsPrefix) {
7828   if (Op->isTypeDependent())
7829     return S.Context.DependentTy;
7830 
7831   QualType ResType = Op->getType();
7832   // Atomic types can be used for increment / decrement where the non-atomic
7833   // versions can, so ignore the _Atomic() specifier for the purpose of
7834   // checking.
7835   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
7836     ResType = ResAtomicType->getValueType();
7837 
7838   assert(!ResType.isNull() && "no type for increment/decrement expression");
7839 
7840   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
7841     // Decrement of bool is not allowed.
7842     if (!IsInc) {
7843       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
7844       return QualType();
7845     }
7846     // Increment of bool sets it to true, but is deprecated.
7847     S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
7848   } else if (ResType->isRealType()) {
7849     // OK!
7850   } else if (ResType->isPointerType()) {
7851     // C99 6.5.2.4p2, 6.5.6p2
7852     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
7853       return QualType();
7854   } else if (ResType->isObjCObjectPointerType()) {
7855     // On modern runtimes, ObjC pointer arithmetic is forbidden.
7856     // Otherwise, we just need a complete type.
7857     if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
7858         checkArithmeticOnObjCPointer(S, OpLoc, Op))
7859       return QualType();
7860   } else if (ResType->isAnyComplexType()) {
7861     // C99 does not support ++/-- on complex types, we allow as an extension.
7862     S.Diag(OpLoc, diag::ext_integer_increment_complex)
7863       << ResType << Op->getSourceRange();
7864   } else if (ResType->isPlaceholderType()) {
7865     ExprResult PR = S.CheckPlaceholderExpr(Op);
7866     if (PR.isInvalid()) return QualType();
7867     return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
7868                                           IsInc, IsPrefix);
7869   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
7870     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
7871   } else {
7872     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
7873       << ResType << int(IsInc) << Op->getSourceRange();
7874     return QualType();
7875   }
7876   // At this point, we know we have a real, complex or pointer type.
7877   // Now make sure the operand is a modifiable lvalue.
7878   if (CheckForModifiableLvalue(Op, OpLoc, S))
7879     return QualType();
7880   // In C++, a prefix increment is the same type as the operand. Otherwise
7881   // (in C or with postfix), the increment is the unqualified type of the
7882   // operand.
7883   if (IsPrefix && S.getLangOpts().CPlusPlus) {
7884     VK = VK_LValue;
7885     return ResType;
7886   } else {
7887     VK = VK_RValue;
7888     return ResType.getUnqualifiedType();
7889   }
7890 }
7891 
7892 
7893 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
7894 /// This routine allows us to typecheck complex/recursive expressions
7895 /// where the declaration is needed for type checking. We only need to
7896 /// handle cases when the expression references a function designator
7897 /// or is an lvalue. Here are some examples:
7898 ///  - &(x) => x
7899 ///  - &*****f => f for f a function designator.
7900 ///  - &s.xx => s
7901 ///  - &s.zz[1].yy -> s, if zz is an array
7902 ///  - *(x + 1) -> x, if x is an array
7903 ///  - &"123"[2] -> 0
7904 ///  - & __real__ x -> x
7905 static ValueDecl *getPrimaryDecl(Expr *E) {
7906   switch (E->getStmtClass()) {
7907   case Stmt::DeclRefExprClass:
7908     return cast<DeclRefExpr>(E)->getDecl();
7909   case Stmt::MemberExprClass:
7910     // If this is an arrow operator, the address is an offset from
7911     // the base's value, so the object the base refers to is
7912     // irrelevant.
7913     if (cast<MemberExpr>(E)->isArrow())
7914       return 0;
7915     // Otherwise, the expression refers to a part of the base
7916     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
7917   case Stmt::ArraySubscriptExprClass: {
7918     // FIXME: This code shouldn't be necessary!  We should catch the implicit
7919     // promotion of register arrays earlier.
7920     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
7921     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
7922       if (ICE->getSubExpr()->getType()->isArrayType())
7923         return getPrimaryDecl(ICE->getSubExpr());
7924     }
7925     return 0;
7926   }
7927   case Stmt::UnaryOperatorClass: {
7928     UnaryOperator *UO = cast<UnaryOperator>(E);
7929 
7930     switch(UO->getOpcode()) {
7931     case UO_Real:
7932     case UO_Imag:
7933     case UO_Extension:
7934       return getPrimaryDecl(UO->getSubExpr());
7935     default:
7936       return 0;
7937     }
7938   }
7939   case Stmt::ParenExprClass:
7940     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
7941   case Stmt::ImplicitCastExprClass:
7942     // If the result of an implicit cast is an l-value, we care about
7943     // the sub-expression; otherwise, the result here doesn't matter.
7944     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
7945   default:
7946     return 0;
7947   }
7948 }
7949 
7950 namespace {
7951   enum {
7952     AO_Bit_Field = 0,
7953     AO_Vector_Element = 1,
7954     AO_Property_Expansion = 2,
7955     AO_Register_Variable = 3,
7956     AO_No_Error = 4
7957   };
7958 }
7959 /// \brief Diagnose invalid operand for address of operations.
7960 ///
7961 /// \param Type The type of operand which cannot have its address taken.
7962 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
7963                                          Expr *E, unsigned Type) {
7964   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
7965 }
7966 
7967 /// CheckAddressOfOperand - The operand of & must be either a function
7968 /// designator or an lvalue designating an object. If it is an lvalue, the
7969 /// object cannot be declared with storage class register or be a bit field.
7970 /// Note: The usual conversions are *not* applied to the operand of the &
7971 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
7972 /// In C++, the operand might be an overloaded function name, in which case
7973 /// we allow the '&' but retain the overloaded-function type.
7974 static QualType CheckAddressOfOperand(Sema &S, ExprResult &OrigOp,
7975                                       SourceLocation OpLoc) {
7976   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
7977     if (PTy->getKind() == BuiltinType::Overload) {
7978       if (!isa<OverloadExpr>(OrigOp.get()->IgnoreParens())) {
7979         S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
7980           << OrigOp.get()->getSourceRange();
7981         return QualType();
7982       }
7983 
7984       return S.Context.OverloadTy;
7985     }
7986 
7987     if (PTy->getKind() == BuiltinType::UnknownAny)
7988       return S.Context.UnknownAnyTy;
7989 
7990     if (PTy->getKind() == BuiltinType::BoundMember) {
7991       S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
7992         << OrigOp.get()->getSourceRange();
7993       return QualType();
7994     }
7995 
7996     OrigOp = S.CheckPlaceholderExpr(OrigOp.take());
7997     if (OrigOp.isInvalid()) return QualType();
7998   }
7999 
8000   if (OrigOp.get()->isTypeDependent())
8001     return S.Context.DependentTy;
8002 
8003   assert(!OrigOp.get()->getType()->isPlaceholderType());
8004 
8005   // Make sure to ignore parentheses in subsequent checks
8006   Expr *op = OrigOp.get()->IgnoreParens();
8007 
8008   if (S.getLangOpts().C99) {
8009     // Implement C99-only parts of addressof rules.
8010     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
8011       if (uOp->getOpcode() == UO_Deref)
8012         // Per C99 6.5.3.2, the address of a deref always returns a valid result
8013         // (assuming the deref expression is valid).
8014         return uOp->getSubExpr()->getType();
8015     }
8016     // Technically, there should be a check for array subscript
8017     // expressions here, but the result of one is always an lvalue anyway.
8018   }
8019   ValueDecl *dcl = getPrimaryDecl(op);
8020   Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
8021   unsigned AddressOfError = AO_No_Error;
8022 
8023   if (lval == Expr::LV_ClassTemporary) {
8024     bool sfinae = S.isSFINAEContext();
8025     S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
8026                          : diag::ext_typecheck_addrof_class_temporary)
8027       << op->getType() << op->getSourceRange();
8028     if (sfinae)
8029       return QualType();
8030   } else if (isa<ObjCSelectorExpr>(op)) {
8031     return S.Context.getPointerType(op->getType());
8032   } else if (lval == Expr::LV_MemberFunction) {
8033     // If it's an instance method, make a member pointer.
8034     // The expression must have exactly the form &A::foo.
8035 
8036     // If the underlying expression isn't a decl ref, give up.
8037     if (!isa<DeclRefExpr>(op)) {
8038       S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
8039         << OrigOp.get()->getSourceRange();
8040       return QualType();
8041     }
8042     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
8043     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
8044 
8045     // The id-expression was parenthesized.
8046     if (OrigOp.get() != DRE) {
8047       S.Diag(OpLoc, diag::err_parens_pointer_member_function)
8048         << OrigOp.get()->getSourceRange();
8049 
8050     // The method was named without a qualifier.
8051     } else if (!DRE->getQualifier()) {
8052       S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
8053         << op->getSourceRange();
8054     }
8055 
8056     return S.Context.getMemberPointerType(op->getType(),
8057               S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
8058   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
8059     // C99 6.5.3.2p1
8060     // The operand must be either an l-value or a function designator
8061     if (!op->getType()->isFunctionType()) {
8062       // Use a special diagnostic for loads from property references.
8063       if (isa<PseudoObjectExpr>(op)) {
8064         AddressOfError = AO_Property_Expansion;
8065       } else {
8066         // FIXME: emit more specific diag...
8067         S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
8068           << op->getSourceRange();
8069         return QualType();
8070       }
8071     }
8072   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
8073     // The operand cannot be a bit-field
8074     AddressOfError = AO_Bit_Field;
8075   } else if (op->getObjectKind() == OK_VectorComponent) {
8076     // The operand cannot be an element of a vector
8077     AddressOfError = AO_Vector_Element;
8078   } else if (dcl) { // C99 6.5.3.2p1
8079     // We have an lvalue with a decl. Make sure the decl is not declared
8080     // with the register storage-class specifier.
8081     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
8082       // in C++ it is not error to take address of a register
8083       // variable (c++03 7.1.1P3)
8084       if (vd->getStorageClass() == SC_Register &&
8085           !S.getLangOpts().CPlusPlus) {
8086         AddressOfError = AO_Register_Variable;
8087       }
8088     } else if (isa<FunctionTemplateDecl>(dcl)) {
8089       return S.Context.OverloadTy;
8090     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
8091       // Okay: we can take the address of a field.
8092       // Could be a pointer to member, though, if there is an explicit
8093       // scope qualifier for the class.
8094       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
8095         DeclContext *Ctx = dcl->getDeclContext();
8096         if (Ctx && Ctx->isRecord()) {
8097           if (dcl->getType()->isReferenceType()) {
8098             S.Diag(OpLoc,
8099                    diag::err_cannot_form_pointer_to_member_of_reference_type)
8100               << dcl->getDeclName() << dcl->getType();
8101             return QualType();
8102           }
8103 
8104           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
8105             Ctx = Ctx->getParent();
8106           return S.Context.getMemberPointerType(op->getType(),
8107                 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
8108         }
8109       }
8110     } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl))
8111       llvm_unreachable("Unknown/unexpected decl type");
8112   }
8113 
8114   if (AddressOfError != AO_No_Error) {
8115     diagnoseAddressOfInvalidType(S, OpLoc, op, AddressOfError);
8116     return QualType();
8117   }
8118 
8119   if (lval == Expr::LV_IncompleteVoidType) {
8120     // Taking the address of a void variable is technically illegal, but we
8121     // allow it in cases which are otherwise valid.
8122     // Example: "extern void x; void* y = &x;".
8123     S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
8124   }
8125 
8126   // If the operand has type "type", the result has type "pointer to type".
8127   if (op->getType()->isObjCObjectType())
8128     return S.Context.getObjCObjectPointerType(op->getType());
8129   return S.Context.getPointerType(op->getType());
8130 }
8131 
8132 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
8133 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
8134                                         SourceLocation OpLoc) {
8135   if (Op->isTypeDependent())
8136     return S.Context.DependentTy;
8137 
8138   ExprResult ConvResult = S.UsualUnaryConversions(Op);
8139   if (ConvResult.isInvalid())
8140     return QualType();
8141   Op = ConvResult.take();
8142   QualType OpTy = Op->getType();
8143   QualType Result;
8144 
8145   if (isa<CXXReinterpretCastExpr>(Op)) {
8146     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
8147     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
8148                                      Op->getSourceRange());
8149   }
8150 
8151   // Note that per both C89 and C99, indirection is always legal, even if OpTy
8152   // is an incomplete type or void.  It would be possible to warn about
8153   // dereferencing a void pointer, but it's completely well-defined, and such a
8154   // warning is unlikely to catch any mistakes.
8155   if (const PointerType *PT = OpTy->getAs<PointerType>())
8156     Result = PT->getPointeeType();
8157   else if (const ObjCObjectPointerType *OPT =
8158              OpTy->getAs<ObjCObjectPointerType>())
8159     Result = OPT->getPointeeType();
8160   else {
8161     ExprResult PR = S.CheckPlaceholderExpr(Op);
8162     if (PR.isInvalid()) return QualType();
8163     if (PR.take() != Op)
8164       return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
8165   }
8166 
8167   if (Result.isNull()) {
8168     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
8169       << OpTy << Op->getSourceRange();
8170     return QualType();
8171   }
8172 
8173   // Dereferences are usually l-values...
8174   VK = VK_LValue;
8175 
8176   // ...except that certain expressions are never l-values in C.
8177   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
8178     VK = VK_RValue;
8179 
8180   return Result;
8181 }
8182 
8183 static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
8184   tok::TokenKind Kind) {
8185   BinaryOperatorKind Opc;
8186   switch (Kind) {
8187   default: llvm_unreachable("Unknown binop!");
8188   case tok::periodstar:           Opc = BO_PtrMemD; break;
8189   case tok::arrowstar:            Opc = BO_PtrMemI; break;
8190   case tok::star:                 Opc = BO_Mul; break;
8191   case tok::slash:                Opc = BO_Div; break;
8192   case tok::percent:              Opc = BO_Rem; break;
8193   case tok::plus:                 Opc = BO_Add; break;
8194   case tok::minus:                Opc = BO_Sub; break;
8195   case tok::lessless:             Opc = BO_Shl; break;
8196   case tok::greatergreater:       Opc = BO_Shr; break;
8197   case tok::lessequal:            Opc = BO_LE; break;
8198   case tok::less:                 Opc = BO_LT; break;
8199   case tok::greaterequal:         Opc = BO_GE; break;
8200   case tok::greater:              Opc = BO_GT; break;
8201   case tok::exclaimequal:         Opc = BO_NE; break;
8202   case tok::equalequal:           Opc = BO_EQ; break;
8203   case tok::amp:                  Opc = BO_And; break;
8204   case tok::caret:                Opc = BO_Xor; break;
8205   case tok::pipe:                 Opc = BO_Or; break;
8206   case tok::ampamp:               Opc = BO_LAnd; break;
8207   case tok::pipepipe:             Opc = BO_LOr; break;
8208   case tok::equal:                Opc = BO_Assign; break;
8209   case tok::starequal:            Opc = BO_MulAssign; break;
8210   case tok::slashequal:           Opc = BO_DivAssign; break;
8211   case tok::percentequal:         Opc = BO_RemAssign; break;
8212   case tok::plusequal:            Opc = BO_AddAssign; break;
8213   case tok::minusequal:           Opc = BO_SubAssign; break;
8214   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
8215   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
8216   case tok::ampequal:             Opc = BO_AndAssign; break;
8217   case tok::caretequal:           Opc = BO_XorAssign; break;
8218   case tok::pipeequal:            Opc = BO_OrAssign; break;
8219   case tok::comma:                Opc = BO_Comma; break;
8220   }
8221   return Opc;
8222 }
8223 
8224 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
8225   tok::TokenKind Kind) {
8226   UnaryOperatorKind Opc;
8227   switch (Kind) {
8228   default: llvm_unreachable("Unknown unary op!");
8229   case tok::plusplus:     Opc = UO_PreInc; break;
8230   case tok::minusminus:   Opc = UO_PreDec; break;
8231   case tok::amp:          Opc = UO_AddrOf; break;
8232   case tok::star:         Opc = UO_Deref; break;
8233   case tok::plus:         Opc = UO_Plus; break;
8234   case tok::minus:        Opc = UO_Minus; break;
8235   case tok::tilde:        Opc = UO_Not; break;
8236   case tok::exclaim:      Opc = UO_LNot; break;
8237   case tok::kw___real:    Opc = UO_Real; break;
8238   case tok::kw___imag:    Opc = UO_Imag; break;
8239   case tok::kw___extension__: Opc = UO_Extension; break;
8240   }
8241   return Opc;
8242 }
8243 
8244 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
8245 /// This warning is only emitted for builtin assignment operations. It is also
8246 /// suppressed in the event of macro expansions.
8247 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
8248                                    SourceLocation OpLoc) {
8249   if (!S.ActiveTemplateInstantiations.empty())
8250     return;
8251   if (OpLoc.isInvalid() || OpLoc.isMacroID())
8252     return;
8253   LHSExpr = LHSExpr->IgnoreParenImpCasts();
8254   RHSExpr = RHSExpr->IgnoreParenImpCasts();
8255   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
8256   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
8257   if (!LHSDeclRef || !RHSDeclRef ||
8258       LHSDeclRef->getLocation().isMacroID() ||
8259       RHSDeclRef->getLocation().isMacroID())
8260     return;
8261   const ValueDecl *LHSDecl =
8262     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
8263   const ValueDecl *RHSDecl =
8264     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
8265   if (LHSDecl != RHSDecl)
8266     return;
8267   if (LHSDecl->getType().isVolatileQualified())
8268     return;
8269   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
8270     if (RefTy->getPointeeType().isVolatileQualified())
8271       return;
8272 
8273   S.Diag(OpLoc, diag::warn_self_assignment)
8274       << LHSDeclRef->getType()
8275       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
8276 }
8277 
8278 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
8279 /// operator @p Opc at location @c TokLoc. This routine only supports
8280 /// built-in operations; ActOnBinOp handles overloaded operators.
8281 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
8282                                     BinaryOperatorKind Opc,
8283                                     Expr *LHSExpr, Expr *RHSExpr) {
8284   if (getLangOpts().CPlusPlus0x && isa<InitListExpr>(RHSExpr)) {
8285     // The syntax only allows initializer lists on the RHS of assignment,
8286     // so we don't need to worry about accepting invalid code for
8287     // non-assignment operators.
8288     // C++11 5.17p9:
8289     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
8290     //   of x = {} is x = T().
8291     InitializationKind Kind =
8292         InitializationKind::CreateDirectList(RHSExpr->getLocStart());
8293     InitializedEntity Entity =
8294         InitializedEntity::InitializeTemporary(LHSExpr->getType());
8295     InitializationSequence InitSeq(*this, Entity, Kind, &RHSExpr, 1);
8296     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
8297     if (Init.isInvalid())
8298       return Init;
8299     RHSExpr = Init.take();
8300   }
8301 
8302   ExprResult LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
8303   QualType ResultTy;     // Result type of the binary operator.
8304   // The following two variables are used for compound assignment operators
8305   QualType CompLHSTy;    // Type of LHS after promotions for computation
8306   QualType CompResultTy; // Type of computation result
8307   ExprValueKind VK = VK_RValue;
8308   ExprObjectKind OK = OK_Ordinary;
8309 
8310   switch (Opc) {
8311   case BO_Assign:
8312     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
8313     if (getLangOpts().CPlusPlus &&
8314         LHS.get()->getObjectKind() != OK_ObjCProperty) {
8315       VK = LHS.get()->getValueKind();
8316       OK = LHS.get()->getObjectKind();
8317     }
8318     if (!ResultTy.isNull())
8319       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
8320     break;
8321   case BO_PtrMemD:
8322   case BO_PtrMemI:
8323     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
8324                                             Opc == BO_PtrMemI);
8325     break;
8326   case BO_Mul:
8327   case BO_Div:
8328     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
8329                                            Opc == BO_Div);
8330     break;
8331   case BO_Rem:
8332     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
8333     break;
8334   case BO_Add:
8335     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
8336     break;
8337   case BO_Sub:
8338     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
8339     break;
8340   case BO_Shl:
8341   case BO_Shr:
8342     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
8343     break;
8344   case BO_LE:
8345   case BO_LT:
8346   case BO_GE:
8347   case BO_GT:
8348     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
8349     break;
8350   case BO_EQ:
8351   case BO_NE:
8352     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
8353     break;
8354   case BO_And:
8355   case BO_Xor:
8356   case BO_Or:
8357     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc);
8358     break;
8359   case BO_LAnd:
8360   case BO_LOr:
8361     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
8362     break;
8363   case BO_MulAssign:
8364   case BO_DivAssign:
8365     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
8366                                                Opc == BO_DivAssign);
8367     CompLHSTy = CompResultTy;
8368     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8369       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
8370     break;
8371   case BO_RemAssign:
8372     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
8373     CompLHSTy = CompResultTy;
8374     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8375       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
8376     break;
8377   case BO_AddAssign:
8378     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
8379     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8380       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
8381     break;
8382   case BO_SubAssign:
8383     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
8384     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8385       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
8386     break;
8387   case BO_ShlAssign:
8388   case BO_ShrAssign:
8389     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
8390     CompLHSTy = CompResultTy;
8391     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8392       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
8393     break;
8394   case BO_AndAssign:
8395   case BO_XorAssign:
8396   case BO_OrAssign:
8397     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true);
8398     CompLHSTy = CompResultTy;
8399     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8400       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
8401     break;
8402   case BO_Comma:
8403     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
8404     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
8405       VK = RHS.get()->getValueKind();
8406       OK = RHS.get()->getObjectKind();
8407     }
8408     break;
8409   }
8410   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
8411     return ExprError();
8412 
8413   // Check for array bounds violations for both sides of the BinaryOperator
8414   CheckArrayAccess(LHS.get());
8415   CheckArrayAccess(RHS.get());
8416 
8417   if (CompResultTy.isNull())
8418     return Owned(new (Context) BinaryOperator(LHS.take(), RHS.take(), Opc,
8419                                               ResultTy, VK, OK, OpLoc,
8420                                               FPFeatures.fp_contract));
8421   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
8422       OK_ObjCProperty) {
8423     VK = VK_LValue;
8424     OK = LHS.get()->getObjectKind();
8425   }
8426   return Owned(new (Context) CompoundAssignOperator(LHS.take(), RHS.take(), Opc,
8427                                                     ResultTy, VK, OK, CompLHSTy,
8428                                                     CompResultTy, OpLoc,
8429                                                     FPFeatures.fp_contract));
8430 }
8431 
8432 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
8433 /// operators are mixed in a way that suggests that the programmer forgot that
8434 /// comparison operators have higher precedence. The most typical example of
8435 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
8436 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
8437                                       SourceLocation OpLoc, Expr *LHSExpr,
8438                                       Expr *RHSExpr) {
8439   typedef BinaryOperator BinOp;
8440   BinOp::Opcode LHSopc = static_cast<BinOp::Opcode>(-1),
8441                 RHSopc = static_cast<BinOp::Opcode>(-1);
8442   if (BinOp *BO = dyn_cast<BinOp>(LHSExpr))
8443     LHSopc = BO->getOpcode();
8444   if (BinOp *BO = dyn_cast<BinOp>(RHSExpr))
8445     RHSopc = BO->getOpcode();
8446 
8447   // Subs are not binary operators.
8448   if (LHSopc == -1 && RHSopc == -1)
8449     return;
8450 
8451   // Bitwise operations are sometimes used as eager logical ops.
8452   // Don't diagnose this.
8453   if ((BinOp::isComparisonOp(LHSopc) || BinOp::isBitwiseOp(LHSopc)) &&
8454       (BinOp::isComparisonOp(RHSopc) || BinOp::isBitwiseOp(RHSopc)))
8455     return;
8456 
8457   bool isLeftComp = BinOp::isComparisonOp(LHSopc);
8458   bool isRightComp = BinOp::isComparisonOp(RHSopc);
8459   if (!isLeftComp && !isRightComp) return;
8460 
8461   SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
8462                                                    OpLoc)
8463                                      : SourceRange(OpLoc, RHSExpr->getLocEnd());
8464   std::string OpStr = isLeftComp ? BinOp::getOpcodeStr(LHSopc)
8465                                  : BinOp::getOpcodeStr(RHSopc);
8466   SourceRange ParensRange = isLeftComp ?
8467       SourceRange(cast<BinOp>(LHSExpr)->getRHS()->getLocStart(),
8468                   RHSExpr->getLocEnd())
8469     : SourceRange(LHSExpr->getLocStart(),
8470                   cast<BinOp>(RHSExpr)->getLHS()->getLocStart());
8471 
8472   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
8473     << DiagRange << BinOp::getOpcodeStr(Opc) << OpStr;
8474   SuggestParentheses(Self, OpLoc,
8475     Self.PDiag(diag::note_precedence_bitwise_silence) << OpStr,
8476     (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
8477   SuggestParentheses(Self, OpLoc,
8478     Self.PDiag(diag::note_precedence_bitwise_first) << BinOp::getOpcodeStr(Opc),
8479     ParensRange);
8480 }
8481 
8482 /// \brief It accepts a '&' expr that is inside a '|' one.
8483 /// Emit a diagnostic together with a fixit hint that wraps the '&' expression
8484 /// in parentheses.
8485 static void
8486 EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc,
8487                                        BinaryOperator *Bop) {
8488   assert(Bop->getOpcode() == BO_And);
8489   Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or)
8490       << Bop->getSourceRange() << OpLoc;
8491   SuggestParentheses(Self, Bop->getOperatorLoc(),
8492     Self.PDiag(diag::note_bitwise_and_in_bitwise_or_silence),
8493     Bop->getSourceRange());
8494 }
8495 
8496 /// \brief It accepts a '&&' expr that is inside a '||' one.
8497 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
8498 /// in parentheses.
8499 static void
8500 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
8501                                        BinaryOperator *Bop) {
8502   assert(Bop->getOpcode() == BO_LAnd);
8503   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
8504       << Bop->getSourceRange() << OpLoc;
8505   SuggestParentheses(Self, Bop->getOperatorLoc(),
8506     Self.PDiag(diag::note_logical_and_in_logical_or_silence),
8507     Bop->getSourceRange());
8508 }
8509 
8510 /// \brief Returns true if the given expression can be evaluated as a constant
8511 /// 'true'.
8512 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
8513   bool Res;
8514   return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
8515 }
8516 
8517 /// \brief Returns true if the given expression can be evaluated as a constant
8518 /// 'false'.
8519 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
8520   bool Res;
8521   return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
8522 }
8523 
8524 /// \brief Look for '&&' in the left hand of a '||' expr.
8525 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
8526                                              Expr *LHSExpr, Expr *RHSExpr) {
8527   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
8528     if (Bop->getOpcode() == BO_LAnd) {
8529       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
8530       if (EvaluatesAsFalse(S, RHSExpr))
8531         return;
8532       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
8533       if (!EvaluatesAsTrue(S, Bop->getLHS()))
8534         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
8535     } else if (Bop->getOpcode() == BO_LOr) {
8536       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
8537         // If it's "a || b && 1 || c" we didn't warn earlier for
8538         // "a || b && 1", but warn now.
8539         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
8540           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
8541       }
8542     }
8543   }
8544 }
8545 
8546 /// \brief Look for '&&' in the right hand of a '||' expr.
8547 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
8548                                              Expr *LHSExpr, Expr *RHSExpr) {
8549   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
8550     if (Bop->getOpcode() == BO_LAnd) {
8551       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
8552       if (EvaluatesAsFalse(S, LHSExpr))
8553         return;
8554       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
8555       if (!EvaluatesAsTrue(S, Bop->getRHS()))
8556         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
8557     }
8558   }
8559 }
8560 
8561 /// \brief Look for '&' in the left or right hand of a '|' expr.
8562 static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc,
8563                                              Expr *OrArg) {
8564   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) {
8565     if (Bop->getOpcode() == BO_And)
8566       return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop);
8567   }
8568 }
8569 
8570 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
8571 /// precedence.
8572 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
8573                                     SourceLocation OpLoc, Expr *LHSExpr,
8574                                     Expr *RHSExpr){
8575   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
8576   if (BinaryOperator::isBitwiseOp(Opc))
8577     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
8578 
8579   // Diagnose "arg1 & arg2 | arg3"
8580   if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) {
8581     DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr);
8582     DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr);
8583   }
8584 
8585   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
8586   // We don't warn for 'assert(a || b && "bad")' since this is safe.
8587   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
8588     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
8589     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
8590   }
8591 }
8592 
8593 // Binary Operators.  'Tok' is the token for the operator.
8594 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
8595                             tok::TokenKind Kind,
8596                             Expr *LHSExpr, Expr *RHSExpr) {
8597   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
8598   assert((LHSExpr != 0) && "ActOnBinOp(): missing left expression");
8599   assert((RHSExpr != 0) && "ActOnBinOp(): missing right expression");
8600 
8601   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
8602   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
8603 
8604   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
8605 }
8606 
8607 /// Build an overloaded binary operator expression in the given scope.
8608 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
8609                                        BinaryOperatorKind Opc,
8610                                        Expr *LHS, Expr *RHS) {
8611   // Find all of the overloaded operators visible from this
8612   // point. We perform both an operator-name lookup from the local
8613   // scope and an argument-dependent lookup based on the types of
8614   // the arguments.
8615   UnresolvedSet<16> Functions;
8616   OverloadedOperatorKind OverOp
8617     = BinaryOperator::getOverloadedOperator(Opc);
8618   if (Sc && OverOp != OO_None)
8619     S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
8620                                    RHS->getType(), Functions);
8621 
8622   // Build the (potentially-overloaded, potentially-dependent)
8623   // binary operation.
8624   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
8625 }
8626 
8627 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
8628                             BinaryOperatorKind Opc,
8629                             Expr *LHSExpr, Expr *RHSExpr) {
8630   // We want to end up calling one of checkPseudoObjectAssignment
8631   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
8632   // both expressions are overloadable or either is type-dependent),
8633   // or CreateBuiltinBinOp (in any other case).  We also want to get
8634   // any placeholder types out of the way.
8635 
8636   // Handle pseudo-objects in the LHS.
8637   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
8638     // Assignments with a pseudo-object l-value need special analysis.
8639     if (pty->getKind() == BuiltinType::PseudoObject &&
8640         BinaryOperator::isAssignmentOp(Opc))
8641       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
8642 
8643     // Don't resolve overloads if the other type is overloadable.
8644     if (pty->getKind() == BuiltinType::Overload) {
8645       // We can't actually test that if we still have a placeholder,
8646       // though.  Fortunately, none of the exceptions we see in that
8647       // code below are valid when the LHS is an overload set.  Note
8648       // that an overload set can be dependently-typed, but it never
8649       // instantiates to having an overloadable type.
8650       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
8651       if (resolvedRHS.isInvalid()) return ExprError();
8652       RHSExpr = resolvedRHS.take();
8653 
8654       if (RHSExpr->isTypeDependent() ||
8655           RHSExpr->getType()->isOverloadableType())
8656         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8657     }
8658 
8659     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
8660     if (LHS.isInvalid()) return ExprError();
8661     LHSExpr = LHS.take();
8662   }
8663 
8664   // Handle pseudo-objects in the RHS.
8665   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
8666     // An overload in the RHS can potentially be resolved by the type
8667     // being assigned to.
8668     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
8669       if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
8670         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8671 
8672       if (LHSExpr->getType()->isOverloadableType())
8673         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8674 
8675       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
8676     }
8677 
8678     // Don't resolve overloads if the other type is overloadable.
8679     if (pty->getKind() == BuiltinType::Overload &&
8680         LHSExpr->getType()->isOverloadableType())
8681       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8682 
8683     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
8684     if (!resolvedRHS.isUsable()) return ExprError();
8685     RHSExpr = resolvedRHS.take();
8686   }
8687 
8688   if (getLangOpts().CPlusPlus) {
8689     // If either expression is type-dependent, always build an
8690     // overloaded op.
8691     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
8692       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8693 
8694     // Otherwise, build an overloaded op if either expression has an
8695     // overloadable type.
8696     if (LHSExpr->getType()->isOverloadableType() ||
8697         RHSExpr->getType()->isOverloadableType())
8698       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8699   }
8700 
8701   // Build a built-in binary operation.
8702   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
8703 }
8704 
8705 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
8706                                       UnaryOperatorKind Opc,
8707                                       Expr *InputExpr) {
8708   ExprResult Input = Owned(InputExpr);
8709   ExprValueKind VK = VK_RValue;
8710   ExprObjectKind OK = OK_Ordinary;
8711   QualType resultType;
8712   switch (Opc) {
8713   case UO_PreInc:
8714   case UO_PreDec:
8715   case UO_PostInc:
8716   case UO_PostDec:
8717     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc,
8718                                                 Opc == UO_PreInc ||
8719                                                 Opc == UO_PostInc,
8720                                                 Opc == UO_PreInc ||
8721                                                 Opc == UO_PreDec);
8722     break;
8723   case UO_AddrOf:
8724     resultType = CheckAddressOfOperand(*this, Input, OpLoc);
8725     break;
8726   case UO_Deref: {
8727     Input = DefaultFunctionArrayLvalueConversion(Input.take());
8728     if (Input.isInvalid()) return ExprError();
8729     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
8730     break;
8731   }
8732   case UO_Plus:
8733   case UO_Minus:
8734     Input = UsualUnaryConversions(Input.take());
8735     if (Input.isInvalid()) return ExprError();
8736     resultType = Input.get()->getType();
8737     if (resultType->isDependentType())
8738       break;
8739     if (resultType->isArithmeticType() || // C99 6.5.3.3p1
8740         resultType->isVectorType())
8741       break;
8742     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6-7
8743              resultType->isEnumeralType())
8744       break;
8745     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
8746              Opc == UO_Plus &&
8747              resultType->isPointerType())
8748       break;
8749 
8750     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
8751       << resultType << Input.get()->getSourceRange());
8752 
8753   case UO_Not: // bitwise complement
8754     Input = UsualUnaryConversions(Input.take());
8755     if (Input.isInvalid()) return ExprError();
8756     resultType = Input.get()->getType();
8757     if (resultType->isDependentType())
8758       break;
8759     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
8760     if (resultType->isComplexType() || resultType->isComplexIntegerType())
8761       // C99 does not support '~' for complex conjugation.
8762       Diag(OpLoc, diag::ext_integer_complement_complex)
8763         << resultType << Input.get()->getSourceRange();
8764     else if (resultType->hasIntegerRepresentation())
8765       break;
8766     else {
8767       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
8768         << resultType << Input.get()->getSourceRange());
8769     }
8770     break;
8771 
8772   case UO_LNot: // logical negation
8773     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
8774     Input = DefaultFunctionArrayLvalueConversion(Input.take());
8775     if (Input.isInvalid()) return ExprError();
8776     resultType = Input.get()->getType();
8777 
8778     // Though we still have to promote half FP to float...
8779     if (resultType->isHalfType()) {
8780       Input = ImpCastExprToType(Input.take(), Context.FloatTy, CK_FloatingCast).take();
8781       resultType = Context.FloatTy;
8782     }
8783 
8784     if (resultType->isDependentType())
8785       break;
8786     if (resultType->isScalarType()) {
8787       // C99 6.5.3.3p1: ok, fallthrough;
8788       if (Context.getLangOpts().CPlusPlus) {
8789         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
8790         // operand contextually converted to bool.
8791         Input = ImpCastExprToType(Input.take(), Context.BoolTy,
8792                                   ScalarTypeToBooleanCastKind(resultType));
8793       }
8794     } else if (resultType->isExtVectorType()) {
8795       // Vector logical not returns the signed variant of the operand type.
8796       resultType = GetSignedVectorType(resultType);
8797       break;
8798     } else {
8799       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
8800         << resultType << Input.get()->getSourceRange());
8801     }
8802 
8803     // LNot always has type int. C99 6.5.3.3p5.
8804     // In C++, it's bool. C++ 5.3.1p8
8805     resultType = Context.getLogicalOperationType();
8806     break;
8807   case UO_Real:
8808   case UO_Imag:
8809     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
8810     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
8811     // complex l-values to ordinary l-values and all other values to r-values.
8812     if (Input.isInvalid()) return ExprError();
8813     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
8814       if (Input.get()->getValueKind() != VK_RValue &&
8815           Input.get()->getObjectKind() == OK_Ordinary)
8816         VK = Input.get()->getValueKind();
8817     } else if (!getLangOpts().CPlusPlus) {
8818       // In C, a volatile scalar is read by __imag. In C++, it is not.
8819       Input = DefaultLvalueConversion(Input.take());
8820     }
8821     break;
8822   case UO_Extension:
8823     resultType = Input.get()->getType();
8824     VK = Input.get()->getValueKind();
8825     OK = Input.get()->getObjectKind();
8826     break;
8827   }
8828   if (resultType.isNull() || Input.isInvalid())
8829     return ExprError();
8830 
8831   // Check for array bounds violations in the operand of the UnaryOperator,
8832   // except for the '*' and '&' operators that have to be handled specially
8833   // by CheckArrayAccess (as there are special cases like &array[arraysize]
8834   // that are explicitly defined as valid by the standard).
8835   if (Opc != UO_AddrOf && Opc != UO_Deref)
8836     CheckArrayAccess(Input.get());
8837 
8838   return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType,
8839                                            VK, OK, OpLoc));
8840 }
8841 
8842 /// \brief Determine whether the given expression is a qualified member
8843 /// access expression, of a form that could be turned into a pointer to member
8844 /// with the address-of operator.
8845 static bool isQualifiedMemberAccess(Expr *E) {
8846   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
8847     if (!DRE->getQualifier())
8848       return false;
8849 
8850     ValueDecl *VD = DRE->getDecl();
8851     if (!VD->isCXXClassMember())
8852       return false;
8853 
8854     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
8855       return true;
8856     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
8857       return Method->isInstance();
8858 
8859     return false;
8860   }
8861 
8862   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
8863     if (!ULE->getQualifier())
8864       return false;
8865 
8866     for (UnresolvedLookupExpr::decls_iterator D = ULE->decls_begin(),
8867                                            DEnd = ULE->decls_end();
8868          D != DEnd; ++D) {
8869       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*D)) {
8870         if (Method->isInstance())
8871           return true;
8872       } else {
8873         // Overload set does not contain methods.
8874         break;
8875       }
8876     }
8877 
8878     return false;
8879   }
8880 
8881   return false;
8882 }
8883 
8884 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
8885                               UnaryOperatorKind Opc, Expr *Input) {
8886   // First things first: handle placeholders so that the
8887   // overloaded-operator check considers the right type.
8888   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
8889     // Increment and decrement of pseudo-object references.
8890     if (pty->getKind() == BuiltinType::PseudoObject &&
8891         UnaryOperator::isIncrementDecrementOp(Opc))
8892       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
8893 
8894     // extension is always a builtin operator.
8895     if (Opc == UO_Extension)
8896       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
8897 
8898     // & gets special logic for several kinds of placeholder.
8899     // The builtin code knows what to do.
8900     if (Opc == UO_AddrOf &&
8901         (pty->getKind() == BuiltinType::Overload ||
8902          pty->getKind() == BuiltinType::UnknownAny ||
8903          pty->getKind() == BuiltinType::BoundMember))
8904       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
8905 
8906     // Anything else needs to be handled now.
8907     ExprResult Result = CheckPlaceholderExpr(Input);
8908     if (Result.isInvalid()) return ExprError();
8909     Input = Result.take();
8910   }
8911 
8912   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
8913       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
8914       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
8915     // Find all of the overloaded operators visible from this
8916     // point. We perform both an operator-name lookup from the local
8917     // scope and an argument-dependent lookup based on the types of
8918     // the arguments.
8919     UnresolvedSet<16> Functions;
8920     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
8921     if (S && OverOp != OO_None)
8922       LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
8923                                    Functions);
8924 
8925     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
8926   }
8927 
8928   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
8929 }
8930 
8931 // Unary Operators.  'Tok' is the token for the operator.
8932 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
8933                               tok::TokenKind Op, Expr *Input) {
8934   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
8935 }
8936 
8937 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
8938 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
8939                                 LabelDecl *TheDecl) {
8940   TheDecl->setUsed();
8941   // Create the AST node.  The address of a label always has type 'void*'.
8942   return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
8943                                        Context.getPointerType(Context.VoidTy)));
8944 }
8945 
8946 /// Given the last statement in a statement-expression, check whether
8947 /// the result is a producing expression (like a call to an
8948 /// ns_returns_retained function) and, if so, rebuild it to hoist the
8949 /// release out of the full-expression.  Otherwise, return null.
8950 /// Cannot fail.
8951 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
8952   // Should always be wrapped with one of these.
8953   ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
8954   if (!cleanups) return 0;
8955 
8956   ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
8957   if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
8958     return 0;
8959 
8960   // Splice out the cast.  This shouldn't modify any interesting
8961   // features of the statement.
8962   Expr *producer = cast->getSubExpr();
8963   assert(producer->getType() == cast->getType());
8964   assert(producer->getValueKind() == cast->getValueKind());
8965   cleanups->setSubExpr(producer);
8966   return cleanups;
8967 }
8968 
8969 void Sema::ActOnStartStmtExpr() {
8970   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
8971 }
8972 
8973 void Sema::ActOnStmtExprError() {
8974   // Note that function is also called by TreeTransform when leaving a
8975   // StmtExpr scope without rebuilding anything.
8976 
8977   DiscardCleanupsInEvaluationContext();
8978   PopExpressionEvaluationContext();
8979 }
8980 
8981 ExprResult
8982 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
8983                     SourceLocation RPLoc) { // "({..})"
8984   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
8985   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
8986 
8987   if (hasAnyUnrecoverableErrorsInThisFunction())
8988     DiscardCleanupsInEvaluationContext();
8989   assert(!ExprNeedsCleanups && "cleanups within StmtExpr not correctly bound!");
8990   PopExpressionEvaluationContext();
8991 
8992   bool isFileScope
8993     = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
8994   if (isFileScope)
8995     return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
8996 
8997   // FIXME: there are a variety of strange constraints to enforce here, for
8998   // example, it is not possible to goto into a stmt expression apparently.
8999   // More semantic analysis is needed.
9000 
9001   // If there are sub stmts in the compound stmt, take the type of the last one
9002   // as the type of the stmtexpr.
9003   QualType Ty = Context.VoidTy;
9004   bool StmtExprMayBindToTemp = false;
9005   if (!Compound->body_empty()) {
9006     Stmt *LastStmt = Compound->body_back();
9007     LabelStmt *LastLabelStmt = 0;
9008     // If LastStmt is a label, skip down through into the body.
9009     while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
9010       LastLabelStmt = Label;
9011       LastStmt = Label->getSubStmt();
9012     }
9013 
9014     if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
9015       // Do function/array conversion on the last expression, but not
9016       // lvalue-to-rvalue.  However, initialize an unqualified type.
9017       ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
9018       if (LastExpr.isInvalid())
9019         return ExprError();
9020       Ty = LastExpr.get()->getType().getUnqualifiedType();
9021 
9022       if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
9023         // In ARC, if the final expression ends in a consume, splice
9024         // the consume out and bind it later.  In the alternate case
9025         // (when dealing with a retainable type), the result
9026         // initialization will create a produce.  In both cases the
9027         // result will be +1, and we'll need to balance that out with
9028         // a bind.
9029         if (Expr *rebuiltLastStmt
9030               = maybeRebuildARCConsumingStmt(LastExpr.get())) {
9031           LastExpr = rebuiltLastStmt;
9032         } else {
9033           LastExpr = PerformCopyInitialization(
9034                             InitializedEntity::InitializeResult(LPLoc,
9035                                                                 Ty,
9036                                                                 false),
9037                                                    SourceLocation(),
9038                                                LastExpr);
9039         }
9040 
9041         if (LastExpr.isInvalid())
9042           return ExprError();
9043         if (LastExpr.get() != 0) {
9044           if (!LastLabelStmt)
9045             Compound->setLastStmt(LastExpr.take());
9046           else
9047             LastLabelStmt->setSubStmt(LastExpr.take());
9048           StmtExprMayBindToTemp = true;
9049         }
9050       }
9051     }
9052   }
9053 
9054   // FIXME: Check that expression type is complete/non-abstract; statement
9055   // expressions are not lvalues.
9056   Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
9057   if (StmtExprMayBindToTemp)
9058     return MaybeBindToTemporary(ResStmtExpr);
9059   return Owned(ResStmtExpr);
9060 }
9061 
9062 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
9063                                       TypeSourceInfo *TInfo,
9064                                       OffsetOfComponent *CompPtr,
9065                                       unsigned NumComponents,
9066                                       SourceLocation RParenLoc) {
9067   QualType ArgTy = TInfo->getType();
9068   bool Dependent = ArgTy->isDependentType();
9069   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
9070 
9071   // We must have at least one component that refers to the type, and the first
9072   // one is known to be a field designator.  Verify that the ArgTy represents
9073   // a struct/union/class.
9074   if (!Dependent && !ArgTy->isRecordType())
9075     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
9076                        << ArgTy << TypeRange);
9077 
9078   // Type must be complete per C99 7.17p3 because a declaring a variable
9079   // with an incomplete type would be ill-formed.
9080   if (!Dependent
9081       && RequireCompleteType(BuiltinLoc, ArgTy,
9082                              diag::err_offsetof_incomplete_type, TypeRange))
9083     return ExprError();
9084 
9085   // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
9086   // GCC extension, diagnose them.
9087   // FIXME: This diagnostic isn't actually visible because the location is in
9088   // a system header!
9089   if (NumComponents != 1)
9090     Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
9091       << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
9092 
9093   bool DidWarnAboutNonPOD = false;
9094   QualType CurrentType = ArgTy;
9095   typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
9096   SmallVector<OffsetOfNode, 4> Comps;
9097   SmallVector<Expr*, 4> Exprs;
9098   for (unsigned i = 0; i != NumComponents; ++i) {
9099     const OffsetOfComponent &OC = CompPtr[i];
9100     if (OC.isBrackets) {
9101       // Offset of an array sub-field.  TODO: Should we allow vector elements?
9102       if (!CurrentType->isDependentType()) {
9103         const ArrayType *AT = Context.getAsArrayType(CurrentType);
9104         if(!AT)
9105           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
9106                            << CurrentType);
9107         CurrentType = AT->getElementType();
9108       } else
9109         CurrentType = Context.DependentTy;
9110 
9111       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
9112       if (IdxRval.isInvalid())
9113         return ExprError();
9114       Expr *Idx = IdxRval.take();
9115 
9116       // The expression must be an integral expression.
9117       // FIXME: An integral constant expression?
9118       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
9119           !Idx->getType()->isIntegerType())
9120         return ExprError(Diag(Idx->getLocStart(),
9121                               diag::err_typecheck_subscript_not_integer)
9122                          << Idx->getSourceRange());
9123 
9124       // Record this array index.
9125       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
9126       Exprs.push_back(Idx);
9127       continue;
9128     }
9129 
9130     // Offset of a field.
9131     if (CurrentType->isDependentType()) {
9132       // We have the offset of a field, but we can't look into the dependent
9133       // type. Just record the identifier of the field.
9134       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
9135       CurrentType = Context.DependentTy;
9136       continue;
9137     }
9138 
9139     // We need to have a complete type to look into.
9140     if (RequireCompleteType(OC.LocStart, CurrentType,
9141                             diag::err_offsetof_incomplete_type))
9142       return ExprError();
9143 
9144     // Look for the designated field.
9145     const RecordType *RC = CurrentType->getAs<RecordType>();
9146     if (!RC)
9147       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
9148                        << CurrentType);
9149     RecordDecl *RD = RC->getDecl();
9150 
9151     // C++ [lib.support.types]p5:
9152     //   The macro offsetof accepts a restricted set of type arguments in this
9153     //   International Standard. type shall be a POD structure or a POD union
9154     //   (clause 9).
9155     // C++11 [support.types]p4:
9156     //   If type is not a standard-layout class (Clause 9), the results are
9157     //   undefined.
9158     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
9159       bool IsSafe = LangOpts.CPlusPlus0x? CRD->isStandardLayout() : CRD->isPOD();
9160       unsigned DiagID =
9161         LangOpts.CPlusPlus0x? diag::warn_offsetof_non_standardlayout_type
9162                             : diag::warn_offsetof_non_pod_type;
9163 
9164       if (!IsSafe && !DidWarnAboutNonPOD &&
9165           DiagRuntimeBehavior(BuiltinLoc, 0,
9166                               PDiag(DiagID)
9167                               << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
9168                               << CurrentType))
9169         DidWarnAboutNonPOD = true;
9170     }
9171 
9172     // Look for the field.
9173     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
9174     LookupQualifiedName(R, RD);
9175     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
9176     IndirectFieldDecl *IndirectMemberDecl = 0;
9177     if (!MemberDecl) {
9178       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
9179         MemberDecl = IndirectMemberDecl->getAnonField();
9180     }
9181 
9182     if (!MemberDecl)
9183       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
9184                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
9185                                                               OC.LocEnd));
9186 
9187     // C99 7.17p3:
9188     //   (If the specified member is a bit-field, the behavior is undefined.)
9189     //
9190     // We diagnose this as an error.
9191     if (MemberDecl->isBitField()) {
9192       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
9193         << MemberDecl->getDeclName()
9194         << SourceRange(BuiltinLoc, RParenLoc);
9195       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
9196       return ExprError();
9197     }
9198 
9199     RecordDecl *Parent = MemberDecl->getParent();
9200     if (IndirectMemberDecl)
9201       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
9202 
9203     // If the member was found in a base class, introduce OffsetOfNodes for
9204     // the base class indirections.
9205     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
9206                        /*DetectVirtual=*/false);
9207     if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
9208       CXXBasePath &Path = Paths.front();
9209       for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
9210            B != BEnd; ++B)
9211         Comps.push_back(OffsetOfNode(B->Base));
9212     }
9213 
9214     if (IndirectMemberDecl) {
9215       for (IndirectFieldDecl::chain_iterator FI =
9216            IndirectMemberDecl->chain_begin(),
9217            FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
9218         assert(isa<FieldDecl>(*FI));
9219         Comps.push_back(OffsetOfNode(OC.LocStart,
9220                                      cast<FieldDecl>(*FI), OC.LocEnd));
9221       }
9222     } else
9223       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
9224 
9225     CurrentType = MemberDecl->getType().getNonReferenceType();
9226   }
9227 
9228   return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
9229                                     TInfo, Comps, Exprs, RParenLoc));
9230 }
9231 
9232 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
9233                                       SourceLocation BuiltinLoc,
9234                                       SourceLocation TypeLoc,
9235                                       ParsedType ParsedArgTy,
9236                                       OffsetOfComponent *CompPtr,
9237                                       unsigned NumComponents,
9238                                       SourceLocation RParenLoc) {
9239 
9240   TypeSourceInfo *ArgTInfo;
9241   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
9242   if (ArgTy.isNull())
9243     return ExprError();
9244 
9245   if (!ArgTInfo)
9246     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
9247 
9248   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
9249                               RParenLoc);
9250 }
9251 
9252 
9253 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
9254                                  Expr *CondExpr,
9255                                  Expr *LHSExpr, Expr *RHSExpr,
9256                                  SourceLocation RPLoc) {
9257   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
9258 
9259   ExprValueKind VK = VK_RValue;
9260   ExprObjectKind OK = OK_Ordinary;
9261   QualType resType;
9262   bool ValueDependent = false;
9263   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
9264     resType = Context.DependentTy;
9265     ValueDependent = true;
9266   } else {
9267     // The conditional expression is required to be a constant expression.
9268     llvm::APSInt condEval(32);
9269     ExprResult CondICE
9270       = VerifyIntegerConstantExpression(CondExpr, &condEval,
9271           diag::err_typecheck_choose_expr_requires_constant, false);
9272     if (CondICE.isInvalid())
9273       return ExprError();
9274     CondExpr = CondICE.take();
9275 
9276     // If the condition is > zero, then the AST type is the same as the LSHExpr.
9277     Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
9278 
9279     resType = ActiveExpr->getType();
9280     ValueDependent = ActiveExpr->isValueDependent();
9281     VK = ActiveExpr->getValueKind();
9282     OK = ActiveExpr->getObjectKind();
9283   }
9284 
9285   return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
9286                                         resType, VK, OK, RPLoc,
9287                                         resType->isDependentType(),
9288                                         ValueDependent));
9289 }
9290 
9291 //===----------------------------------------------------------------------===//
9292 // Clang Extensions.
9293 //===----------------------------------------------------------------------===//
9294 
9295 /// ActOnBlockStart - This callback is invoked when a block literal is started.
9296 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
9297   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
9298   PushBlockScope(CurScope, Block);
9299   CurContext->addDecl(Block);
9300   if (CurScope)
9301     PushDeclContext(CurScope, Block);
9302   else
9303     CurContext = Block;
9304 
9305   getCurBlock()->HasImplicitReturnType = true;
9306 
9307   // Enter a new evaluation context to insulate the block from any
9308   // cleanups from the enclosing full-expression.
9309   PushExpressionEvaluationContext(PotentiallyEvaluated);
9310 }
9311 
9312 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
9313                                Scope *CurScope) {
9314   assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
9315   assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
9316   BlockScopeInfo *CurBlock = getCurBlock();
9317 
9318   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
9319   QualType T = Sig->getType();
9320 
9321   // FIXME: We should allow unexpanded parameter packs here, but that would,
9322   // in turn, make the block expression contain unexpanded parameter packs.
9323   if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
9324     // Drop the parameters.
9325     FunctionProtoType::ExtProtoInfo EPI;
9326     EPI.HasTrailingReturn = false;
9327     EPI.TypeQuals |= DeclSpec::TQ_const;
9328     T = Context.getFunctionType(Context.DependentTy, /*Args=*/0, /*NumArgs=*/0,
9329                                 EPI);
9330     Sig = Context.getTrivialTypeSourceInfo(T);
9331   }
9332 
9333   // GetTypeForDeclarator always produces a function type for a block
9334   // literal signature.  Furthermore, it is always a FunctionProtoType
9335   // unless the function was written with a typedef.
9336   assert(T->isFunctionType() &&
9337          "GetTypeForDeclarator made a non-function block signature");
9338 
9339   // Look for an explicit signature in that function type.
9340   FunctionProtoTypeLoc ExplicitSignature;
9341 
9342   TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
9343   if (isa<FunctionProtoTypeLoc>(tmp)) {
9344     ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp);
9345 
9346     // Check whether that explicit signature was synthesized by
9347     // GetTypeForDeclarator.  If so, don't save that as part of the
9348     // written signature.
9349     if (ExplicitSignature.getLocalRangeBegin() ==
9350         ExplicitSignature.getLocalRangeEnd()) {
9351       // This would be much cheaper if we stored TypeLocs instead of
9352       // TypeSourceInfos.
9353       TypeLoc Result = ExplicitSignature.getResultLoc();
9354       unsigned Size = Result.getFullDataSize();
9355       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
9356       Sig->getTypeLoc().initializeFullCopy(Result, Size);
9357 
9358       ExplicitSignature = FunctionProtoTypeLoc();
9359     }
9360   }
9361 
9362   CurBlock->TheDecl->setSignatureAsWritten(Sig);
9363   CurBlock->FunctionType = T;
9364 
9365   const FunctionType *Fn = T->getAs<FunctionType>();
9366   QualType RetTy = Fn->getResultType();
9367   bool isVariadic =
9368     (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
9369 
9370   CurBlock->TheDecl->setIsVariadic(isVariadic);
9371 
9372   // Don't allow returning a objc interface by value.
9373   if (RetTy->isObjCObjectType()) {
9374     Diag(ParamInfo.getLocStart(),
9375          diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
9376     return;
9377   }
9378 
9379   // Context.DependentTy is used as a placeholder for a missing block
9380   // return type.  TODO:  what should we do with declarators like:
9381   //   ^ * { ... }
9382   // If the answer is "apply template argument deduction"....
9383   if (RetTy != Context.DependentTy) {
9384     CurBlock->ReturnType = RetTy;
9385     CurBlock->TheDecl->setBlockMissingReturnType(false);
9386     CurBlock->HasImplicitReturnType = false;
9387   }
9388 
9389   // Push block parameters from the declarator if we had them.
9390   SmallVector<ParmVarDecl*, 8> Params;
9391   if (ExplicitSignature) {
9392     for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
9393       ParmVarDecl *Param = ExplicitSignature.getArg(I);
9394       if (Param->getIdentifier() == 0 &&
9395           !Param->isImplicit() &&
9396           !Param->isInvalidDecl() &&
9397           !getLangOpts().CPlusPlus)
9398         Diag(Param->getLocation(), diag::err_parameter_name_omitted);
9399       Params.push_back(Param);
9400     }
9401 
9402   // Fake up parameter variables if we have a typedef, like
9403   //   ^ fntype { ... }
9404   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
9405     for (FunctionProtoType::arg_type_iterator
9406            I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
9407       ParmVarDecl *Param =
9408         BuildParmVarDeclForTypedef(CurBlock->TheDecl,
9409                                    ParamInfo.getLocStart(),
9410                                    *I);
9411       Params.push_back(Param);
9412     }
9413   }
9414 
9415   // Set the parameters on the block decl.
9416   if (!Params.empty()) {
9417     CurBlock->TheDecl->setParams(Params);
9418     CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
9419                              CurBlock->TheDecl->param_end(),
9420                              /*CheckParameterNames=*/false);
9421   }
9422 
9423   // Finally we can process decl attributes.
9424   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
9425 
9426   // Put the parameter variables in scope.  We can bail out immediately
9427   // if we don't have any.
9428   if (Params.empty())
9429     return;
9430 
9431   for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
9432          E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
9433     (*AI)->setOwningFunction(CurBlock->TheDecl);
9434 
9435     // If this has an identifier, add it to the scope stack.
9436     if ((*AI)->getIdentifier()) {
9437       CheckShadow(CurBlock->TheScope, *AI);
9438 
9439       PushOnScopeChains(*AI, CurBlock->TheScope);
9440     }
9441   }
9442 }
9443 
9444 /// ActOnBlockError - If there is an error parsing a block, this callback
9445 /// is invoked to pop the information about the block from the action impl.
9446 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
9447   // Leave the expression-evaluation context.
9448   DiscardCleanupsInEvaluationContext();
9449   PopExpressionEvaluationContext();
9450 
9451   // Pop off CurBlock, handle nested blocks.
9452   PopDeclContext();
9453   PopFunctionScopeInfo();
9454 }
9455 
9456 /// ActOnBlockStmtExpr - This is called when the body of a block statement
9457 /// literal was successfully completed.  ^(int x){...}
9458 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
9459                                     Stmt *Body, Scope *CurScope) {
9460   // If blocks are disabled, emit an error.
9461   if (!LangOpts.Blocks)
9462     Diag(CaretLoc, diag::err_blocks_disable);
9463 
9464   // Leave the expression-evaluation context.
9465   if (hasAnyUnrecoverableErrorsInThisFunction())
9466     DiscardCleanupsInEvaluationContext();
9467   assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!");
9468   PopExpressionEvaluationContext();
9469 
9470   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
9471 
9472   if (BSI->HasImplicitReturnType)
9473     deduceClosureReturnType(*BSI);
9474 
9475   PopDeclContext();
9476 
9477   QualType RetTy = Context.VoidTy;
9478   if (!BSI->ReturnType.isNull())
9479     RetTy = BSI->ReturnType;
9480 
9481   bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
9482   QualType BlockTy;
9483 
9484   // Set the captured variables on the block.
9485   // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
9486   SmallVector<BlockDecl::Capture, 4> Captures;
9487   for (unsigned i = 0, e = BSI->Captures.size(); i != e; i++) {
9488     CapturingScopeInfo::Capture &Cap = BSI->Captures[i];
9489     if (Cap.isThisCapture())
9490       continue;
9491     BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
9492                               Cap.isNested(), Cap.getCopyExpr());
9493     Captures.push_back(NewCap);
9494   }
9495   BSI->TheDecl->setCaptures(Context, Captures.begin(), Captures.end(),
9496                             BSI->CXXThisCaptureIndex != 0);
9497 
9498   // If the user wrote a function type in some form, try to use that.
9499   if (!BSI->FunctionType.isNull()) {
9500     const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
9501 
9502     FunctionType::ExtInfo Ext = FTy->getExtInfo();
9503     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
9504 
9505     // Turn protoless block types into nullary block types.
9506     if (isa<FunctionNoProtoType>(FTy)) {
9507       FunctionProtoType::ExtProtoInfo EPI;
9508       EPI.ExtInfo = Ext;
9509       BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
9510 
9511     // Otherwise, if we don't need to change anything about the function type,
9512     // preserve its sugar structure.
9513     } else if (FTy->getResultType() == RetTy &&
9514                (!NoReturn || FTy->getNoReturnAttr())) {
9515       BlockTy = BSI->FunctionType;
9516 
9517     // Otherwise, make the minimal modifications to the function type.
9518     } else {
9519       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
9520       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9521       EPI.TypeQuals = 0; // FIXME: silently?
9522       EPI.ExtInfo = Ext;
9523       BlockTy = Context.getFunctionType(RetTy,
9524                                         FPT->arg_type_begin(),
9525                                         FPT->getNumArgs(),
9526                                         EPI);
9527     }
9528 
9529   // If we don't have a function type, just build one from nothing.
9530   } else {
9531     FunctionProtoType::ExtProtoInfo EPI;
9532     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
9533     BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
9534   }
9535 
9536   DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
9537                            BSI->TheDecl->param_end());
9538   BlockTy = Context.getBlockPointerType(BlockTy);
9539 
9540   // If needed, diagnose invalid gotos and switches in the block.
9541   if (getCurFunction()->NeedsScopeChecking() &&
9542       !hasAnyUnrecoverableErrorsInThisFunction() &&
9543       !PP.isCodeCompletionEnabled())
9544     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
9545 
9546   BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
9547 
9548   // Try to apply the named return value optimization. We have to check again
9549   // if we can do this, though, because blocks keep return statements around
9550   // to deduce an implicit return type.
9551   if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
9552       !BSI->TheDecl->isDependentContext())
9553     computeNRVO(Body, getCurBlock());
9554 
9555   BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
9556   const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy();
9557   PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
9558 
9559   // If the block isn't obviously global, i.e. it captures anything at
9560   // all, then we need to do a few things in the surrounding context:
9561   if (Result->getBlockDecl()->hasCaptures()) {
9562     // First, this expression has a new cleanup object.
9563     ExprCleanupObjects.push_back(Result->getBlockDecl());
9564     ExprNeedsCleanups = true;
9565 
9566     // It also gets a branch-protected scope if any of the captured
9567     // variables needs destruction.
9568     for (BlockDecl::capture_const_iterator
9569            ci = Result->getBlockDecl()->capture_begin(),
9570            ce = Result->getBlockDecl()->capture_end(); ci != ce; ++ci) {
9571       const VarDecl *var = ci->getVariable();
9572       if (var->getType().isDestructedType() != QualType::DK_none) {
9573         getCurFunction()->setHasBranchProtectedScope();
9574         break;
9575       }
9576     }
9577   }
9578 
9579   return Owned(Result);
9580 }
9581 
9582 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
9583                                         Expr *E, ParsedType Ty,
9584                                         SourceLocation RPLoc) {
9585   TypeSourceInfo *TInfo;
9586   GetTypeFromParser(Ty, &TInfo);
9587   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
9588 }
9589 
9590 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
9591                                 Expr *E, TypeSourceInfo *TInfo,
9592                                 SourceLocation RPLoc) {
9593   Expr *OrigExpr = E;
9594 
9595   // Get the va_list type
9596   QualType VaListType = Context.getBuiltinVaListType();
9597   if (VaListType->isArrayType()) {
9598     // Deal with implicit array decay; for example, on x86-64,
9599     // va_list is an array, but it's supposed to decay to
9600     // a pointer for va_arg.
9601     VaListType = Context.getArrayDecayedType(VaListType);
9602     // Make sure the input expression also decays appropriately.
9603     ExprResult Result = UsualUnaryConversions(E);
9604     if (Result.isInvalid())
9605       return ExprError();
9606     E = Result.take();
9607   } else {
9608     // Otherwise, the va_list argument must be an l-value because
9609     // it is modified by va_arg.
9610     if (!E->isTypeDependent() &&
9611         CheckForModifiableLvalue(E, BuiltinLoc, *this))
9612       return ExprError();
9613   }
9614 
9615   if (!E->isTypeDependent() &&
9616       !Context.hasSameType(VaListType, E->getType())) {
9617     return ExprError(Diag(E->getLocStart(),
9618                          diag::err_first_argument_to_va_arg_not_of_type_va_list)
9619       << OrigExpr->getType() << E->getSourceRange());
9620   }
9621 
9622   if (!TInfo->getType()->isDependentType()) {
9623     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
9624                             diag::err_second_parameter_to_va_arg_incomplete,
9625                             TInfo->getTypeLoc()))
9626       return ExprError();
9627 
9628     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
9629                                TInfo->getType(),
9630                                diag::err_second_parameter_to_va_arg_abstract,
9631                                TInfo->getTypeLoc()))
9632       return ExprError();
9633 
9634     if (!TInfo->getType().isPODType(Context)) {
9635       Diag(TInfo->getTypeLoc().getBeginLoc(),
9636            TInfo->getType()->isObjCLifetimeType()
9637              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
9638              : diag::warn_second_parameter_to_va_arg_not_pod)
9639         << TInfo->getType()
9640         << TInfo->getTypeLoc().getSourceRange();
9641     }
9642 
9643     // Check for va_arg where arguments of the given type will be promoted
9644     // (i.e. this va_arg is guaranteed to have undefined behavior).
9645     QualType PromoteType;
9646     if (TInfo->getType()->isPromotableIntegerType()) {
9647       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
9648       if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
9649         PromoteType = QualType();
9650     }
9651     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
9652       PromoteType = Context.DoubleTy;
9653     if (!PromoteType.isNull())
9654       Diag(TInfo->getTypeLoc().getBeginLoc(),
9655           diag::warn_second_parameter_to_va_arg_never_compatible)
9656         << TInfo->getType()
9657         << PromoteType
9658         << TInfo->getTypeLoc().getSourceRange();
9659   }
9660 
9661   QualType T = TInfo->getType().getNonLValueExprType(Context);
9662   return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
9663 }
9664 
9665 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
9666   // The type of __null will be int or long, depending on the size of
9667   // pointers on the target.
9668   QualType Ty;
9669   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
9670   if (pw == Context.getTargetInfo().getIntWidth())
9671     Ty = Context.IntTy;
9672   else if (pw == Context.getTargetInfo().getLongWidth())
9673     Ty = Context.LongTy;
9674   else if (pw == Context.getTargetInfo().getLongLongWidth())
9675     Ty = Context.LongLongTy;
9676   else {
9677     llvm_unreachable("I don't know size of pointer!");
9678   }
9679 
9680   return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
9681 }
9682 
9683 static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
9684                                            Expr *SrcExpr, FixItHint &Hint) {
9685   if (!SemaRef.getLangOpts().ObjC1)
9686     return;
9687 
9688   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
9689   if (!PT)
9690     return;
9691 
9692   // Check if the destination is of type 'id'.
9693   if (!PT->isObjCIdType()) {
9694     // Check if the destination is the 'NSString' interface.
9695     const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
9696     if (!ID || !ID->getIdentifier()->isStr("NSString"))
9697       return;
9698   }
9699 
9700   // Ignore any parens, implicit casts (should only be
9701   // array-to-pointer decays), and not-so-opaque values.  The last is
9702   // important for making this trigger for property assignments.
9703   SrcExpr = SrcExpr->IgnoreParenImpCasts();
9704   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
9705     if (OV->getSourceExpr())
9706       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
9707 
9708   StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
9709   if (!SL || !SL->isAscii())
9710     return;
9711 
9712   Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
9713 }
9714 
9715 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
9716                                     SourceLocation Loc,
9717                                     QualType DstType, QualType SrcType,
9718                                     Expr *SrcExpr, AssignmentAction Action,
9719                                     bool *Complained) {
9720   if (Complained)
9721     *Complained = false;
9722 
9723   // Decode the result (notice that AST's are still created for extensions).
9724   bool CheckInferredResultType = false;
9725   bool isInvalid = false;
9726   unsigned DiagKind = 0;
9727   FixItHint Hint;
9728   ConversionFixItGenerator ConvHints;
9729   bool MayHaveConvFixit = false;
9730   bool MayHaveFunctionDiff = false;
9731 
9732   switch (ConvTy) {
9733   case Compatible:
9734       DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
9735       return false;
9736 
9737   case PointerToInt:
9738     DiagKind = diag::ext_typecheck_convert_pointer_int;
9739     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9740     MayHaveConvFixit = true;
9741     break;
9742   case IntToPointer:
9743     DiagKind = diag::ext_typecheck_convert_int_pointer;
9744     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9745     MayHaveConvFixit = true;
9746     break;
9747   case IncompatiblePointer:
9748     MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
9749     DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
9750     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
9751       SrcType->isObjCObjectPointerType();
9752     if (Hint.isNull() && !CheckInferredResultType) {
9753       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9754     }
9755     MayHaveConvFixit = true;
9756     break;
9757   case IncompatiblePointerSign:
9758     DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
9759     break;
9760   case FunctionVoidPointer:
9761     DiagKind = diag::ext_typecheck_convert_pointer_void_func;
9762     break;
9763   case IncompatiblePointerDiscardsQualifiers: {
9764     // Perform array-to-pointer decay if necessary.
9765     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
9766 
9767     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
9768     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
9769     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
9770       DiagKind = diag::err_typecheck_incompatible_address_space;
9771       break;
9772 
9773 
9774     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
9775       DiagKind = diag::err_typecheck_incompatible_ownership;
9776       break;
9777     }
9778 
9779     llvm_unreachable("unknown error case for discarding qualifiers!");
9780     // fallthrough
9781   }
9782   case CompatiblePointerDiscardsQualifiers:
9783     // If the qualifiers lost were because we were applying the
9784     // (deprecated) C++ conversion from a string literal to a char*
9785     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
9786     // Ideally, this check would be performed in
9787     // checkPointerTypesForAssignment. However, that would require a
9788     // bit of refactoring (so that the second argument is an
9789     // expression, rather than a type), which should be done as part
9790     // of a larger effort to fix checkPointerTypesForAssignment for
9791     // C++ semantics.
9792     if (getLangOpts().CPlusPlus &&
9793         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
9794       return false;
9795     DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
9796     break;
9797   case IncompatibleNestedPointerQualifiers:
9798     DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
9799     break;
9800   case IntToBlockPointer:
9801     DiagKind = diag::err_int_to_block_pointer;
9802     break;
9803   case IncompatibleBlockPointer:
9804     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
9805     break;
9806   case IncompatibleObjCQualifiedId:
9807     // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
9808     // it can give a more specific diagnostic.
9809     DiagKind = diag::warn_incompatible_qualified_id;
9810     break;
9811   case IncompatibleVectors:
9812     DiagKind = diag::warn_incompatible_vectors;
9813     break;
9814   case IncompatibleObjCWeakRef:
9815     DiagKind = diag::err_arc_weak_unavailable_assign;
9816     break;
9817   case Incompatible:
9818     DiagKind = diag::err_typecheck_convert_incompatible;
9819     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9820     MayHaveConvFixit = true;
9821     isInvalid = true;
9822     MayHaveFunctionDiff = true;
9823     break;
9824   }
9825 
9826   QualType FirstType, SecondType;
9827   switch (Action) {
9828   case AA_Assigning:
9829   case AA_Initializing:
9830     // The destination type comes first.
9831     FirstType = DstType;
9832     SecondType = SrcType;
9833     break;
9834 
9835   case AA_Returning:
9836   case AA_Passing:
9837   case AA_Converting:
9838   case AA_Sending:
9839   case AA_Casting:
9840     // The source type comes first.
9841     FirstType = SrcType;
9842     SecondType = DstType;
9843     break;
9844   }
9845 
9846   PartialDiagnostic FDiag = PDiag(DiagKind);
9847   FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
9848 
9849   // If we can fix the conversion, suggest the FixIts.
9850   assert(ConvHints.isNull() || Hint.isNull());
9851   if (!ConvHints.isNull()) {
9852     for (std::vector<FixItHint>::iterator HI = ConvHints.Hints.begin(),
9853          HE = ConvHints.Hints.end(); HI != HE; ++HI)
9854       FDiag << *HI;
9855   } else {
9856     FDiag << Hint;
9857   }
9858   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
9859 
9860   if (MayHaveFunctionDiff)
9861     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
9862 
9863   Diag(Loc, FDiag);
9864 
9865   if (SecondType == Context.OverloadTy)
9866     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
9867                               FirstType);
9868 
9869   if (CheckInferredResultType)
9870     EmitRelatedResultTypeNote(SrcExpr);
9871 
9872   if (Complained)
9873     *Complained = true;
9874   return isInvalid;
9875 }
9876 
9877 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
9878                                                  llvm::APSInt *Result) {
9879   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
9880   public:
9881     virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
9882       S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
9883     }
9884   } Diagnoser;
9885 
9886   return VerifyIntegerConstantExpression(E, Result, Diagnoser);
9887 }
9888 
9889 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
9890                                                  llvm::APSInt *Result,
9891                                                  unsigned DiagID,
9892                                                  bool AllowFold) {
9893   class IDDiagnoser : public VerifyICEDiagnoser {
9894     unsigned DiagID;
9895 
9896   public:
9897     IDDiagnoser(unsigned DiagID)
9898       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
9899 
9900     virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
9901       S.Diag(Loc, DiagID) << SR;
9902     }
9903   } Diagnoser(DiagID);
9904 
9905   return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
9906 }
9907 
9908 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
9909                                             SourceRange SR) {
9910   S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
9911 }
9912 
9913 ExprResult
9914 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
9915                                       VerifyICEDiagnoser &Diagnoser,
9916                                       bool AllowFold) {
9917   SourceLocation DiagLoc = E->getLocStart();
9918 
9919   if (getLangOpts().CPlusPlus0x) {
9920     // C++11 [expr.const]p5:
9921     //   If an expression of literal class type is used in a context where an
9922     //   integral constant expression is required, then that class type shall
9923     //   have a single non-explicit conversion function to an integral or
9924     //   unscoped enumeration type
9925     ExprResult Converted;
9926     if (!Diagnoser.Suppress) {
9927       class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
9928       public:
9929         CXX11ConvertDiagnoser() : ICEConvertDiagnoser(false, true) { }
9930 
9931         virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
9932                                                  QualType T) {
9933           return S.Diag(Loc, diag::err_ice_not_integral) << T;
9934         }
9935 
9936         virtual DiagnosticBuilder diagnoseIncomplete(Sema &S,
9937                                                      SourceLocation Loc,
9938                                                      QualType T) {
9939           return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
9940         }
9941 
9942         virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S,
9943                                                        SourceLocation Loc,
9944                                                        QualType T,
9945                                                        QualType ConvTy) {
9946           return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
9947         }
9948 
9949         virtual DiagnosticBuilder noteExplicitConv(Sema &S,
9950                                                    CXXConversionDecl *Conv,
9951                                                    QualType ConvTy) {
9952           return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
9953                    << ConvTy->isEnumeralType() << ConvTy;
9954         }
9955 
9956         virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
9957                                                     QualType T) {
9958           return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
9959         }
9960 
9961         virtual DiagnosticBuilder noteAmbiguous(Sema &S,
9962                                                 CXXConversionDecl *Conv,
9963                                                 QualType ConvTy) {
9964           return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
9965                    << ConvTy->isEnumeralType() << ConvTy;
9966         }
9967 
9968         virtual DiagnosticBuilder diagnoseConversion(Sema &S,
9969                                                      SourceLocation Loc,
9970                                                      QualType T,
9971                                                      QualType ConvTy) {
9972           return DiagnosticBuilder::getEmpty();
9973         }
9974       } ConvertDiagnoser;
9975 
9976       Converted = ConvertToIntegralOrEnumerationType(DiagLoc, E,
9977                                                      ConvertDiagnoser,
9978                                              /*AllowScopedEnumerations*/ false);
9979     } else {
9980       // The caller wants to silently enquire whether this is an ICE. Don't
9981       // produce any diagnostics if it isn't.
9982       class SilentICEConvertDiagnoser : public ICEConvertDiagnoser {
9983       public:
9984         SilentICEConvertDiagnoser() : ICEConvertDiagnoser(true, true) { }
9985 
9986         virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
9987                                                  QualType T) {
9988           return DiagnosticBuilder::getEmpty();
9989         }
9990 
9991         virtual DiagnosticBuilder diagnoseIncomplete(Sema &S,
9992                                                      SourceLocation Loc,
9993                                                      QualType T) {
9994           return DiagnosticBuilder::getEmpty();
9995         }
9996 
9997         virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S,
9998                                                        SourceLocation Loc,
9999                                                        QualType T,
10000                                                        QualType ConvTy) {
10001           return DiagnosticBuilder::getEmpty();
10002         }
10003 
10004         virtual DiagnosticBuilder noteExplicitConv(Sema &S,
10005                                                    CXXConversionDecl *Conv,
10006                                                    QualType ConvTy) {
10007           return DiagnosticBuilder::getEmpty();
10008         }
10009 
10010         virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
10011                                                     QualType T) {
10012           return DiagnosticBuilder::getEmpty();
10013         }
10014 
10015         virtual DiagnosticBuilder noteAmbiguous(Sema &S,
10016                                                 CXXConversionDecl *Conv,
10017                                                 QualType ConvTy) {
10018           return DiagnosticBuilder::getEmpty();
10019         }
10020 
10021         virtual DiagnosticBuilder diagnoseConversion(Sema &S,
10022                                                      SourceLocation Loc,
10023                                                      QualType T,
10024                                                      QualType ConvTy) {
10025           return DiagnosticBuilder::getEmpty();
10026         }
10027       } ConvertDiagnoser;
10028 
10029       Converted = ConvertToIntegralOrEnumerationType(DiagLoc, E,
10030                                                      ConvertDiagnoser, false);
10031     }
10032     if (Converted.isInvalid())
10033       return Converted;
10034     E = Converted.take();
10035     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
10036       return ExprError();
10037   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
10038     // An ICE must be of integral or unscoped enumeration type.
10039     if (!Diagnoser.Suppress)
10040       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
10041     return ExprError();
10042   }
10043 
10044   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
10045   // in the non-ICE case.
10046   if (!getLangOpts().CPlusPlus0x && E->isIntegerConstantExpr(Context)) {
10047     if (Result)
10048       *Result = E->EvaluateKnownConstInt(Context);
10049     return Owned(E);
10050   }
10051 
10052   Expr::EvalResult EvalResult;
10053   llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
10054   EvalResult.Diag = &Notes;
10055 
10056   // Try to evaluate the expression, and produce diagnostics explaining why it's
10057   // not a constant expression as a side-effect.
10058   bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
10059                 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
10060 
10061   // In C++11, we can rely on diagnostics being produced for any expression
10062   // which is not a constant expression. If no diagnostics were produced, then
10063   // this is a constant expression.
10064   if (Folded && getLangOpts().CPlusPlus0x && Notes.empty()) {
10065     if (Result)
10066       *Result = EvalResult.Val.getInt();
10067     return Owned(E);
10068   }
10069 
10070   // If our only note is the usual "invalid subexpression" note, just point
10071   // the caret at its location rather than producing an essentially
10072   // redundant note.
10073   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
10074         diag::note_invalid_subexpr_in_const_expr) {
10075     DiagLoc = Notes[0].first;
10076     Notes.clear();
10077   }
10078 
10079   if (!Folded || !AllowFold) {
10080     if (!Diagnoser.Suppress) {
10081       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
10082       for (unsigned I = 0, N = Notes.size(); I != N; ++I)
10083         Diag(Notes[I].first, Notes[I].second);
10084     }
10085 
10086     return ExprError();
10087   }
10088 
10089   Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
10090   for (unsigned I = 0, N = Notes.size(); I != N; ++I)
10091     Diag(Notes[I].first, Notes[I].second);
10092 
10093   if (Result)
10094     *Result = EvalResult.Val.getInt();
10095   return Owned(E);
10096 }
10097 
10098 namespace {
10099   // Handle the case where we conclude a expression which we speculatively
10100   // considered to be unevaluated is actually evaluated.
10101   class TransformToPE : public TreeTransform<TransformToPE> {
10102     typedef TreeTransform<TransformToPE> BaseTransform;
10103 
10104   public:
10105     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
10106 
10107     // Make sure we redo semantic analysis
10108     bool AlwaysRebuild() { return true; }
10109 
10110     // Make sure we handle LabelStmts correctly.
10111     // FIXME: This does the right thing, but maybe we need a more general
10112     // fix to TreeTransform?
10113     StmtResult TransformLabelStmt(LabelStmt *S) {
10114       S->getDecl()->setStmt(0);
10115       return BaseTransform::TransformLabelStmt(S);
10116     }
10117 
10118     // We need to special-case DeclRefExprs referring to FieldDecls which
10119     // are not part of a member pointer formation; normal TreeTransforming
10120     // doesn't catch this case because of the way we represent them in the AST.
10121     // FIXME: This is a bit ugly; is it really the best way to handle this
10122     // case?
10123     //
10124     // Error on DeclRefExprs referring to FieldDecls.
10125     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
10126       if (isa<FieldDecl>(E->getDecl()) &&
10127           !SemaRef.isUnevaluatedContext())
10128         return SemaRef.Diag(E->getLocation(),
10129                             diag::err_invalid_non_static_member_use)
10130             << E->getDecl() << E->getSourceRange();
10131 
10132       return BaseTransform::TransformDeclRefExpr(E);
10133     }
10134 
10135     // Exception: filter out member pointer formation
10136     ExprResult TransformUnaryOperator(UnaryOperator *E) {
10137       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
10138         return E;
10139 
10140       return BaseTransform::TransformUnaryOperator(E);
10141     }
10142 
10143     ExprResult TransformLambdaExpr(LambdaExpr *E) {
10144       // Lambdas never need to be transformed.
10145       return E;
10146     }
10147   };
10148 }
10149 
10150 ExprResult Sema::TranformToPotentiallyEvaluated(Expr *E) {
10151   assert(ExprEvalContexts.back().Context == Unevaluated &&
10152          "Should only transform unevaluated expressions");
10153   ExprEvalContexts.back().Context =
10154       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
10155   if (ExprEvalContexts.back().Context == Unevaluated)
10156     return E;
10157   return TransformToPE(*this).TransformExpr(E);
10158 }
10159 
10160 void
10161 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
10162                                       Decl *LambdaContextDecl,
10163                                       bool IsDecltype) {
10164   ExprEvalContexts.push_back(
10165              ExpressionEvaluationContextRecord(NewContext,
10166                                                ExprCleanupObjects.size(),
10167                                                ExprNeedsCleanups,
10168                                                LambdaContextDecl,
10169                                                IsDecltype));
10170   ExprNeedsCleanups = false;
10171   if (!MaybeODRUseExprs.empty())
10172     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
10173 }
10174 
10175 void
10176 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
10177                                       ReuseLambdaContextDecl_t,
10178                                       bool IsDecltype) {
10179   Decl *LambdaContextDecl = ExprEvalContexts.back().LambdaContextDecl;
10180   PushExpressionEvaluationContext(NewContext, LambdaContextDecl, IsDecltype);
10181 }
10182 
10183 void Sema::PopExpressionEvaluationContext() {
10184   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
10185 
10186   if (!Rec.Lambdas.empty()) {
10187     if (Rec.Context == Unevaluated) {
10188       // C++11 [expr.prim.lambda]p2:
10189       //   A lambda-expression shall not appear in an unevaluated operand
10190       //   (Clause 5).
10191       for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I)
10192         Diag(Rec.Lambdas[I]->getLocStart(),
10193              diag::err_lambda_unevaluated_operand);
10194     } else {
10195       // Mark the capture expressions odr-used. This was deferred
10196       // during lambda expression creation.
10197       for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I) {
10198         LambdaExpr *Lambda = Rec.Lambdas[I];
10199         for (LambdaExpr::capture_init_iterator
10200                   C = Lambda->capture_init_begin(),
10201                CEnd = Lambda->capture_init_end();
10202              C != CEnd; ++C) {
10203           MarkDeclarationsReferencedInExpr(*C);
10204         }
10205       }
10206     }
10207   }
10208 
10209   // When are coming out of an unevaluated context, clear out any
10210   // temporaries that we may have created as part of the evaluation of
10211   // the expression in that context: they aren't relevant because they
10212   // will never be constructed.
10213   if (Rec.Context == Unevaluated || Rec.Context == ConstantEvaluated) {
10214     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
10215                              ExprCleanupObjects.end());
10216     ExprNeedsCleanups = Rec.ParentNeedsCleanups;
10217     CleanupVarDeclMarking();
10218     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
10219   // Otherwise, merge the contexts together.
10220   } else {
10221     ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
10222     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
10223                             Rec.SavedMaybeODRUseExprs.end());
10224   }
10225 
10226   // Pop the current expression evaluation context off the stack.
10227   ExprEvalContexts.pop_back();
10228 }
10229 
10230 void Sema::DiscardCleanupsInEvaluationContext() {
10231   ExprCleanupObjects.erase(
10232          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
10233          ExprCleanupObjects.end());
10234   ExprNeedsCleanups = false;
10235   MaybeODRUseExprs.clear();
10236 }
10237 
10238 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
10239   if (!E->getType()->isVariablyModifiedType())
10240     return E;
10241   return TranformToPotentiallyEvaluated(E);
10242 }
10243 
10244 static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) {
10245   // Do not mark anything as "used" within a dependent context; wait for
10246   // an instantiation.
10247   if (SemaRef.CurContext->isDependentContext())
10248     return false;
10249 
10250   switch (SemaRef.ExprEvalContexts.back().Context) {
10251     case Sema::Unevaluated:
10252       // We are in an expression that is not potentially evaluated; do nothing.
10253       // (Depending on how you read the standard, we actually do need to do
10254       // something here for null pointer constants, but the standard's
10255       // definition of a null pointer constant is completely crazy.)
10256       return false;
10257 
10258     case Sema::ConstantEvaluated:
10259     case Sema::PotentiallyEvaluated:
10260       // We are in a potentially evaluated expression (or a constant-expression
10261       // in C++03); we need to do implicit template instantiation, implicitly
10262       // define class members, and mark most declarations as used.
10263       return true;
10264 
10265     case Sema::PotentiallyEvaluatedIfUsed:
10266       // Referenced declarations will only be used if the construct in the
10267       // containing expression is used.
10268       return false;
10269   }
10270   llvm_unreachable("Invalid context");
10271 }
10272 
10273 /// \brief Mark a function referenced, and check whether it is odr-used
10274 /// (C++ [basic.def.odr]p2, C99 6.9p3)
10275 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func) {
10276   assert(Func && "No function?");
10277 
10278   Func->setReferenced();
10279 
10280   // Don't mark this function as used multiple times, unless it's a constexpr
10281   // function which we need to instantiate.
10282   if (Func->isUsed(false) &&
10283       !(Func->isConstexpr() && !Func->getBody() &&
10284         Func->isImplicitlyInstantiable()))
10285     return;
10286 
10287   if (!IsPotentiallyEvaluatedContext(*this))
10288     return;
10289 
10290   // Note that this declaration has been used.
10291   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
10292     if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
10293       if (Constructor->isDefaultConstructor()) {
10294         if (Constructor->isTrivial())
10295           return;
10296         if (!Constructor->isUsed(false))
10297           DefineImplicitDefaultConstructor(Loc, Constructor);
10298       } else if (Constructor->isCopyConstructor()) {
10299         if (!Constructor->isUsed(false))
10300           DefineImplicitCopyConstructor(Loc, Constructor);
10301       } else if (Constructor->isMoveConstructor()) {
10302         if (!Constructor->isUsed(false))
10303           DefineImplicitMoveConstructor(Loc, Constructor);
10304       }
10305     }
10306 
10307     MarkVTableUsed(Loc, Constructor->getParent());
10308   } else if (CXXDestructorDecl *Destructor =
10309                  dyn_cast<CXXDestructorDecl>(Func)) {
10310     if (Destructor->isDefaulted() && !Destructor->isDeleted() &&
10311         !Destructor->isUsed(false))
10312       DefineImplicitDestructor(Loc, Destructor);
10313     if (Destructor->isVirtual())
10314       MarkVTableUsed(Loc, Destructor->getParent());
10315   } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
10316     if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted() &&
10317         MethodDecl->isOverloadedOperator() &&
10318         MethodDecl->getOverloadedOperator() == OO_Equal) {
10319       if (!MethodDecl->isUsed(false)) {
10320         if (MethodDecl->isCopyAssignmentOperator())
10321           DefineImplicitCopyAssignment(Loc, MethodDecl);
10322         else
10323           DefineImplicitMoveAssignment(Loc, MethodDecl);
10324       }
10325     } else if (isa<CXXConversionDecl>(MethodDecl) &&
10326                MethodDecl->getParent()->isLambda()) {
10327       CXXConversionDecl *Conversion = cast<CXXConversionDecl>(MethodDecl);
10328       if (Conversion->isLambdaToBlockPointerConversion())
10329         DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
10330       else
10331         DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
10332     } else if (MethodDecl->isVirtual())
10333       MarkVTableUsed(Loc, MethodDecl->getParent());
10334   }
10335 
10336   // Recursive functions should be marked when used from another function.
10337   // FIXME: Is this really right?
10338   if (CurContext == Func) return;
10339 
10340   // Resolve the exception specification for any function which is
10341   // used: CodeGen will need it.
10342   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
10343   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
10344     ResolveExceptionSpec(Loc, FPT);
10345 
10346   // Implicit instantiation of function templates and member functions of
10347   // class templates.
10348   if (Func->isImplicitlyInstantiable()) {
10349     bool AlreadyInstantiated = false;
10350     SourceLocation PointOfInstantiation = Loc;
10351     if (FunctionTemplateSpecializationInfo *SpecInfo
10352                               = Func->getTemplateSpecializationInfo()) {
10353       if (SpecInfo->getPointOfInstantiation().isInvalid())
10354         SpecInfo->setPointOfInstantiation(Loc);
10355       else if (SpecInfo->getTemplateSpecializationKind()
10356                  == TSK_ImplicitInstantiation) {
10357         AlreadyInstantiated = true;
10358         PointOfInstantiation = SpecInfo->getPointOfInstantiation();
10359       }
10360     } else if (MemberSpecializationInfo *MSInfo
10361                                 = Func->getMemberSpecializationInfo()) {
10362       if (MSInfo->getPointOfInstantiation().isInvalid())
10363         MSInfo->setPointOfInstantiation(Loc);
10364       else if (MSInfo->getTemplateSpecializationKind()
10365                  == TSK_ImplicitInstantiation) {
10366         AlreadyInstantiated = true;
10367         PointOfInstantiation = MSInfo->getPointOfInstantiation();
10368       }
10369     }
10370 
10371     if (!AlreadyInstantiated || Func->isConstexpr()) {
10372       if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
10373           cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass())
10374         PendingLocalImplicitInstantiations.push_back(
10375             std::make_pair(Func, PointOfInstantiation));
10376       else if (Func->isConstexpr())
10377         // Do not defer instantiations of constexpr functions, to avoid the
10378         // expression evaluator needing to call back into Sema if it sees a
10379         // call to such a function.
10380         InstantiateFunctionDefinition(PointOfInstantiation, Func);
10381       else {
10382         PendingInstantiations.push_back(std::make_pair(Func,
10383                                                        PointOfInstantiation));
10384         // Notify the consumer that a function was implicitly instantiated.
10385         Consumer.HandleCXXImplicitFunctionInstantiation(Func);
10386       }
10387     }
10388   } else {
10389     // Walk redefinitions, as some of them may be instantiable.
10390     for (FunctionDecl::redecl_iterator i(Func->redecls_begin()),
10391          e(Func->redecls_end()); i != e; ++i) {
10392       if (!i->isUsed(false) && i->isImplicitlyInstantiable())
10393         MarkFunctionReferenced(Loc, *i);
10394     }
10395   }
10396 
10397   // Keep track of used but undefined functions.
10398   if (!Func->isPure() && !Func->hasBody() &&
10399       Func->getLinkage() != ExternalLinkage) {
10400     SourceLocation &old = UndefinedInternals[Func->getCanonicalDecl()];
10401     if (old.isInvalid()) old = Loc;
10402   }
10403 
10404   Func->setUsed(true);
10405 }
10406 
10407 static void
10408 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
10409                                    VarDecl *var, DeclContext *DC) {
10410   DeclContext *VarDC = var->getDeclContext();
10411 
10412   //  If the parameter still belongs to the translation unit, then
10413   //  we're actually just using one parameter in the declaration of
10414   //  the next.
10415   if (isa<ParmVarDecl>(var) &&
10416       isa<TranslationUnitDecl>(VarDC))
10417     return;
10418 
10419   // For C code, don't diagnose about capture if we're not actually in code
10420   // right now; it's impossible to write a non-constant expression outside of
10421   // function context, so we'll get other (more useful) diagnostics later.
10422   //
10423   // For C++, things get a bit more nasty... it would be nice to suppress this
10424   // diagnostic for certain cases like using a local variable in an array bound
10425   // for a member of a local class, but the correct predicate is not obvious.
10426   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
10427     return;
10428 
10429   if (isa<CXXMethodDecl>(VarDC) &&
10430       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
10431     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda)
10432       << var->getIdentifier();
10433   } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) {
10434     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
10435       << var->getIdentifier() << fn->getDeclName();
10436   } else if (isa<BlockDecl>(VarDC)) {
10437     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block)
10438       << var->getIdentifier();
10439   } else {
10440     // FIXME: Is there any other context where a local variable can be
10441     // declared?
10442     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context)
10443       << var->getIdentifier();
10444   }
10445 
10446   S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
10447     << var->getIdentifier();
10448 
10449   // FIXME: Add additional diagnostic info about class etc. which prevents
10450   // capture.
10451 }
10452 
10453 /// \brief Capture the given variable in the given lambda expression.
10454 static ExprResult captureInLambda(Sema &S, LambdaScopeInfo *LSI,
10455                                   VarDecl *Var, QualType FieldType,
10456                                   QualType DeclRefType,
10457                                   SourceLocation Loc,
10458                                   bool RefersToEnclosingLocal) {
10459   CXXRecordDecl *Lambda = LSI->Lambda;
10460 
10461   // Build the non-static data member.
10462   FieldDecl *Field
10463     = FieldDecl::Create(S.Context, Lambda, Loc, Loc, 0, FieldType,
10464                         S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
10465                         0, false, ICIS_NoInit);
10466   Field->setImplicit(true);
10467   Field->setAccess(AS_private);
10468   Lambda->addDecl(Field);
10469 
10470   // C++11 [expr.prim.lambda]p21:
10471   //   When the lambda-expression is evaluated, the entities that
10472   //   are captured by copy are used to direct-initialize each
10473   //   corresponding non-static data member of the resulting closure
10474   //   object. (For array members, the array elements are
10475   //   direct-initialized in increasing subscript order.) These
10476   //   initializations are performed in the (unspecified) order in
10477   //   which the non-static data members are declared.
10478 
10479   // Introduce a new evaluation context for the initialization, so
10480   // that temporaries introduced as part of the capture are retained
10481   // to be re-"exported" from the lambda expression itself.
10482   S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
10483 
10484   // C++ [expr.prim.labda]p12:
10485   //   An entity captured by a lambda-expression is odr-used (3.2) in
10486   //   the scope containing the lambda-expression.
10487   Expr *Ref = new (S.Context) DeclRefExpr(Var, RefersToEnclosingLocal,
10488                                           DeclRefType, VK_LValue, Loc);
10489   Var->setReferenced(true);
10490   Var->setUsed(true);
10491 
10492   // When the field has array type, create index variables for each
10493   // dimension of the array. We use these index variables to subscript
10494   // the source array, and other clients (e.g., CodeGen) will perform
10495   // the necessary iteration with these index variables.
10496   SmallVector<VarDecl *, 4> IndexVariables;
10497   QualType BaseType = FieldType;
10498   QualType SizeType = S.Context.getSizeType();
10499   LSI->ArrayIndexStarts.push_back(LSI->ArrayIndexVars.size());
10500   while (const ConstantArrayType *Array
10501                         = S.Context.getAsConstantArrayType(BaseType)) {
10502     // Create the iteration variable for this array index.
10503     IdentifierInfo *IterationVarName = 0;
10504     {
10505       SmallString<8> Str;
10506       llvm::raw_svector_ostream OS(Str);
10507       OS << "__i" << IndexVariables.size();
10508       IterationVarName = &S.Context.Idents.get(OS.str());
10509     }
10510     VarDecl *IterationVar
10511       = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
10512                         IterationVarName, SizeType,
10513                         S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
10514                         SC_None, SC_None);
10515     IndexVariables.push_back(IterationVar);
10516     LSI->ArrayIndexVars.push_back(IterationVar);
10517 
10518     // Create a reference to the iteration variable.
10519     ExprResult IterationVarRef
10520       = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
10521     assert(!IterationVarRef.isInvalid() &&
10522            "Reference to invented variable cannot fail!");
10523     IterationVarRef = S.DefaultLvalueConversion(IterationVarRef.take());
10524     assert(!IterationVarRef.isInvalid() &&
10525            "Conversion of invented variable cannot fail!");
10526 
10527     // Subscript the array with this iteration variable.
10528     ExprResult Subscript = S.CreateBuiltinArraySubscriptExpr(
10529                              Ref, Loc, IterationVarRef.take(), Loc);
10530     if (Subscript.isInvalid()) {
10531       S.CleanupVarDeclMarking();
10532       S.DiscardCleanupsInEvaluationContext();
10533       S.PopExpressionEvaluationContext();
10534       return ExprError();
10535     }
10536 
10537     Ref = Subscript.take();
10538     BaseType = Array->getElementType();
10539   }
10540 
10541   // Construct the entity that we will be initializing. For an array, this
10542   // will be first element in the array, which may require several levels
10543   // of array-subscript entities.
10544   SmallVector<InitializedEntity, 4> Entities;
10545   Entities.reserve(1 + IndexVariables.size());
10546   Entities.push_back(
10547     InitializedEntity::InitializeLambdaCapture(Var, Field, Loc));
10548   for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
10549     Entities.push_back(InitializedEntity::InitializeElement(S.Context,
10550                                                             0,
10551                                                             Entities.back()));
10552 
10553   InitializationKind InitKind
10554     = InitializationKind::CreateDirect(Loc, Loc, Loc);
10555   InitializationSequence Init(S, Entities.back(), InitKind, &Ref, 1);
10556   ExprResult Result(true);
10557   if (!Init.Diagnose(S, Entities.back(), InitKind, &Ref, 1))
10558     Result = Init.Perform(S, Entities.back(), InitKind, Ref);
10559 
10560   // If this initialization requires any cleanups (e.g., due to a
10561   // default argument to a copy constructor), note that for the
10562   // lambda.
10563   if (S.ExprNeedsCleanups)
10564     LSI->ExprNeedsCleanups = true;
10565 
10566   // Exit the expression evaluation context used for the capture.
10567   S.CleanupVarDeclMarking();
10568   S.DiscardCleanupsInEvaluationContext();
10569   S.PopExpressionEvaluationContext();
10570   return Result;
10571 }
10572 
10573 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
10574                               TryCaptureKind Kind, SourceLocation EllipsisLoc,
10575                               bool BuildAndDiagnose,
10576                               QualType &CaptureType,
10577                               QualType &DeclRefType) {
10578   bool Nested = false;
10579 
10580   DeclContext *DC = CurContext;
10581   if (Var->getDeclContext() == DC) return true;
10582   if (!Var->hasLocalStorage()) return true;
10583 
10584   bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
10585 
10586   // Walk up the stack to determine whether we can capture the variable,
10587   // performing the "simple" checks that don't depend on type. We stop when
10588   // we've either hit the declared scope of the variable or find an existing
10589   // capture of that variable.
10590   CaptureType = Var->getType();
10591   DeclRefType = CaptureType.getNonReferenceType();
10592   bool Explicit = (Kind != TryCapture_Implicit);
10593   unsigned FunctionScopesIndex = FunctionScopes.size() - 1;
10594   do {
10595     // Only block literals and lambda expressions can capture; other
10596     // scopes don't work.
10597     DeclContext *ParentDC;
10598     if (isa<BlockDecl>(DC))
10599       ParentDC = DC->getParent();
10600     else if (isa<CXXMethodDecl>(DC) &&
10601              cast<CXXMethodDecl>(DC)->getOverloadedOperator() == OO_Call &&
10602              cast<CXXRecordDecl>(DC->getParent())->isLambda())
10603       ParentDC = DC->getParent()->getParent();
10604     else {
10605       if (BuildAndDiagnose)
10606         diagnoseUncapturableValueReference(*this, Loc, Var, DC);
10607       return true;
10608     }
10609 
10610     CapturingScopeInfo *CSI =
10611       cast<CapturingScopeInfo>(FunctionScopes[FunctionScopesIndex]);
10612 
10613     // Check whether we've already captured it.
10614     if (CSI->CaptureMap.count(Var)) {
10615       // If we found a capture, any subcaptures are nested.
10616       Nested = true;
10617 
10618       // Retrieve the capture type for this variable.
10619       CaptureType = CSI->getCapture(Var).getCaptureType();
10620 
10621       // Compute the type of an expression that refers to this variable.
10622       DeclRefType = CaptureType.getNonReferenceType();
10623 
10624       const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var);
10625       if (Cap.isCopyCapture() &&
10626           !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable))
10627         DeclRefType.addConst();
10628       break;
10629     }
10630 
10631     bool IsBlock = isa<BlockScopeInfo>(CSI);
10632     bool IsLambda = !IsBlock;
10633 
10634     // Lambdas are not allowed to capture unnamed variables
10635     // (e.g. anonymous unions).
10636     // FIXME: The C++11 rule don't actually state this explicitly, but I'm
10637     // assuming that's the intent.
10638     if (IsLambda && !Var->getDeclName()) {
10639       if (BuildAndDiagnose) {
10640         Diag(Loc, diag::err_lambda_capture_anonymous_var);
10641         Diag(Var->getLocation(), diag::note_declared_at);
10642       }
10643       return true;
10644     }
10645 
10646     // Prohibit variably-modified types; they're difficult to deal with.
10647     if (Var->getType()->isVariablyModifiedType()) {
10648       if (BuildAndDiagnose) {
10649         if (IsBlock)
10650           Diag(Loc, diag::err_ref_vm_type);
10651         else
10652           Diag(Loc, diag::err_lambda_capture_vm_type) << Var->getDeclName();
10653         Diag(Var->getLocation(), diag::note_previous_decl)
10654           << Var->getDeclName();
10655       }
10656       return true;
10657     }
10658 
10659     // Lambdas are not allowed to capture __block variables; they don't
10660     // support the expected semantics.
10661     if (IsLambda && HasBlocksAttr) {
10662       if (BuildAndDiagnose) {
10663         Diag(Loc, diag::err_lambda_capture_block)
10664           << Var->getDeclName();
10665         Diag(Var->getLocation(), diag::note_previous_decl)
10666           << Var->getDeclName();
10667       }
10668       return true;
10669     }
10670 
10671     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
10672       // No capture-default
10673       if (BuildAndDiagnose) {
10674         Diag(Loc, diag::err_lambda_impcap) << Var->getDeclName();
10675         Diag(Var->getLocation(), diag::note_previous_decl)
10676           << Var->getDeclName();
10677         Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
10678              diag::note_lambda_decl);
10679       }
10680       return true;
10681     }
10682 
10683     FunctionScopesIndex--;
10684     DC = ParentDC;
10685     Explicit = false;
10686   } while (!Var->getDeclContext()->Equals(DC));
10687 
10688   // Walk back down the scope stack, computing the type of the capture at
10689   // each step, checking type-specific requirements, and adding captures if
10690   // requested.
10691   for (unsigned I = ++FunctionScopesIndex, N = FunctionScopes.size(); I != N;
10692        ++I) {
10693     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
10694 
10695     // Compute the type of the capture and of a reference to the capture within
10696     // this scope.
10697     if (isa<BlockScopeInfo>(CSI)) {
10698       Expr *CopyExpr = 0;
10699       bool ByRef = false;
10700 
10701       // Blocks are not allowed to capture arrays.
10702       if (CaptureType->isArrayType()) {
10703         if (BuildAndDiagnose) {
10704           Diag(Loc, diag::err_ref_array_type);
10705           Diag(Var->getLocation(), diag::note_previous_decl)
10706           << Var->getDeclName();
10707         }
10708         return true;
10709       }
10710 
10711       // Forbid the block-capture of autoreleasing variables.
10712       if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
10713         if (BuildAndDiagnose) {
10714           Diag(Loc, diag::err_arc_autoreleasing_capture)
10715             << /*block*/ 0;
10716           Diag(Var->getLocation(), diag::note_previous_decl)
10717             << Var->getDeclName();
10718         }
10719         return true;
10720       }
10721 
10722       if (HasBlocksAttr || CaptureType->isReferenceType()) {
10723         // Block capture by reference does not change the capture or
10724         // declaration reference types.
10725         ByRef = true;
10726       } else {
10727         // Block capture by copy introduces 'const'.
10728         CaptureType = CaptureType.getNonReferenceType().withConst();
10729         DeclRefType = CaptureType;
10730 
10731         if (getLangOpts().CPlusPlus && BuildAndDiagnose) {
10732           if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
10733             // The capture logic needs the destructor, so make sure we mark it.
10734             // Usually this is unnecessary because most local variables have
10735             // their destructors marked at declaration time, but parameters are
10736             // an exception because it's technically only the call site that
10737             // actually requires the destructor.
10738             if (isa<ParmVarDecl>(Var))
10739               FinalizeVarWithDestructor(Var, Record);
10740 
10741             // According to the blocks spec, the capture of a variable from
10742             // the stack requires a const copy constructor.  This is not true
10743             // of the copy/move done to move a __block variable to the heap.
10744             Expr *DeclRef = new (Context) DeclRefExpr(Var, false,
10745                                                       DeclRefType.withConst(),
10746                                                       VK_LValue, Loc);
10747             ExprResult Result
10748               = PerformCopyInitialization(
10749                   InitializedEntity::InitializeBlock(Var->getLocation(),
10750                                                      CaptureType, false),
10751                   Loc, Owned(DeclRef));
10752 
10753             // Build a full-expression copy expression if initialization
10754             // succeeded and used a non-trivial constructor.  Recover from
10755             // errors by pretending that the copy isn't necessary.
10756             if (!Result.isInvalid() &&
10757                 !cast<CXXConstructExpr>(Result.get())->getConstructor()
10758                    ->isTrivial()) {
10759               Result = MaybeCreateExprWithCleanups(Result);
10760               CopyExpr = Result.take();
10761             }
10762           }
10763         }
10764       }
10765 
10766       // Actually capture the variable.
10767       if (BuildAndDiagnose)
10768         CSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
10769                         SourceLocation(), CaptureType, CopyExpr);
10770       Nested = true;
10771       continue;
10772     }
10773 
10774     LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
10775 
10776     // Determine whether we are capturing by reference or by value.
10777     bool ByRef = false;
10778     if (I == N - 1 && Kind != TryCapture_Implicit) {
10779       ByRef = (Kind == TryCapture_ExplicitByRef);
10780     } else {
10781       ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
10782     }
10783 
10784     // Compute the type of the field that will capture this variable.
10785     if (ByRef) {
10786       // C++11 [expr.prim.lambda]p15:
10787       //   An entity is captured by reference if it is implicitly or
10788       //   explicitly captured but not captured by copy. It is
10789       //   unspecified whether additional unnamed non-static data
10790       //   members are declared in the closure type for entities
10791       //   captured by reference.
10792       //
10793       // FIXME: It is not clear whether we want to build an lvalue reference
10794       // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
10795       // to do the former, while EDG does the latter. Core issue 1249 will
10796       // clarify, but for now we follow GCC because it's a more permissive and
10797       // easily defensible position.
10798       CaptureType = Context.getLValueReferenceType(DeclRefType);
10799     } else {
10800       // C++11 [expr.prim.lambda]p14:
10801       //   For each entity captured by copy, an unnamed non-static
10802       //   data member is declared in the closure type. The
10803       //   declaration order of these members is unspecified. The type
10804       //   of such a data member is the type of the corresponding
10805       //   captured entity if the entity is not a reference to an
10806       //   object, or the referenced type otherwise. [Note: If the
10807       //   captured entity is a reference to a function, the
10808       //   corresponding data member is also a reference to a
10809       //   function. - end note ]
10810       if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
10811         if (!RefType->getPointeeType()->isFunctionType())
10812           CaptureType = RefType->getPointeeType();
10813       }
10814 
10815       // Forbid the lambda copy-capture of autoreleasing variables.
10816       if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
10817         if (BuildAndDiagnose) {
10818           Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
10819           Diag(Var->getLocation(), diag::note_previous_decl)
10820             << Var->getDeclName();
10821         }
10822         return true;
10823       }
10824     }
10825 
10826     // Capture this variable in the lambda.
10827     Expr *CopyExpr = 0;
10828     if (BuildAndDiagnose) {
10829       ExprResult Result = captureInLambda(*this, LSI, Var, CaptureType,
10830                                           DeclRefType, Loc,
10831                                           I == N-1);
10832       if (!Result.isInvalid())
10833         CopyExpr = Result.take();
10834     }
10835 
10836     // Compute the type of a reference to this captured variable.
10837     if (ByRef)
10838       DeclRefType = CaptureType.getNonReferenceType();
10839     else {
10840       // C++ [expr.prim.lambda]p5:
10841       //   The closure type for a lambda-expression has a public inline
10842       //   function call operator [...]. This function call operator is
10843       //   declared const (9.3.1) if and only if the lambda-expression’s
10844       //   parameter-declaration-clause is not followed by mutable.
10845       DeclRefType = CaptureType.getNonReferenceType();
10846       if (!LSI->Mutable && !CaptureType->isReferenceType())
10847         DeclRefType.addConst();
10848     }
10849 
10850     // Add the capture.
10851     if (BuildAndDiagnose)
10852       CSI->addCapture(Var, /*IsBlock=*/false, ByRef, Nested, Loc,
10853                       EllipsisLoc, CaptureType, CopyExpr);
10854     Nested = true;
10855   }
10856 
10857   return false;
10858 }
10859 
10860 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
10861                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {
10862   QualType CaptureType;
10863   QualType DeclRefType;
10864   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
10865                             /*BuildAndDiagnose=*/true, CaptureType,
10866                             DeclRefType);
10867 }
10868 
10869 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
10870   QualType CaptureType;
10871   QualType DeclRefType;
10872 
10873   // Determine whether we can capture this variable.
10874   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
10875                          /*BuildAndDiagnose=*/false, CaptureType, DeclRefType))
10876     return QualType();
10877 
10878   return DeclRefType;
10879 }
10880 
10881 static void MarkVarDeclODRUsed(Sema &SemaRef, VarDecl *Var,
10882                                SourceLocation Loc) {
10883   // Keep track of used but undefined variables.
10884   // FIXME: We shouldn't suppress this warning for static data members.
10885   if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
10886       Var->getLinkage() != ExternalLinkage &&
10887       !(Var->isStaticDataMember() && Var->hasInit())) {
10888     SourceLocation &old = SemaRef.UndefinedInternals[Var->getCanonicalDecl()];
10889     if (old.isInvalid()) old = Loc;
10890   }
10891 
10892   SemaRef.tryCaptureVariable(Var, Loc);
10893 
10894   Var->setUsed(true);
10895 }
10896 
10897 void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
10898   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
10899   // an object that satisfies the requirements for appearing in a
10900   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
10901   // is immediately applied."  This function handles the lvalue-to-rvalue
10902   // conversion part.
10903   MaybeODRUseExprs.erase(E->IgnoreParens());
10904 }
10905 
10906 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
10907   if (!Res.isUsable())
10908     return Res;
10909 
10910   // If a constant-expression is a reference to a variable where we delay
10911   // deciding whether it is an odr-use, just assume we will apply the
10912   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
10913   // (a non-type template argument), we have special handling anyway.
10914   UpdateMarkingForLValueToRValue(Res.get());
10915   return Res;
10916 }
10917 
10918 void Sema::CleanupVarDeclMarking() {
10919   for (llvm::SmallPtrSetIterator<Expr*> i = MaybeODRUseExprs.begin(),
10920                                         e = MaybeODRUseExprs.end();
10921        i != e; ++i) {
10922     VarDecl *Var;
10923     SourceLocation Loc;
10924     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(*i)) {
10925       Var = cast<VarDecl>(DRE->getDecl());
10926       Loc = DRE->getLocation();
10927     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(*i)) {
10928       Var = cast<VarDecl>(ME->getMemberDecl());
10929       Loc = ME->getMemberLoc();
10930     } else {
10931       llvm_unreachable("Unexpcted expression");
10932     }
10933 
10934     MarkVarDeclODRUsed(*this, Var, Loc);
10935   }
10936 
10937   MaybeODRUseExprs.clear();
10938 }
10939 
10940 // Mark a VarDecl referenced, and perform the necessary handling to compute
10941 // odr-uses.
10942 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
10943                                     VarDecl *Var, Expr *E) {
10944   Var->setReferenced();
10945 
10946   if (!IsPotentiallyEvaluatedContext(SemaRef))
10947     return;
10948 
10949   // Implicit instantiation of static data members of class templates.
10950   if (Var->isStaticDataMember() && Var->getInstantiatedFromStaticDataMember()) {
10951     MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
10952     assert(MSInfo && "Missing member specialization information?");
10953     bool AlreadyInstantiated = !MSInfo->getPointOfInstantiation().isInvalid();
10954     if (MSInfo->getTemplateSpecializationKind() == TSK_ImplicitInstantiation &&
10955         (!AlreadyInstantiated ||
10956          Var->isUsableInConstantExpressions(SemaRef.Context))) {
10957       if (!AlreadyInstantiated) {
10958         // This is a modification of an existing AST node. Notify listeners.
10959         if (ASTMutationListener *L = SemaRef.getASTMutationListener())
10960           L->StaticDataMemberInstantiated(Var);
10961         MSInfo->setPointOfInstantiation(Loc);
10962       }
10963       SourceLocation PointOfInstantiation = MSInfo->getPointOfInstantiation();
10964       if (Var->isUsableInConstantExpressions(SemaRef.Context))
10965         // Do not defer instantiations of variables which could be used in a
10966         // constant expression.
10967         SemaRef.InstantiateStaticDataMemberDefinition(PointOfInstantiation,Var);
10968       else
10969         SemaRef.PendingInstantiations.push_back(
10970             std::make_pair(Var, PointOfInstantiation));
10971     }
10972   }
10973 
10974   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
10975   // an object that satisfies the requirements for appearing in a
10976   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
10977   // is immediately applied."  We check the first part here, and
10978   // Sema::UpdateMarkingForLValueToRValue deals with the second part.
10979   // Note that we use the C++11 definition everywhere because nothing in
10980   // C++03 depends on whether we get the C++03 version correct. This does not
10981   // apply to references, since they are not objects.
10982   const VarDecl *DefVD;
10983   if (E && !isa<ParmVarDecl>(Var) && !Var->getType()->isReferenceType() &&
10984       Var->isUsableInConstantExpressions(SemaRef.Context) &&
10985       Var->getAnyInitializer(DefVD) && DefVD->checkInitIsICE())
10986     SemaRef.MaybeODRUseExprs.insert(E);
10987   else
10988     MarkVarDeclODRUsed(SemaRef, Var, Loc);
10989 }
10990 
10991 /// \brief Mark a variable referenced, and check whether it is odr-used
10992 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
10993 /// used directly for normal expressions referring to VarDecl.
10994 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
10995   DoMarkVarDeclReferenced(*this, Loc, Var, 0);
10996 }
10997 
10998 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
10999                                Decl *D, Expr *E) {
11000   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
11001     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
11002     return;
11003   }
11004 
11005   SemaRef.MarkAnyDeclReferenced(Loc, D);
11006 
11007   // If this is a call to a method via a cast, also mark the method in the
11008   // derived class used in case codegen can devirtualize the call.
11009   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
11010   if (!ME)
11011     return;
11012   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
11013   if (!MD)
11014     return;
11015   const Expr *Base = ME->getBase();
11016   const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
11017   if (!MostDerivedClassDecl)
11018     return;
11019   CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl);
11020   if (!DM)
11021     return;
11022   SemaRef.MarkAnyDeclReferenced(Loc, DM);
11023 }
11024 
11025 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
11026 void Sema::MarkDeclRefReferenced(DeclRefExpr *E) {
11027   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E);
11028 }
11029 
11030 /// \brief Perform reference-marking and odr-use handling for a MemberExpr.
11031 void Sema::MarkMemberReferenced(MemberExpr *E) {
11032   MarkExprReferenced(*this, E->getMemberLoc(), E->getMemberDecl(), E);
11033 }
11034 
11035 /// \brief Perform marking for a reference to an arbitrary declaration.  It
11036 /// marks the declaration referenced, and performs odr-use checking for functions
11037 /// and variables. This method should not be used when building an normal
11038 /// expression which refers to a variable.
11039 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D) {
11040   if (VarDecl *VD = dyn_cast<VarDecl>(D))
11041     MarkVariableReferenced(Loc, VD);
11042   else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
11043     MarkFunctionReferenced(Loc, FD);
11044   else
11045     D->setReferenced();
11046 }
11047 
11048 namespace {
11049   // Mark all of the declarations referenced
11050   // FIXME: Not fully implemented yet! We need to have a better understanding
11051   // of when we're entering
11052   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
11053     Sema &S;
11054     SourceLocation Loc;
11055 
11056   public:
11057     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
11058 
11059     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
11060 
11061     bool TraverseTemplateArgument(const TemplateArgument &Arg);
11062     bool TraverseRecordType(RecordType *T);
11063   };
11064 }
11065 
11066 bool MarkReferencedDecls::TraverseTemplateArgument(
11067   const TemplateArgument &Arg) {
11068   if (Arg.getKind() == TemplateArgument::Declaration) {
11069     if (Decl *D = Arg.getAsDecl())
11070       S.MarkAnyDeclReferenced(Loc, D);
11071   }
11072 
11073   return Inherited::TraverseTemplateArgument(Arg);
11074 }
11075 
11076 bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
11077   if (ClassTemplateSpecializationDecl *Spec
11078                   = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
11079     const TemplateArgumentList &Args = Spec->getTemplateArgs();
11080     return TraverseTemplateArguments(Args.data(), Args.size());
11081   }
11082 
11083   return true;
11084 }
11085 
11086 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
11087   MarkReferencedDecls Marker(*this, Loc);
11088   Marker.TraverseType(Context.getCanonicalType(T));
11089 }
11090 
11091 namespace {
11092   /// \brief Helper class that marks all of the declarations referenced by
11093   /// potentially-evaluated subexpressions as "referenced".
11094   class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
11095     Sema &S;
11096     bool SkipLocalVariables;
11097 
11098   public:
11099     typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
11100 
11101     EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
11102       : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
11103 
11104     void VisitDeclRefExpr(DeclRefExpr *E) {
11105       // If we were asked not to visit local variables, don't.
11106       if (SkipLocalVariables) {
11107         if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
11108           if (VD->hasLocalStorage())
11109             return;
11110       }
11111 
11112       S.MarkDeclRefReferenced(E);
11113     }
11114 
11115     void VisitMemberExpr(MemberExpr *E) {
11116       S.MarkMemberReferenced(E);
11117       Inherited::VisitMemberExpr(E);
11118     }
11119 
11120     void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
11121       S.MarkFunctionReferenced(E->getLocStart(),
11122             const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
11123       Visit(E->getSubExpr());
11124     }
11125 
11126     void VisitCXXNewExpr(CXXNewExpr *E) {
11127       if (E->getOperatorNew())
11128         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
11129       if (E->getOperatorDelete())
11130         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
11131       Inherited::VisitCXXNewExpr(E);
11132     }
11133 
11134     void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
11135       if (E->getOperatorDelete())
11136         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
11137       QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
11138       if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
11139         CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
11140         S.MarkFunctionReferenced(E->getLocStart(),
11141                                     S.LookupDestructor(Record));
11142       }
11143 
11144       Inherited::VisitCXXDeleteExpr(E);
11145     }
11146 
11147     void VisitCXXConstructExpr(CXXConstructExpr *E) {
11148       S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
11149       Inherited::VisitCXXConstructExpr(E);
11150     }
11151 
11152     void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
11153       Visit(E->getExpr());
11154     }
11155 
11156     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
11157       Inherited::VisitImplicitCastExpr(E);
11158 
11159       if (E->getCastKind() == CK_LValueToRValue)
11160         S.UpdateMarkingForLValueToRValue(E->getSubExpr());
11161     }
11162   };
11163 }
11164 
11165 /// \brief Mark any declarations that appear within this expression or any
11166 /// potentially-evaluated subexpressions as "referenced".
11167 ///
11168 /// \param SkipLocalVariables If true, don't mark local variables as
11169 /// 'referenced'.
11170 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
11171                                             bool SkipLocalVariables) {
11172   EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
11173 }
11174 
11175 /// \brief Emit a diagnostic that describes an effect on the run-time behavior
11176 /// of the program being compiled.
11177 ///
11178 /// This routine emits the given diagnostic when the code currently being
11179 /// type-checked is "potentially evaluated", meaning that there is a
11180 /// possibility that the code will actually be executable. Code in sizeof()
11181 /// expressions, code used only during overload resolution, etc., are not
11182 /// potentially evaluated. This routine will suppress such diagnostics or,
11183 /// in the absolutely nutty case of potentially potentially evaluated
11184 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
11185 /// later.
11186 ///
11187 /// This routine should be used for all diagnostics that describe the run-time
11188 /// behavior of a program, such as passing a non-POD value through an ellipsis.
11189 /// Failure to do so will likely result in spurious diagnostics or failures
11190 /// during overload resolution or within sizeof/alignof/typeof/typeid.
11191 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
11192                                const PartialDiagnostic &PD) {
11193   switch (ExprEvalContexts.back().Context) {
11194   case Unevaluated:
11195     // The argument will never be evaluated, so don't complain.
11196     break;
11197 
11198   case ConstantEvaluated:
11199     // Relevant diagnostics should be produced by constant evaluation.
11200     break;
11201 
11202   case PotentiallyEvaluated:
11203   case PotentiallyEvaluatedIfUsed:
11204     if (Statement && getCurFunctionOrMethodDecl()) {
11205       FunctionScopes.back()->PossiblyUnreachableDiags.
11206         push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
11207     }
11208     else
11209       Diag(Loc, PD);
11210 
11211     return true;
11212   }
11213 
11214   return false;
11215 }
11216 
11217 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
11218                                CallExpr *CE, FunctionDecl *FD) {
11219   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
11220     return false;
11221 
11222   // If we're inside a decltype's expression, don't check for a valid return
11223   // type or construct temporaries until we know whether this is the last call.
11224   if (ExprEvalContexts.back().IsDecltype) {
11225     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
11226     return false;
11227   }
11228 
11229   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
11230     FunctionDecl *FD;
11231     CallExpr *CE;
11232 
11233   public:
11234     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
11235       : FD(FD), CE(CE) { }
11236 
11237     virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
11238       if (!FD) {
11239         S.Diag(Loc, diag::err_call_incomplete_return)
11240           << T << CE->getSourceRange();
11241         return;
11242       }
11243 
11244       S.Diag(Loc, diag::err_call_function_incomplete_return)
11245         << CE->getSourceRange() << FD->getDeclName() << T;
11246       S.Diag(FD->getLocation(),
11247              diag::note_function_with_incomplete_return_type_declared_here)
11248         << FD->getDeclName();
11249     }
11250   } Diagnoser(FD, CE);
11251 
11252   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
11253     return true;
11254 
11255   return false;
11256 }
11257 
11258 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
11259 // will prevent this condition from triggering, which is what we want.
11260 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
11261   SourceLocation Loc;
11262 
11263   unsigned diagnostic = diag::warn_condition_is_assignment;
11264   bool IsOrAssign = false;
11265 
11266   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
11267     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
11268       return;
11269 
11270     IsOrAssign = Op->getOpcode() == BO_OrAssign;
11271 
11272     // Greylist some idioms by putting them into a warning subcategory.
11273     if (ObjCMessageExpr *ME
11274           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
11275       Selector Sel = ME->getSelector();
11276 
11277       // self = [<foo> init...]
11278       if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init"))
11279         diagnostic = diag::warn_condition_is_idiomatic_assignment;
11280 
11281       // <foo> = [<bar> nextObject]
11282       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
11283         diagnostic = diag::warn_condition_is_idiomatic_assignment;
11284     }
11285 
11286     Loc = Op->getOperatorLoc();
11287   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
11288     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
11289       return;
11290 
11291     IsOrAssign = Op->getOperator() == OO_PipeEqual;
11292     Loc = Op->getOperatorLoc();
11293   } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
11294     return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
11295   else {
11296     // Not an assignment.
11297     return;
11298   }
11299 
11300   Diag(Loc, diagnostic) << E->getSourceRange();
11301 
11302   SourceLocation Open = E->getLocStart();
11303   SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
11304   Diag(Loc, diag::note_condition_assign_silence)
11305         << FixItHint::CreateInsertion(Open, "(")
11306         << FixItHint::CreateInsertion(Close, ")");
11307 
11308   if (IsOrAssign)
11309     Diag(Loc, diag::note_condition_or_assign_to_comparison)
11310       << FixItHint::CreateReplacement(Loc, "!=");
11311   else
11312     Diag(Loc, diag::note_condition_assign_to_comparison)
11313       << FixItHint::CreateReplacement(Loc, "==");
11314 }
11315 
11316 /// \brief Redundant parentheses over an equality comparison can indicate
11317 /// that the user intended an assignment used as condition.
11318 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
11319   // Don't warn if the parens came from a macro.
11320   SourceLocation parenLoc = ParenE->getLocStart();
11321   if (parenLoc.isInvalid() || parenLoc.isMacroID())
11322     return;
11323   // Don't warn for dependent expressions.
11324   if (ParenE->isTypeDependent())
11325     return;
11326 
11327   Expr *E = ParenE->IgnoreParens();
11328 
11329   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
11330     if (opE->getOpcode() == BO_EQ &&
11331         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
11332                                                            == Expr::MLV_Valid) {
11333       SourceLocation Loc = opE->getOperatorLoc();
11334 
11335       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
11336       SourceRange ParenERange = ParenE->getSourceRange();
11337       Diag(Loc, diag::note_equality_comparison_silence)
11338         << FixItHint::CreateRemoval(ParenERange.getBegin())
11339         << FixItHint::CreateRemoval(ParenERange.getEnd());
11340       Diag(Loc, diag::note_equality_comparison_to_assign)
11341         << FixItHint::CreateReplacement(Loc, "=");
11342     }
11343 }
11344 
11345 ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
11346   DiagnoseAssignmentAsCondition(E);
11347   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
11348     DiagnoseEqualityWithExtraParens(parenE);
11349 
11350   ExprResult result = CheckPlaceholderExpr(E);
11351   if (result.isInvalid()) return ExprError();
11352   E = result.take();
11353 
11354   if (!E->isTypeDependent()) {
11355     if (getLangOpts().CPlusPlus)
11356       return CheckCXXBooleanCondition(E); // C++ 6.4p4
11357 
11358     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
11359     if (ERes.isInvalid())
11360       return ExprError();
11361     E = ERes.take();
11362 
11363     QualType T = E->getType();
11364     if (!T->isScalarType()) { // C99 6.8.4.1p1
11365       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
11366         << T << E->getSourceRange();
11367       return ExprError();
11368     }
11369   }
11370 
11371   return Owned(E);
11372 }
11373 
11374 ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
11375                                        Expr *SubExpr) {
11376   if (!SubExpr)
11377     return ExprError();
11378 
11379   return CheckBooleanCondition(SubExpr, Loc);
11380 }
11381 
11382 namespace {
11383   /// A visitor for rebuilding a call to an __unknown_any expression
11384   /// to have an appropriate type.
11385   struct RebuildUnknownAnyFunction
11386     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
11387 
11388     Sema &S;
11389 
11390     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
11391 
11392     ExprResult VisitStmt(Stmt *S) {
11393       llvm_unreachable("unexpected statement!");
11394     }
11395 
11396     ExprResult VisitExpr(Expr *E) {
11397       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
11398         << E->getSourceRange();
11399       return ExprError();
11400     }
11401 
11402     /// Rebuild an expression which simply semantically wraps another
11403     /// expression which it shares the type and value kind of.
11404     template <class T> ExprResult rebuildSugarExpr(T *E) {
11405       ExprResult SubResult = Visit(E->getSubExpr());
11406       if (SubResult.isInvalid()) return ExprError();
11407 
11408       Expr *SubExpr = SubResult.take();
11409       E->setSubExpr(SubExpr);
11410       E->setType(SubExpr->getType());
11411       E->setValueKind(SubExpr->getValueKind());
11412       assert(E->getObjectKind() == OK_Ordinary);
11413       return E;
11414     }
11415 
11416     ExprResult VisitParenExpr(ParenExpr *E) {
11417       return rebuildSugarExpr(E);
11418     }
11419 
11420     ExprResult VisitUnaryExtension(UnaryOperator *E) {
11421       return rebuildSugarExpr(E);
11422     }
11423 
11424     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
11425       ExprResult SubResult = Visit(E->getSubExpr());
11426       if (SubResult.isInvalid()) return ExprError();
11427 
11428       Expr *SubExpr = SubResult.take();
11429       E->setSubExpr(SubExpr);
11430       E->setType(S.Context.getPointerType(SubExpr->getType()));
11431       assert(E->getValueKind() == VK_RValue);
11432       assert(E->getObjectKind() == OK_Ordinary);
11433       return E;
11434     }
11435 
11436     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
11437       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
11438 
11439       E->setType(VD->getType());
11440 
11441       assert(E->getValueKind() == VK_RValue);
11442       if (S.getLangOpts().CPlusPlus &&
11443           !(isa<CXXMethodDecl>(VD) &&
11444             cast<CXXMethodDecl>(VD)->isInstance()))
11445         E->setValueKind(VK_LValue);
11446 
11447       return E;
11448     }
11449 
11450     ExprResult VisitMemberExpr(MemberExpr *E) {
11451       return resolveDecl(E, E->getMemberDecl());
11452     }
11453 
11454     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
11455       return resolveDecl(E, E->getDecl());
11456     }
11457   };
11458 }
11459 
11460 /// Given a function expression of unknown-any type, try to rebuild it
11461 /// to have a function type.
11462 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
11463   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
11464   if (Result.isInvalid()) return ExprError();
11465   return S.DefaultFunctionArrayConversion(Result.take());
11466 }
11467 
11468 namespace {
11469   /// A visitor for rebuilding an expression of type __unknown_anytype
11470   /// into one which resolves the type directly on the referring
11471   /// expression.  Strict preservation of the original source
11472   /// structure is not a goal.
11473   struct RebuildUnknownAnyExpr
11474     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
11475 
11476     Sema &S;
11477 
11478     /// The current destination type.
11479     QualType DestType;
11480 
11481     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
11482       : S(S), DestType(CastType) {}
11483 
11484     ExprResult VisitStmt(Stmt *S) {
11485       llvm_unreachable("unexpected statement!");
11486     }
11487 
11488     ExprResult VisitExpr(Expr *E) {
11489       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
11490         << E->getSourceRange();
11491       return ExprError();
11492     }
11493 
11494     ExprResult VisitCallExpr(CallExpr *E);
11495     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
11496 
11497     /// Rebuild an expression which simply semantically wraps another
11498     /// expression which it shares the type and value kind of.
11499     template <class T> ExprResult rebuildSugarExpr(T *E) {
11500       ExprResult SubResult = Visit(E->getSubExpr());
11501       if (SubResult.isInvalid()) return ExprError();
11502       Expr *SubExpr = SubResult.take();
11503       E->setSubExpr(SubExpr);
11504       E->setType(SubExpr->getType());
11505       E->setValueKind(SubExpr->getValueKind());
11506       assert(E->getObjectKind() == OK_Ordinary);
11507       return E;
11508     }
11509 
11510     ExprResult VisitParenExpr(ParenExpr *E) {
11511       return rebuildSugarExpr(E);
11512     }
11513 
11514     ExprResult VisitUnaryExtension(UnaryOperator *E) {
11515       return rebuildSugarExpr(E);
11516     }
11517 
11518     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
11519       const PointerType *Ptr = DestType->getAs<PointerType>();
11520       if (!Ptr) {
11521         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
11522           << E->getSourceRange();
11523         return ExprError();
11524       }
11525       assert(E->getValueKind() == VK_RValue);
11526       assert(E->getObjectKind() == OK_Ordinary);
11527       E->setType(DestType);
11528 
11529       // Build the sub-expression as if it were an object of the pointee type.
11530       DestType = Ptr->getPointeeType();
11531       ExprResult SubResult = Visit(E->getSubExpr());
11532       if (SubResult.isInvalid()) return ExprError();
11533       E->setSubExpr(SubResult.take());
11534       return E;
11535     }
11536 
11537     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
11538 
11539     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
11540 
11541     ExprResult VisitMemberExpr(MemberExpr *E) {
11542       return resolveDecl(E, E->getMemberDecl());
11543     }
11544 
11545     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
11546       return resolveDecl(E, E->getDecl());
11547     }
11548   };
11549 }
11550 
11551 /// Rebuilds a call expression which yielded __unknown_anytype.
11552 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
11553   Expr *CalleeExpr = E->getCallee();
11554 
11555   enum FnKind {
11556     FK_MemberFunction,
11557     FK_FunctionPointer,
11558     FK_BlockPointer
11559   };
11560 
11561   FnKind Kind;
11562   QualType CalleeType = CalleeExpr->getType();
11563   if (CalleeType == S.Context.BoundMemberTy) {
11564     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
11565     Kind = FK_MemberFunction;
11566     CalleeType = Expr::findBoundMemberType(CalleeExpr);
11567   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
11568     CalleeType = Ptr->getPointeeType();
11569     Kind = FK_FunctionPointer;
11570   } else {
11571     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
11572     Kind = FK_BlockPointer;
11573   }
11574   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
11575 
11576   // Verify that this is a legal result type of a function.
11577   if (DestType->isArrayType() || DestType->isFunctionType()) {
11578     unsigned diagID = diag::err_func_returning_array_function;
11579     if (Kind == FK_BlockPointer)
11580       diagID = diag::err_block_returning_array_function;
11581 
11582     S.Diag(E->getExprLoc(), diagID)
11583       << DestType->isFunctionType() << DestType;
11584     return ExprError();
11585   }
11586 
11587   // Otherwise, go ahead and set DestType as the call's result.
11588   E->setType(DestType.getNonLValueExprType(S.Context));
11589   E->setValueKind(Expr::getValueKindForType(DestType));
11590   assert(E->getObjectKind() == OK_Ordinary);
11591 
11592   // Rebuild the function type, replacing the result type with DestType.
11593   if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType))
11594     DestType = S.Context.getFunctionType(DestType,
11595                                          Proto->arg_type_begin(),
11596                                          Proto->getNumArgs(),
11597                                          Proto->getExtProtoInfo());
11598   else
11599     DestType = S.Context.getFunctionNoProtoType(DestType,
11600                                                 FnType->getExtInfo());
11601 
11602   // Rebuild the appropriate pointer-to-function type.
11603   switch (Kind) {
11604   case FK_MemberFunction:
11605     // Nothing to do.
11606     break;
11607 
11608   case FK_FunctionPointer:
11609     DestType = S.Context.getPointerType(DestType);
11610     break;
11611 
11612   case FK_BlockPointer:
11613     DestType = S.Context.getBlockPointerType(DestType);
11614     break;
11615   }
11616 
11617   // Finally, we can recurse.
11618   ExprResult CalleeResult = Visit(CalleeExpr);
11619   if (!CalleeResult.isUsable()) return ExprError();
11620   E->setCallee(CalleeResult.take());
11621 
11622   // Bind a temporary if necessary.
11623   return S.MaybeBindToTemporary(E);
11624 }
11625 
11626 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
11627   // Verify that this is a legal result type of a call.
11628   if (DestType->isArrayType() || DestType->isFunctionType()) {
11629     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
11630       << DestType->isFunctionType() << DestType;
11631     return ExprError();
11632   }
11633 
11634   // Rewrite the method result type if available.
11635   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
11636     assert(Method->getResultType() == S.Context.UnknownAnyTy);
11637     Method->setResultType(DestType);
11638   }
11639 
11640   // Change the type of the message.
11641   E->setType(DestType.getNonReferenceType());
11642   E->setValueKind(Expr::getValueKindForType(DestType));
11643 
11644   return S.MaybeBindToTemporary(E);
11645 }
11646 
11647 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
11648   // The only case we should ever see here is a function-to-pointer decay.
11649   if (E->getCastKind() == CK_FunctionToPointerDecay) {
11650     assert(E->getValueKind() == VK_RValue);
11651     assert(E->getObjectKind() == OK_Ordinary);
11652 
11653     E->setType(DestType);
11654 
11655     // Rebuild the sub-expression as the pointee (function) type.
11656     DestType = DestType->castAs<PointerType>()->getPointeeType();
11657 
11658     ExprResult Result = Visit(E->getSubExpr());
11659     if (!Result.isUsable()) return ExprError();
11660 
11661     E->setSubExpr(Result.take());
11662     return S.Owned(E);
11663   } else if (E->getCastKind() == CK_LValueToRValue) {
11664     assert(E->getValueKind() == VK_RValue);
11665     assert(E->getObjectKind() == OK_Ordinary);
11666 
11667     assert(isa<BlockPointerType>(E->getType()));
11668 
11669     E->setType(DestType);
11670 
11671     // The sub-expression has to be a lvalue reference, so rebuild it as such.
11672     DestType = S.Context.getLValueReferenceType(DestType);
11673 
11674     ExprResult Result = Visit(E->getSubExpr());
11675     if (!Result.isUsable()) return ExprError();
11676 
11677     E->setSubExpr(Result.take());
11678     return S.Owned(E);
11679   } else {
11680     llvm_unreachable("Unhandled cast type!");
11681   }
11682 }
11683 
11684 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
11685   ExprValueKind ValueKind = VK_LValue;
11686   QualType Type = DestType;
11687 
11688   // We know how to make this work for certain kinds of decls:
11689 
11690   //  - functions
11691   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
11692     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
11693       DestType = Ptr->getPointeeType();
11694       ExprResult Result = resolveDecl(E, VD);
11695       if (Result.isInvalid()) return ExprError();
11696       return S.ImpCastExprToType(Result.take(), Type,
11697                                  CK_FunctionToPointerDecay, VK_RValue);
11698     }
11699 
11700     if (!Type->isFunctionType()) {
11701       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
11702         << VD << E->getSourceRange();
11703       return ExprError();
11704     }
11705 
11706     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
11707       if (MD->isInstance()) {
11708         ValueKind = VK_RValue;
11709         Type = S.Context.BoundMemberTy;
11710       }
11711 
11712     // Function references aren't l-values in C.
11713     if (!S.getLangOpts().CPlusPlus)
11714       ValueKind = VK_RValue;
11715 
11716   //  - variables
11717   } else if (isa<VarDecl>(VD)) {
11718     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
11719       Type = RefTy->getPointeeType();
11720     } else if (Type->isFunctionType()) {
11721       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
11722         << VD << E->getSourceRange();
11723       return ExprError();
11724     }
11725 
11726   //  - nothing else
11727   } else {
11728     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
11729       << VD << E->getSourceRange();
11730     return ExprError();
11731   }
11732 
11733   VD->setType(DestType);
11734   E->setType(Type);
11735   E->setValueKind(ValueKind);
11736   return S.Owned(E);
11737 }
11738 
11739 /// Check a cast of an unknown-any type.  We intentionally only
11740 /// trigger this for C-style casts.
11741 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
11742                                      Expr *CastExpr, CastKind &CastKind,
11743                                      ExprValueKind &VK, CXXCastPath &Path) {
11744   // Rewrite the casted expression from scratch.
11745   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
11746   if (!result.isUsable()) return ExprError();
11747 
11748   CastExpr = result.take();
11749   VK = CastExpr->getValueKind();
11750   CastKind = CK_NoOp;
11751 
11752   return CastExpr;
11753 }
11754 
11755 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
11756   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
11757 }
11758 
11759 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
11760   Expr *orig = E;
11761   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
11762   while (true) {
11763     E = E->IgnoreParenImpCasts();
11764     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
11765       E = call->getCallee();
11766       diagID = diag::err_uncasted_call_of_unknown_any;
11767     } else {
11768       break;
11769     }
11770   }
11771 
11772   SourceLocation loc;
11773   NamedDecl *d;
11774   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
11775     loc = ref->getLocation();
11776     d = ref->getDecl();
11777   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
11778     loc = mem->getMemberLoc();
11779     d = mem->getMemberDecl();
11780   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
11781     diagID = diag::err_uncasted_call_of_unknown_any;
11782     loc = msg->getSelectorStartLoc();
11783     d = msg->getMethodDecl();
11784     if (!d) {
11785       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
11786         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
11787         << orig->getSourceRange();
11788       return ExprError();
11789     }
11790   } else {
11791     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
11792       << E->getSourceRange();
11793     return ExprError();
11794   }
11795 
11796   S.Diag(loc, diagID) << d << orig->getSourceRange();
11797 
11798   // Never recoverable.
11799   return ExprError();
11800 }
11801 
11802 /// Check for operands with placeholder types and complain if found.
11803 /// Returns true if there was an error and no recovery was possible.
11804 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
11805   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
11806   if (!placeholderType) return Owned(E);
11807 
11808   switch (placeholderType->getKind()) {
11809 
11810   // Overloaded expressions.
11811   case BuiltinType::Overload: {
11812     // Try to resolve a single function template specialization.
11813     // This is obligatory.
11814     ExprResult result = Owned(E);
11815     if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) {
11816       return result;
11817 
11818     // If that failed, try to recover with a call.
11819     } else {
11820       tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable),
11821                            /*complain*/ true);
11822       return result;
11823     }
11824   }
11825 
11826   // Bound member functions.
11827   case BuiltinType::BoundMember: {
11828     ExprResult result = Owned(E);
11829     tryToRecoverWithCall(result, PDiag(diag::err_bound_member_function),
11830                          /*complain*/ true);
11831     return result;
11832   }
11833 
11834   // ARC unbridged casts.
11835   case BuiltinType::ARCUnbridgedCast: {
11836     Expr *realCast = stripARCUnbridgedCast(E);
11837     diagnoseARCUnbridgedCast(realCast);
11838     return Owned(realCast);
11839   }
11840 
11841   // Expressions of unknown type.
11842   case BuiltinType::UnknownAny:
11843     return diagnoseUnknownAnyExpr(*this, E);
11844 
11845   // Pseudo-objects.
11846   case BuiltinType::PseudoObject:
11847     return checkPseudoObjectRValue(E);
11848 
11849   case BuiltinType::BuiltinFn:
11850     Diag(E->getLocStart(), diag::err_builtin_fn_use);
11851     return ExprError();
11852 
11853   // Everything else should be impossible.
11854 #define BUILTIN_TYPE(Id, SingletonId) \
11855   case BuiltinType::Id:
11856 #define PLACEHOLDER_TYPE(Id, SingletonId)
11857 #include "clang/AST/BuiltinTypes.def"
11858     break;
11859   }
11860 
11861   llvm_unreachable("invalid placeholder type!");
11862 }
11863 
11864 bool Sema::CheckCaseExpression(Expr *E) {
11865   if (E->isTypeDependent())
11866     return true;
11867   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
11868     return E->getType()->isIntegralOrEnumerationType();
11869   return false;
11870 }
11871 
11872 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
11873 ExprResult
11874 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
11875   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
11876          "Unknown Objective-C Boolean value!");
11877   QualType BoolT = Context.ObjCBuiltinBoolTy;
11878   if (!Context.getBOOLDecl()) {
11879     LookupResult Result(*this, &Context.Idents.get("BOOL"), SourceLocation(),
11880                         Sema::LookupOrdinaryName);
11881     if (LookupName(Result, getCurScope())) {
11882       NamedDecl *ND = Result.getFoundDecl();
11883       if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
11884         Context.setBOOLDecl(TD);
11885     }
11886   }
11887   if (Context.getBOOLDecl())
11888     BoolT = Context.getBOOLType();
11889   return Owned(new (Context) ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes,
11890                                         BoolT, OpLoc));
11891 }
11892