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/Initialization.h"
16 #include "clang/Sema/Lookup.h"
17 #include "clang/Sema/AnalysisBasedWarnings.h"
18 #include "clang/AST/ASTContext.h"
19 #include "clang/AST/ASTMutationListener.h"
20 #include "clang/AST/CXXInheritance.h"
21 #include "clang/AST/DeclObjC.h"
22 #include "clang/AST/DeclTemplate.h"
23 #include "clang/AST/EvaluatedExprVisitor.h"
24 #include "clang/AST/Expr.h"
25 #include "clang/AST/ExprCXX.h"
26 #include "clang/AST/ExprObjC.h"
27 #include "clang/AST/RecursiveASTVisitor.h"
28 #include "clang/AST/TypeLoc.h"
29 #include "clang/Basic/PartialDiagnostic.h"
30 #include "clang/Basic/SourceManager.h"
31 #include "clang/Basic/TargetInfo.h"
32 #include "clang/Lex/LiteralSupport.h"
33 #include "clang/Lex/Preprocessor.h"
34 #include "clang/Sema/DeclSpec.h"
35 #include "clang/Sema/Designator.h"
36 #include "clang/Sema/Scope.h"
37 #include "clang/Sema/ScopeInfo.h"
38 #include "clang/Sema/ParsedTemplate.h"
39 #include "clang/Sema/SemaFixItUtils.h"
40 #include "clang/Sema/Template.h"
41 using namespace clang;
42 using namespace sema;
43 
44 /// \brief Determine whether the use of this declaration is valid, without
45 /// emitting diagnostics.
46 bool Sema::CanUseDecl(NamedDecl *D) {
47   // See if this is an auto-typed variable whose initializer we are parsing.
48   if (ParsingInitForAutoVars.count(D))
49     return false;
50 
51   // See if this is a deleted function.
52   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
53     if (FD->isDeleted())
54       return false;
55   }
56 
57   // See if this function is unavailable.
58   if (D->getAvailability() == AR_Unavailable &&
59       cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
60     return false;
61 
62   return true;
63 }
64 
65 static AvailabilityResult DiagnoseAvailabilityOfDecl(Sema &S,
66                               NamedDecl *D, SourceLocation Loc,
67                               const ObjCInterfaceDecl *UnknownObjCClass) {
68   // See if this declaration is unavailable or deprecated.
69   std::string Message;
70   AvailabilityResult Result = D->getAvailability(&Message);
71   switch (Result) {
72     case AR_Available:
73     case AR_NotYetIntroduced:
74       break;
75 
76     case AR_Deprecated:
77       S.EmitDeprecationWarning(D, Message, Loc, UnknownObjCClass);
78       break;
79 
80     case AR_Unavailable:
81       if (S.getCurContextAvailability() != AR_Unavailable) {
82         if (Message.empty()) {
83           if (!UnknownObjCClass)
84             S.Diag(Loc, diag::err_unavailable) << D->getDeclName();
85           else
86             S.Diag(Loc, diag::warn_unavailable_fwdclass_message)
87               << D->getDeclName();
88         }
89         else
90           S.Diag(Loc, diag::err_unavailable_message)
91             << D->getDeclName() << Message;
92           S.Diag(D->getLocation(), diag::note_unavailable_here)
93           << isa<FunctionDecl>(D) << false;
94       }
95       break;
96     }
97     return Result;
98 }
99 
100 /// \brief Determine whether the use of this declaration is valid, and
101 /// emit any corresponding diagnostics.
102 ///
103 /// This routine diagnoses various problems with referencing
104 /// declarations that can occur when using a declaration. For example,
105 /// it might warn if a deprecated or unavailable declaration is being
106 /// used, or produce an error (and return true) if a C++0x deleted
107 /// function is being used.
108 ///
109 /// \returns true if there was an error (this declaration cannot be
110 /// referenced), false otherwise.
111 ///
112 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
113                              const ObjCInterfaceDecl *UnknownObjCClass) {
114   if (getLangOptions().CPlusPlus && isa<FunctionDecl>(D)) {
115     // If there were any diagnostics suppressed by template argument deduction,
116     // emit them now.
117     llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >::iterator
118       Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
119     if (Pos != SuppressedDiagnostics.end()) {
120       SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second;
121       for (unsigned I = 0, N = Suppressed.size(); I != N; ++I)
122         Diag(Suppressed[I].first, Suppressed[I].second);
123 
124       // Clear out the list of suppressed diagnostics, so that we don't emit
125       // them again for this specialization. However, we don't obsolete this
126       // entry from the table, because we want to avoid ever emitting these
127       // diagnostics again.
128       Suppressed.clear();
129     }
130   }
131 
132   // See if this is an auto-typed variable whose initializer we are parsing.
133   if (ParsingInitForAutoVars.count(D)) {
134     Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
135       << D->getDeclName();
136     return true;
137   }
138 
139   // See if this is a deleted function.
140   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
141     if (FD->isDeleted()) {
142       Diag(Loc, diag::err_deleted_function_use);
143       Diag(D->getLocation(), diag::note_unavailable_here) << 1 << true;
144       return true;
145     }
146   }
147   AvailabilityResult Result =
148     DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass);
149 
150   // Warn if this is used but marked unused.
151   if (D->hasAttr<UnusedAttr>())
152     Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
153   // For available enumerator, it will become unavailable/deprecated
154   // if its enum declaration is as such.
155   if (Result == AR_Available)
156     if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
157       const DeclContext *DC = ECD->getDeclContext();
158       if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC))
159         DiagnoseAvailabilityOfDecl(*this,
160                           const_cast< EnumDecl *>(TheEnumDecl),
161                           Loc, UnknownObjCClass);
162     }
163   return false;
164 }
165 
166 /// \brief Retrieve the message suffix that should be added to a
167 /// diagnostic complaining about the given function being deleted or
168 /// unavailable.
169 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
170   // FIXME: C++0x implicitly-deleted special member functions could be
171   // detected here so that we could improve diagnostics to say, e.g.,
172   // "base class 'A' had a deleted copy constructor".
173   if (FD->isDeleted())
174     return std::string();
175 
176   std::string Message;
177   if (FD->getAvailability(&Message))
178     return ": " + Message;
179 
180   return std::string();
181 }
182 
183 /// DiagnoseSentinelCalls - This routine checks whether a call or
184 /// message-send is to a declaration with the sentinel attribute, and
185 /// if so, it checks that the requirements of the sentinel are
186 /// satisfied.
187 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
188                                  Expr **args, unsigned numArgs) {
189   const SentinelAttr *attr = D->getAttr<SentinelAttr>();
190   if (!attr)
191     return;
192 
193   // The number of formal parameters of the declaration.
194   unsigned numFormalParams;
195 
196   // The kind of declaration.  This is also an index into a %select in
197   // the diagnostic.
198   enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
199 
200   if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
201     numFormalParams = MD->param_size();
202     calleeType = CT_Method;
203   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
204     numFormalParams = FD->param_size();
205     calleeType = CT_Function;
206   } else if (isa<VarDecl>(D)) {
207     QualType type = cast<ValueDecl>(D)->getType();
208     const FunctionType *fn = 0;
209     if (const PointerType *ptr = type->getAs<PointerType>()) {
210       fn = ptr->getPointeeType()->getAs<FunctionType>();
211       if (!fn) return;
212       calleeType = CT_Function;
213     } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
214       fn = ptr->getPointeeType()->castAs<FunctionType>();
215       calleeType = CT_Block;
216     } else {
217       return;
218     }
219 
220     if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
221       numFormalParams = proto->getNumArgs();
222     } else {
223       numFormalParams = 0;
224     }
225   } else {
226     return;
227   }
228 
229   // "nullPos" is the number of formal parameters at the end which
230   // effectively count as part of the variadic arguments.  This is
231   // useful if you would prefer to not have *any* formal parameters,
232   // but the language forces you to have at least one.
233   unsigned nullPos = attr->getNullPos();
234   assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
235   numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
236 
237   // The number of arguments which should follow the sentinel.
238   unsigned numArgsAfterSentinel = attr->getSentinel();
239 
240   // If there aren't enough arguments for all the formal parameters,
241   // the sentinel, and the args after the sentinel, complain.
242   if (numArgs < numFormalParams + numArgsAfterSentinel + 1) {
243     Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
244     Diag(D->getLocation(), diag::note_sentinel_here) << calleeType;
245     return;
246   }
247 
248   // Otherwise, find the sentinel expression.
249   Expr *sentinelExpr = args[numArgs - numArgsAfterSentinel - 1];
250   if (!sentinelExpr) return;
251   if (sentinelExpr->isValueDependent()) return;
252 
253   // nullptr_t is always treated as null.
254   if (sentinelExpr->getType()->isNullPtrType()) return;
255 
256   if (sentinelExpr->getType()->isAnyPointerType() &&
257       sentinelExpr->IgnoreParenCasts()->isNullPointerConstant(Context,
258                                             Expr::NPC_ValueDependentIsNull))
259     return;
260 
261   // Unfortunately, __null has type 'int'.
262   if (isa<GNUNullExpr>(sentinelExpr)) return;
263 
264   // Pick a reasonable string to insert.  Optimistically use 'nil' or
265   // 'NULL' if those are actually defined in the context.  Only use
266   // 'nil' for ObjC methods, where it's much more likely that the
267   // variadic arguments form a list of object pointers.
268   SourceLocation MissingNilLoc
269     = PP.getLocForEndOfToken(sentinelExpr->getLocEnd());
270   std::string NullValue;
271   if (calleeType == CT_Method &&
272       PP.getIdentifierInfo("nil")->hasMacroDefinition())
273     NullValue = "nil";
274   else if (PP.getIdentifierInfo("NULL")->hasMacroDefinition())
275     NullValue = "NULL";
276   else
277     NullValue = "(void*) 0";
278 
279   if (MissingNilLoc.isInvalid())
280     Diag(Loc, diag::warn_missing_sentinel) << calleeType;
281   else
282     Diag(MissingNilLoc, diag::warn_missing_sentinel)
283       << calleeType
284       << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
285   Diag(D->getLocation(), diag::note_sentinel_here) << calleeType;
286 }
287 
288 SourceRange Sema::getExprRange(Expr *E) const {
289   return E ? E->getSourceRange() : SourceRange();
290 }
291 
292 //===----------------------------------------------------------------------===//
293 //  Standard Promotions and Conversions
294 //===----------------------------------------------------------------------===//
295 
296 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
297 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) {
298   // Handle any placeholder expressions which made it here.
299   if (E->getType()->isPlaceholderType()) {
300     ExprResult result = CheckPlaceholderExpr(E);
301     if (result.isInvalid()) return ExprError();
302     E = result.take();
303   }
304 
305   QualType Ty = E->getType();
306   assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
307 
308   if (Ty->isFunctionType())
309     E = ImpCastExprToType(E, Context.getPointerType(Ty),
310                           CK_FunctionToPointerDecay).take();
311   else if (Ty->isArrayType()) {
312     // In C90 mode, arrays only promote to pointers if the array expression is
313     // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
314     // type 'array of type' is converted to an expression that has type 'pointer
315     // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
316     // that has type 'array of type' ...".  The relevant change is "an lvalue"
317     // (C90) to "an expression" (C99).
318     //
319     // C++ 4.2p1:
320     // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
321     // T" can be converted to an rvalue of type "pointer to T".
322     //
323     if (getLangOptions().C99 || getLangOptions().CPlusPlus || E->isLValue())
324       E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
325                             CK_ArrayToPointerDecay).take();
326   }
327   return Owned(E);
328 }
329 
330 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
331   // Check to see if we are dereferencing a null pointer.  If so,
332   // and if not volatile-qualified, this is undefined behavior that the
333   // optimizer will delete, so warn about it.  People sometimes try to use this
334   // to get a deterministic trap and are surprised by clang's behavior.  This
335   // only handles the pattern "*null", which is a very syntactic check.
336   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
337     if (UO->getOpcode() == UO_Deref &&
338         UO->getSubExpr()->IgnoreParenCasts()->
339           isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
340         !UO->getType().isVolatileQualified()) {
341     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
342                           S.PDiag(diag::warn_indirection_through_null)
343                             << UO->getSubExpr()->getSourceRange());
344     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
345                         S.PDiag(diag::note_indirection_through_null));
346   }
347 }
348 
349 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
350   // Handle any placeholder expressions which made it here.
351   if (E->getType()->isPlaceholderType()) {
352     ExprResult result = CheckPlaceholderExpr(E);
353     if (result.isInvalid()) return ExprError();
354     E = result.take();
355   }
356 
357   // C++ [conv.lval]p1:
358   //   A glvalue of a non-function, non-array type T can be
359   //   converted to a prvalue.
360   if (!E->isGLValue()) return Owned(E);
361 
362   QualType T = E->getType();
363   assert(!T.isNull() && "r-value conversion on typeless expression?");
364 
365   // We can't do lvalue-to-rvalue on atomics yet.
366   if (T->isAtomicType())
367     return Owned(E);
368 
369   // We don't want to throw lvalue-to-rvalue casts on top of
370   // expressions of certain types in C++.
371   if (getLangOptions().CPlusPlus &&
372       (E->getType() == Context.OverloadTy ||
373        T->isDependentType() ||
374        T->isRecordType()))
375     return Owned(E);
376 
377   // The C standard is actually really unclear on this point, and
378   // DR106 tells us what the result should be but not why.  It's
379   // generally best to say that void types just doesn't undergo
380   // lvalue-to-rvalue at all.  Note that expressions of unqualified
381   // 'void' type are never l-values, but qualified void can be.
382   if (T->isVoidType())
383     return Owned(E);
384 
385   CheckForNullPointerDereference(*this, E);
386 
387   // C++ [conv.lval]p1:
388   //   [...] If T is a non-class type, the type of the prvalue is the
389   //   cv-unqualified version of T. Otherwise, the type of the
390   //   rvalue is T.
391   //
392   // C99 6.3.2.1p2:
393   //   If the lvalue has qualified type, the value has the unqualified
394   //   version of the type of the lvalue; otherwise, the value has the
395   //   type of the lvalue.
396   if (T.hasQualifiers())
397     T = T.getUnqualifiedType();
398 
399   ExprResult Res = Owned(ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
400                                                   E, 0, VK_RValue));
401 
402   return Res;
403 }
404 
405 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) {
406   ExprResult Res = DefaultFunctionArrayConversion(E);
407   if (Res.isInvalid())
408     return ExprError();
409   Res = DefaultLvalueConversion(Res.take());
410   if (Res.isInvalid())
411     return ExprError();
412   return move(Res);
413 }
414 
415 
416 /// UsualUnaryConversions - Performs various conversions that are common to most
417 /// operators (C99 6.3). The conversions of array and function types are
418 /// sometimes suppressed. For example, the array->pointer conversion doesn't
419 /// apply if the array is an argument to the sizeof or address (&) operators.
420 /// In these instances, this routine should *not* be called.
421 ExprResult Sema::UsualUnaryConversions(Expr *E) {
422   // First, convert to an r-value.
423   ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
424   if (Res.isInvalid())
425     return Owned(E);
426   E = Res.take();
427 
428   QualType Ty = E->getType();
429   assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
430 
431   // Half FP is a bit different: it's a storage-only type, meaning that any
432   // "use" of it should be promoted to float.
433   if (Ty->isHalfType())
434     return ImpCastExprToType(Res.take(), Context.FloatTy, CK_FloatingCast);
435 
436   // Try to perform integral promotions if the object has a theoretically
437   // promotable type.
438   if (Ty->isIntegralOrUnscopedEnumerationType()) {
439     // C99 6.3.1.1p2:
440     //
441     //   The following may be used in an expression wherever an int or
442     //   unsigned int may be used:
443     //     - an object or expression with an integer type whose integer
444     //       conversion rank is less than or equal to the rank of int
445     //       and unsigned int.
446     //     - A bit-field of type _Bool, int, signed int, or unsigned int.
447     //
448     //   If an int can represent all values of the original type, the
449     //   value is converted to an int; otherwise, it is converted to an
450     //   unsigned int. These are called the integer promotions. All
451     //   other types are unchanged by the integer promotions.
452 
453     QualType PTy = Context.isPromotableBitField(E);
454     if (!PTy.isNull()) {
455       E = ImpCastExprToType(E, PTy, CK_IntegralCast).take();
456       return Owned(E);
457     }
458     if (Ty->isPromotableIntegerType()) {
459       QualType PT = Context.getPromotedIntegerType(Ty);
460       E = ImpCastExprToType(E, PT, CK_IntegralCast).take();
461       return Owned(E);
462     }
463   }
464   return Owned(E);
465 }
466 
467 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
468 /// do not have a prototype. Arguments that have type float are promoted to
469 /// double. All other argument types are converted by UsualUnaryConversions().
470 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
471   QualType Ty = E->getType();
472   assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
473 
474   ExprResult Res = UsualUnaryConversions(E);
475   if (Res.isInvalid())
476     return Owned(E);
477   E = Res.take();
478 
479   // If this is a 'float' (CVR qualified or typedef) promote to double.
480   if (Ty->isSpecificBuiltinType(BuiltinType::Float))
481     E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).take();
482 
483   // C++ performs lvalue-to-rvalue conversion as a default argument
484   // promotion, even on class types, but note:
485   //   C++11 [conv.lval]p2:
486   //     When an lvalue-to-rvalue conversion occurs in an unevaluated
487   //     operand or a subexpression thereof the value contained in the
488   //     referenced object is not accessed. Otherwise, if the glvalue
489   //     has a class type, the conversion copy-initializes a temporary
490   //     of type T from the glvalue and the result of the conversion
491   //     is a prvalue for the temporary.
492   // FIXME: add some way to gate this entire thing for correctness in
493   // potentially potentially evaluated contexts.
494   if (getLangOptions().CPlusPlus && E->isGLValue() &&
495       ExprEvalContexts.back().Context != Unevaluated) {
496     ExprResult Temp = PerformCopyInitialization(
497                        InitializedEntity::InitializeTemporary(E->getType()),
498                                                 E->getExprLoc(),
499                                                 Owned(E));
500     if (Temp.isInvalid())
501       return ExprError();
502     E = Temp.get();
503   }
504 
505   return Owned(E);
506 }
507 
508 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
509 /// will warn if the resulting type is not a POD type, and rejects ObjC
510 /// interfaces passed by value.
511 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
512                                                   FunctionDecl *FDecl) {
513   if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
514     // Strip the unbridged-cast placeholder expression off, if applicable.
515     if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
516         (CT == VariadicMethod ||
517          (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
518       E = stripARCUnbridgedCast(E);
519 
520     // Otherwise, do normal placeholder checking.
521     } else {
522       ExprResult ExprRes = CheckPlaceholderExpr(E);
523       if (ExprRes.isInvalid())
524         return ExprError();
525       E = ExprRes.take();
526     }
527   }
528 
529   ExprResult ExprRes = DefaultArgumentPromotion(E);
530   if (ExprRes.isInvalid())
531     return ExprError();
532   E = ExprRes.take();
533 
534   // Don't allow one to pass an Objective-C interface to a vararg.
535   if (E->getType()->isObjCObjectType() &&
536     DiagRuntimeBehavior(E->getLocStart(), 0,
537                         PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
538                           << E->getType() << CT))
539     return ExprError();
540 
541   // Complain about passing non-POD types through varargs. However, don't
542   // perform this check for incomplete types, which we can get here when we're
543   // in an unevaluated context.
544   if (!E->getType()->isIncompleteType() && !E->getType().isPODType(Context)) {
545     // C++0x [expr.call]p7:
546     //   Passing a potentially-evaluated argument of class type (Clause 9)
547     //   having a non-trivial copy constructor, a non-trivial move constructor,
548     //   or a non-trivial destructor, with no corresponding parameter,
549     //   is conditionally-supported with implementation-defined semantics.
550     bool TrivialEnough = false;
551     if (getLangOptions().CPlusPlus0x && !E->getType()->isDependentType())  {
552       if (CXXRecordDecl *Record = E->getType()->getAsCXXRecordDecl()) {
553         if (Record->hasTrivialCopyConstructor() &&
554             Record->hasTrivialMoveConstructor() &&
555             Record->hasTrivialDestructor()) {
556           DiagRuntimeBehavior(E->getLocStart(), 0,
557             PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
558               << E->getType() << CT);
559           TrivialEnough = true;
560         }
561       }
562     }
563 
564     if (!TrivialEnough &&
565         getLangOptions().ObjCAutoRefCount &&
566         E->getType()->isObjCLifetimeType())
567       TrivialEnough = true;
568 
569     if (TrivialEnough) {
570       // Nothing to diagnose. This is okay.
571     } else if (DiagRuntimeBehavior(E->getLocStart(), 0,
572                           PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
573                             << getLangOptions().CPlusPlus0x << E->getType()
574                             << CT)) {
575       // Turn this into a trap.
576       CXXScopeSpec SS;
577       UnqualifiedId Name;
578       Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
579                          E->getLocStart());
580       ExprResult TrapFn = ActOnIdExpression(TUScope, SS, Name, true, false);
581       if (TrapFn.isInvalid())
582         return ExprError();
583 
584       ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), E->getLocStart(),
585                                       MultiExprArg(), E->getLocEnd());
586       if (Call.isInvalid())
587         return ExprError();
588 
589       ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
590                                     Call.get(), E);
591       if (Comma.isInvalid())
592         return ExprError();
593       E = Comma.get();
594     }
595   }
596 
597   return Owned(E);
598 }
599 
600 /// \brief Converts an integer to complex float type.  Helper function of
601 /// UsualArithmeticConversions()
602 ///
603 /// \return false if the integer expression is an integer type and is
604 /// successfully converted to the complex type.
605 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
606                                                   ExprResult &ComplexExpr,
607                                                   QualType IntTy,
608                                                   QualType ComplexTy,
609                                                   bool SkipCast) {
610   if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
611   if (SkipCast) return false;
612   if (IntTy->isIntegerType()) {
613     QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
614     IntExpr = S.ImpCastExprToType(IntExpr.take(), fpTy, CK_IntegralToFloating);
615     IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
616                                   CK_FloatingRealToComplex);
617   } else {
618     assert(IntTy->isComplexIntegerType());
619     IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
620                                   CK_IntegralComplexToFloatingComplex);
621   }
622   return false;
623 }
624 
625 /// \brief Takes two complex float types and converts them to the same type.
626 /// Helper function of UsualArithmeticConversions()
627 static QualType
628 handleComplexFloatToComplexFloatConverstion(Sema &S, ExprResult &LHS,
629                                             ExprResult &RHS, QualType LHSType,
630                                             QualType RHSType,
631                                             bool IsCompAssign) {
632   int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
633 
634   if (order < 0) {
635     // _Complex float -> _Complex double
636     if (!IsCompAssign)
637       LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingComplexCast);
638     return RHSType;
639   }
640   if (order > 0)
641     // _Complex float -> _Complex double
642     RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingComplexCast);
643   return LHSType;
644 }
645 
646 /// \brief Converts otherExpr to complex float and promotes complexExpr if
647 /// necessary.  Helper function of UsualArithmeticConversions()
648 static QualType handleOtherComplexFloatConversion(Sema &S,
649                                                   ExprResult &ComplexExpr,
650                                                   ExprResult &OtherExpr,
651                                                   QualType ComplexTy,
652                                                   QualType OtherTy,
653                                                   bool ConvertComplexExpr,
654                                                   bool ConvertOtherExpr) {
655   int order = S.Context.getFloatingTypeOrder(ComplexTy, OtherTy);
656 
657   // If just the complexExpr is complex, the otherExpr needs to be converted,
658   // and the complexExpr might need to be promoted.
659   if (order > 0) { // complexExpr is wider
660     // float -> _Complex double
661     if (ConvertOtherExpr) {
662       QualType fp = cast<ComplexType>(ComplexTy)->getElementType();
663       OtherExpr = S.ImpCastExprToType(OtherExpr.take(), fp, CK_FloatingCast);
664       OtherExpr = S.ImpCastExprToType(OtherExpr.take(), ComplexTy,
665                                       CK_FloatingRealToComplex);
666     }
667     return ComplexTy;
668   }
669 
670   // otherTy is at least as wide.  Find its corresponding complex type.
671   QualType result = (order == 0 ? ComplexTy :
672                                   S.Context.getComplexType(OtherTy));
673 
674   // double -> _Complex double
675   if (ConvertOtherExpr)
676     OtherExpr = S.ImpCastExprToType(OtherExpr.take(), result,
677                                     CK_FloatingRealToComplex);
678 
679   // _Complex float -> _Complex double
680   if (ConvertComplexExpr && order < 0)
681     ComplexExpr = S.ImpCastExprToType(ComplexExpr.take(), result,
682                                       CK_FloatingComplexCast);
683 
684   return result;
685 }
686 
687 /// \brief Handle arithmetic conversion with complex types.  Helper function of
688 /// UsualArithmeticConversions()
689 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
690                                              ExprResult &RHS, QualType LHSType,
691                                              QualType RHSType,
692                                              bool IsCompAssign) {
693   // if we have an integer operand, the result is the complex type.
694   if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
695                                              /*skipCast*/false))
696     return LHSType;
697   if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
698                                              /*skipCast*/IsCompAssign))
699     return RHSType;
700 
701   // This handles complex/complex, complex/float, or float/complex.
702   // When both operands are complex, the shorter operand is converted to the
703   // type of the longer, and that is the type of the result. This corresponds
704   // to what is done when combining two real floating-point operands.
705   // The fun begins when size promotion occur across type domains.
706   // From H&S 6.3.4: When one operand is complex and the other is a real
707   // floating-point type, the less precise type is converted, within it's
708   // real or complex domain, to the precision of the other type. For example,
709   // when combining a "long double" with a "double _Complex", the
710   // "double _Complex" is promoted to "long double _Complex".
711 
712   bool LHSComplexFloat = LHSType->isComplexType();
713   bool RHSComplexFloat = RHSType->isComplexType();
714 
715   // If both are complex, just cast to the more precise type.
716   if (LHSComplexFloat && RHSComplexFloat)
717     return handleComplexFloatToComplexFloatConverstion(S, LHS, RHS,
718                                                        LHSType, RHSType,
719                                                        IsCompAssign);
720 
721   // If only one operand is complex, promote it if necessary and convert the
722   // other operand to complex.
723   if (LHSComplexFloat)
724     return handleOtherComplexFloatConversion(
725         S, LHS, RHS, LHSType, RHSType, /*convertComplexExpr*/!IsCompAssign,
726         /*convertOtherExpr*/ true);
727 
728   assert(RHSComplexFloat);
729   return handleOtherComplexFloatConversion(
730       S, RHS, LHS, RHSType, LHSType, /*convertComplexExpr*/true,
731       /*convertOtherExpr*/ !IsCompAssign);
732 }
733 
734 /// \brief Hande arithmetic conversion from integer to float.  Helper function
735 /// of UsualArithmeticConversions()
736 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
737                                            ExprResult &IntExpr,
738                                            QualType FloatTy, QualType IntTy,
739                                            bool ConvertFloat, bool ConvertInt) {
740   if (IntTy->isIntegerType()) {
741     if (ConvertInt)
742       // Convert intExpr to the lhs floating point type.
743       IntExpr = S.ImpCastExprToType(IntExpr.take(), FloatTy,
744                                     CK_IntegralToFloating);
745     return FloatTy;
746   }
747 
748   // Convert both sides to the appropriate complex float.
749   assert(IntTy->isComplexIntegerType());
750   QualType result = S.Context.getComplexType(FloatTy);
751 
752   // _Complex int -> _Complex float
753   if (ConvertInt)
754     IntExpr = S.ImpCastExprToType(IntExpr.take(), result,
755                                   CK_IntegralComplexToFloatingComplex);
756 
757   // float -> _Complex float
758   if (ConvertFloat)
759     FloatExpr = S.ImpCastExprToType(FloatExpr.take(), result,
760                                     CK_FloatingRealToComplex);
761 
762   return result;
763 }
764 
765 /// \brief Handle arithmethic conversion with floating point types.  Helper
766 /// function of UsualArithmeticConversions()
767 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
768                                       ExprResult &RHS, QualType LHSType,
769                                       QualType RHSType, bool IsCompAssign) {
770   bool LHSFloat = LHSType->isRealFloatingType();
771   bool RHSFloat = RHSType->isRealFloatingType();
772 
773   // If we have two real floating types, convert the smaller operand
774   // to the bigger result.
775   if (LHSFloat && RHSFloat) {
776     int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
777     if (order > 0) {
778       RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingCast);
779       return LHSType;
780     }
781 
782     assert(order < 0 && "illegal float comparison");
783     if (!IsCompAssign)
784       LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingCast);
785     return RHSType;
786   }
787 
788   if (LHSFloat)
789     return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
790                                       /*convertFloat=*/!IsCompAssign,
791                                       /*convertInt=*/ true);
792   assert(RHSFloat);
793   return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
794                                     /*convertInt=*/ true,
795                                     /*convertFloat=*/!IsCompAssign);
796 }
797 
798 /// \brief Handle conversions with GCC complex int extension.  Helper function
799 /// of UsualArithmeticConversions()
800 // FIXME: if the operands are (int, _Complex long), we currently
801 // don't promote the complex.  Also, signedness?
802 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
803                                            ExprResult &RHS, QualType LHSType,
804                                            QualType RHSType,
805                                            bool IsCompAssign) {
806   const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
807   const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
808 
809   if (LHSComplexInt && RHSComplexInt) {
810     int order = S.Context.getIntegerTypeOrder(LHSComplexInt->getElementType(),
811                                               RHSComplexInt->getElementType());
812     assert(order && "inequal types with equal element ordering");
813     if (order > 0) {
814       // _Complex int -> _Complex long
815       RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralComplexCast);
816       return LHSType;
817     }
818 
819     if (!IsCompAssign)
820       LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralComplexCast);
821     return RHSType;
822   }
823 
824   if (LHSComplexInt) {
825     // int -> _Complex int
826     // FIXME: This needs to take integer ranks into account
827     RHS = S.ImpCastExprToType(RHS.take(), LHSComplexInt->getElementType(),
828                               CK_IntegralCast);
829     RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralRealToComplex);
830     return LHSType;
831   }
832 
833   assert(RHSComplexInt);
834   // int -> _Complex int
835   // FIXME: This needs to take integer ranks into account
836   if (!IsCompAssign) {
837     LHS = S.ImpCastExprToType(LHS.take(), RHSComplexInt->getElementType(),
838                               CK_IntegralCast);
839     LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralRealToComplex);
840   }
841   return RHSType;
842 }
843 
844 /// \brief Handle integer arithmetic conversions.  Helper function of
845 /// UsualArithmeticConversions()
846 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
847                                         ExprResult &RHS, QualType LHSType,
848                                         QualType RHSType, bool IsCompAssign) {
849   // The rules for this case are in C99 6.3.1.8
850   int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
851   bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
852   bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
853   if (LHSSigned == RHSSigned) {
854     // Same signedness; use the higher-ranked type
855     if (order >= 0) {
856       RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
857       return LHSType;
858     } else if (!IsCompAssign)
859       LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
860     return RHSType;
861   } else if (order != (LHSSigned ? 1 : -1)) {
862     // The unsigned type has greater than or equal rank to the
863     // signed type, so use the unsigned type
864     if (RHSSigned) {
865       RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
866       return LHSType;
867     } else if (!IsCompAssign)
868       LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
869     return RHSType;
870   } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
871     // The two types are different widths; if we are here, that
872     // means the signed type is larger than the unsigned type, so
873     // use the signed type.
874     if (LHSSigned) {
875       RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
876       return LHSType;
877     } else if (!IsCompAssign)
878       LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
879     return RHSType;
880   } else {
881     // The signed type is higher-ranked than the unsigned type,
882     // but isn't actually any bigger (like unsigned int and long
883     // on most 32-bit systems).  Use the unsigned type corresponding
884     // to the signed type.
885     QualType result =
886       S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
887     RHS = S.ImpCastExprToType(RHS.take(), result, CK_IntegralCast);
888     if (!IsCompAssign)
889       LHS = S.ImpCastExprToType(LHS.take(), result, CK_IntegralCast);
890     return result;
891   }
892 }
893 
894 /// UsualArithmeticConversions - Performs various conversions that are common to
895 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
896 /// routine returns the first non-arithmetic type found. The client is
897 /// responsible for emitting appropriate error diagnostics.
898 /// FIXME: verify the conversion rules for "complex int" are consistent with
899 /// GCC.
900 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
901                                           bool IsCompAssign) {
902   if (!IsCompAssign) {
903     LHS = UsualUnaryConversions(LHS.take());
904     if (LHS.isInvalid())
905       return QualType();
906   }
907 
908   RHS = UsualUnaryConversions(RHS.take());
909   if (RHS.isInvalid())
910     return QualType();
911 
912   // For conversion purposes, we ignore any qualifiers.
913   // For example, "const float" and "float" are equivalent.
914   QualType LHSType =
915     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
916   QualType RHSType =
917     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
918 
919   // If both types are identical, no conversion is needed.
920   if (LHSType == RHSType)
921     return LHSType;
922 
923   // If either side is a non-arithmetic type (e.g. a pointer), we are done.
924   // The caller can deal with this (e.g. pointer + int).
925   if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
926     return LHSType;
927 
928   // Apply unary and bitfield promotions to the LHS's type.
929   QualType LHSUnpromotedType = LHSType;
930   if (LHSType->isPromotableIntegerType())
931     LHSType = Context.getPromotedIntegerType(LHSType);
932   QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
933   if (!LHSBitfieldPromoteTy.isNull())
934     LHSType = LHSBitfieldPromoteTy;
935   if (LHSType != LHSUnpromotedType && !IsCompAssign)
936     LHS = ImpCastExprToType(LHS.take(), LHSType, CK_IntegralCast);
937 
938   // If both types are identical, no conversion is needed.
939   if (LHSType == RHSType)
940     return LHSType;
941 
942   // At this point, we have two different arithmetic types.
943 
944   // Handle complex types first (C99 6.3.1.8p1).
945   if (LHSType->isComplexType() || RHSType->isComplexType())
946     return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
947                                         IsCompAssign);
948 
949   // Now handle "real" floating types (i.e. float, double, long double).
950   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
951     return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
952                                  IsCompAssign);
953 
954   // Handle GCC complex int extension.
955   if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
956     return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
957                                       IsCompAssign);
958 
959   // Finally, we have two differing integer types.
960   return handleIntegerConversion(*this, LHS, RHS, LHSType, RHSType,
961                                  IsCompAssign);
962 }
963 
964 //===----------------------------------------------------------------------===//
965 //  Semantic Analysis for various Expression Types
966 //===----------------------------------------------------------------------===//
967 
968 
969 ExprResult
970 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
971                                 SourceLocation DefaultLoc,
972                                 SourceLocation RParenLoc,
973                                 Expr *ControllingExpr,
974                                 MultiTypeArg ArgTypes,
975                                 MultiExprArg ArgExprs) {
976   unsigned NumAssocs = ArgTypes.size();
977   assert(NumAssocs == ArgExprs.size());
978 
979   ParsedType *ParsedTypes = ArgTypes.release();
980   Expr **Exprs = ArgExprs.release();
981 
982   TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
983   for (unsigned i = 0; i < NumAssocs; ++i) {
984     if (ParsedTypes[i])
985       (void) GetTypeFromParser(ParsedTypes[i], &Types[i]);
986     else
987       Types[i] = 0;
988   }
989 
990   ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
991                                              ControllingExpr, Types, Exprs,
992                                              NumAssocs);
993   delete [] Types;
994   return ER;
995 }
996 
997 ExprResult
998 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
999                                  SourceLocation DefaultLoc,
1000                                  SourceLocation RParenLoc,
1001                                  Expr *ControllingExpr,
1002                                  TypeSourceInfo **Types,
1003                                  Expr **Exprs,
1004                                  unsigned NumAssocs) {
1005   bool TypeErrorFound = false,
1006        IsResultDependent = ControllingExpr->isTypeDependent(),
1007        ContainsUnexpandedParameterPack
1008          = ControllingExpr->containsUnexpandedParameterPack();
1009 
1010   for (unsigned i = 0; i < NumAssocs; ++i) {
1011     if (Exprs[i]->containsUnexpandedParameterPack())
1012       ContainsUnexpandedParameterPack = true;
1013 
1014     if (Types[i]) {
1015       if (Types[i]->getType()->containsUnexpandedParameterPack())
1016         ContainsUnexpandedParameterPack = true;
1017 
1018       if (Types[i]->getType()->isDependentType()) {
1019         IsResultDependent = true;
1020       } else {
1021         // C1X 6.5.1.1p2 "The type name in a generic association shall specify a
1022         // complete object type other than a variably modified type."
1023         unsigned D = 0;
1024         if (Types[i]->getType()->isIncompleteType())
1025           D = diag::err_assoc_type_incomplete;
1026         else if (!Types[i]->getType()->isObjectType())
1027           D = diag::err_assoc_type_nonobject;
1028         else if (Types[i]->getType()->isVariablyModifiedType())
1029           D = diag::err_assoc_type_variably_modified;
1030 
1031         if (D != 0) {
1032           Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1033             << Types[i]->getTypeLoc().getSourceRange()
1034             << Types[i]->getType();
1035           TypeErrorFound = true;
1036         }
1037 
1038         // C1X 6.5.1.1p2 "No two generic associations in the same generic
1039         // selection shall specify compatible types."
1040         for (unsigned j = i+1; j < NumAssocs; ++j)
1041           if (Types[j] && !Types[j]->getType()->isDependentType() &&
1042               Context.typesAreCompatible(Types[i]->getType(),
1043                                          Types[j]->getType())) {
1044             Diag(Types[j]->getTypeLoc().getBeginLoc(),
1045                  diag::err_assoc_compatible_types)
1046               << Types[j]->getTypeLoc().getSourceRange()
1047               << Types[j]->getType()
1048               << Types[i]->getType();
1049             Diag(Types[i]->getTypeLoc().getBeginLoc(),
1050                  diag::note_compat_assoc)
1051               << Types[i]->getTypeLoc().getSourceRange()
1052               << Types[i]->getType();
1053             TypeErrorFound = true;
1054           }
1055       }
1056     }
1057   }
1058   if (TypeErrorFound)
1059     return ExprError();
1060 
1061   // If we determined that the generic selection is result-dependent, don't
1062   // try to compute the result expression.
1063   if (IsResultDependent)
1064     return Owned(new (Context) GenericSelectionExpr(
1065                    Context, KeyLoc, ControllingExpr,
1066                    Types, Exprs, NumAssocs, DefaultLoc,
1067                    RParenLoc, ContainsUnexpandedParameterPack));
1068 
1069   SmallVector<unsigned, 1> CompatIndices;
1070   unsigned DefaultIndex = -1U;
1071   for (unsigned i = 0; i < NumAssocs; ++i) {
1072     if (!Types[i])
1073       DefaultIndex = i;
1074     else if (Context.typesAreCompatible(ControllingExpr->getType(),
1075                                         Types[i]->getType()))
1076       CompatIndices.push_back(i);
1077   }
1078 
1079   // C1X 6.5.1.1p2 "The controlling expression of a generic selection shall have
1080   // type compatible with at most one of the types named in its generic
1081   // association list."
1082   if (CompatIndices.size() > 1) {
1083     // We strip parens here because the controlling expression is typically
1084     // parenthesized in macro definitions.
1085     ControllingExpr = ControllingExpr->IgnoreParens();
1086     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1087       << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1088       << (unsigned) CompatIndices.size();
1089     for (SmallVector<unsigned, 1>::iterator I = CompatIndices.begin(),
1090          E = CompatIndices.end(); I != E; ++I) {
1091       Diag(Types[*I]->getTypeLoc().getBeginLoc(),
1092            diag::note_compat_assoc)
1093         << Types[*I]->getTypeLoc().getSourceRange()
1094         << Types[*I]->getType();
1095     }
1096     return ExprError();
1097   }
1098 
1099   // C1X 6.5.1.1p2 "If a generic selection has no default generic association,
1100   // its controlling expression shall have type compatible with exactly one of
1101   // the types named in its generic association list."
1102   if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1103     // We strip parens here because the controlling expression is typically
1104     // parenthesized in macro definitions.
1105     ControllingExpr = ControllingExpr->IgnoreParens();
1106     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1107       << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1108     return ExprError();
1109   }
1110 
1111   // C1X 6.5.1.1p3 "If a generic selection has a generic association with a
1112   // type name that is compatible with the type of the controlling expression,
1113   // then the result expression of the generic selection is the expression
1114   // in that generic association. Otherwise, the result expression of the
1115   // generic selection is the expression in the default generic association."
1116   unsigned ResultIndex =
1117     CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1118 
1119   return Owned(new (Context) GenericSelectionExpr(
1120                  Context, KeyLoc, ControllingExpr,
1121                  Types, Exprs, NumAssocs, DefaultLoc,
1122                  RParenLoc, ContainsUnexpandedParameterPack,
1123                  ResultIndex));
1124 }
1125 
1126 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1127 /// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
1128 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1129 /// multiple tokens.  However, the common case is that StringToks points to one
1130 /// string.
1131 ///
1132 ExprResult
1133 Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
1134   assert(NumStringToks && "Must have at least one string!");
1135 
1136   StringLiteralParser Literal(StringToks, NumStringToks, PP);
1137   if (Literal.hadError)
1138     return ExprError();
1139 
1140   SmallVector<SourceLocation, 4> StringTokLocs;
1141   for (unsigned i = 0; i != NumStringToks; ++i)
1142     StringTokLocs.push_back(StringToks[i].getLocation());
1143 
1144   QualType StrTy = Context.CharTy;
1145   if (Literal.isWide())
1146     StrTy = Context.getWCharType();
1147   else if (Literal.isUTF16())
1148     StrTy = Context.Char16Ty;
1149   else if (Literal.isUTF32())
1150     StrTy = Context.Char32Ty;
1151   else if (Literal.isPascal())
1152     StrTy = Context.UnsignedCharTy;
1153 
1154   StringLiteral::StringKind Kind = StringLiteral::Ascii;
1155   if (Literal.isWide())
1156     Kind = StringLiteral::Wide;
1157   else if (Literal.isUTF8())
1158     Kind = StringLiteral::UTF8;
1159   else if (Literal.isUTF16())
1160     Kind = StringLiteral::UTF16;
1161   else if (Literal.isUTF32())
1162     Kind = StringLiteral::UTF32;
1163 
1164   // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
1165   if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings)
1166     StrTy.addConst();
1167 
1168   // Get an array type for the string, according to C99 6.4.5.  This includes
1169   // the nul terminator character as well as the string length for pascal
1170   // strings.
1171   StrTy = Context.getConstantArrayType(StrTy,
1172                                  llvm::APInt(32, Literal.GetNumStringChars()+1),
1173                                        ArrayType::Normal, 0);
1174 
1175   // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1176   return Owned(StringLiteral::Create(Context, Literal.GetString(),
1177                                      Kind, Literal.Pascal, StrTy,
1178                                      &StringTokLocs[0],
1179                                      StringTokLocs.size()));
1180 }
1181 
1182 enum CaptureResult {
1183   /// No capture is required.
1184   CR_NoCapture,
1185 
1186   /// A capture is required.
1187   CR_Capture,
1188 
1189   /// A by-ref capture is required.
1190   CR_CaptureByRef,
1191 
1192   /// An error occurred when trying to capture the given variable.
1193   CR_Error
1194 };
1195 
1196 /// Diagnose an uncapturable value reference.
1197 ///
1198 /// \param var - the variable referenced
1199 /// \param DC - the context which we couldn't capture through
1200 static CaptureResult
1201 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
1202                                    VarDecl *var, DeclContext *DC) {
1203   switch (S.ExprEvalContexts.back().Context) {
1204   case Sema::Unevaluated:
1205     // The argument will never be evaluated, so don't complain.
1206     return CR_NoCapture;
1207 
1208   case Sema::PotentiallyEvaluated:
1209   case Sema::PotentiallyEvaluatedIfUsed:
1210     break;
1211 
1212   case Sema::PotentiallyPotentiallyEvaluated:
1213     // FIXME: delay these!
1214     break;
1215   }
1216 
1217   // Don't diagnose about capture if we're not actually in code right
1218   // now; in general, there are more appropriate places that will
1219   // diagnose this.
1220   if (!S.CurContext->isFunctionOrMethod()) return CR_NoCapture;
1221 
1222   // Certain madnesses can happen with parameter declarations, which
1223   // we want to ignore.
1224   if (isa<ParmVarDecl>(var)) {
1225     // - If the parameter still belongs to the translation unit, then
1226     //   we're actually just using one parameter in the declaration of
1227     //   the next.  This is useful in e.g. VLAs.
1228     if (isa<TranslationUnitDecl>(var->getDeclContext()))
1229       return CR_NoCapture;
1230 
1231     // - This particular madness can happen in ill-formed default
1232     //   arguments; claim it's okay and let downstream code handle it.
1233     if (S.CurContext == var->getDeclContext()->getParent())
1234       return CR_NoCapture;
1235   }
1236 
1237   DeclarationName functionName;
1238   if (FunctionDecl *fn = dyn_cast<FunctionDecl>(var->getDeclContext()))
1239     functionName = fn->getDeclName();
1240   // FIXME: variable from enclosing block that we couldn't capture from!
1241 
1242   S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
1243     << var->getIdentifier() << functionName;
1244   S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
1245     << var->getIdentifier();
1246 
1247   return CR_Error;
1248 }
1249 
1250 /// There is a well-formed capture at a particular scope level;
1251 /// propagate it through all the nested blocks.
1252 static CaptureResult propagateCapture(Sema &S, unsigned ValidScopeIndex,
1253                                       const BlockDecl::Capture &Capture) {
1254   VarDecl *var = Capture.getVariable();
1255 
1256   // Update all the inner blocks with the capture information.
1257   for (unsigned i = ValidScopeIndex + 1, e = S.FunctionScopes.size();
1258          i != e; ++i) {
1259     BlockScopeInfo *innerBlock = cast<BlockScopeInfo>(S.FunctionScopes[i]);
1260     innerBlock->Captures.push_back(
1261       BlockDecl::Capture(Capture.getVariable(), Capture.isByRef(),
1262                          /*nested*/ true, Capture.getCopyExpr()));
1263     innerBlock->CaptureMap[var] = innerBlock->Captures.size(); // +1
1264   }
1265 
1266   return Capture.isByRef() ? CR_CaptureByRef : CR_Capture;
1267 }
1268 
1269 /// shouldCaptureValueReference - Determine if a reference to the
1270 /// given value in the current context requires a variable capture.
1271 ///
1272 /// This also keeps the captures set in the BlockScopeInfo records
1273 /// up-to-date.
1274 static CaptureResult shouldCaptureValueReference(Sema &S, SourceLocation loc,
1275                                                  ValueDecl *Value) {
1276   // Only variables ever require capture.
1277   VarDecl *var = dyn_cast<VarDecl>(Value);
1278   if (!var) return CR_NoCapture;
1279 
1280   // Fast path: variables from the current context never require capture.
1281   DeclContext *DC = S.CurContext;
1282   if (var->getDeclContext() == DC) return CR_NoCapture;
1283 
1284   // Only variables with local storage require capture.
1285   // FIXME: What about 'const' variables in C++?
1286   if (!var->hasLocalStorage()) return CR_NoCapture;
1287 
1288   // Otherwise, we need to capture.
1289 
1290   unsigned functionScopesIndex = S.FunctionScopes.size() - 1;
1291   do {
1292     // Only blocks (and eventually C++0x closures) can capture; other
1293     // scopes don't work.
1294     if (!isa<BlockDecl>(DC))
1295       return diagnoseUncapturableValueReference(S, loc, var, DC);
1296 
1297     BlockScopeInfo *blockScope =
1298       cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
1299     assert(blockScope->TheDecl == static_cast<BlockDecl*>(DC));
1300 
1301     // Check whether we've already captured it in this block.  If so,
1302     // we're done.
1303     if (unsigned indexPlus1 = blockScope->CaptureMap[var])
1304       return propagateCapture(S, functionScopesIndex,
1305                               blockScope->Captures[indexPlus1 - 1]);
1306 
1307     functionScopesIndex--;
1308     DC = cast<BlockDecl>(DC)->getDeclContext();
1309   } while (var->getDeclContext() != DC);
1310 
1311   // Okay, we descended all the way to the block that defines the variable.
1312   // Actually try to capture it.
1313   QualType type = var->getType();
1314 
1315   // Prohibit variably-modified types.
1316   if (type->isVariablyModifiedType()) {
1317     S.Diag(loc, diag::err_ref_vm_type);
1318     S.Diag(var->getLocation(), diag::note_declared_at);
1319     return CR_Error;
1320   }
1321 
1322   // Prohibit arrays, even in __block variables, but not references to
1323   // them.
1324   if (type->isArrayType()) {
1325     S.Diag(loc, diag::err_ref_array_type);
1326     S.Diag(var->getLocation(), diag::note_declared_at);
1327     return CR_Error;
1328   }
1329 
1330   S.MarkDeclarationReferenced(loc, var);
1331 
1332   // The BlocksAttr indicates the variable is bound by-reference.
1333   bool byRef = var->hasAttr<BlocksAttr>();
1334 
1335   // Build a copy expression.
1336   Expr *copyExpr = 0;
1337   const RecordType *rtype;
1338   if (!byRef && S.getLangOptions().CPlusPlus && !type->isDependentType() &&
1339       (rtype = type->getAs<RecordType>())) {
1340 
1341     // The capture logic needs the destructor, so make sure we mark it.
1342     // Usually this is unnecessary because most local variables have
1343     // their destructors marked at declaration time, but parameters are
1344     // an exception because it's technically only the call site that
1345     // actually requires the destructor.
1346     if (isa<ParmVarDecl>(var))
1347       S.FinalizeVarWithDestructor(var, rtype);
1348 
1349     // According to the blocks spec, the capture of a variable from
1350     // the stack requires a const copy constructor.  This is not true
1351     // of the copy/move done to move a __block variable to the heap.
1352     type.addConst();
1353 
1354     Expr *declRef = new (S.Context) DeclRefExpr(var, type, VK_LValue, loc);
1355     ExprResult result =
1356       S.PerformCopyInitialization(
1357                       InitializedEntity::InitializeBlock(var->getLocation(),
1358                                                          type, false),
1359                                   loc, S.Owned(declRef));
1360 
1361     // Build a full-expression copy expression if initialization
1362     // succeeded and used a non-trivial constructor.  Recover from
1363     // errors by pretending that the copy isn't necessary.
1364     if (!result.isInvalid() &&
1365         !cast<CXXConstructExpr>(result.get())->getConstructor()->isTrivial()) {
1366       result = S.MaybeCreateExprWithCleanups(result);
1367       copyExpr = result.take();
1368     }
1369   }
1370 
1371   // We're currently at the declarer; go back to the closure.
1372   functionScopesIndex++;
1373   BlockScopeInfo *blockScope =
1374     cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
1375 
1376   // Build a valid capture in this scope.
1377   blockScope->Captures.push_back(
1378                  BlockDecl::Capture(var, byRef, /*nested*/ false, copyExpr));
1379   blockScope->CaptureMap[var] = blockScope->Captures.size(); // +1
1380 
1381   // Propagate that to inner captures if necessary.
1382   return propagateCapture(S, functionScopesIndex,
1383                           blockScope->Captures.back());
1384 }
1385 
1386 static ExprResult BuildBlockDeclRefExpr(Sema &S, ValueDecl *VD,
1387                                         const DeclarationNameInfo &NameInfo,
1388                                         bool ByRef) {
1389   assert(isa<VarDecl>(VD) && "capturing non-variable");
1390 
1391   VarDecl *var = cast<VarDecl>(VD);
1392   assert(var->hasLocalStorage() && "capturing non-local");
1393   assert(ByRef == var->hasAttr<BlocksAttr>() && "byref set wrong");
1394 
1395   QualType exprType = var->getType().getNonReferenceType();
1396 
1397   BlockDeclRefExpr *BDRE;
1398   if (!ByRef) {
1399     // The variable will be bound by copy; make it const within the
1400     // closure, but record that this was done in the expression.
1401     bool constAdded = !exprType.isConstQualified();
1402     exprType.addConst();
1403 
1404     BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
1405                                             NameInfo.getLoc(), false,
1406                                             constAdded);
1407   } else {
1408     BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
1409                                             NameInfo.getLoc(), true);
1410   }
1411 
1412   return S.Owned(BDRE);
1413 }
1414 
1415 ExprResult
1416 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1417                        SourceLocation Loc,
1418                        const CXXScopeSpec *SS) {
1419   DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1420   return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1421 }
1422 
1423 /// BuildDeclRefExpr - Build an expression that references a
1424 /// declaration that does not require a closure capture.
1425 ExprResult
1426 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1427                        const DeclarationNameInfo &NameInfo,
1428                        const CXXScopeSpec *SS) {
1429   if (getLangOptions().CUDA)
1430     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
1431       if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) {
1432         CUDAFunctionTarget CallerTarget = IdentifyCUDATarget(Caller),
1433                            CalleeTarget = IdentifyCUDATarget(Callee);
1434         if (CheckCUDATarget(CallerTarget, CalleeTarget)) {
1435           Diag(NameInfo.getLoc(), diag::err_ref_bad_target)
1436             << CalleeTarget << D->getIdentifier() << CallerTarget;
1437           Diag(D->getLocation(), diag::note_previous_decl)
1438             << D->getIdentifier();
1439           return ExprError();
1440         }
1441       }
1442 
1443   MarkDeclarationReferenced(NameInfo.getLoc(), D);
1444 
1445   Expr *E = DeclRefExpr::Create(Context,
1446                                 SS? SS->getWithLocInContext(Context)
1447                                   : NestedNameSpecifierLoc(),
1448                                 D, NameInfo, Ty, VK);
1449 
1450   // Just in case we're building an illegal pointer-to-member.
1451   FieldDecl *FD = dyn_cast<FieldDecl>(D);
1452   if (FD && FD->isBitField())
1453     E->setObjectKind(OK_BitField);
1454 
1455   return Owned(E);
1456 }
1457 
1458 /// Decomposes the given name into a DeclarationNameInfo, its location, and
1459 /// possibly a list of template arguments.
1460 ///
1461 /// If this produces template arguments, it is permitted to call
1462 /// DecomposeTemplateName.
1463 ///
1464 /// This actually loses a lot of source location information for
1465 /// non-standard name kinds; we should consider preserving that in
1466 /// some way.
1467 void
1468 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1469                              TemplateArgumentListInfo &Buffer,
1470                              DeclarationNameInfo &NameInfo,
1471                              const TemplateArgumentListInfo *&TemplateArgs) {
1472   if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1473     Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1474     Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1475 
1476     ASTTemplateArgsPtr TemplateArgsPtr(*this,
1477                                        Id.TemplateId->getTemplateArgs(),
1478                                        Id.TemplateId->NumArgs);
1479     translateTemplateArguments(TemplateArgsPtr, Buffer);
1480     TemplateArgsPtr.release();
1481 
1482     TemplateName TName = Id.TemplateId->Template.get();
1483     SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1484     NameInfo = Context.getNameForTemplate(TName, TNameLoc);
1485     TemplateArgs = &Buffer;
1486   } else {
1487     NameInfo = GetNameFromUnqualifiedId(Id);
1488     TemplateArgs = 0;
1489   }
1490 }
1491 
1492 /// Diagnose an empty lookup.
1493 ///
1494 /// \return false if new lookup candidates were found
1495 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1496                                CorrectTypoContext CTC,
1497                                TemplateArgumentListInfo *ExplicitTemplateArgs,
1498                                Expr **Args, unsigned NumArgs) {
1499   DeclarationName Name = R.getLookupName();
1500 
1501   unsigned diagnostic = diag::err_undeclared_var_use;
1502   unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
1503   if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1504       Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
1505       Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
1506     diagnostic = diag::err_undeclared_use;
1507     diagnostic_suggest = diag::err_undeclared_use_suggest;
1508   }
1509 
1510   // If the original lookup was an unqualified lookup, fake an
1511   // unqualified lookup.  This is useful when (for example) the
1512   // original lookup would not have found something because it was a
1513   // dependent name.
1514   for (DeclContext *DC = SS.isEmpty() ? CurContext : 0;
1515        DC; DC = DC->getParent()) {
1516     if (isa<CXXRecordDecl>(DC)) {
1517       LookupQualifiedName(R, DC);
1518 
1519       if (!R.empty()) {
1520         // Don't give errors about ambiguities in this lookup.
1521         R.suppressDiagnostics();
1522 
1523         // During a default argument instantiation the CurContext points
1524         // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1525         // function parameter list, hence add an explicit check.
1526         bool isDefaultArgument = !ActiveTemplateInstantiations.empty() &&
1527                               ActiveTemplateInstantiations.back().Kind ==
1528             ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
1529         CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1530         bool isInstance = CurMethod &&
1531                           CurMethod->isInstance() &&
1532                           DC == CurMethod->getParent() && !isDefaultArgument;
1533 
1534 
1535         // Give a code modification hint to insert 'this->'.
1536         // TODO: fixit for inserting 'Base<T>::' in the other cases.
1537         // Actually quite difficult!
1538         if (isInstance) {
1539           UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1540               CallsUndergoingInstantiation.back()->getCallee());
1541           CXXMethodDecl *DepMethod = cast_or_null<CXXMethodDecl>(
1542               CurMethod->getInstantiatedFromMemberFunction());
1543           if (DepMethod) {
1544             if (getLangOptions().MicrosoftMode)
1545               diagnostic = diag::warn_found_via_dependent_bases_lookup;
1546             Diag(R.getNameLoc(), diagnostic) << Name
1547               << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1548             QualType DepThisType = DepMethod->getThisType(Context);
1549             CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1550                                        R.getNameLoc(), DepThisType, false);
1551             TemplateArgumentListInfo TList;
1552             if (ULE->hasExplicitTemplateArgs())
1553               ULE->copyTemplateArgumentsInto(TList);
1554 
1555             CXXScopeSpec SS;
1556             SS.Adopt(ULE->getQualifierLoc());
1557             CXXDependentScopeMemberExpr *DepExpr =
1558                 CXXDependentScopeMemberExpr::Create(
1559                     Context, DepThis, DepThisType, true, SourceLocation(),
1560                     SS.getWithLocInContext(Context), NULL,
1561                     R.getLookupNameInfo(),
1562                     ULE->hasExplicitTemplateArgs() ? &TList : 0);
1563             CallsUndergoingInstantiation.back()->setCallee(DepExpr);
1564           } else {
1565             // FIXME: we should be able to handle this case too. It is correct
1566             // to add this-> here. This is a workaround for PR7947.
1567             Diag(R.getNameLoc(), diagnostic) << Name;
1568           }
1569         } else {
1570           if (getLangOptions().MicrosoftMode)
1571             diagnostic = diag::warn_found_via_dependent_bases_lookup;
1572           Diag(R.getNameLoc(), diagnostic) << Name;
1573         }
1574 
1575         // Do we really want to note all of these?
1576         for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1577           Diag((*I)->getLocation(), diag::note_dependent_var_use);
1578 
1579         // Return true if we are inside a default argument instantiation
1580         // and the found name refers to an instance member function, otherwise
1581         // the function calling DiagnoseEmptyLookup will try to create an
1582         // implicit member call and this is wrong for default argument.
1583         if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1584           Diag(R.getNameLoc(), diag::err_member_call_without_object);
1585           return true;
1586         }
1587 
1588         // Tell the callee to try to recover.
1589         return false;
1590       }
1591 
1592       R.clear();
1593     }
1594   }
1595 
1596   // We didn't find anything, so try to correct for a typo.
1597   TypoCorrection Corrected;
1598   if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
1599                                     S, &SS, NULL, false, CTC))) {
1600     std::string CorrectedStr(Corrected.getAsString(getLangOptions()));
1601     std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOptions()));
1602     R.setLookupName(Corrected.getCorrection());
1603 
1604     if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
1605       if (Corrected.isOverloaded()) {
1606         OverloadCandidateSet OCS(R.getNameLoc());
1607         OverloadCandidateSet::iterator Best;
1608         for (TypoCorrection::decl_iterator CD = Corrected.begin(),
1609                                         CDEnd = Corrected.end();
1610              CD != CDEnd; ++CD) {
1611           if (FunctionTemplateDecl *FTD =
1612                    dyn_cast<FunctionTemplateDecl>(*CD))
1613             AddTemplateOverloadCandidate(
1614                 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
1615                 Args, NumArgs, OCS);
1616           else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
1617             if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1618               AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
1619                                    Args, NumArgs, OCS);
1620         }
1621         switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1622           case OR_Success:
1623             ND = Best->Function;
1624             break;
1625           default:
1626             break;
1627         }
1628       }
1629       R.addDecl(ND);
1630       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
1631         if (SS.isEmpty())
1632           Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr
1633             << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1634         else
1635           Diag(R.getNameLoc(), diag::err_no_member_suggest)
1636             << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
1637             << SS.getRange()
1638             << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1639         if (ND)
1640           Diag(ND->getLocation(), diag::note_previous_decl)
1641             << CorrectedQuotedStr;
1642 
1643         // Tell the callee to try to recover.
1644         return false;
1645       }
1646 
1647       if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) {
1648         // FIXME: If we ended up with a typo for a type name or
1649         // Objective-C class name, we're in trouble because the parser
1650         // is in the wrong place to recover. Suggest the typo
1651         // correction, but don't make it a fix-it since we're not going
1652         // to recover well anyway.
1653         if (SS.isEmpty())
1654           Diag(R.getNameLoc(), diagnostic_suggest)
1655             << Name << CorrectedQuotedStr;
1656         else
1657           Diag(R.getNameLoc(), diag::err_no_member_suggest)
1658             << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
1659             << SS.getRange();
1660 
1661         // Don't try to recover; it won't work.
1662         return true;
1663       }
1664     } else {
1665       // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
1666       // because we aren't able to recover.
1667       if (SS.isEmpty())
1668         Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr;
1669       else
1670         Diag(R.getNameLoc(), diag::err_no_member_suggest)
1671         << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
1672         << SS.getRange();
1673       return true;
1674     }
1675   }
1676   R.clear();
1677 
1678   // Emit a special diagnostic for failed member lookups.
1679   // FIXME: computing the declaration context might fail here (?)
1680   if (!SS.isEmpty()) {
1681     Diag(R.getNameLoc(), diag::err_no_member)
1682       << Name << computeDeclContext(SS, false)
1683       << SS.getRange();
1684     return true;
1685   }
1686 
1687   // Give up, we can't recover.
1688   Diag(R.getNameLoc(), diagnostic) << Name;
1689   return true;
1690 }
1691 
1692 ExprResult Sema::ActOnIdExpression(Scope *S,
1693                                    CXXScopeSpec &SS,
1694                                    UnqualifiedId &Id,
1695                                    bool HasTrailingLParen,
1696                                    bool IsAddressOfOperand) {
1697   assert(!(IsAddressOfOperand && HasTrailingLParen) &&
1698          "cannot be direct & operand and have a trailing lparen");
1699 
1700   if (SS.isInvalid())
1701     return ExprError();
1702 
1703   TemplateArgumentListInfo TemplateArgsBuffer;
1704 
1705   // Decompose the UnqualifiedId into the following data.
1706   DeclarationNameInfo NameInfo;
1707   const TemplateArgumentListInfo *TemplateArgs;
1708   DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
1709 
1710   DeclarationName Name = NameInfo.getName();
1711   IdentifierInfo *II = Name.getAsIdentifierInfo();
1712   SourceLocation NameLoc = NameInfo.getLoc();
1713 
1714   // C++ [temp.dep.expr]p3:
1715   //   An id-expression is type-dependent if it contains:
1716   //     -- an identifier that was declared with a dependent type,
1717   //        (note: handled after lookup)
1718   //     -- a template-id that is dependent,
1719   //        (note: handled in BuildTemplateIdExpr)
1720   //     -- a conversion-function-id that specifies a dependent type,
1721   //     -- a nested-name-specifier that contains a class-name that
1722   //        names a dependent type.
1723   // Determine whether this is a member of an unknown specialization;
1724   // we need to handle these differently.
1725   bool DependentID = false;
1726   if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1727       Name.getCXXNameType()->isDependentType()) {
1728     DependentID = true;
1729   } else if (SS.isSet()) {
1730     if (DeclContext *DC = computeDeclContext(SS, false)) {
1731       if (RequireCompleteDeclContext(SS, DC))
1732         return ExprError();
1733     } else {
1734       DependentID = true;
1735     }
1736   }
1737 
1738   if (DependentID)
1739     return ActOnDependentIdExpression(SS, NameInfo, IsAddressOfOperand,
1740                                       TemplateArgs);
1741 
1742   bool IvarLookupFollowUp = false;
1743   // Perform the required lookup.
1744   LookupResult R(*this, NameInfo,
1745                  (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
1746                   ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
1747   if (TemplateArgs) {
1748     // Lookup the template name again to correctly establish the context in
1749     // which it was found. This is really unfortunate as we already did the
1750     // lookup to determine that it was a template name in the first place. If
1751     // this becomes a performance hit, we can work harder to preserve those
1752     // results until we get here but it's likely not worth it.
1753     bool MemberOfUnknownSpecialization;
1754     LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1755                        MemberOfUnknownSpecialization);
1756 
1757     if (MemberOfUnknownSpecialization ||
1758         (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
1759       return ActOnDependentIdExpression(SS, NameInfo, IsAddressOfOperand,
1760                                         TemplateArgs);
1761   } else {
1762     IvarLookupFollowUp = (!SS.isSet() && II && getCurMethodDecl());
1763     LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
1764 
1765     // If the result might be in a dependent base class, this is a dependent
1766     // id-expression.
1767     if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
1768       return ActOnDependentIdExpression(SS, NameInfo, IsAddressOfOperand,
1769                                         TemplateArgs);
1770 
1771     // If this reference is in an Objective-C method, then we need to do
1772     // some special Objective-C lookup, too.
1773     if (IvarLookupFollowUp) {
1774       ExprResult E(LookupInObjCMethod(R, S, II, true));
1775       if (E.isInvalid())
1776         return ExprError();
1777 
1778       if (Expr *Ex = E.takeAs<Expr>())
1779         return Owned(Ex);
1780 
1781       // for further use, this must be set to false if in class method.
1782       IvarLookupFollowUp = getCurMethodDecl()->isInstanceMethod();
1783     }
1784   }
1785 
1786   if (R.isAmbiguous())
1787     return ExprError();
1788 
1789   // Determine whether this name might be a candidate for
1790   // argument-dependent lookup.
1791   bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
1792 
1793   if (R.empty() && !ADL) {
1794     // Otherwise, this could be an implicitly declared function reference (legal
1795     // in C90, extension in C99, forbidden in C++).
1796     if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) {
1797       NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1798       if (D) R.addDecl(D);
1799     }
1800 
1801     // If this name wasn't predeclared and if this is not a function
1802     // call, diagnose the problem.
1803     if (R.empty()) {
1804 
1805       // In Microsoft mode, if we are inside a template class member function
1806       // and we can't resolve an identifier then assume the identifier is type
1807       // dependent. The goal is to postpone name lookup to instantiation time
1808       // to be able to search into type dependent base classes.
1809       if (getLangOptions().MicrosoftMode && CurContext->isDependentContext() &&
1810           isa<CXXMethodDecl>(CurContext))
1811         return ActOnDependentIdExpression(SS, NameInfo, IsAddressOfOperand,
1812                                           TemplateArgs);
1813 
1814       if (DiagnoseEmptyLookup(S, SS, R, CTC_Unknown))
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 move(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, R, TemplateArgs);
1878   }
1879 
1880   if (TemplateArgs)
1881     return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs);
1882 
1883   return BuildDeclarationNameExpr(SS, R, ADL);
1884 }
1885 
1886 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1887 /// declaration name, generally during template instantiation.
1888 /// There's a large number of things which don't need to be done along
1889 /// this path.
1890 ExprResult
1891 Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
1892                                         const DeclarationNameInfo &NameInfo) {
1893   DeclContext *DC;
1894   if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
1895     return BuildDependentDeclRefExpr(SS, NameInfo, 0);
1896 
1897   if (RequireCompleteDeclContext(SS, DC))
1898     return ExprError();
1899 
1900   LookupResult R(*this, NameInfo, LookupOrdinaryName);
1901   LookupQualifiedName(R, DC);
1902 
1903   if (R.isAmbiguous())
1904     return ExprError();
1905 
1906   if (R.empty()) {
1907     Diag(NameInfo.getLoc(), diag::err_no_member)
1908       << NameInfo.getName() << DC << SS.getRange();
1909     return ExprError();
1910   }
1911 
1912   return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1913 }
1914 
1915 /// LookupInObjCMethod - The parser has read a name in, and Sema has
1916 /// detected that we're currently inside an ObjC method.  Perform some
1917 /// additional lookup.
1918 ///
1919 /// Ideally, most of this would be done by lookup, but there's
1920 /// actually quite a lot of extra work involved.
1921 ///
1922 /// Returns a null sentinel to indicate trivial success.
1923 ExprResult
1924 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
1925                          IdentifierInfo *II, bool AllowBuiltinCreation) {
1926   SourceLocation Loc = Lookup.getNameLoc();
1927   ObjCMethodDecl *CurMethod = getCurMethodDecl();
1928 
1929   // There are two cases to handle here.  1) scoped lookup could have failed,
1930   // in which case we should look for an ivar.  2) scoped lookup could have
1931   // found a decl, but that decl is outside the current instance method (i.e.
1932   // a global variable).  In these two cases, we do a lookup for an ivar with
1933   // this name, if the lookup sucedes, we replace it our current decl.
1934 
1935   // If we're in a class method, we don't normally want to look for
1936   // ivars.  But if we don't find anything else, and there's an
1937   // ivar, that's an error.
1938   bool IsClassMethod = CurMethod->isClassMethod();
1939 
1940   bool LookForIvars;
1941   if (Lookup.empty())
1942     LookForIvars = true;
1943   else if (IsClassMethod)
1944     LookForIvars = false;
1945   else
1946     LookForIvars = (Lookup.isSingleResult() &&
1947                     Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
1948   ObjCInterfaceDecl *IFace = 0;
1949   if (LookForIvars) {
1950     IFace = CurMethod->getClassInterface();
1951     ObjCInterfaceDecl *ClassDeclared;
1952     ObjCIvarDecl *IV = 0;
1953     if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
1954       // Diagnose using an ivar in a class method.
1955       if (IsClassMethod)
1956         return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1957                          << IV->getDeclName());
1958 
1959       // If we're referencing an invalid decl, just return this as a silent
1960       // error node.  The error diagnostic was already emitted on the decl.
1961       if (IV->isInvalidDecl())
1962         return ExprError();
1963 
1964       // Check if referencing a field with __attribute__((deprecated)).
1965       if (DiagnoseUseOfDecl(IV, Loc))
1966         return ExprError();
1967 
1968       // Diagnose the use of an ivar outside of the declaring class.
1969       if (IV->getAccessControl() == ObjCIvarDecl::Private &&
1970           ClassDeclared != IFace)
1971         Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1972 
1973       // FIXME: This should use a new expr for a direct reference, don't
1974       // turn this into Self->ivar, just return a BareIVarExpr or something.
1975       IdentifierInfo &II = Context.Idents.get("self");
1976       UnqualifiedId SelfName;
1977       SelfName.setIdentifier(&II, SourceLocation());
1978       SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
1979       CXXScopeSpec SelfScopeSpec;
1980       ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
1981                                               SelfName, false, false);
1982       if (SelfExpr.isInvalid())
1983         return ExprError();
1984 
1985       SelfExpr = DefaultLvalueConversion(SelfExpr.take());
1986       if (SelfExpr.isInvalid())
1987         return ExprError();
1988 
1989       MarkDeclarationReferenced(Loc, IV);
1990       return Owned(new (Context)
1991                    ObjCIvarRefExpr(IV, IV->getType(), Loc,
1992                                    SelfExpr.take(), true, true));
1993     }
1994   } else if (CurMethod->isInstanceMethod()) {
1995     // We should warn if a local variable hides an ivar.
1996     if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
1997       ObjCInterfaceDecl *ClassDeclared;
1998       if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1999         if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2000             IFace == ClassDeclared)
2001           Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2002       }
2003     }
2004   }
2005 
2006   if (Lookup.empty() && II && AllowBuiltinCreation) {
2007     // FIXME. Consolidate this with similar code in LookupName.
2008     if (unsigned BuiltinID = II->getBuiltinID()) {
2009       if (!(getLangOptions().CPlusPlus &&
2010             Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2011         NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2012                                            S, Lookup.isForRedeclaration(),
2013                                            Lookup.getNameLoc());
2014         if (D) Lookup.addDecl(D);
2015       }
2016     }
2017   }
2018   // Sentinel value saying that we didn't do anything special.
2019   return Owned((Expr*) 0);
2020 }
2021 
2022 /// \brief Cast a base object to a member's actual type.
2023 ///
2024 /// Logically this happens in three phases:
2025 ///
2026 /// * First we cast from the base type to the naming class.
2027 ///   The naming class is the class into which we were looking
2028 ///   when we found the member;  it's the qualifier type if a
2029 ///   qualifier was provided, and otherwise it's the base type.
2030 ///
2031 /// * Next we cast from the naming class to the declaring class.
2032 ///   If the member we found was brought into a class's scope by
2033 ///   a using declaration, this is that class;  otherwise it's
2034 ///   the class declaring the member.
2035 ///
2036 /// * Finally we cast from the declaring class to the "true"
2037 ///   declaring class of the member.  This conversion does not
2038 ///   obey access control.
2039 ExprResult
2040 Sema::PerformObjectMemberConversion(Expr *From,
2041                                     NestedNameSpecifier *Qualifier,
2042                                     NamedDecl *FoundDecl,
2043                                     NamedDecl *Member) {
2044   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2045   if (!RD)
2046     return Owned(From);
2047 
2048   QualType DestRecordType;
2049   QualType DestType;
2050   QualType FromRecordType;
2051   QualType FromType = From->getType();
2052   bool PointerConversions = false;
2053   if (isa<FieldDecl>(Member)) {
2054     DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2055 
2056     if (FromType->getAs<PointerType>()) {
2057       DestType = Context.getPointerType(DestRecordType);
2058       FromRecordType = FromType->getPointeeType();
2059       PointerConversions = true;
2060     } else {
2061       DestType = DestRecordType;
2062       FromRecordType = FromType;
2063     }
2064   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2065     if (Method->isStatic())
2066       return Owned(From);
2067 
2068     DestType = Method->getThisType(Context);
2069     DestRecordType = DestType->getPointeeType();
2070 
2071     if (FromType->getAs<PointerType>()) {
2072       FromRecordType = FromType->getPointeeType();
2073       PointerConversions = true;
2074     } else {
2075       FromRecordType = FromType;
2076       DestType = DestRecordType;
2077     }
2078   } else {
2079     // No conversion necessary.
2080     return Owned(From);
2081   }
2082 
2083   if (DestType->isDependentType() || FromType->isDependentType())
2084     return Owned(From);
2085 
2086   // If the unqualified types are the same, no conversion is necessary.
2087   if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2088     return Owned(From);
2089 
2090   SourceRange FromRange = From->getSourceRange();
2091   SourceLocation FromLoc = FromRange.getBegin();
2092 
2093   ExprValueKind VK = From->getValueKind();
2094 
2095   // C++ [class.member.lookup]p8:
2096   //   [...] Ambiguities can often be resolved by qualifying a name with its
2097   //   class name.
2098   //
2099   // If the member was a qualified name and the qualified referred to a
2100   // specific base subobject type, we'll cast to that intermediate type
2101   // first and then to the object in which the member is declared. That allows
2102   // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2103   //
2104   //   class Base { public: int x; };
2105   //   class Derived1 : public Base { };
2106   //   class Derived2 : public Base { };
2107   //   class VeryDerived : public Derived1, public Derived2 { void f(); };
2108   //
2109   //   void VeryDerived::f() {
2110   //     x = 17; // error: ambiguous base subobjects
2111   //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
2112   //   }
2113   if (Qualifier) {
2114     QualType QType = QualType(Qualifier->getAsType(), 0);
2115     assert(!QType.isNull() && "lookup done with dependent qualifier?");
2116     assert(QType->isRecordType() && "lookup done with non-record type");
2117 
2118     QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2119 
2120     // In C++98, the qualifier type doesn't actually have to be a base
2121     // type of the object type, in which case we just ignore it.
2122     // Otherwise build the appropriate casts.
2123     if (IsDerivedFrom(FromRecordType, QRecordType)) {
2124       CXXCastPath BasePath;
2125       if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2126                                        FromLoc, FromRange, &BasePath))
2127         return ExprError();
2128 
2129       if (PointerConversions)
2130         QType = Context.getPointerType(QType);
2131       From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2132                                VK, &BasePath).take();
2133 
2134       FromType = QType;
2135       FromRecordType = QRecordType;
2136 
2137       // If the qualifier type was the same as the destination type,
2138       // we're done.
2139       if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2140         return Owned(From);
2141     }
2142   }
2143 
2144   bool IgnoreAccess = false;
2145 
2146   // If we actually found the member through a using declaration, cast
2147   // down to the using declaration's type.
2148   //
2149   // Pointer equality is fine here because only one declaration of a
2150   // class ever has member declarations.
2151   if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2152     assert(isa<UsingShadowDecl>(FoundDecl));
2153     QualType URecordType = Context.getTypeDeclType(
2154                            cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2155 
2156     // We only need to do this if the naming-class to declaring-class
2157     // conversion is non-trivial.
2158     if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2159       assert(IsDerivedFrom(FromRecordType, URecordType));
2160       CXXCastPath BasePath;
2161       if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2162                                        FromLoc, FromRange, &BasePath))
2163         return ExprError();
2164 
2165       QualType UType = URecordType;
2166       if (PointerConversions)
2167         UType = Context.getPointerType(UType);
2168       From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2169                                VK, &BasePath).take();
2170       FromType = UType;
2171       FromRecordType = URecordType;
2172     }
2173 
2174     // We don't do access control for the conversion from the
2175     // declaring class to the true declaring class.
2176     IgnoreAccess = true;
2177   }
2178 
2179   CXXCastPath BasePath;
2180   if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2181                                    FromLoc, FromRange, &BasePath,
2182                                    IgnoreAccess))
2183     return ExprError();
2184 
2185   return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2186                            VK, &BasePath);
2187 }
2188 
2189 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2190                                       const LookupResult &R,
2191                                       bool HasTrailingLParen) {
2192   // Only when used directly as the postfix-expression of a call.
2193   if (!HasTrailingLParen)
2194     return false;
2195 
2196   // Never if a scope specifier was provided.
2197   if (SS.isSet())
2198     return false;
2199 
2200   // Only in C++ or ObjC++.
2201   if (!getLangOptions().CPlusPlus)
2202     return false;
2203 
2204   // Turn off ADL when we find certain kinds of declarations during
2205   // normal lookup:
2206   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2207     NamedDecl *D = *I;
2208 
2209     // C++0x [basic.lookup.argdep]p3:
2210     //     -- a declaration of a class member
2211     // Since using decls preserve this property, we check this on the
2212     // original decl.
2213     if (D->isCXXClassMember())
2214       return false;
2215 
2216     // C++0x [basic.lookup.argdep]p3:
2217     //     -- a block-scope function declaration that is not a
2218     //        using-declaration
2219     // NOTE: we also trigger this for function templates (in fact, we
2220     // don't check the decl type at all, since all other decl types
2221     // turn off ADL anyway).
2222     if (isa<UsingShadowDecl>(D))
2223       D = cast<UsingShadowDecl>(D)->getTargetDecl();
2224     else if (D->getDeclContext()->isFunctionOrMethod())
2225       return false;
2226 
2227     // C++0x [basic.lookup.argdep]p3:
2228     //     -- a declaration that is neither a function or a function
2229     //        template
2230     // And also for builtin functions.
2231     if (isa<FunctionDecl>(D)) {
2232       FunctionDecl *FDecl = cast<FunctionDecl>(D);
2233 
2234       // But also builtin functions.
2235       if (FDecl->getBuiltinID() && FDecl->isImplicit())
2236         return false;
2237     } else if (!isa<FunctionTemplateDecl>(D))
2238       return false;
2239   }
2240 
2241   return true;
2242 }
2243 
2244 
2245 /// Diagnoses obvious problems with the use of the given declaration
2246 /// as an expression.  This is only actually called for lookups that
2247 /// were not overloaded, and it doesn't promise that the declaration
2248 /// will in fact be used.
2249 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2250   if (isa<TypedefNameDecl>(D)) {
2251     S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2252     return true;
2253   }
2254 
2255   if (isa<ObjCInterfaceDecl>(D)) {
2256     S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2257     return true;
2258   }
2259 
2260   if (isa<NamespaceDecl>(D)) {
2261     S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2262     return true;
2263   }
2264 
2265   return false;
2266 }
2267 
2268 ExprResult
2269 Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2270                                LookupResult &R,
2271                                bool NeedsADL) {
2272   // If this is a single, fully-resolved result and we don't need ADL,
2273   // just build an ordinary singleton decl ref.
2274   if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
2275     return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
2276                                     R.getFoundDecl());
2277 
2278   // We only need to check the declaration if there's exactly one
2279   // result, because in the overloaded case the results can only be
2280   // functions and function templates.
2281   if (R.isSingleResult() &&
2282       CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
2283     return ExprError();
2284 
2285   // Otherwise, just build an unresolved lookup expression.  Suppress
2286   // any lookup-related diagnostics; we'll hash these out later, when
2287   // we've picked a target.
2288   R.suppressDiagnostics();
2289 
2290   UnresolvedLookupExpr *ULE
2291     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2292                                    SS.getWithLocInContext(Context),
2293                                    R.getLookupNameInfo(),
2294                                    NeedsADL, R.isOverloadedResult(),
2295                                    R.begin(), R.end());
2296 
2297   return Owned(ULE);
2298 }
2299 
2300 /// \brief Complete semantic analysis for a reference to the given declaration.
2301 ExprResult
2302 Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2303                                const DeclarationNameInfo &NameInfo,
2304                                NamedDecl *D) {
2305   assert(D && "Cannot refer to a NULL declaration");
2306   assert(!isa<FunctionTemplateDecl>(D) &&
2307          "Cannot refer unambiguously to a function template");
2308 
2309   SourceLocation Loc = NameInfo.getLoc();
2310   if (CheckDeclInExpr(*this, Loc, D))
2311     return ExprError();
2312 
2313   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2314     // Specifically diagnose references to class templates that are missing
2315     // a template argument list.
2316     Diag(Loc, diag::err_template_decl_ref)
2317       << Template << SS.getRange();
2318     Diag(Template->getLocation(), diag::note_template_decl_here);
2319     return ExprError();
2320   }
2321 
2322   // Make sure that we're referring to a value.
2323   ValueDecl *VD = dyn_cast<ValueDecl>(D);
2324   if (!VD) {
2325     Diag(Loc, diag::err_ref_non_value)
2326       << D << SS.getRange();
2327     Diag(D->getLocation(), diag::note_declared_at);
2328     return ExprError();
2329   }
2330 
2331   // Check whether this declaration can be used. Note that we suppress
2332   // this check when we're going to perform argument-dependent lookup
2333   // on this function name, because this might not be the function
2334   // that overload resolution actually selects.
2335   if (DiagnoseUseOfDecl(VD, Loc))
2336     return ExprError();
2337 
2338   // Only create DeclRefExpr's for valid Decl's.
2339   if (VD->isInvalidDecl())
2340     return ExprError();
2341 
2342   // Handle members of anonymous structs and unions.  If we got here,
2343   // and the reference is to a class member indirect field, then this
2344   // must be the subject of a pointer-to-member expression.
2345   if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2346     if (!indirectField->isCXXClassMember())
2347       return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2348                                                       indirectField);
2349 
2350   // If the identifier reference is inside a block, and it refers to a value
2351   // that is outside the block, create a BlockDeclRefExpr instead of a
2352   // DeclRefExpr.  This ensures the value is treated as a copy-in snapshot when
2353   // the block is formed.
2354   //
2355   // We do not do this for things like enum constants, global variables, etc,
2356   // as they do not get snapshotted.
2357   //
2358   switch (shouldCaptureValueReference(*this, NameInfo.getLoc(), VD)) {
2359   case CR_Error:
2360     return ExprError();
2361 
2362   case CR_Capture:
2363     assert(!SS.isSet() && "referenced local variable with scope specifier?");
2364     return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ false);
2365 
2366   case CR_CaptureByRef:
2367     assert(!SS.isSet() && "referenced local variable with scope specifier?");
2368     return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ true);
2369 
2370   case CR_NoCapture: {
2371     // If this reference is not in a block or if the referenced
2372     // variable is within the block, create a normal DeclRefExpr.
2373 
2374     QualType type = VD->getType();
2375     ExprValueKind valueKind = VK_RValue;
2376 
2377     switch (D->getKind()) {
2378     // Ignore all the non-ValueDecl kinds.
2379 #define ABSTRACT_DECL(kind)
2380 #define VALUE(type, base)
2381 #define DECL(type, base) \
2382     case Decl::type:
2383 #include "clang/AST/DeclNodes.inc"
2384       llvm_unreachable("invalid value decl kind");
2385       return ExprError();
2386 
2387     // These shouldn't make it here.
2388     case Decl::ObjCAtDefsField:
2389     case Decl::ObjCIvar:
2390       llvm_unreachable("forming non-member reference to ivar?");
2391       return ExprError();
2392 
2393     // Enum constants are always r-values and never references.
2394     // Unresolved using declarations are dependent.
2395     case Decl::EnumConstant:
2396     case Decl::UnresolvedUsingValue:
2397       valueKind = VK_RValue;
2398       break;
2399 
2400     // Fields and indirect fields that got here must be for
2401     // pointer-to-member expressions; we just call them l-values for
2402     // internal consistency, because this subexpression doesn't really
2403     // exist in the high-level semantics.
2404     case Decl::Field:
2405     case Decl::IndirectField:
2406       assert(getLangOptions().CPlusPlus &&
2407              "building reference to field in C?");
2408 
2409       // These can't have reference type in well-formed programs, but
2410       // for internal consistency we do this anyway.
2411       type = type.getNonReferenceType();
2412       valueKind = VK_LValue;
2413       break;
2414 
2415     // Non-type template parameters are either l-values or r-values
2416     // depending on the type.
2417     case Decl::NonTypeTemplateParm: {
2418       if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2419         type = reftype->getPointeeType();
2420         valueKind = VK_LValue; // even if the parameter is an r-value reference
2421         break;
2422       }
2423 
2424       // For non-references, we need to strip qualifiers just in case
2425       // the template parameter was declared as 'const int' or whatever.
2426       valueKind = VK_RValue;
2427       type = type.getUnqualifiedType();
2428       break;
2429     }
2430 
2431     case Decl::Var:
2432       // In C, "extern void blah;" is valid and is an r-value.
2433       if (!getLangOptions().CPlusPlus &&
2434           !type.hasQualifiers() &&
2435           type->isVoidType()) {
2436         valueKind = VK_RValue;
2437         break;
2438       }
2439       // fallthrough
2440 
2441     case Decl::ImplicitParam:
2442     case Decl::ParmVar:
2443       // These are always l-values.
2444       valueKind = VK_LValue;
2445       type = type.getNonReferenceType();
2446       break;
2447 
2448     case Decl::Function: {
2449       const FunctionType *fty = type->castAs<FunctionType>();
2450 
2451       // If we're referring to a function with an __unknown_anytype
2452       // result type, make the entire expression __unknown_anytype.
2453       if (fty->getResultType() == Context.UnknownAnyTy) {
2454         type = Context.UnknownAnyTy;
2455         valueKind = VK_RValue;
2456         break;
2457       }
2458 
2459       // Functions are l-values in C++.
2460       if (getLangOptions().CPlusPlus) {
2461         valueKind = VK_LValue;
2462         break;
2463       }
2464 
2465       // C99 DR 316 says that, if a function type comes from a
2466       // function definition (without a prototype), that type is only
2467       // used for checking compatibility. Therefore, when referencing
2468       // the function, we pretend that we don't have the full function
2469       // type.
2470       if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2471           isa<FunctionProtoType>(fty))
2472         type = Context.getFunctionNoProtoType(fty->getResultType(),
2473                                               fty->getExtInfo());
2474 
2475       // Functions are r-values in C.
2476       valueKind = VK_RValue;
2477       break;
2478     }
2479 
2480     case Decl::CXXMethod:
2481       // If we're referring to a method with an __unknown_anytype
2482       // result type, make the entire expression __unknown_anytype.
2483       // This should only be possible with a type written directly.
2484       if (const FunctionProtoType *proto
2485             = dyn_cast<FunctionProtoType>(VD->getType()))
2486         if (proto->getResultType() == Context.UnknownAnyTy) {
2487           type = Context.UnknownAnyTy;
2488           valueKind = VK_RValue;
2489           break;
2490         }
2491 
2492       // C++ methods are l-values if static, r-values if non-static.
2493       if (cast<CXXMethodDecl>(VD)->isStatic()) {
2494         valueKind = VK_LValue;
2495         break;
2496       }
2497       // fallthrough
2498 
2499     case Decl::CXXConversion:
2500     case Decl::CXXDestructor:
2501     case Decl::CXXConstructor:
2502       valueKind = VK_RValue;
2503       break;
2504     }
2505 
2506     return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS);
2507   }
2508 
2509   }
2510 
2511   llvm_unreachable("unknown capture result");
2512   return ExprError();
2513 }
2514 
2515 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
2516   PredefinedExpr::IdentType IT;
2517 
2518   switch (Kind) {
2519   default: llvm_unreachable("Unknown simple primary expr!");
2520   case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2521   case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
2522   case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
2523   }
2524 
2525   // Pre-defined identifiers are of type char[x], where x is the length of the
2526   // string.
2527 
2528   Decl *currentDecl = getCurFunctionOrMethodDecl();
2529   if (!currentDecl && getCurBlock())
2530     currentDecl = getCurBlock()->TheDecl;
2531   if (!currentDecl) {
2532     Diag(Loc, diag::ext_predef_outside_function);
2533     currentDecl = Context.getTranslationUnitDecl();
2534   }
2535 
2536   QualType ResTy;
2537   if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2538     ResTy = Context.DependentTy;
2539   } else {
2540     unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
2541 
2542     llvm::APInt LengthI(32, Length + 1);
2543     ResTy = Context.CharTy.withConst();
2544     ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2545   }
2546   return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
2547 }
2548 
2549 ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
2550   llvm::SmallString<16> CharBuffer;
2551   bool Invalid = false;
2552   StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
2553   if (Invalid)
2554     return ExprError();
2555 
2556   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
2557                             PP, Tok.getKind());
2558   if (Literal.hadError())
2559     return ExprError();
2560 
2561   QualType Ty;
2562   if (!getLangOptions().CPlusPlus)
2563     Ty = Context.IntTy;   // 'x' and L'x' -> int in C.
2564   else if (Literal.isWide())
2565     Ty = Context.WCharTy; // L'x' -> wchar_t in C++.
2566   else if (Literal.isUTF16())
2567     Ty = Context.Char16Ty; // u'x' -> char16_t in C++0x.
2568   else if (Literal.isUTF32())
2569     Ty = Context.Char32Ty; // U'x' -> char32_t in C++0x.
2570   else if (Literal.isMultiChar())
2571     Ty = Context.IntTy;   // 'wxyz' -> int in C++.
2572   else
2573     Ty = Context.CharTy;  // 'x' -> char in C++
2574 
2575   CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
2576   if (Literal.isWide())
2577     Kind = CharacterLiteral::Wide;
2578   else if (Literal.isUTF16())
2579     Kind = CharacterLiteral::UTF16;
2580   else if (Literal.isUTF32())
2581     Kind = CharacterLiteral::UTF32;
2582 
2583   return Owned(new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
2584                                               Tok.getLocation()));
2585 }
2586 
2587 ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
2588   // Fast path for a single digit (which is quite common).  A single digit
2589   // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
2590   if (Tok.getLength() == 1) {
2591     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
2592     unsigned IntSize = Context.getTargetInfo().getIntWidth();
2593     return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val-'0'),
2594                     Context.IntTy, Tok.getLocation()));
2595   }
2596 
2597   llvm::SmallString<512> IntegerBuffer;
2598   // Add padding so that NumericLiteralParser can overread by one character.
2599   IntegerBuffer.resize(Tok.getLength()+1);
2600   const char *ThisTokBegin = &IntegerBuffer[0];
2601 
2602   // Get the spelling of the token, which eliminates trigraphs, etc.
2603   bool Invalid = false;
2604   unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
2605   if (Invalid)
2606     return ExprError();
2607 
2608   NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
2609                                Tok.getLocation(), PP);
2610   if (Literal.hadError)
2611     return ExprError();
2612 
2613   Expr *Res;
2614 
2615   if (Literal.isFloatingLiteral()) {
2616     QualType Ty;
2617     if (Literal.isFloat)
2618       Ty = Context.FloatTy;
2619     else if (!Literal.isLong)
2620       Ty = Context.DoubleTy;
2621     else
2622       Ty = Context.LongDoubleTy;
2623 
2624     const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
2625 
2626     using llvm::APFloat;
2627     APFloat Val(Format);
2628 
2629     APFloat::opStatus result = Literal.GetFloatValue(Val);
2630 
2631     // Overflow is always an error, but underflow is only an error if
2632     // we underflowed to zero (APFloat reports denormals as underflow).
2633     if ((result & APFloat::opOverflow) ||
2634         ((result & APFloat::opUnderflow) && Val.isZero())) {
2635       unsigned diagnostic;
2636       llvm::SmallString<20> buffer;
2637       if (result & APFloat::opOverflow) {
2638         diagnostic = diag::warn_float_overflow;
2639         APFloat::getLargest(Format).toString(buffer);
2640       } else {
2641         diagnostic = diag::warn_float_underflow;
2642         APFloat::getSmallest(Format).toString(buffer);
2643       }
2644 
2645       Diag(Tok.getLocation(), diagnostic)
2646         << Ty
2647         << StringRef(buffer.data(), buffer.size());
2648     }
2649 
2650     bool isExact = (result == APFloat::opOK);
2651     Res = FloatingLiteral::Create(Context, Val, isExact, Ty, Tok.getLocation());
2652 
2653     if (Ty == Context.DoubleTy) {
2654       if (getLangOptions().SinglePrecisionConstants) {
2655         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
2656       } else if (getLangOptions().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
2657         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
2658         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
2659       }
2660     }
2661   } else if (!Literal.isIntegerLiteral()) {
2662     return ExprError();
2663   } else {
2664     QualType Ty;
2665 
2666     // long long is a C99 feature.
2667     if (!getLangOptions().C99 && Literal.isLongLong)
2668       Diag(Tok.getLocation(),
2669            getLangOptions().CPlusPlus0x ?
2670              diag::warn_cxx98_compat_longlong : diag::ext_longlong);
2671 
2672     // Get the value in the widest-possible width.
2673     llvm::APInt ResultVal(Context.getTargetInfo().getIntMaxTWidth(), 0);
2674 
2675     if (Literal.GetIntegerValue(ResultVal)) {
2676       // If this value didn't fit into uintmax_t, warn and force to ull.
2677       Diag(Tok.getLocation(), diag::warn_integer_too_large);
2678       Ty = Context.UnsignedLongLongTy;
2679       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
2680              "long long is not intmax_t?");
2681     } else {
2682       // If this value fits into a ULL, try to figure out what else it fits into
2683       // according to the rules of C99 6.4.4.1p5.
2684 
2685       // Octal, Hexadecimal, and integers with a U suffix are allowed to
2686       // be an unsigned int.
2687       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2688 
2689       // Check from smallest to largest, picking the smallest type we can.
2690       unsigned Width = 0;
2691       if (!Literal.isLong && !Literal.isLongLong) {
2692         // Are int/unsigned possibilities?
2693         unsigned IntSize = Context.getTargetInfo().getIntWidth();
2694 
2695         // Does it fit in a unsigned int?
2696         if (ResultVal.isIntN(IntSize)) {
2697           // Does it fit in a signed int?
2698           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
2699             Ty = Context.IntTy;
2700           else if (AllowUnsigned)
2701             Ty = Context.UnsignedIntTy;
2702           Width = IntSize;
2703         }
2704       }
2705 
2706       // Are long/unsigned long possibilities?
2707       if (Ty.isNull() && !Literal.isLongLong) {
2708         unsigned LongSize = Context.getTargetInfo().getLongWidth();
2709 
2710         // Does it fit in a unsigned long?
2711         if (ResultVal.isIntN(LongSize)) {
2712           // Does it fit in a signed long?
2713           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
2714             Ty = Context.LongTy;
2715           else if (AllowUnsigned)
2716             Ty = Context.UnsignedLongTy;
2717           Width = LongSize;
2718         }
2719       }
2720 
2721       // Finally, check long long if needed.
2722       if (Ty.isNull()) {
2723         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
2724 
2725         // Does it fit in a unsigned long long?
2726         if (ResultVal.isIntN(LongLongSize)) {
2727           // Does it fit in a signed long long?
2728           // To be compatible with MSVC, hex integer literals ending with the
2729           // LL or i64 suffix are always signed in Microsoft mode.
2730           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
2731               (getLangOptions().MicrosoftExt && Literal.isLongLong)))
2732             Ty = Context.LongLongTy;
2733           else if (AllowUnsigned)
2734             Ty = Context.UnsignedLongLongTy;
2735           Width = LongLongSize;
2736         }
2737       }
2738 
2739       // If we still couldn't decide a type, we probably have something that
2740       // does not fit in a signed long long, but has no U suffix.
2741       if (Ty.isNull()) {
2742         Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
2743         Ty = Context.UnsignedLongLongTy;
2744         Width = Context.getTargetInfo().getLongLongWidth();
2745       }
2746 
2747       if (ResultVal.getBitWidth() != Width)
2748         ResultVal = ResultVal.trunc(Width);
2749     }
2750     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
2751   }
2752 
2753   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
2754   if (Literal.isImaginary)
2755     Res = new (Context) ImaginaryLiteral(Res,
2756                                         Context.getComplexType(Res->getType()));
2757 
2758   return Owned(Res);
2759 }
2760 
2761 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
2762   assert((E != 0) && "ActOnParenExpr() missing expr");
2763   return Owned(new (Context) ParenExpr(L, R, E));
2764 }
2765 
2766 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
2767                                          SourceLocation Loc,
2768                                          SourceRange ArgRange) {
2769   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
2770   // scalar or vector data type argument..."
2771   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
2772   // type (C99 6.2.5p18) or void.
2773   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
2774     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
2775       << T << ArgRange;
2776     return true;
2777   }
2778 
2779   assert((T->isVoidType() || !T->isIncompleteType()) &&
2780          "Scalar types should always be complete");
2781   return false;
2782 }
2783 
2784 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
2785                                            SourceLocation Loc,
2786                                            SourceRange ArgRange,
2787                                            UnaryExprOrTypeTrait TraitKind) {
2788   // C99 6.5.3.4p1:
2789   if (T->isFunctionType()) {
2790     // alignof(function) is allowed as an extension.
2791     if (TraitKind == UETT_SizeOf)
2792       S.Diag(Loc, diag::ext_sizeof_function_type) << ArgRange;
2793     return false;
2794   }
2795 
2796   // Allow sizeof(void)/alignof(void) as an extension.
2797   if (T->isVoidType()) {
2798     S.Diag(Loc, diag::ext_sizeof_void_type) << TraitKind << ArgRange;
2799     return false;
2800   }
2801 
2802   return true;
2803 }
2804 
2805 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
2806                                              SourceLocation Loc,
2807                                              SourceRange ArgRange,
2808                                              UnaryExprOrTypeTrait TraitKind) {
2809   // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
2810   if (S.LangOpts.ObjCNonFragileABI && T->isObjCObjectType()) {
2811     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
2812       << T << (TraitKind == UETT_SizeOf)
2813       << ArgRange;
2814     return true;
2815   }
2816 
2817   return false;
2818 }
2819 
2820 /// \brief Check the constrains on expression operands to unary type expression
2821 /// and type traits.
2822 ///
2823 /// Completes any types necessary and validates the constraints on the operand
2824 /// expression. The logic mostly mirrors the type-based overload, but may modify
2825 /// the expression as it completes the type for that expression through template
2826 /// instantiation, etc.
2827 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
2828                                             UnaryExprOrTypeTrait ExprKind) {
2829   QualType ExprTy = E->getType();
2830 
2831   // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2832   //   the result is the size of the referenced type."
2833   // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2834   //   result shall be the alignment of the referenced type."
2835   if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2836     ExprTy = Ref->getPointeeType();
2837 
2838   if (ExprKind == UETT_VecStep)
2839     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
2840                                         E->getSourceRange());
2841 
2842   // Whitelist some types as extensions
2843   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
2844                                       E->getSourceRange(), ExprKind))
2845     return false;
2846 
2847   if (RequireCompleteExprType(E,
2848                               PDiag(diag::err_sizeof_alignof_incomplete_type)
2849                               << ExprKind << E->getSourceRange(),
2850                               std::make_pair(SourceLocation(), PDiag(0))))
2851     return true;
2852 
2853   // Completeing the expression's type may have changed it.
2854   ExprTy = E->getType();
2855   if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2856     ExprTy = Ref->getPointeeType();
2857 
2858   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
2859                                        E->getSourceRange(), ExprKind))
2860     return true;
2861 
2862   if (ExprKind == UETT_SizeOf) {
2863     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
2864       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
2865         QualType OType = PVD->getOriginalType();
2866         QualType Type = PVD->getType();
2867         if (Type->isPointerType() && OType->isArrayType()) {
2868           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
2869             << Type << OType;
2870           Diag(PVD->getLocation(), diag::note_declared_at);
2871         }
2872       }
2873     }
2874   }
2875 
2876   return false;
2877 }
2878 
2879 /// \brief Check the constraints on operands to unary expression and type
2880 /// traits.
2881 ///
2882 /// This will complete any types necessary, and validate the various constraints
2883 /// on those operands.
2884 ///
2885 /// The UsualUnaryConversions() function is *not* called by this routine.
2886 /// C99 6.3.2.1p[2-4] all state:
2887 ///   Except when it is the operand of the sizeof operator ...
2888 ///
2889 /// C++ [expr.sizeof]p4
2890 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
2891 ///   standard conversions are not applied to the operand of sizeof.
2892 ///
2893 /// This policy is followed for all of the unary trait expressions.
2894 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
2895                                             SourceLocation OpLoc,
2896                                             SourceRange ExprRange,
2897                                             UnaryExprOrTypeTrait ExprKind) {
2898   if (ExprType->isDependentType())
2899     return false;
2900 
2901   // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2902   //   the result is the size of the referenced type."
2903   // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2904   //   result shall be the alignment of the referenced type."
2905   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
2906     ExprType = Ref->getPointeeType();
2907 
2908   if (ExprKind == UETT_VecStep)
2909     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
2910 
2911   // Whitelist some types as extensions
2912   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
2913                                       ExprKind))
2914     return false;
2915 
2916   if (RequireCompleteType(OpLoc, ExprType,
2917                           PDiag(diag::err_sizeof_alignof_incomplete_type)
2918                           << ExprKind << ExprRange))
2919     return true;
2920 
2921   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
2922                                        ExprKind))
2923     return true;
2924 
2925   return false;
2926 }
2927 
2928 static bool CheckAlignOfExpr(Sema &S, Expr *E) {
2929   E = E->IgnoreParens();
2930 
2931   // alignof decl is always ok.
2932   if (isa<DeclRefExpr>(E))
2933     return false;
2934 
2935   // Cannot know anything else if the expression is dependent.
2936   if (E->isTypeDependent())
2937     return false;
2938 
2939   if (E->getBitField()) {
2940     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield)
2941        << 1 << E->getSourceRange();
2942     return true;
2943   }
2944 
2945   // Alignment of a field access is always okay, so long as it isn't a
2946   // bit-field.
2947   if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2948     if (isa<FieldDecl>(ME->getMemberDecl()))
2949       return false;
2950 
2951   return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
2952 }
2953 
2954 bool Sema::CheckVecStepExpr(Expr *E) {
2955   E = E->IgnoreParens();
2956 
2957   // Cannot know anything else if the expression is dependent.
2958   if (E->isTypeDependent())
2959     return false;
2960 
2961   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
2962 }
2963 
2964 /// \brief Build a sizeof or alignof expression given a type operand.
2965 ExprResult
2966 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
2967                                      SourceLocation OpLoc,
2968                                      UnaryExprOrTypeTrait ExprKind,
2969                                      SourceRange R) {
2970   if (!TInfo)
2971     return ExprError();
2972 
2973   QualType T = TInfo->getType();
2974 
2975   if (!T->isDependentType() &&
2976       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
2977     return ExprError();
2978 
2979   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
2980   return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo,
2981                                                       Context.getSizeType(),
2982                                                       OpLoc, R.getEnd()));
2983 }
2984 
2985 /// \brief Build a sizeof or alignof expression given an expression
2986 /// operand.
2987 ExprResult
2988 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
2989                                      UnaryExprOrTypeTrait ExprKind) {
2990   ExprResult PE = CheckPlaceholderExpr(E);
2991   if (PE.isInvalid())
2992     return ExprError();
2993 
2994   E = PE.get();
2995 
2996   // Verify that the operand is valid.
2997   bool isInvalid = false;
2998   if (E->isTypeDependent()) {
2999     // Delay type-checking for type-dependent expressions.
3000   } else if (ExprKind == UETT_AlignOf) {
3001     isInvalid = CheckAlignOfExpr(*this, E);
3002   } else if (ExprKind == UETT_VecStep) {
3003     isInvalid = CheckVecStepExpr(E);
3004   } else if (E->getBitField()) {  // C99 6.5.3.4p1.
3005     Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0;
3006     isInvalid = true;
3007   } else {
3008     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
3009   }
3010 
3011   if (isInvalid)
3012     return ExprError();
3013 
3014   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
3015   return Owned(new (Context) UnaryExprOrTypeTraitExpr(
3016       ExprKind, E, Context.getSizeType(), OpLoc,
3017       E->getSourceRange().getEnd()));
3018 }
3019 
3020 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
3021 /// expr and the same for @c alignof and @c __alignof
3022 /// Note that the ArgRange is invalid if isType is false.
3023 ExprResult
3024 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
3025                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
3026                                     void *TyOrEx, const SourceRange &ArgRange) {
3027   // If error parsing type, ignore.
3028   if (TyOrEx == 0) return ExprError();
3029 
3030   if (IsType) {
3031     TypeSourceInfo *TInfo;
3032     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
3033     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
3034   }
3035 
3036   Expr *ArgEx = (Expr *)TyOrEx;
3037   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
3038   return move(Result);
3039 }
3040 
3041 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
3042                                      bool IsReal) {
3043   if (V.get()->isTypeDependent())
3044     return S.Context.DependentTy;
3045 
3046   // _Real and _Imag are only l-values for normal l-values.
3047   if (V.get()->getObjectKind() != OK_Ordinary) {
3048     V = S.DefaultLvalueConversion(V.take());
3049     if (V.isInvalid())
3050       return QualType();
3051   }
3052 
3053   // These operators return the element type of a complex type.
3054   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
3055     return CT->getElementType();
3056 
3057   // Otherwise they pass through real integer and floating point types here.
3058   if (V.get()->getType()->isArithmeticType())
3059     return V.get()->getType();
3060 
3061   // Test for placeholders.
3062   ExprResult PR = S.CheckPlaceholderExpr(V.get());
3063   if (PR.isInvalid()) return QualType();
3064   if (PR.get() != V.get()) {
3065     V = move(PR);
3066     return CheckRealImagOperand(S, V, Loc, IsReal);
3067   }
3068 
3069   // Reject anything else.
3070   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
3071     << (IsReal ? "__real" : "__imag");
3072   return QualType();
3073 }
3074 
3075 
3076 
3077 ExprResult
3078 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
3079                           tok::TokenKind Kind, Expr *Input) {
3080   UnaryOperatorKind Opc;
3081   switch (Kind) {
3082   default: llvm_unreachable("Unknown unary op!");
3083   case tok::plusplus:   Opc = UO_PostInc; break;
3084   case tok::minusminus: Opc = UO_PostDec; break;
3085   }
3086 
3087   return BuildUnaryOp(S, OpLoc, Opc, Input);
3088 }
3089 
3090 ExprResult
3091 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
3092                               Expr *Idx, SourceLocation RLoc) {
3093   // Since this might be a postfix expression, get rid of ParenListExprs.
3094   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
3095   if (Result.isInvalid()) return ExprError();
3096   Base = Result.take();
3097 
3098   Expr *LHSExp = Base, *RHSExp = Idx;
3099 
3100   if (getLangOptions().CPlusPlus &&
3101       (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
3102     return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
3103                                                   Context.DependentTy,
3104                                                   VK_LValue, OK_Ordinary,
3105                                                   RLoc));
3106   }
3107 
3108   if (getLangOptions().CPlusPlus &&
3109       (LHSExp->getType()->isRecordType() ||
3110        LHSExp->getType()->isEnumeralType() ||
3111        RHSExp->getType()->isRecordType() ||
3112        RHSExp->getType()->isEnumeralType())) {
3113     return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
3114   }
3115 
3116   return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
3117 }
3118 
3119 
3120 ExprResult
3121 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
3122                                       Expr *Idx, SourceLocation RLoc) {
3123   Expr *LHSExp = Base;
3124   Expr *RHSExp = Idx;
3125 
3126   // Perform default conversions.
3127   if (!LHSExp->getType()->getAs<VectorType>()) {
3128     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
3129     if (Result.isInvalid())
3130       return ExprError();
3131     LHSExp = Result.take();
3132   }
3133   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
3134   if (Result.isInvalid())
3135     return ExprError();
3136   RHSExp = Result.take();
3137 
3138   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
3139   ExprValueKind VK = VK_LValue;
3140   ExprObjectKind OK = OK_Ordinary;
3141 
3142   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
3143   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
3144   // in the subscript position. As a result, we need to derive the array base
3145   // and index from the expression types.
3146   Expr *BaseExpr, *IndexExpr;
3147   QualType ResultType;
3148   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3149     BaseExpr = LHSExp;
3150     IndexExpr = RHSExp;
3151     ResultType = Context.DependentTy;
3152   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
3153     BaseExpr = LHSExp;
3154     IndexExpr = RHSExp;
3155     ResultType = PTy->getPointeeType();
3156   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
3157      // Handle the uncommon case of "123[Ptr]".
3158     BaseExpr = RHSExp;
3159     IndexExpr = LHSExp;
3160     ResultType = PTy->getPointeeType();
3161   } else if (const ObjCObjectPointerType *PTy =
3162                LHSTy->getAs<ObjCObjectPointerType>()) {
3163     BaseExpr = LHSExp;
3164     IndexExpr = RHSExp;
3165     ResultType = PTy->getPointeeType();
3166   } else if (const ObjCObjectPointerType *PTy =
3167                RHSTy->getAs<ObjCObjectPointerType>()) {
3168      // Handle the uncommon case of "123[Ptr]".
3169     BaseExpr = RHSExp;
3170     IndexExpr = LHSExp;
3171     ResultType = PTy->getPointeeType();
3172   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
3173     BaseExpr = LHSExp;    // vectors: V[123]
3174     IndexExpr = RHSExp;
3175     VK = LHSExp->getValueKind();
3176     if (VK != VK_RValue)
3177       OK = OK_VectorComponent;
3178 
3179     // FIXME: need to deal with const...
3180     ResultType = VTy->getElementType();
3181   } else if (LHSTy->isArrayType()) {
3182     // If we see an array that wasn't promoted by
3183     // DefaultFunctionArrayLvalueConversion, it must be an array that
3184     // wasn't promoted because of the C90 rule that doesn't
3185     // allow promoting non-lvalue arrays.  Warn, then
3186     // force the promotion here.
3187     Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3188         LHSExp->getSourceRange();
3189     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
3190                                CK_ArrayToPointerDecay).take();
3191     LHSTy = LHSExp->getType();
3192 
3193     BaseExpr = LHSExp;
3194     IndexExpr = RHSExp;
3195     ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
3196   } else if (RHSTy->isArrayType()) {
3197     // Same as previous, except for 123[f().a] case
3198     Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3199         RHSExp->getSourceRange();
3200     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
3201                                CK_ArrayToPointerDecay).take();
3202     RHSTy = RHSExp->getType();
3203 
3204     BaseExpr = RHSExp;
3205     IndexExpr = LHSExp;
3206     ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
3207   } else {
3208     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3209        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
3210   }
3211   // C99 6.5.2.1p1
3212   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
3213     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3214                      << IndexExpr->getSourceRange());
3215 
3216   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
3217        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3218          && !IndexExpr->isTypeDependent())
3219     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3220 
3221   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
3222   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3223   // type. Note that Functions are not objects, and that (in C99 parlance)
3224   // incomplete types are not object types.
3225   if (ResultType->isFunctionType()) {
3226     Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3227       << ResultType << BaseExpr->getSourceRange();
3228     return ExprError();
3229   }
3230 
3231   if (ResultType->isVoidType() && !getLangOptions().CPlusPlus) {
3232     // GNU extension: subscripting on pointer to void
3233     Diag(LLoc, diag::ext_gnu_subscript_void_type)
3234       << BaseExpr->getSourceRange();
3235 
3236     // C forbids expressions of unqualified void type from being l-values.
3237     // See IsCForbiddenLValueType.
3238     if (!ResultType.hasQualifiers()) VK = VK_RValue;
3239   } else if (!ResultType->isDependentType() &&
3240       RequireCompleteType(LLoc, ResultType,
3241                           PDiag(diag::err_subscript_incomplete_type)
3242                             << BaseExpr->getSourceRange()))
3243     return ExprError();
3244 
3245   // Diagnose bad cases where we step over interface counts.
3246   if (ResultType->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
3247     Diag(LLoc, diag::err_subscript_nonfragile_interface)
3248       << ResultType << BaseExpr->getSourceRange();
3249     return ExprError();
3250   }
3251 
3252   assert(VK == VK_RValue || LangOpts.CPlusPlus ||
3253          !ResultType.isCForbiddenLValueType());
3254 
3255   return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
3256                                                 ResultType, VK, OK, RLoc));
3257 }
3258 
3259 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
3260                                         FunctionDecl *FD,
3261                                         ParmVarDecl *Param) {
3262   if (Param->hasUnparsedDefaultArg()) {
3263     Diag(CallLoc,
3264          diag::err_use_of_default_argument_to_function_declared_later) <<
3265       FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
3266     Diag(UnparsedDefaultArgLocs[Param],
3267          diag::note_default_argument_declared_here);
3268     return ExprError();
3269   }
3270 
3271   if (Param->hasUninstantiatedDefaultArg()) {
3272     Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
3273 
3274     // Instantiate the expression.
3275     MultiLevelTemplateArgumentList ArgList
3276       = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
3277 
3278     std::pair<const TemplateArgument *, unsigned> Innermost
3279       = ArgList.getInnermost();
3280     InstantiatingTemplate Inst(*this, CallLoc, Param, Innermost.first,
3281                                Innermost.second);
3282 
3283     ExprResult Result;
3284     {
3285       // C++ [dcl.fct.default]p5:
3286       //   The names in the [default argument] expression are bound, and
3287       //   the semantic constraints are checked, at the point where the
3288       //   default argument expression appears.
3289       ContextRAII SavedContext(*this, FD);
3290       Result = SubstExpr(UninstExpr, ArgList);
3291     }
3292     if (Result.isInvalid())
3293       return ExprError();
3294 
3295     // Check the expression as an initializer for the parameter.
3296     InitializedEntity Entity
3297       = InitializedEntity::InitializeParameter(Context, Param);
3298     InitializationKind Kind
3299       = InitializationKind::CreateCopy(Param->getLocation(),
3300              /*FIXME:EqualLoc*/UninstExpr->getSourceRange().getBegin());
3301     Expr *ResultE = Result.takeAs<Expr>();
3302 
3303     InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
3304     Result = InitSeq.Perform(*this, Entity, Kind,
3305                              MultiExprArg(*this, &ResultE, 1));
3306     if (Result.isInvalid())
3307       return ExprError();
3308 
3309     // Build the default argument expression.
3310     return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param,
3311                                            Result.takeAs<Expr>()));
3312   }
3313 
3314   // If the default expression creates temporaries, we need to
3315   // push them to the current stack of expression temporaries so they'll
3316   // be properly destroyed.
3317   // FIXME: We should really be rebuilding the default argument with new
3318   // bound temporaries; see the comment in PR5810.
3319   // We don't need to do that with block decls, though, because
3320   // blocks in default argument expression can never capture anything.
3321   if (isa<ExprWithCleanups>(Param->getInit())) {
3322     // Set the "needs cleanups" bit regardless of whether there are
3323     // any explicit objects.
3324     ExprNeedsCleanups = true;
3325 
3326     // Append all the objects to the cleanup list.  Right now, this
3327     // should always be a no-op, because blocks in default argument
3328     // expressions should never be able to capture anything.
3329     assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() &&
3330            "default argument expression has capturing blocks?");
3331   }
3332 
3333   // We already type-checked the argument, so we know it works.
3334   // Just mark all of the declarations in this potentially-evaluated expression
3335   // as being "referenced".
3336   MarkDeclarationsReferencedInExpr(Param->getDefaultArg());
3337   return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
3338 }
3339 
3340 /// ConvertArgumentsForCall - Converts the arguments specified in
3341 /// Args/NumArgs to the parameter types of the function FDecl with
3342 /// function prototype Proto. Call is the call expression itself, and
3343 /// Fn is the function expression. For a C++ member function, this
3344 /// routine does not attempt to convert the object argument. Returns
3345 /// true if the call is ill-formed.
3346 bool
3347 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
3348                               FunctionDecl *FDecl,
3349                               const FunctionProtoType *Proto,
3350                               Expr **Args, unsigned NumArgs,
3351                               SourceLocation RParenLoc,
3352                               bool IsExecConfig) {
3353   // Bail out early if calling a builtin with custom typechecking.
3354   // We don't need to do this in the
3355   if (FDecl)
3356     if (unsigned ID = FDecl->getBuiltinID())
3357       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
3358         return false;
3359 
3360   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
3361   // assignment, to the types of the corresponding parameter, ...
3362   unsigned NumArgsInProto = Proto->getNumArgs();
3363   bool Invalid = false;
3364   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumArgsInProto;
3365   unsigned FnKind = Fn->getType()->isBlockPointerType()
3366                        ? 1 /* block */
3367                        : (IsExecConfig ? 3 /* kernel function (exec config) */
3368                                        : 0 /* function */);
3369 
3370   // If too few arguments are available (and we don't have default
3371   // arguments for the remaining parameters), don't make the call.
3372   if (NumArgs < NumArgsInProto) {
3373     if (NumArgs < MinArgs) {
3374       Diag(RParenLoc, MinArgs == NumArgsInProto
3375                         ? diag::err_typecheck_call_too_few_args
3376                         : diag::err_typecheck_call_too_few_args_at_least)
3377         << FnKind
3378         << MinArgs << NumArgs << Fn->getSourceRange();
3379 
3380       // Emit the location of the prototype.
3381       if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
3382         Diag(FDecl->getLocStart(), diag::note_callee_decl)
3383           << FDecl;
3384 
3385       return true;
3386     }
3387     Call->setNumArgs(Context, NumArgsInProto);
3388   }
3389 
3390   // If too many are passed and not variadic, error on the extras and drop
3391   // them.
3392   if (NumArgs > NumArgsInProto) {
3393     if (!Proto->isVariadic()) {
3394       Diag(Args[NumArgsInProto]->getLocStart(),
3395            MinArgs == NumArgsInProto
3396              ? diag::err_typecheck_call_too_many_args
3397              : diag::err_typecheck_call_too_many_args_at_most)
3398         << FnKind
3399         << NumArgsInProto << NumArgs << Fn->getSourceRange()
3400         << SourceRange(Args[NumArgsInProto]->getLocStart(),
3401                        Args[NumArgs-1]->getLocEnd());
3402 
3403       // Emit the location of the prototype.
3404       if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
3405         Diag(FDecl->getLocStart(), diag::note_callee_decl)
3406           << FDecl;
3407 
3408       // This deletes the extra arguments.
3409       Call->setNumArgs(Context, NumArgsInProto);
3410       return true;
3411     }
3412   }
3413   SmallVector<Expr *, 8> AllArgs;
3414   VariadicCallType CallType =
3415     Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
3416   if (Fn->getType()->isBlockPointerType())
3417     CallType = VariadicBlock; // Block
3418   else if (isa<MemberExpr>(Fn))
3419     CallType = VariadicMethod;
3420   Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
3421                                    Proto, 0, Args, NumArgs, AllArgs, CallType);
3422   if (Invalid)
3423     return true;
3424   unsigned TotalNumArgs = AllArgs.size();
3425   for (unsigned i = 0; i < TotalNumArgs; ++i)
3426     Call->setArg(i, AllArgs[i]);
3427 
3428   return false;
3429 }
3430 
3431 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
3432                                   FunctionDecl *FDecl,
3433                                   const FunctionProtoType *Proto,
3434                                   unsigned FirstProtoArg,
3435                                   Expr **Args, unsigned NumArgs,
3436                                   SmallVector<Expr *, 8> &AllArgs,
3437                                   VariadicCallType CallType) {
3438   unsigned NumArgsInProto = Proto->getNumArgs();
3439   unsigned NumArgsToCheck = NumArgs;
3440   bool Invalid = false;
3441   if (NumArgs != NumArgsInProto)
3442     // Use default arguments for missing arguments
3443     NumArgsToCheck = NumArgsInProto;
3444   unsigned ArgIx = 0;
3445   // Continue to check argument types (even if we have too few/many args).
3446   for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
3447     QualType ProtoArgType = Proto->getArgType(i);
3448 
3449     Expr *Arg;
3450     ParmVarDecl *Param;
3451     if (ArgIx < NumArgs) {
3452       Arg = Args[ArgIx++];
3453 
3454       if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3455                               ProtoArgType,
3456                               PDiag(diag::err_call_incomplete_argument)
3457                               << Arg->getSourceRange()))
3458         return true;
3459 
3460       // Pass the argument
3461       Param = 0;
3462       if (FDecl && i < FDecl->getNumParams())
3463         Param = FDecl->getParamDecl(i);
3464 
3465       // Strip the unbridged-cast placeholder expression off, if applicable.
3466       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
3467           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
3468           (!Param || !Param->hasAttr<CFConsumedAttr>()))
3469         Arg = stripARCUnbridgedCast(Arg);
3470 
3471       InitializedEntity Entity =
3472         Param? InitializedEntity::InitializeParameter(Context, Param)
3473              : InitializedEntity::InitializeParameter(Context, ProtoArgType,
3474                                                       Proto->isArgConsumed(i));
3475       ExprResult ArgE = PerformCopyInitialization(Entity,
3476                                                   SourceLocation(),
3477                                                   Owned(Arg));
3478       if (ArgE.isInvalid())
3479         return true;
3480 
3481       Arg = ArgE.takeAs<Expr>();
3482     } else {
3483       Param = FDecl->getParamDecl(i);
3484 
3485       ExprResult ArgExpr =
3486         BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
3487       if (ArgExpr.isInvalid())
3488         return true;
3489 
3490       Arg = ArgExpr.takeAs<Expr>();
3491     }
3492 
3493     // Check for array bounds violations for each argument to the call. This
3494     // check only triggers warnings when the argument isn't a more complex Expr
3495     // with its own checking, such as a BinaryOperator.
3496     CheckArrayAccess(Arg);
3497 
3498     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
3499     CheckStaticArrayArgument(CallLoc, Param, Arg);
3500 
3501     AllArgs.push_back(Arg);
3502   }
3503 
3504   // If this is a variadic call, handle args passed through "...".
3505   if (CallType != VariadicDoesNotApply) {
3506 
3507     // Assume that extern "C" functions with variadic arguments that
3508     // return __unknown_anytype aren't *really* variadic.
3509     if (Proto->getResultType() == Context.UnknownAnyTy &&
3510         FDecl && FDecl->isExternC()) {
3511       for (unsigned i = ArgIx; i != NumArgs; ++i) {
3512         ExprResult arg;
3513         if (isa<ExplicitCastExpr>(Args[i]->IgnoreParens()))
3514           arg = DefaultFunctionArrayLvalueConversion(Args[i]);
3515         else
3516           arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl);
3517         Invalid |= arg.isInvalid();
3518         AllArgs.push_back(arg.take());
3519       }
3520 
3521     // Otherwise do argument promotion, (C99 6.5.2.2p7).
3522     } else {
3523       for (unsigned i = ArgIx; i != NumArgs; ++i) {
3524         ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType,
3525                                                           FDecl);
3526         Invalid |= Arg.isInvalid();
3527         AllArgs.push_back(Arg.take());
3528       }
3529     }
3530 
3531     // Check for array bounds violations.
3532     for (unsigned i = ArgIx; i != NumArgs; ++i)
3533       CheckArrayAccess(Args[i]);
3534   }
3535   return Invalid;
3536 }
3537 
3538 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
3539   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
3540   if (ArrayTypeLoc *ATL = dyn_cast<ArrayTypeLoc>(&TL))
3541     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
3542       << ATL->getLocalSourceRange();
3543 }
3544 
3545 /// CheckStaticArrayArgument - If the given argument corresponds to a static
3546 /// array parameter, check that it is non-null, and that if it is formed by
3547 /// array-to-pointer decay, the underlying array is sufficiently large.
3548 ///
3549 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
3550 /// array type derivation, then for each call to the function, the value of the
3551 /// corresponding actual argument shall provide access to the first element of
3552 /// an array with at least as many elements as specified by the size expression.
3553 void
3554 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
3555                                ParmVarDecl *Param,
3556                                const Expr *ArgExpr) {
3557   // Static array parameters are not supported in C++.
3558   if (!Param || getLangOptions().CPlusPlus)
3559     return;
3560 
3561   QualType OrigTy = Param->getOriginalType();
3562 
3563   const ArrayType *AT = Context.getAsArrayType(OrigTy);
3564   if (!AT || AT->getSizeModifier() != ArrayType::Static)
3565     return;
3566 
3567   if (ArgExpr->isNullPointerConstant(Context,
3568                                      Expr::NPC_NeverValueDependent)) {
3569     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
3570     DiagnoseCalleeStaticArrayParam(*this, Param);
3571     return;
3572   }
3573 
3574   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
3575   if (!CAT)
3576     return;
3577 
3578   const ConstantArrayType *ArgCAT =
3579     Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
3580   if (!ArgCAT)
3581     return;
3582 
3583   if (ArgCAT->getSize().ult(CAT->getSize())) {
3584     Diag(CallLoc, diag::warn_static_array_too_small)
3585       << ArgExpr->getSourceRange()
3586       << (unsigned) ArgCAT->getSize().getZExtValue()
3587       << (unsigned) CAT->getSize().getZExtValue();
3588     DiagnoseCalleeStaticArrayParam(*this, Param);
3589   }
3590 }
3591 
3592 /// Given a function expression of unknown-any type, try to rebuild it
3593 /// to have a function type.
3594 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
3595 
3596 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
3597 /// This provides the location of the left/right parens and a list of comma
3598 /// locations.
3599 ExprResult
3600 Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
3601                     MultiExprArg ArgExprs, SourceLocation RParenLoc,
3602                     Expr *ExecConfig, bool IsExecConfig) {
3603   unsigned NumArgs = ArgExprs.size();
3604 
3605   // Since this might be a postfix expression, get rid of ParenListExprs.
3606   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
3607   if (Result.isInvalid()) return ExprError();
3608   Fn = Result.take();
3609 
3610   Expr **Args = ArgExprs.release();
3611 
3612   if (getLangOptions().CPlusPlus) {
3613     // If this is a pseudo-destructor expression, build the call immediately.
3614     if (isa<CXXPseudoDestructorExpr>(Fn)) {
3615       if (NumArgs > 0) {
3616         // Pseudo-destructor calls should not have any arguments.
3617         Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
3618           << FixItHint::CreateRemoval(
3619                                     SourceRange(Args[0]->getLocStart(),
3620                                                 Args[NumArgs-1]->getLocEnd()));
3621 
3622         NumArgs = 0;
3623       }
3624 
3625       return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
3626                                           VK_RValue, RParenLoc));
3627     }
3628 
3629     // Determine whether this is a dependent call inside a C++ template,
3630     // in which case we won't do any semantic analysis now.
3631     // FIXME: Will need to cache the results of name lookup (including ADL) in
3632     // Fn.
3633     bool Dependent = false;
3634     if (Fn->isTypeDependent())
3635       Dependent = true;
3636     else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
3637       Dependent = true;
3638 
3639     if (Dependent) {
3640       if (ExecConfig) {
3641         return Owned(new (Context) CUDAKernelCallExpr(
3642             Context, Fn, cast<CallExpr>(ExecConfig), Args, NumArgs,
3643             Context.DependentTy, VK_RValue, RParenLoc));
3644       } else {
3645         return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
3646                                             Context.DependentTy, VK_RValue,
3647                                             RParenLoc));
3648       }
3649     }
3650 
3651     // Determine whether this is a call to an object (C++ [over.call.object]).
3652     if (Fn->getType()->isRecordType())
3653       return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
3654                                                 RParenLoc));
3655 
3656     if (Fn->getType() == Context.UnknownAnyTy) {
3657       ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
3658       if (result.isInvalid()) return ExprError();
3659       Fn = result.take();
3660     }
3661 
3662     if (Fn->getType() == Context.BoundMemberTy) {
3663       return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
3664                                        RParenLoc);
3665     }
3666   }
3667 
3668   // Check for overloaded calls.  This can happen even in C due to extensions.
3669   if (Fn->getType() == Context.OverloadTy) {
3670     OverloadExpr::FindResult find = OverloadExpr::find(Fn);
3671 
3672     // We aren't supposed to apply this logic for if there's an '&' involved.
3673     if (!find.HasFormOfMemberPointer) {
3674       OverloadExpr *ovl = find.Expression;
3675       if (isa<UnresolvedLookupExpr>(ovl)) {
3676         UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
3677         return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, Args, NumArgs,
3678                                        RParenLoc, ExecConfig);
3679       } else {
3680         return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
3681                                          RParenLoc);
3682       }
3683     }
3684   }
3685 
3686   // If we're directly calling a function, get the appropriate declaration.
3687 
3688   Expr *NakedFn = Fn->IgnoreParens();
3689 
3690   NamedDecl *NDecl = 0;
3691   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
3692     if (UnOp->getOpcode() == UO_AddrOf)
3693       NakedFn = UnOp->getSubExpr()->IgnoreParens();
3694 
3695   if (isa<DeclRefExpr>(NakedFn))
3696     NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
3697   else if (isa<MemberExpr>(NakedFn))
3698     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
3699 
3700   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc,
3701                                ExecConfig, IsExecConfig);
3702 }
3703 
3704 ExprResult
3705 Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
3706                               MultiExprArg ExecConfig, SourceLocation GGGLoc) {
3707   FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
3708   if (!ConfigDecl)
3709     return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
3710                           << "cudaConfigureCall");
3711   QualType ConfigQTy = ConfigDecl->getType();
3712 
3713   DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
3714       ConfigDecl, ConfigQTy, VK_LValue, LLLLoc);
3715 
3716   return ActOnCallExpr(S, ConfigDR, LLLLoc, ExecConfig, GGGLoc, 0,
3717                        /*IsExecConfig=*/true);
3718 }
3719 
3720 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
3721 ///
3722 /// __builtin_astype( value, dst type )
3723 ///
3724 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
3725                                  SourceLocation BuiltinLoc,
3726                                  SourceLocation RParenLoc) {
3727   ExprValueKind VK = VK_RValue;
3728   ExprObjectKind OK = OK_Ordinary;
3729   QualType DstTy = GetTypeFromParser(ParsedDestTy);
3730   QualType SrcTy = E->getType();
3731   if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
3732     return ExprError(Diag(BuiltinLoc,
3733                           diag::err_invalid_astype_of_different_size)
3734                      << DstTy
3735                      << SrcTy
3736                      << E->getSourceRange());
3737   return Owned(new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc,
3738                RParenLoc));
3739 }
3740 
3741 /// BuildResolvedCallExpr - Build a call to a resolved expression,
3742 /// i.e. an expression not of \p OverloadTy.  The expression should
3743 /// unary-convert to an expression of function-pointer or
3744 /// block-pointer type.
3745 ///
3746 /// \param NDecl the declaration being called, if available
3747 ExprResult
3748 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
3749                             SourceLocation LParenLoc,
3750                             Expr **Args, unsigned NumArgs,
3751                             SourceLocation RParenLoc,
3752                             Expr *Config, bool IsExecConfig) {
3753   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
3754 
3755   // Promote the function operand.
3756   ExprResult Result = UsualUnaryConversions(Fn);
3757   if (Result.isInvalid())
3758     return ExprError();
3759   Fn = Result.take();
3760 
3761   // Make the call expr early, before semantic checks.  This guarantees cleanup
3762   // of arguments and function on error.
3763   CallExpr *TheCall;
3764   if (Config) {
3765     TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
3766                                                cast<CallExpr>(Config),
3767                                                Args, NumArgs,
3768                                                Context.BoolTy,
3769                                                VK_RValue,
3770                                                RParenLoc);
3771   } else {
3772     TheCall = new (Context) CallExpr(Context, Fn,
3773                                      Args, NumArgs,
3774                                      Context.BoolTy,
3775                                      VK_RValue,
3776                                      RParenLoc);
3777   }
3778 
3779   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
3780 
3781   // Bail out early if calling a builtin with custom typechecking.
3782   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
3783     return CheckBuiltinFunctionCall(BuiltinID, TheCall);
3784 
3785  retry:
3786   const FunctionType *FuncT;
3787   if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
3788     // C99 6.5.2.2p1 - "The expression that denotes the called function shall
3789     // have type pointer to function".
3790     FuncT = PT->getPointeeType()->getAs<FunctionType>();
3791     if (FuncT == 0)
3792       return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3793                          << Fn->getType() << Fn->getSourceRange());
3794   } else if (const BlockPointerType *BPT =
3795                Fn->getType()->getAs<BlockPointerType>()) {
3796     FuncT = BPT->getPointeeType()->castAs<FunctionType>();
3797   } else {
3798     // Handle calls to expressions of unknown-any type.
3799     if (Fn->getType() == Context.UnknownAnyTy) {
3800       ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
3801       if (rewrite.isInvalid()) return ExprError();
3802       Fn = rewrite.take();
3803       TheCall->setCallee(Fn);
3804       goto retry;
3805     }
3806 
3807     return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3808       << Fn->getType() << Fn->getSourceRange());
3809   }
3810 
3811   if (getLangOptions().CUDA) {
3812     if (Config) {
3813       // CUDA: Kernel calls must be to global functions
3814       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
3815         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
3816             << FDecl->getName() << Fn->getSourceRange());
3817 
3818       // CUDA: Kernel function must have 'void' return type
3819       if (!FuncT->getResultType()->isVoidType())
3820         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
3821             << Fn->getType() << Fn->getSourceRange());
3822     } else {
3823       // CUDA: Calls to global functions must be configured
3824       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
3825         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
3826             << FDecl->getName() << Fn->getSourceRange());
3827     }
3828   }
3829 
3830   // Check for a valid return type
3831   if (CheckCallReturnType(FuncT->getResultType(),
3832                           Fn->getSourceRange().getBegin(), TheCall,
3833                           FDecl))
3834     return ExprError();
3835 
3836   // We know the result type of the call, set it.
3837   TheCall->setType(FuncT->getCallResultType(Context));
3838   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
3839 
3840   if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
3841     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
3842                                 RParenLoc, IsExecConfig))
3843       return ExprError();
3844   } else {
3845     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
3846 
3847     if (FDecl) {
3848       // Check if we have too few/too many template arguments, based
3849       // on our knowledge of the function definition.
3850       const FunctionDecl *Def = 0;
3851       if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
3852         const FunctionProtoType *Proto
3853           = Def->getType()->getAs<FunctionProtoType>();
3854         if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
3855           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
3856             << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
3857       }
3858 
3859       // If the function we're calling isn't a function prototype, but we have
3860       // a function prototype from a prior declaratiom, use that prototype.
3861       if (!FDecl->hasPrototype())
3862         Proto = FDecl->getType()->getAs<FunctionProtoType>();
3863     }
3864 
3865     // Promote the arguments (C99 6.5.2.2p6).
3866     for (unsigned i = 0; i != NumArgs; i++) {
3867       Expr *Arg = Args[i];
3868 
3869       if (Proto && i < Proto->getNumArgs()) {
3870         InitializedEntity Entity
3871           = InitializedEntity::InitializeParameter(Context,
3872                                                    Proto->getArgType(i),
3873                                                    Proto->isArgConsumed(i));
3874         ExprResult ArgE = PerformCopyInitialization(Entity,
3875                                                     SourceLocation(),
3876                                                     Owned(Arg));
3877         if (ArgE.isInvalid())
3878           return true;
3879 
3880         Arg = ArgE.takeAs<Expr>();
3881 
3882       } else {
3883         ExprResult ArgE = DefaultArgumentPromotion(Arg);
3884 
3885         if (ArgE.isInvalid())
3886           return true;
3887 
3888         Arg = ArgE.takeAs<Expr>();
3889       }
3890 
3891       if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3892                               Arg->getType(),
3893                               PDiag(diag::err_call_incomplete_argument)
3894                                 << Arg->getSourceRange()))
3895         return ExprError();
3896 
3897       TheCall->setArg(i, Arg);
3898     }
3899   }
3900 
3901   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3902     if (!Method->isStatic())
3903       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
3904         << Fn->getSourceRange());
3905 
3906   // Check for sentinels
3907   if (NDecl)
3908     DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
3909 
3910   // Do special checking on direct calls to functions.
3911   if (FDecl) {
3912     if (CheckFunctionCall(FDecl, TheCall))
3913       return ExprError();
3914 
3915     if (BuiltinID)
3916       return CheckBuiltinFunctionCall(BuiltinID, TheCall);
3917   } else if (NDecl) {
3918     if (CheckBlockCall(NDecl, TheCall))
3919       return ExprError();
3920   }
3921 
3922   return MaybeBindToTemporary(TheCall);
3923 }
3924 
3925 ExprResult
3926 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
3927                            SourceLocation RParenLoc, Expr *InitExpr) {
3928   assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
3929   // FIXME: put back this assert when initializers are worked out.
3930   //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
3931 
3932   TypeSourceInfo *TInfo;
3933   QualType literalType = GetTypeFromParser(Ty, &TInfo);
3934   if (!TInfo)
3935     TInfo = Context.getTrivialTypeSourceInfo(literalType);
3936 
3937   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
3938 }
3939 
3940 ExprResult
3941 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
3942                                SourceLocation RParenLoc, Expr *LiteralExpr) {
3943   QualType literalType = TInfo->getType();
3944 
3945   if (literalType->isArrayType()) {
3946     if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
3947              PDiag(diag::err_illegal_decl_array_incomplete_type)
3948                << SourceRange(LParenLoc,
3949                               LiteralExpr->getSourceRange().getEnd())))
3950       return ExprError();
3951     if (literalType->isVariableArrayType())
3952       return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
3953         << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
3954   } else if (!literalType->isDependentType() &&
3955              RequireCompleteType(LParenLoc, literalType,
3956                       PDiag(diag::err_typecheck_decl_incomplete_type)
3957                         << SourceRange(LParenLoc,
3958                                        LiteralExpr->getSourceRange().getEnd())))
3959     return ExprError();
3960 
3961   InitializedEntity Entity
3962     = InitializedEntity::InitializeTemporary(literalType);
3963   InitializationKind Kind
3964     = InitializationKind::CreateCStyleCast(LParenLoc,
3965                                            SourceRange(LParenLoc, RParenLoc));
3966   InitializationSequence InitSeq(*this, Entity, Kind, &LiteralExpr, 1);
3967   ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
3968                                        MultiExprArg(*this, &LiteralExpr, 1),
3969                                             &literalType);
3970   if (Result.isInvalid())
3971     return ExprError();
3972   LiteralExpr = Result.get();
3973 
3974   bool isFileScope = getCurFunctionOrMethodDecl() == 0;
3975   if (isFileScope) { // 6.5.2.5p3
3976     if (CheckForConstantInitializer(LiteralExpr, literalType))
3977       return ExprError();
3978   }
3979 
3980   // In C, compound literals are l-values for some reason.
3981   ExprValueKind VK = getLangOptions().CPlusPlus ? VK_RValue : VK_LValue;
3982 
3983   return MaybeBindToTemporary(
3984            new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
3985                                              VK, LiteralExpr, isFileScope));
3986 }
3987 
3988 ExprResult
3989 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
3990                     SourceLocation RBraceLoc) {
3991   unsigned NumInit = InitArgList.size();
3992   Expr **InitList = InitArgList.release();
3993 
3994   // Immediately handle non-overload placeholders.  Overloads can be
3995   // resolved contextually, but everything else here can't.
3996   for (unsigned I = 0; I != NumInit; ++I) {
3997     if (InitList[I]->getType()->isNonOverloadPlaceholderType()) {
3998       ExprResult result = CheckPlaceholderExpr(InitList[I]);
3999 
4000       // Ignore failures; dropping the entire initializer list because
4001       // of one failure would be terrible for indexing/etc.
4002       if (result.isInvalid()) continue;
4003 
4004       InitList[I] = result.take();
4005     }
4006   }
4007 
4008   // Semantic analysis for initializers is done by ActOnDeclarator() and
4009   // CheckInitializer() - it requires knowledge of the object being intialized.
4010 
4011   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitList,
4012                                                NumInit, RBraceLoc);
4013   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
4014   return Owned(E);
4015 }
4016 
4017 /// Do an explicit extend of the given block pointer if we're in ARC.
4018 static void maybeExtendBlockObject(Sema &S, ExprResult &E) {
4019   assert(E.get()->getType()->isBlockPointerType());
4020   assert(E.get()->isRValue());
4021 
4022   // Only do this in an r-value context.
4023   if (!S.getLangOptions().ObjCAutoRefCount) return;
4024 
4025   E = ImplicitCastExpr::Create(S.Context, E.get()->getType(),
4026                                CK_ARCExtendBlockObject, E.get(),
4027                                /*base path*/ 0, VK_RValue);
4028   S.ExprNeedsCleanups = true;
4029 }
4030 
4031 /// Prepare a conversion of the given expression to an ObjC object
4032 /// pointer type.
4033 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
4034   QualType type = E.get()->getType();
4035   if (type->isObjCObjectPointerType()) {
4036     return CK_BitCast;
4037   } else if (type->isBlockPointerType()) {
4038     maybeExtendBlockObject(*this, E);
4039     return CK_BlockPointerToObjCPointerCast;
4040   } else {
4041     assert(type->isPointerType());
4042     return CK_CPointerToObjCPointerCast;
4043   }
4044 }
4045 
4046 /// Prepares for a scalar cast, performing all the necessary stages
4047 /// except the final cast and returning the kind required.
4048 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
4049   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
4050   // Also, callers should have filtered out the invalid cases with
4051   // pointers.  Everything else should be possible.
4052 
4053   QualType SrcTy = Src.get()->getType();
4054   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
4055     return CK_NoOp;
4056 
4057   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
4058   case Type::STK_MemberPointer:
4059     llvm_unreachable("member pointer type in C");
4060 
4061   case Type::STK_CPointer:
4062   case Type::STK_BlockPointer:
4063   case Type::STK_ObjCObjectPointer:
4064     switch (DestTy->getScalarTypeKind()) {
4065     case Type::STK_CPointer:
4066       return CK_BitCast;
4067     case Type::STK_BlockPointer:
4068       return (SrcKind == Type::STK_BlockPointer
4069                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
4070     case Type::STK_ObjCObjectPointer:
4071       if (SrcKind == Type::STK_ObjCObjectPointer)
4072         return CK_BitCast;
4073       else if (SrcKind == Type::STK_CPointer)
4074         return CK_CPointerToObjCPointerCast;
4075       else {
4076         maybeExtendBlockObject(*this, Src);
4077         return CK_BlockPointerToObjCPointerCast;
4078       }
4079     case Type::STK_Bool:
4080       return CK_PointerToBoolean;
4081     case Type::STK_Integral:
4082       return CK_PointerToIntegral;
4083     case Type::STK_Floating:
4084     case Type::STK_FloatingComplex:
4085     case Type::STK_IntegralComplex:
4086     case Type::STK_MemberPointer:
4087       llvm_unreachable("illegal cast from pointer");
4088     }
4089     break;
4090 
4091   case Type::STK_Bool: // casting from bool is like casting from an integer
4092   case Type::STK_Integral:
4093     switch (DestTy->getScalarTypeKind()) {
4094     case Type::STK_CPointer:
4095     case Type::STK_ObjCObjectPointer:
4096     case Type::STK_BlockPointer:
4097       if (Src.get()->isNullPointerConstant(Context,
4098                                            Expr::NPC_ValueDependentIsNull))
4099         return CK_NullToPointer;
4100       return CK_IntegralToPointer;
4101     case Type::STK_Bool:
4102       return CK_IntegralToBoolean;
4103     case Type::STK_Integral:
4104       return CK_IntegralCast;
4105     case Type::STK_Floating:
4106       return CK_IntegralToFloating;
4107     case Type::STK_IntegralComplex:
4108       Src = ImpCastExprToType(Src.take(),
4109                               DestTy->castAs<ComplexType>()->getElementType(),
4110                               CK_IntegralCast);
4111       return CK_IntegralRealToComplex;
4112     case Type::STK_FloatingComplex:
4113       Src = ImpCastExprToType(Src.take(),
4114                               DestTy->castAs<ComplexType>()->getElementType(),
4115                               CK_IntegralToFloating);
4116       return CK_FloatingRealToComplex;
4117     case Type::STK_MemberPointer:
4118       llvm_unreachable("member pointer type in C");
4119     }
4120     break;
4121 
4122   case Type::STK_Floating:
4123     switch (DestTy->getScalarTypeKind()) {
4124     case Type::STK_Floating:
4125       return CK_FloatingCast;
4126     case Type::STK_Bool:
4127       return CK_FloatingToBoolean;
4128     case Type::STK_Integral:
4129       return CK_FloatingToIntegral;
4130     case Type::STK_FloatingComplex:
4131       Src = ImpCastExprToType(Src.take(),
4132                               DestTy->castAs<ComplexType>()->getElementType(),
4133                               CK_FloatingCast);
4134       return CK_FloatingRealToComplex;
4135     case Type::STK_IntegralComplex:
4136       Src = ImpCastExprToType(Src.take(),
4137                               DestTy->castAs<ComplexType>()->getElementType(),
4138                               CK_FloatingToIntegral);
4139       return CK_IntegralRealToComplex;
4140     case Type::STK_CPointer:
4141     case Type::STK_ObjCObjectPointer:
4142     case Type::STK_BlockPointer:
4143       llvm_unreachable("valid float->pointer cast?");
4144     case Type::STK_MemberPointer:
4145       llvm_unreachable("member pointer type in C");
4146     }
4147     break;
4148 
4149   case Type::STK_FloatingComplex:
4150     switch (DestTy->getScalarTypeKind()) {
4151     case Type::STK_FloatingComplex:
4152       return CK_FloatingComplexCast;
4153     case Type::STK_IntegralComplex:
4154       return CK_FloatingComplexToIntegralComplex;
4155     case Type::STK_Floating: {
4156       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
4157       if (Context.hasSameType(ET, DestTy))
4158         return CK_FloatingComplexToReal;
4159       Src = ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal);
4160       return CK_FloatingCast;
4161     }
4162     case Type::STK_Bool:
4163       return CK_FloatingComplexToBoolean;
4164     case Type::STK_Integral:
4165       Src = ImpCastExprToType(Src.take(),
4166                               SrcTy->castAs<ComplexType>()->getElementType(),
4167                               CK_FloatingComplexToReal);
4168       return CK_FloatingToIntegral;
4169     case Type::STK_CPointer:
4170     case Type::STK_ObjCObjectPointer:
4171     case Type::STK_BlockPointer:
4172       llvm_unreachable("valid complex float->pointer cast?");
4173     case Type::STK_MemberPointer:
4174       llvm_unreachable("member pointer type in C");
4175     }
4176     break;
4177 
4178   case Type::STK_IntegralComplex:
4179     switch (DestTy->getScalarTypeKind()) {
4180     case Type::STK_FloatingComplex:
4181       return CK_IntegralComplexToFloatingComplex;
4182     case Type::STK_IntegralComplex:
4183       return CK_IntegralComplexCast;
4184     case Type::STK_Integral: {
4185       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
4186       if (Context.hasSameType(ET, DestTy))
4187         return CK_IntegralComplexToReal;
4188       Src = ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal);
4189       return CK_IntegralCast;
4190     }
4191     case Type::STK_Bool:
4192       return CK_IntegralComplexToBoolean;
4193     case Type::STK_Floating:
4194       Src = ImpCastExprToType(Src.take(),
4195                               SrcTy->castAs<ComplexType>()->getElementType(),
4196                               CK_IntegralComplexToReal);
4197       return CK_IntegralToFloating;
4198     case Type::STK_CPointer:
4199     case Type::STK_ObjCObjectPointer:
4200     case Type::STK_BlockPointer:
4201       llvm_unreachable("valid complex int->pointer cast?");
4202     case Type::STK_MemberPointer:
4203       llvm_unreachable("member pointer type in C");
4204     }
4205     break;
4206   }
4207 
4208   llvm_unreachable("Unhandled scalar cast");
4209 }
4210 
4211 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
4212                            CastKind &Kind) {
4213   assert(VectorTy->isVectorType() && "Not a vector type!");
4214 
4215   if (Ty->isVectorType() || Ty->isIntegerType()) {
4216     if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
4217       return Diag(R.getBegin(),
4218                   Ty->isVectorType() ?
4219                   diag::err_invalid_conversion_between_vectors :
4220                   diag::err_invalid_conversion_between_vector_and_integer)
4221         << VectorTy << Ty << R;
4222   } else
4223     return Diag(R.getBegin(),
4224                 diag::err_invalid_conversion_between_vector_and_scalar)
4225       << VectorTy << Ty << R;
4226 
4227   Kind = CK_BitCast;
4228   return false;
4229 }
4230 
4231 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
4232                                     Expr *CastExpr, CastKind &Kind) {
4233   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
4234 
4235   QualType SrcTy = CastExpr->getType();
4236 
4237   // If SrcTy is a VectorType, the total size must match to explicitly cast to
4238   // an ExtVectorType.
4239   // In OpenCL, casts between vectors of different types are not allowed.
4240   // (See OpenCL 6.2).
4241   if (SrcTy->isVectorType()) {
4242     if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)
4243         || (getLangOptions().OpenCL &&
4244             (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
4245       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
4246         << DestTy << SrcTy << R;
4247       return ExprError();
4248     }
4249     Kind = CK_BitCast;
4250     return Owned(CastExpr);
4251   }
4252 
4253   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
4254   // conversion will take place first from scalar to elt type, and then
4255   // splat from elt type to vector.
4256   if (SrcTy->isPointerType())
4257     return Diag(R.getBegin(),
4258                 diag::err_invalid_conversion_between_vector_and_scalar)
4259       << DestTy << SrcTy << R;
4260 
4261   QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
4262   ExprResult CastExprRes = Owned(CastExpr);
4263   CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy);
4264   if (CastExprRes.isInvalid())
4265     return ExprError();
4266   CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take();
4267 
4268   Kind = CK_VectorSplat;
4269   return Owned(CastExpr);
4270 }
4271 
4272 ExprResult
4273 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
4274                     Declarator &D, ParsedType &Ty,
4275                     SourceLocation RParenLoc, Expr *CastExpr) {
4276   assert(!D.isInvalidType() && (CastExpr != 0) &&
4277          "ActOnCastExpr(): missing type or expr");
4278 
4279   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
4280   if (D.isInvalidType())
4281     return ExprError();
4282 
4283   if (getLangOptions().CPlusPlus) {
4284     // Check that there are no default arguments (C++ only).
4285     CheckExtraCXXDefaultArguments(D);
4286   }
4287 
4288   checkUnusedDeclAttributes(D);
4289 
4290   QualType castType = castTInfo->getType();
4291   Ty = CreateParsedType(castType, castTInfo);
4292 
4293   bool isVectorLiteral = false;
4294 
4295   // Check for an altivec or OpenCL literal,
4296   // i.e. all the elements are integer constants.
4297   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
4298   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
4299   if ((getLangOptions().AltiVec || getLangOptions().OpenCL)
4300        && castType->isVectorType() && (PE || PLE)) {
4301     if (PLE && PLE->getNumExprs() == 0) {
4302       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
4303       return ExprError();
4304     }
4305     if (PE || PLE->getNumExprs() == 1) {
4306       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
4307       if (!E->getType()->isVectorType())
4308         isVectorLiteral = true;
4309     }
4310     else
4311       isVectorLiteral = true;
4312   }
4313 
4314   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
4315   // then handle it as such.
4316   if (isVectorLiteral)
4317     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
4318 
4319   // If the Expr being casted is a ParenListExpr, handle it specially.
4320   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
4321   // sequence of BinOp comma operators.
4322   if (isa<ParenListExpr>(CastExpr)) {
4323     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
4324     if (Result.isInvalid()) return ExprError();
4325     CastExpr = Result.take();
4326   }
4327 
4328   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
4329 }
4330 
4331 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
4332                                     SourceLocation RParenLoc, Expr *E,
4333                                     TypeSourceInfo *TInfo) {
4334   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
4335          "Expected paren or paren list expression");
4336 
4337   Expr **exprs;
4338   unsigned numExprs;
4339   Expr *subExpr;
4340   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
4341     exprs = PE->getExprs();
4342     numExprs = PE->getNumExprs();
4343   } else {
4344     subExpr = cast<ParenExpr>(E)->getSubExpr();
4345     exprs = &subExpr;
4346     numExprs = 1;
4347   }
4348 
4349   QualType Ty = TInfo->getType();
4350   assert(Ty->isVectorType() && "Expected vector type");
4351 
4352   SmallVector<Expr *, 8> initExprs;
4353   const VectorType *VTy = Ty->getAs<VectorType>();
4354   unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
4355 
4356   // '(...)' form of vector initialization in AltiVec: the number of
4357   // initializers must be one or must match the size of the vector.
4358   // If a single value is specified in the initializer then it will be
4359   // replicated to all the components of the vector
4360   if (VTy->getVectorKind() == VectorType::AltiVecVector) {
4361     // The number of initializers must be one or must match the size of the
4362     // vector. If a single value is specified in the initializer then it will
4363     // be replicated to all the components of the vector
4364     if (numExprs == 1) {
4365       QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
4366       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
4367       if (Literal.isInvalid())
4368         return ExprError();
4369       Literal = ImpCastExprToType(Literal.take(), ElemTy,
4370                                   PrepareScalarCast(Literal, ElemTy));
4371       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4372     }
4373     else if (numExprs < numElems) {
4374       Diag(E->getExprLoc(),
4375            diag::err_incorrect_number_of_vector_initializers);
4376       return ExprError();
4377     }
4378     else
4379       for (unsigned i = 0, e = numExprs; i != e; ++i)
4380         initExprs.push_back(exprs[i]);
4381   }
4382   else {
4383     // For OpenCL, when the number of initializers is a single value,
4384     // it will be replicated to all components of the vector.
4385     if (getLangOptions().OpenCL &&
4386         VTy->getVectorKind() == VectorType::GenericVector &&
4387         numExprs == 1) {
4388         QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
4389         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
4390         if (Literal.isInvalid())
4391           return ExprError();
4392         Literal = ImpCastExprToType(Literal.take(), ElemTy,
4393                                     PrepareScalarCast(Literal, ElemTy));
4394         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4395     }
4396 
4397     for (unsigned i = 0, e = numExprs; i != e; ++i)
4398       initExprs.push_back(exprs[i]);
4399   }
4400   // FIXME: This means that pretty-printing the final AST will produce curly
4401   // braces instead of the original commas.
4402   InitListExpr *initE = new (Context) InitListExpr(Context, LParenLoc,
4403                                                    &initExprs[0],
4404                                                    initExprs.size(), RParenLoc);
4405   initE->setType(Ty);
4406   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
4407 }
4408 
4409 /// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
4410 /// of comma binary operators.
4411 ExprResult
4412 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
4413   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
4414   if (!E)
4415     return Owned(OrigExpr);
4416 
4417   ExprResult Result(E->getExpr(0));
4418 
4419   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
4420     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
4421                         E->getExpr(i));
4422 
4423   if (Result.isInvalid()) return ExprError();
4424 
4425   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
4426 }
4427 
4428 ExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
4429                                            SourceLocation R,
4430                                            MultiExprArg Val) {
4431   unsigned nexprs = Val.size();
4432   Expr **exprs = reinterpret_cast<Expr**>(Val.release());
4433   assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
4434   Expr *expr;
4435   if (nexprs == 1)
4436     expr = new (Context) ParenExpr(L, R, exprs[0]);
4437   else
4438     expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R,
4439                                        exprs[nexprs-1]->getType());
4440   return Owned(expr);
4441 }
4442 
4443 /// \brief Emit a specialized diagnostic when one expression is a null pointer
4444 /// constant and the other is not a pointer.  Returns true if a diagnostic is
4445 /// emitted.
4446 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
4447                                       SourceLocation QuestionLoc) {
4448   Expr *NullExpr = LHSExpr;
4449   Expr *NonPointerExpr = RHSExpr;
4450   Expr::NullPointerConstantKind NullKind =
4451       NullExpr->isNullPointerConstant(Context,
4452                                       Expr::NPC_ValueDependentIsNotNull);
4453 
4454   if (NullKind == Expr::NPCK_NotNull) {
4455     NullExpr = RHSExpr;
4456     NonPointerExpr = LHSExpr;
4457     NullKind =
4458         NullExpr->isNullPointerConstant(Context,
4459                                         Expr::NPC_ValueDependentIsNotNull);
4460   }
4461 
4462   if (NullKind == Expr::NPCK_NotNull)
4463     return false;
4464 
4465   if (NullKind == Expr::NPCK_ZeroInteger) {
4466     // In this case, check to make sure that we got here from a "NULL"
4467     // string in the source code.
4468     NullExpr = NullExpr->IgnoreParenImpCasts();
4469     SourceLocation loc = NullExpr->getExprLoc();
4470     if (!findMacroSpelling(loc, "NULL"))
4471       return false;
4472   }
4473 
4474   int DiagType = (NullKind == Expr::NPCK_CXX0X_nullptr);
4475   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
4476       << NonPointerExpr->getType() << DiagType
4477       << NonPointerExpr->getSourceRange();
4478   return true;
4479 }
4480 
4481 /// \brief Return false if the condition expression is valid, true otherwise.
4482 static bool checkCondition(Sema &S, Expr *Cond) {
4483   QualType CondTy = Cond->getType();
4484 
4485   // C99 6.5.15p2
4486   if (CondTy->isScalarType()) return false;
4487 
4488   // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
4489   if (S.getLangOptions().OpenCL && CondTy->isVectorType())
4490     return false;
4491 
4492   // Emit the proper error message.
4493   S.Diag(Cond->getLocStart(), S.getLangOptions().OpenCL ?
4494                               diag::err_typecheck_cond_expect_scalar :
4495                               diag::err_typecheck_cond_expect_scalar_or_vector)
4496     << CondTy;
4497   return true;
4498 }
4499 
4500 /// \brief Return false if the two expressions can be converted to a vector,
4501 /// true otherwise
4502 static bool checkConditionalConvertScalarsToVectors(Sema &S, ExprResult &LHS,
4503                                                     ExprResult &RHS,
4504                                                     QualType CondTy) {
4505   // Both operands should be of scalar type.
4506   if (!LHS.get()->getType()->isScalarType()) {
4507     S.Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4508       << CondTy;
4509     return true;
4510   }
4511   if (!RHS.get()->getType()->isScalarType()) {
4512     S.Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4513       << CondTy;
4514     return true;
4515   }
4516 
4517   // Implicity convert these scalars to the type of the condition.
4518   LHS = S.ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast);
4519   RHS = S.ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast);
4520   return false;
4521 }
4522 
4523 /// \brief Handle when one or both operands are void type.
4524 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
4525                                          ExprResult &RHS) {
4526     Expr *LHSExpr = LHS.get();
4527     Expr *RHSExpr = RHS.get();
4528 
4529     if (!LHSExpr->getType()->isVoidType())
4530       S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4531         << RHSExpr->getSourceRange();
4532     if (!RHSExpr->getType()->isVoidType())
4533       S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4534         << LHSExpr->getSourceRange();
4535     LHS = S.ImpCastExprToType(LHS.take(), S.Context.VoidTy, CK_ToVoid);
4536     RHS = S.ImpCastExprToType(RHS.take(), S.Context.VoidTy, CK_ToVoid);
4537     return S.Context.VoidTy;
4538 }
4539 
4540 /// \brief Return false if the NullExpr can be promoted to PointerTy,
4541 /// true otherwise.
4542 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
4543                                         QualType PointerTy) {
4544   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
4545       !NullExpr.get()->isNullPointerConstant(S.Context,
4546                                             Expr::NPC_ValueDependentIsNull))
4547     return true;
4548 
4549   NullExpr = S.ImpCastExprToType(NullExpr.take(), PointerTy, CK_NullToPointer);
4550   return false;
4551 }
4552 
4553 /// \brief Checks compatibility between two pointers and return the resulting
4554 /// type.
4555 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
4556                                                      ExprResult &RHS,
4557                                                      SourceLocation Loc) {
4558   QualType LHSTy = LHS.get()->getType();
4559   QualType RHSTy = RHS.get()->getType();
4560 
4561   if (S.Context.hasSameType(LHSTy, RHSTy)) {
4562     // Two identical pointers types are always compatible.
4563     return LHSTy;
4564   }
4565 
4566   QualType lhptee, rhptee;
4567 
4568   // Get the pointee types.
4569   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
4570     lhptee = LHSBTy->getPointeeType();
4571     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
4572   } else {
4573     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
4574     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
4575   }
4576 
4577   if (!S.Context.typesAreCompatible(lhptee.getUnqualifiedType(),
4578                                     rhptee.getUnqualifiedType())) {
4579     S.Diag(Loc, diag::warn_typecheck_cond_incompatible_pointers)
4580       << LHSTy << RHSTy << LHS.get()->getSourceRange()
4581       << RHS.get()->getSourceRange();
4582     // In this situation, we assume void* type. No especially good
4583     // reason, but this is what gcc does, and we do have to pick
4584     // to get a consistent AST.
4585     QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy);
4586     LHS = S.ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4587     RHS = S.ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
4588     return incompatTy;
4589   }
4590 
4591   // The pointer types are compatible.
4592   // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
4593   // differently qualified versions of compatible types, the result type is
4594   // a pointer to an appropriately qualified version of the *composite*
4595   // type.
4596   // FIXME: Need to calculate the composite type.
4597   // FIXME: Need to add qualifiers
4598 
4599   LHS = S.ImpCastExprToType(LHS.take(), LHSTy, CK_BitCast);
4600   RHS = S.ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
4601   return LHSTy;
4602 }
4603 
4604 /// \brief Return the resulting type when the operands are both block pointers.
4605 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
4606                                                           ExprResult &LHS,
4607                                                           ExprResult &RHS,
4608                                                           SourceLocation Loc) {
4609   QualType LHSTy = LHS.get()->getType();
4610   QualType RHSTy = RHS.get()->getType();
4611 
4612   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
4613     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
4614       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
4615       LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4616       RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4617       return destType;
4618     }
4619     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
4620       << LHSTy << RHSTy << LHS.get()->getSourceRange()
4621       << RHS.get()->getSourceRange();
4622     return QualType();
4623   }
4624 
4625   // We have 2 block pointer types.
4626   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
4627 }
4628 
4629 /// \brief Return the resulting type when the operands are both pointers.
4630 static QualType
4631 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
4632                                             ExprResult &RHS,
4633                                             SourceLocation Loc) {
4634   // get the pointer types
4635   QualType LHSTy = LHS.get()->getType();
4636   QualType RHSTy = RHS.get()->getType();
4637 
4638   // get the "pointed to" types
4639   QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4640   QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4641 
4642   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
4643   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
4644     // Figure out necessary qualifiers (C99 6.5.15p6)
4645     QualType destPointee
4646       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4647     QualType destType = S.Context.getPointerType(destPointee);
4648     // Add qualifiers if necessary.
4649     LHS = S.ImpCastExprToType(LHS.take(), destType, CK_NoOp);
4650     // Promote to void*.
4651     RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4652     return destType;
4653   }
4654   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
4655     QualType destPointee
4656       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4657     QualType destType = S.Context.getPointerType(destPointee);
4658     // Add qualifiers if necessary.
4659     RHS = S.ImpCastExprToType(RHS.take(), destType, CK_NoOp);
4660     // Promote to void*.
4661     LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4662     return destType;
4663   }
4664 
4665   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
4666 }
4667 
4668 /// \brief Return false if the first expression is not an integer and the second
4669 /// expression is not a pointer, true otherwise.
4670 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
4671                                         Expr* PointerExpr, SourceLocation Loc,
4672                                         bool IsIntFirstExpr) {
4673   if (!PointerExpr->getType()->isPointerType() ||
4674       !Int.get()->getType()->isIntegerType())
4675     return false;
4676 
4677   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
4678   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
4679 
4680   S.Diag(Loc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4681     << Expr1->getType() << Expr2->getType()
4682     << Expr1->getSourceRange() << Expr2->getSourceRange();
4683   Int = S.ImpCastExprToType(Int.take(), PointerExpr->getType(),
4684                             CK_IntegralToPointer);
4685   return true;
4686 }
4687 
4688 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
4689 /// In that case, LHS = cond.
4690 /// C99 6.5.15
4691 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
4692                                         ExprResult &RHS, ExprValueKind &VK,
4693                                         ExprObjectKind &OK,
4694                                         SourceLocation QuestionLoc) {
4695 
4696   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
4697   if (!LHSResult.isUsable()) return QualType();
4698   LHS = move(LHSResult);
4699 
4700   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
4701   if (!RHSResult.isUsable()) return QualType();
4702   RHS = move(RHSResult);
4703 
4704   // C++ is sufficiently different to merit its own checker.
4705   if (getLangOptions().CPlusPlus)
4706     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
4707 
4708   VK = VK_RValue;
4709   OK = OK_Ordinary;
4710 
4711   Cond = UsualUnaryConversions(Cond.take());
4712   if (Cond.isInvalid())
4713     return QualType();
4714   LHS = UsualUnaryConversions(LHS.take());
4715   if (LHS.isInvalid())
4716     return QualType();
4717   RHS = UsualUnaryConversions(RHS.take());
4718   if (RHS.isInvalid())
4719     return QualType();
4720 
4721   QualType CondTy = Cond.get()->getType();
4722   QualType LHSTy = LHS.get()->getType();
4723   QualType RHSTy = RHS.get()->getType();
4724 
4725   // first, check the condition.
4726   if (checkCondition(*this, Cond.get()))
4727     return QualType();
4728 
4729   // Now check the two expressions.
4730   if (LHSTy->isVectorType() || RHSTy->isVectorType())
4731     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
4732 
4733   // OpenCL: If the condition is a vector, and both operands are scalar,
4734   // attempt to implicity convert them to the vector type to act like the
4735   // built in select.
4736   if (getLangOptions().OpenCL && CondTy->isVectorType())
4737     if (checkConditionalConvertScalarsToVectors(*this, LHS, RHS, CondTy))
4738       return QualType();
4739 
4740   // If both operands have arithmetic type, do the usual arithmetic conversions
4741   // to find a common type: C99 6.5.15p3,5.
4742   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
4743     UsualArithmeticConversions(LHS, RHS);
4744     if (LHS.isInvalid() || RHS.isInvalid())
4745       return QualType();
4746     return LHS.get()->getType();
4747   }
4748 
4749   // If both operands are the same structure or union type, the result is that
4750   // type.
4751   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
4752     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
4753       if (LHSRT->getDecl() == RHSRT->getDecl())
4754         // "If both the operands have structure or union type, the result has
4755         // that type."  This implies that CV qualifiers are dropped.
4756         return LHSTy.getUnqualifiedType();
4757     // FIXME: Type of conditional expression must be complete in C mode.
4758   }
4759 
4760   // C99 6.5.15p5: "If both operands have void type, the result has void type."
4761   // The following || allows only one side to be void (a GCC-ism).
4762   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
4763     return checkConditionalVoidType(*this, LHS, RHS);
4764   }
4765 
4766   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
4767   // the type of the other operand."
4768   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
4769   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
4770 
4771   // All objective-c pointer type analysis is done here.
4772   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
4773                                                         QuestionLoc);
4774   if (LHS.isInvalid() || RHS.isInvalid())
4775     return QualType();
4776   if (!compositeType.isNull())
4777     return compositeType;
4778 
4779 
4780   // Handle block pointer types.
4781   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
4782     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
4783                                                      QuestionLoc);
4784 
4785   // Check constraints for C object pointers types (C99 6.5.15p3,6).
4786   if (LHSTy->isPointerType() && RHSTy->isPointerType())
4787     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
4788                                                        QuestionLoc);
4789 
4790   // GCC compatibility: soften pointer/integer mismatch.  Note that
4791   // null pointers have been filtered out by this point.
4792   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
4793       /*isIntFirstExpr=*/true))
4794     return RHSTy;
4795   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
4796       /*isIntFirstExpr=*/false))
4797     return LHSTy;
4798 
4799   // Emit a better diagnostic if one of the expressions is a null pointer
4800   // constant and the other is not a pointer type. In this case, the user most
4801   // likely forgot to take the address of the other expression.
4802   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
4803     return QualType();
4804 
4805   // Otherwise, the operands are not compatible.
4806   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
4807     << LHSTy << RHSTy << LHS.get()->getSourceRange()
4808     << RHS.get()->getSourceRange();
4809   return QualType();
4810 }
4811 
4812 /// FindCompositeObjCPointerType - Helper method to find composite type of
4813 /// two objective-c pointer types of the two input expressions.
4814 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
4815                                             SourceLocation QuestionLoc) {
4816   QualType LHSTy = LHS.get()->getType();
4817   QualType RHSTy = RHS.get()->getType();
4818 
4819   // Handle things like Class and struct objc_class*.  Here we case the result
4820   // to the pseudo-builtin, because that will be implicitly cast back to the
4821   // redefinition type if an attempt is made to access its fields.
4822   if (LHSTy->isObjCClassType() &&
4823       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
4824     RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
4825     return LHSTy;
4826   }
4827   if (RHSTy->isObjCClassType() &&
4828       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
4829     LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
4830     return RHSTy;
4831   }
4832   // And the same for struct objc_object* / id
4833   if (LHSTy->isObjCIdType() &&
4834       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
4835     RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
4836     return LHSTy;
4837   }
4838   if (RHSTy->isObjCIdType() &&
4839       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
4840     LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
4841     return RHSTy;
4842   }
4843   // And the same for struct objc_selector* / SEL
4844   if (Context.isObjCSelType(LHSTy) &&
4845       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
4846     RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
4847     return LHSTy;
4848   }
4849   if (Context.isObjCSelType(RHSTy) &&
4850       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
4851     LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
4852     return RHSTy;
4853   }
4854   // Check constraints for Objective-C object pointers types.
4855   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
4856 
4857     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4858       // Two identical object pointer types are always compatible.
4859       return LHSTy;
4860     }
4861     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
4862     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
4863     QualType compositeType = LHSTy;
4864 
4865     // If both operands are interfaces and either operand can be
4866     // assigned to the other, use that type as the composite
4867     // type. This allows
4868     //   xxx ? (A*) a : (B*) b
4869     // where B is a subclass of A.
4870     //
4871     // Additionally, as for assignment, if either type is 'id'
4872     // allow silent coercion. Finally, if the types are
4873     // incompatible then make sure to use 'id' as the composite
4874     // type so the result is acceptable for sending messages to.
4875 
4876     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
4877     // It could return the composite type.
4878     if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
4879       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
4880     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
4881       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
4882     } else if ((LHSTy->isObjCQualifiedIdType() ||
4883                 RHSTy->isObjCQualifiedIdType()) &&
4884                Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
4885       // Need to handle "id<xx>" explicitly.
4886       // GCC allows qualified id and any Objective-C type to devolve to
4887       // id. Currently localizing to here until clear this should be
4888       // part of ObjCQualifiedIdTypesAreCompatible.
4889       compositeType = Context.getObjCIdType();
4890     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
4891       compositeType = Context.getObjCIdType();
4892     } else if (!(compositeType =
4893                  Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
4894       ;
4895     else {
4896       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
4897       << LHSTy << RHSTy
4898       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
4899       QualType incompatTy = Context.getObjCIdType();
4900       LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4901       RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
4902       return incompatTy;
4903     }
4904     // The object pointer types are compatible.
4905     LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast);
4906     RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast);
4907     return compositeType;
4908   }
4909   // Check Objective-C object pointer types and 'void *'
4910   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
4911     QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4912     QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4913     QualType destPointee
4914     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4915     QualType destType = Context.getPointerType(destPointee);
4916     // Add qualifiers if necessary.
4917     LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
4918     // Promote to void*.
4919     RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4920     return destType;
4921   }
4922   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
4923     QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4924     QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4925     QualType destPointee
4926     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4927     QualType destType = Context.getPointerType(destPointee);
4928     // Add qualifiers if necessary.
4929     RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
4930     // Promote to void*.
4931     LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4932     return destType;
4933   }
4934   return QualType();
4935 }
4936 
4937 /// SuggestParentheses - Emit a note with a fixit hint that wraps
4938 /// ParenRange in parentheses.
4939 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
4940                                const PartialDiagnostic &Note,
4941                                SourceRange ParenRange) {
4942   SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
4943   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
4944       EndLoc.isValid()) {
4945     Self.Diag(Loc, Note)
4946       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
4947       << FixItHint::CreateInsertion(EndLoc, ")");
4948   } else {
4949     // We can't display the parentheses, so just show the bare note.
4950     Self.Diag(Loc, Note) << ParenRange;
4951   }
4952 }
4953 
4954 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
4955   return Opc >= BO_Mul && Opc <= BO_Shr;
4956 }
4957 
4958 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
4959 /// expression, either using a built-in or overloaded operator,
4960 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
4961 /// expression.
4962 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
4963                                    Expr **RHSExprs) {
4964   // Don't strip parenthesis: we should not warn if E is in parenthesis.
4965   E = E->IgnoreImpCasts();
4966   E = E->IgnoreConversionOperator();
4967   E = E->IgnoreImpCasts();
4968 
4969   // Built-in binary operator.
4970   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
4971     if (IsArithmeticOp(OP->getOpcode())) {
4972       *Opcode = OP->getOpcode();
4973       *RHSExprs = OP->getRHS();
4974       return true;
4975     }
4976   }
4977 
4978   // Overloaded operator.
4979   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
4980     if (Call->getNumArgs() != 2)
4981       return false;
4982 
4983     // Make sure this is really a binary operator that is safe to pass into
4984     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
4985     OverloadedOperatorKind OO = Call->getOperator();
4986     if (OO < OO_Plus || OO > OO_Arrow)
4987       return false;
4988 
4989     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
4990     if (IsArithmeticOp(OpKind)) {
4991       *Opcode = OpKind;
4992       *RHSExprs = Call->getArg(1);
4993       return true;
4994     }
4995   }
4996 
4997   return false;
4998 }
4999 
5000 static bool IsLogicOp(BinaryOperatorKind Opc) {
5001   return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
5002 }
5003 
5004 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
5005 /// or is a logical expression such as (x==y) which has int type, but is
5006 /// commonly interpreted as boolean.
5007 static bool ExprLooksBoolean(Expr *E) {
5008   E = E->IgnoreParenImpCasts();
5009 
5010   if (E->getType()->isBooleanType())
5011     return true;
5012   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
5013     return IsLogicOp(OP->getOpcode());
5014   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
5015     return OP->getOpcode() == UO_LNot;
5016 
5017   return false;
5018 }
5019 
5020 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
5021 /// and binary operator are mixed in a way that suggests the programmer assumed
5022 /// the conditional operator has higher precedence, for example:
5023 /// "int x = a + someBinaryCondition ? 1 : 2".
5024 static void DiagnoseConditionalPrecedence(Sema &Self,
5025                                           SourceLocation OpLoc,
5026                                           Expr *Condition,
5027                                           Expr *LHSExpr,
5028                                           Expr *RHSExpr) {
5029   BinaryOperatorKind CondOpcode;
5030   Expr *CondRHS;
5031 
5032   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
5033     return;
5034   if (!ExprLooksBoolean(CondRHS))
5035     return;
5036 
5037   // The condition is an arithmetic binary expression, with a right-
5038   // hand side that looks boolean, so warn.
5039 
5040   Self.Diag(OpLoc, diag::warn_precedence_conditional)
5041       << Condition->getSourceRange()
5042       << BinaryOperator::getOpcodeStr(CondOpcode);
5043 
5044   SuggestParentheses(Self, OpLoc,
5045     Self.PDiag(diag::note_precedence_conditional_silence)
5046       << BinaryOperator::getOpcodeStr(CondOpcode),
5047     SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
5048 
5049   SuggestParentheses(Self, OpLoc,
5050     Self.PDiag(diag::note_precedence_conditional_first),
5051     SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
5052 }
5053 
5054 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
5055 /// in the case of a the GNU conditional expr extension.
5056 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
5057                                     SourceLocation ColonLoc,
5058                                     Expr *CondExpr, Expr *LHSExpr,
5059                                     Expr *RHSExpr) {
5060   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
5061   // was the condition.
5062   OpaqueValueExpr *opaqueValue = 0;
5063   Expr *commonExpr = 0;
5064   if (LHSExpr == 0) {
5065     commonExpr = CondExpr;
5066 
5067     // We usually want to apply unary conversions *before* saving, except
5068     // in the special case of a C++ l-value conditional.
5069     if (!(getLangOptions().CPlusPlus
5070           && !commonExpr->isTypeDependent()
5071           && commonExpr->getValueKind() == RHSExpr->getValueKind()
5072           && commonExpr->isGLValue()
5073           && commonExpr->isOrdinaryOrBitFieldObject()
5074           && RHSExpr->isOrdinaryOrBitFieldObject()
5075           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
5076       ExprResult commonRes = UsualUnaryConversions(commonExpr);
5077       if (commonRes.isInvalid())
5078         return ExprError();
5079       commonExpr = commonRes.take();
5080     }
5081 
5082     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
5083                                                 commonExpr->getType(),
5084                                                 commonExpr->getValueKind(),
5085                                                 commonExpr->getObjectKind());
5086     LHSExpr = CondExpr = opaqueValue;
5087   }
5088 
5089   ExprValueKind VK = VK_RValue;
5090   ExprObjectKind OK = OK_Ordinary;
5091   ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
5092   QualType result = CheckConditionalOperands(Cond, LHS, RHS,
5093                                              VK, OK, QuestionLoc);
5094   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
5095       RHS.isInvalid())
5096     return ExprError();
5097 
5098   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
5099                                 RHS.get());
5100 
5101   if (!commonExpr)
5102     return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc,
5103                                                    LHS.take(), ColonLoc,
5104                                                    RHS.take(), result, VK, OK));
5105 
5106   return Owned(new (Context)
5107     BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(),
5108                               RHS.take(), QuestionLoc, ColonLoc, result, VK,
5109                               OK));
5110 }
5111 
5112 // checkPointerTypesForAssignment - This is a very tricky routine (despite
5113 // being closely modeled after the C99 spec:-). The odd characteristic of this
5114 // routine is it effectively iqnores the qualifiers on the top level pointee.
5115 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
5116 // FIXME: add a couple examples in this comment.
5117 static Sema::AssignConvertType
5118 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
5119   assert(LHSType.isCanonical() && "LHS not canonicalized!");
5120   assert(RHSType.isCanonical() && "RHS not canonicalized!");
5121 
5122   // get the "pointed to" type (ignoring qualifiers at the top level)
5123   const Type *lhptee, *rhptee;
5124   Qualifiers lhq, rhq;
5125   llvm::tie(lhptee, lhq) = cast<PointerType>(LHSType)->getPointeeType().split();
5126   llvm::tie(rhptee, rhq) = cast<PointerType>(RHSType)->getPointeeType().split();
5127 
5128   Sema::AssignConvertType ConvTy = Sema::Compatible;
5129 
5130   // C99 6.5.16.1p1: This following citation is common to constraints
5131   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
5132   // qualifiers of the type *pointed to* by the right;
5133   Qualifiers lq;
5134 
5135   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
5136   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
5137       lhq.compatiblyIncludesObjCLifetime(rhq)) {
5138     // Ignore lifetime for further calculation.
5139     lhq.removeObjCLifetime();
5140     rhq.removeObjCLifetime();
5141   }
5142 
5143   if (!lhq.compatiblyIncludes(rhq)) {
5144     // Treat address-space mismatches as fatal.  TODO: address subspaces
5145     if (lhq.getAddressSpace() != rhq.getAddressSpace())
5146       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5147 
5148     // It's okay to add or remove GC or lifetime qualifiers when converting to
5149     // and from void*.
5150     else if (lhq.withoutObjCGCAttr().withoutObjCGLifetime()
5151                         .compatiblyIncludes(
5152                                 rhq.withoutObjCGCAttr().withoutObjCGLifetime())
5153              && (lhptee->isVoidType() || rhptee->isVoidType()))
5154       ; // keep old
5155 
5156     // Treat lifetime mismatches as fatal.
5157     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
5158       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5159 
5160     // For GCC compatibility, other qualifier mismatches are treated
5161     // as still compatible in C.
5162     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
5163   }
5164 
5165   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
5166   // incomplete type and the other is a pointer to a qualified or unqualified
5167   // version of void...
5168   if (lhptee->isVoidType()) {
5169     if (rhptee->isIncompleteOrObjectType())
5170       return ConvTy;
5171 
5172     // As an extension, we allow cast to/from void* to function pointer.
5173     assert(rhptee->isFunctionType());
5174     return Sema::FunctionVoidPointer;
5175   }
5176 
5177   if (rhptee->isVoidType()) {
5178     if (lhptee->isIncompleteOrObjectType())
5179       return ConvTy;
5180 
5181     // As an extension, we allow cast to/from void* to function pointer.
5182     assert(lhptee->isFunctionType());
5183     return Sema::FunctionVoidPointer;
5184   }
5185 
5186   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
5187   // unqualified versions of compatible types, ...
5188   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
5189   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
5190     // Check if the pointee types are compatible ignoring the sign.
5191     // We explicitly check for char so that we catch "char" vs
5192     // "unsigned char" on systems where "char" is unsigned.
5193     if (lhptee->isCharType())
5194       ltrans = S.Context.UnsignedCharTy;
5195     else if (lhptee->hasSignedIntegerRepresentation())
5196       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
5197 
5198     if (rhptee->isCharType())
5199       rtrans = S.Context.UnsignedCharTy;
5200     else if (rhptee->hasSignedIntegerRepresentation())
5201       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
5202 
5203     if (ltrans == rtrans) {
5204       // Types are compatible ignoring the sign. Qualifier incompatibility
5205       // takes priority over sign incompatibility because the sign
5206       // warning can be disabled.
5207       if (ConvTy != Sema::Compatible)
5208         return ConvTy;
5209 
5210       return Sema::IncompatiblePointerSign;
5211     }
5212 
5213     // If we are a multi-level pointer, it's possible that our issue is simply
5214     // one of qualification - e.g. char ** -> const char ** is not allowed. If
5215     // the eventual target type is the same and the pointers have the same
5216     // level of indirection, this must be the issue.
5217     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
5218       do {
5219         lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
5220         rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
5221       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
5222 
5223       if (lhptee == rhptee)
5224         return Sema::IncompatibleNestedPointerQualifiers;
5225     }
5226 
5227     // General pointer incompatibility takes priority over qualifiers.
5228     return Sema::IncompatiblePointer;
5229   }
5230   if (!S.getLangOptions().CPlusPlus &&
5231       S.IsNoReturnConversion(ltrans, rtrans, ltrans))
5232     return Sema::IncompatiblePointer;
5233   return ConvTy;
5234 }
5235 
5236 /// checkBlockPointerTypesForAssignment - This routine determines whether two
5237 /// block pointer types are compatible or whether a block and normal pointer
5238 /// are compatible. It is more restrict than comparing two function pointer
5239 // types.
5240 static Sema::AssignConvertType
5241 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
5242                                     QualType RHSType) {
5243   assert(LHSType.isCanonical() && "LHS not canonicalized!");
5244   assert(RHSType.isCanonical() && "RHS not canonicalized!");
5245 
5246   QualType lhptee, rhptee;
5247 
5248   // get the "pointed to" type (ignoring qualifiers at the top level)
5249   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
5250   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
5251 
5252   // In C++, the types have to match exactly.
5253   if (S.getLangOptions().CPlusPlus)
5254     return Sema::IncompatibleBlockPointer;
5255 
5256   Sema::AssignConvertType ConvTy = Sema::Compatible;
5257 
5258   // For blocks we enforce that qualifiers are identical.
5259   if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
5260     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
5261 
5262   if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
5263     return Sema::IncompatibleBlockPointer;
5264 
5265   return ConvTy;
5266 }
5267 
5268 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
5269 /// for assignment compatibility.
5270 static Sema::AssignConvertType
5271 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
5272                                    QualType RHSType) {
5273   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
5274   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
5275 
5276   if (LHSType->isObjCBuiltinType()) {
5277     // Class is not compatible with ObjC object pointers.
5278     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
5279         !RHSType->isObjCQualifiedClassType())
5280       return Sema::IncompatiblePointer;
5281     return Sema::Compatible;
5282   }
5283   if (RHSType->isObjCBuiltinType()) {
5284     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
5285         !LHSType->isObjCQualifiedClassType())
5286       return Sema::IncompatiblePointer;
5287     return Sema::Compatible;
5288   }
5289   QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
5290   QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
5291 
5292   if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
5293     return Sema::CompatiblePointerDiscardsQualifiers;
5294 
5295   if (S.Context.typesAreCompatible(LHSType, RHSType))
5296     return Sema::Compatible;
5297   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
5298     return Sema::IncompatibleObjCQualifiedId;
5299   return Sema::IncompatiblePointer;
5300 }
5301 
5302 Sema::AssignConvertType
5303 Sema::CheckAssignmentConstraints(SourceLocation Loc,
5304                                  QualType LHSType, QualType RHSType) {
5305   // Fake up an opaque expression.  We don't actually care about what
5306   // cast operations are required, so if CheckAssignmentConstraints
5307   // adds casts to this they'll be wasted, but fortunately that doesn't
5308   // usually happen on valid code.
5309   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
5310   ExprResult RHSPtr = &RHSExpr;
5311   CastKind K = CK_Invalid;
5312 
5313   return CheckAssignmentConstraints(LHSType, RHSPtr, K);
5314 }
5315 
5316 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
5317 /// has code to accommodate several GCC extensions when type checking
5318 /// pointers. Here are some objectionable examples that GCC considers warnings:
5319 ///
5320 ///  int a, *pint;
5321 ///  short *pshort;
5322 ///  struct foo *pfoo;
5323 ///
5324 ///  pint = pshort; // warning: assignment from incompatible pointer type
5325 ///  a = pint; // warning: assignment makes integer from pointer without a cast
5326 ///  pint = a; // warning: assignment makes pointer from integer without a cast
5327 ///  pint = pfoo; // warning: assignment from incompatible pointer type
5328 ///
5329 /// As a result, the code for dealing with pointers is more complex than the
5330 /// C99 spec dictates.
5331 ///
5332 /// Sets 'Kind' for any result kind except Incompatible.
5333 Sema::AssignConvertType
5334 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
5335                                  CastKind &Kind) {
5336   QualType RHSType = RHS.get()->getType();
5337   QualType OrigLHSType = LHSType;
5338 
5339   // Get canonical types.  We're not formatting these types, just comparing
5340   // them.
5341   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
5342   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
5343 
5344   // We can't do assignment from/to atomics yet.
5345   if (LHSType->isAtomicType())
5346     return Incompatible;
5347 
5348   // Common case: no conversion required.
5349   if (LHSType == RHSType) {
5350     Kind = CK_NoOp;
5351     return Compatible;
5352   }
5353 
5354   // If the left-hand side is a reference type, then we are in a
5355   // (rare!) case where we've allowed the use of references in C,
5356   // e.g., as a parameter type in a built-in function. In this case,
5357   // just make sure that the type referenced is compatible with the
5358   // right-hand side type. The caller is responsible for adjusting
5359   // LHSType so that the resulting expression does not have reference
5360   // type.
5361   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
5362     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
5363       Kind = CK_LValueBitCast;
5364       return Compatible;
5365     }
5366     return Incompatible;
5367   }
5368 
5369   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
5370   // to the same ExtVector type.
5371   if (LHSType->isExtVectorType()) {
5372     if (RHSType->isExtVectorType())
5373       return Incompatible;
5374     if (RHSType->isArithmeticType()) {
5375       // CK_VectorSplat does T -> vector T, so first cast to the
5376       // element type.
5377       QualType elType = cast<ExtVectorType>(LHSType)->getElementType();
5378       if (elType != RHSType) {
5379         Kind = PrepareScalarCast(RHS, elType);
5380         RHS = ImpCastExprToType(RHS.take(), elType, Kind);
5381       }
5382       Kind = CK_VectorSplat;
5383       return Compatible;
5384     }
5385   }
5386 
5387   // Conversions to or from vector type.
5388   if (LHSType->isVectorType() || RHSType->isVectorType()) {
5389     if (LHSType->isVectorType() && RHSType->isVectorType()) {
5390       // Allow assignments of an AltiVec vector type to an equivalent GCC
5391       // vector type and vice versa
5392       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
5393         Kind = CK_BitCast;
5394         return Compatible;
5395       }
5396 
5397       // If we are allowing lax vector conversions, and LHS and RHS are both
5398       // vectors, the total size only needs to be the same. This is a bitcast;
5399       // no bits are changed but the result type is different.
5400       if (getLangOptions().LaxVectorConversions &&
5401           (Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType))) {
5402         Kind = CK_BitCast;
5403         return IncompatibleVectors;
5404       }
5405     }
5406     return Incompatible;
5407   }
5408 
5409   // Arithmetic conversions.
5410   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
5411       !(getLangOptions().CPlusPlus && LHSType->isEnumeralType())) {
5412     Kind = PrepareScalarCast(RHS, LHSType);
5413     return Compatible;
5414   }
5415 
5416   // Conversions to normal pointers.
5417   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
5418     // U* -> T*
5419     if (isa<PointerType>(RHSType)) {
5420       Kind = CK_BitCast;
5421       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
5422     }
5423 
5424     // int -> T*
5425     if (RHSType->isIntegerType()) {
5426       Kind = CK_IntegralToPointer; // FIXME: null?
5427       return IntToPointer;
5428     }
5429 
5430     // C pointers are not compatible with ObjC object pointers,
5431     // with two exceptions:
5432     if (isa<ObjCObjectPointerType>(RHSType)) {
5433       //  - conversions to void*
5434       if (LHSPointer->getPointeeType()->isVoidType()) {
5435         Kind = CK_BitCast;
5436         return Compatible;
5437       }
5438 
5439       //  - conversions from 'Class' to the redefinition type
5440       if (RHSType->isObjCClassType() &&
5441           Context.hasSameType(LHSType,
5442                               Context.getObjCClassRedefinitionType())) {
5443         Kind = CK_BitCast;
5444         return Compatible;
5445       }
5446 
5447       Kind = CK_BitCast;
5448       return IncompatiblePointer;
5449     }
5450 
5451     // U^ -> void*
5452     if (RHSType->getAs<BlockPointerType>()) {
5453       if (LHSPointer->getPointeeType()->isVoidType()) {
5454         Kind = CK_BitCast;
5455         return Compatible;
5456       }
5457     }
5458 
5459     return Incompatible;
5460   }
5461 
5462   // Conversions to block pointers.
5463   if (isa<BlockPointerType>(LHSType)) {
5464     // U^ -> T^
5465     if (RHSType->isBlockPointerType()) {
5466       Kind = CK_BitCast;
5467       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
5468     }
5469 
5470     // int or null -> T^
5471     if (RHSType->isIntegerType()) {
5472       Kind = CK_IntegralToPointer; // FIXME: null
5473       return IntToBlockPointer;
5474     }
5475 
5476     // id -> T^
5477     if (getLangOptions().ObjC1 && RHSType->isObjCIdType()) {
5478       Kind = CK_AnyPointerToBlockPointerCast;
5479       return Compatible;
5480     }
5481 
5482     // void* -> T^
5483     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
5484       if (RHSPT->getPointeeType()->isVoidType()) {
5485         Kind = CK_AnyPointerToBlockPointerCast;
5486         return Compatible;
5487       }
5488 
5489     return Incompatible;
5490   }
5491 
5492   // Conversions to Objective-C pointers.
5493   if (isa<ObjCObjectPointerType>(LHSType)) {
5494     // A* -> B*
5495     if (RHSType->isObjCObjectPointerType()) {
5496       Kind = CK_BitCast;
5497       Sema::AssignConvertType result =
5498         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
5499       if (getLangOptions().ObjCAutoRefCount &&
5500           result == Compatible &&
5501           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
5502         result = IncompatibleObjCWeakRef;
5503       return result;
5504     }
5505 
5506     // int or null -> A*
5507     if (RHSType->isIntegerType()) {
5508       Kind = CK_IntegralToPointer; // FIXME: null
5509       return IntToPointer;
5510     }
5511 
5512     // In general, C pointers are not compatible with ObjC object pointers,
5513     // with two exceptions:
5514     if (isa<PointerType>(RHSType)) {
5515       Kind = CK_CPointerToObjCPointerCast;
5516 
5517       //  - conversions from 'void*'
5518       if (RHSType->isVoidPointerType()) {
5519         return Compatible;
5520       }
5521 
5522       //  - conversions to 'Class' from its redefinition type
5523       if (LHSType->isObjCClassType() &&
5524           Context.hasSameType(RHSType,
5525                               Context.getObjCClassRedefinitionType())) {
5526         return Compatible;
5527       }
5528 
5529       return IncompatiblePointer;
5530     }
5531 
5532     // T^ -> A*
5533     if (RHSType->isBlockPointerType()) {
5534       maybeExtendBlockObject(*this, RHS);
5535       Kind = CK_BlockPointerToObjCPointerCast;
5536       return Compatible;
5537     }
5538 
5539     return Incompatible;
5540   }
5541 
5542   // Conversions from pointers that are not covered by the above.
5543   if (isa<PointerType>(RHSType)) {
5544     // T* -> _Bool
5545     if (LHSType == Context.BoolTy) {
5546       Kind = CK_PointerToBoolean;
5547       return Compatible;
5548     }
5549 
5550     // T* -> int
5551     if (LHSType->isIntegerType()) {
5552       Kind = CK_PointerToIntegral;
5553       return PointerToInt;
5554     }
5555 
5556     return Incompatible;
5557   }
5558 
5559   // Conversions from Objective-C pointers that are not covered by the above.
5560   if (isa<ObjCObjectPointerType>(RHSType)) {
5561     // T* -> _Bool
5562     if (LHSType == Context.BoolTy) {
5563       Kind = CK_PointerToBoolean;
5564       return Compatible;
5565     }
5566 
5567     // T* -> int
5568     if (LHSType->isIntegerType()) {
5569       Kind = CK_PointerToIntegral;
5570       return PointerToInt;
5571     }
5572 
5573     return Incompatible;
5574   }
5575 
5576   // struct A -> struct B
5577   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
5578     if (Context.typesAreCompatible(LHSType, RHSType)) {
5579       Kind = CK_NoOp;
5580       return Compatible;
5581     }
5582   }
5583 
5584   return Incompatible;
5585 }
5586 
5587 /// \brief Constructs a transparent union from an expression that is
5588 /// used to initialize the transparent union.
5589 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
5590                                       ExprResult &EResult, QualType UnionType,
5591                                       FieldDecl *Field) {
5592   // Build an initializer list that designates the appropriate member
5593   // of the transparent union.
5594   Expr *E = EResult.take();
5595   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
5596                                                    &E, 1,
5597                                                    SourceLocation());
5598   Initializer->setType(UnionType);
5599   Initializer->setInitializedFieldInUnion(Field);
5600 
5601   // Build a compound literal constructing a value of the transparent
5602   // union type from this initializer list.
5603   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
5604   EResult = S.Owned(
5605     new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
5606                                 VK_RValue, Initializer, false));
5607 }
5608 
5609 Sema::AssignConvertType
5610 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
5611                                                ExprResult &RHS) {
5612   QualType RHSType = RHS.get()->getType();
5613 
5614   // If the ArgType is a Union type, we want to handle a potential
5615   // transparent_union GCC extension.
5616   const RecordType *UT = ArgType->getAsUnionType();
5617   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
5618     return Incompatible;
5619 
5620   // The field to initialize within the transparent union.
5621   RecordDecl *UD = UT->getDecl();
5622   FieldDecl *InitField = 0;
5623   // It's compatible if the expression matches any of the fields.
5624   for (RecordDecl::field_iterator it = UD->field_begin(),
5625          itend = UD->field_end();
5626        it != itend; ++it) {
5627     if (it->getType()->isPointerType()) {
5628       // If the transparent union contains a pointer type, we allow:
5629       // 1) void pointer
5630       // 2) null pointer constant
5631       if (RHSType->isPointerType())
5632         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
5633           RHS = ImpCastExprToType(RHS.take(), it->getType(), CK_BitCast);
5634           InitField = *it;
5635           break;
5636         }
5637 
5638       if (RHS.get()->isNullPointerConstant(Context,
5639                                            Expr::NPC_ValueDependentIsNull)) {
5640         RHS = ImpCastExprToType(RHS.take(), it->getType(),
5641                                 CK_NullToPointer);
5642         InitField = *it;
5643         break;
5644       }
5645     }
5646 
5647     CastKind Kind = CK_Invalid;
5648     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
5649           == Compatible) {
5650       RHS = ImpCastExprToType(RHS.take(), it->getType(), Kind);
5651       InitField = *it;
5652       break;
5653     }
5654   }
5655 
5656   if (!InitField)
5657     return Incompatible;
5658 
5659   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
5660   return Compatible;
5661 }
5662 
5663 Sema::AssignConvertType
5664 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS,
5665                                        bool Diagnose) {
5666   if (getLangOptions().CPlusPlus) {
5667     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
5668       // C++ 5.17p3: If the left operand is not of class type, the
5669       // expression is implicitly converted (C++ 4) to the
5670       // cv-unqualified type of the left operand.
5671       ExprResult Res;
5672       if (Diagnose) {
5673         Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5674                                         AA_Assigning);
5675       } else {
5676         ImplicitConversionSequence ICS =
5677             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5678                                   /*SuppressUserConversions=*/false,
5679                                   /*AllowExplicit=*/false,
5680                                   /*InOverloadResolution=*/false,
5681                                   /*CStyle=*/false,
5682                                   /*AllowObjCWritebackConversion=*/false);
5683         if (ICS.isFailure())
5684           return Incompatible;
5685         Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5686                                         ICS, AA_Assigning);
5687       }
5688       if (Res.isInvalid())
5689         return Incompatible;
5690       Sema::AssignConvertType result = Compatible;
5691       if (getLangOptions().ObjCAutoRefCount &&
5692           !CheckObjCARCUnavailableWeakConversion(LHSType,
5693                                                  RHS.get()->getType()))
5694         result = IncompatibleObjCWeakRef;
5695       RHS = move(Res);
5696       return result;
5697     }
5698 
5699     // FIXME: Currently, we fall through and treat C++ classes like C
5700     // structures.
5701     // FIXME: We also fall through for atomics; not sure what should
5702     // happen there, though.
5703   }
5704 
5705   // C99 6.5.16.1p1: the left operand is a pointer and the right is
5706   // a null pointer constant.
5707   if ((LHSType->isPointerType() ||
5708        LHSType->isObjCObjectPointerType() ||
5709        LHSType->isBlockPointerType())
5710       && RHS.get()->isNullPointerConstant(Context,
5711                                           Expr::NPC_ValueDependentIsNull)) {
5712     RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
5713     return Compatible;
5714   }
5715 
5716   // This check seems unnatural, however it is necessary to ensure the proper
5717   // conversion of functions/arrays. If the conversion were done for all
5718   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
5719   // expressions that suppress this implicit conversion (&, sizeof).
5720   //
5721   // Suppress this for references: C++ 8.5.3p5.
5722   if (!LHSType->isReferenceType()) {
5723     RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
5724     if (RHS.isInvalid())
5725       return Incompatible;
5726   }
5727 
5728   CastKind Kind = CK_Invalid;
5729   Sema::AssignConvertType result =
5730     CheckAssignmentConstraints(LHSType, RHS, Kind);
5731 
5732   // C99 6.5.16.1p2: The value of the right operand is converted to the
5733   // type of the assignment expression.
5734   // CheckAssignmentConstraints allows the left-hand side to be a reference,
5735   // so that we can use references in built-in functions even in C.
5736   // The getNonReferenceType() call makes sure that the resulting expression
5737   // does not have reference type.
5738   if (result != Incompatible && RHS.get()->getType() != LHSType)
5739     RHS = ImpCastExprToType(RHS.take(),
5740                             LHSType.getNonLValueExprType(Context), Kind);
5741   return result;
5742 }
5743 
5744 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
5745                                ExprResult &RHS) {
5746   Diag(Loc, diag::err_typecheck_invalid_operands)
5747     << LHS.get()->getType() << RHS.get()->getType()
5748     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5749   return QualType();
5750 }
5751 
5752 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
5753                                    SourceLocation Loc, bool IsCompAssign) {
5754   if (!IsCompAssign) {
5755     LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
5756     if (LHS.isInvalid())
5757       return QualType();
5758   }
5759   RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
5760   if (RHS.isInvalid())
5761     return QualType();
5762 
5763   // For conversion purposes, we ignore any qualifiers.
5764   // For example, "const float" and "float" are equivalent.
5765   QualType LHSType =
5766     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
5767   QualType RHSType =
5768     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
5769 
5770   // If the vector types are identical, return.
5771   if (LHSType == RHSType)
5772     return LHSType;
5773 
5774   // Handle the case of equivalent AltiVec and GCC vector types
5775   if (LHSType->isVectorType() && RHSType->isVectorType() &&
5776       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
5777     if (LHSType->isExtVectorType()) {
5778       RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
5779       return LHSType;
5780     }
5781 
5782     if (!IsCompAssign)
5783       LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
5784     return RHSType;
5785   }
5786 
5787   if (getLangOptions().LaxVectorConversions &&
5788       Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType)) {
5789     // If we are allowing lax vector conversions, and LHS and RHS are both
5790     // vectors, the total size only needs to be the same. This is a
5791     // bitcast; no bits are changed but the result type is different.
5792     // FIXME: Should we really be allowing this?
5793     RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
5794     return LHSType;
5795   }
5796 
5797   // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
5798   // swap back (so that we don't reverse the inputs to a subtract, for instance.
5799   bool swapped = false;
5800   if (RHSType->isExtVectorType() && !IsCompAssign) {
5801     swapped = true;
5802     std::swap(RHS, LHS);
5803     std::swap(RHSType, LHSType);
5804   }
5805 
5806   // Handle the case of an ext vector and scalar.
5807   if (const ExtVectorType *LV = LHSType->getAs<ExtVectorType>()) {
5808     QualType EltTy = LV->getElementType();
5809     if (EltTy->isIntegralType(Context) && RHSType->isIntegralType(Context)) {
5810       int order = Context.getIntegerTypeOrder(EltTy, RHSType);
5811       if (order > 0)
5812         RHS = ImpCastExprToType(RHS.take(), EltTy, CK_IntegralCast);
5813       if (order >= 0) {
5814         RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
5815         if (swapped) std::swap(RHS, LHS);
5816         return LHSType;
5817       }
5818     }
5819     if (EltTy->isRealFloatingType() && RHSType->isScalarType() &&
5820         RHSType->isRealFloatingType()) {
5821       int order = Context.getFloatingTypeOrder(EltTy, RHSType);
5822       if (order > 0)
5823         RHS = ImpCastExprToType(RHS.take(), EltTy, CK_FloatingCast);
5824       if (order >= 0) {
5825         RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
5826         if (swapped) std::swap(RHS, LHS);
5827         return LHSType;
5828       }
5829     }
5830   }
5831 
5832   // Vectors of different size or scalar and non-ext-vector are errors.
5833   if (swapped) std::swap(RHS, LHS);
5834   Diag(Loc, diag::err_typecheck_vector_not_convertable)
5835     << LHS.get()->getType() << RHS.get()->getType()
5836     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5837   return QualType();
5838 }
5839 
5840 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
5841 // expression.  These are mainly cases where the null pointer is used as an
5842 // integer instead of a pointer.
5843 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
5844                                 SourceLocation Loc, bool IsCompare) {
5845   // The canonical way to check for a GNU null is with isNullPointerConstant,
5846   // but we use a bit of a hack here for speed; this is a relatively
5847   // hot path, and isNullPointerConstant is slow.
5848   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
5849   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
5850 
5851   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
5852 
5853   // Avoid analyzing cases where the result will either be invalid (and
5854   // diagnosed as such) or entirely valid and not something to warn about.
5855   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
5856       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
5857     return;
5858 
5859   // Comparison operations would not make sense with a null pointer no matter
5860   // what the other expression is.
5861   if (!IsCompare) {
5862     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
5863         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
5864         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
5865     return;
5866   }
5867 
5868   // The rest of the operations only make sense with a null pointer
5869   // if the other expression is a pointer.
5870   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
5871       NonNullType->canDecayToPointerType())
5872     return;
5873 
5874   S.Diag(Loc, diag::warn_null_in_comparison_operation)
5875       << LHSNull /* LHS is NULL */ << NonNullType
5876       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5877 }
5878 
5879 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
5880                                            SourceLocation Loc,
5881                                            bool IsCompAssign, bool IsDiv) {
5882   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
5883 
5884   if (LHS.get()->getType()->isVectorType() ||
5885       RHS.get()->getType()->isVectorType())
5886     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
5887 
5888   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
5889   if (LHS.isInvalid() || RHS.isInvalid())
5890     return QualType();
5891 
5892   if (!LHS.get()->getType()->isArithmeticType() ||
5893       !RHS.get()->getType()->isArithmeticType())
5894     return InvalidOperands(Loc, LHS, RHS);
5895 
5896   // Check for division by zero.
5897   if (IsDiv &&
5898       RHS.get()->isNullPointerConstant(Context,
5899                                        Expr::NPC_ValueDependentIsNotNull))
5900     DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_division_by_zero)
5901                                           << RHS.get()->getSourceRange());
5902 
5903   return compType;
5904 }
5905 
5906 QualType Sema::CheckRemainderOperands(
5907   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
5908   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
5909 
5910   if (LHS.get()->getType()->isVectorType() ||
5911       RHS.get()->getType()->isVectorType()) {
5912     if (LHS.get()->getType()->hasIntegerRepresentation() &&
5913         RHS.get()->getType()->hasIntegerRepresentation())
5914       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
5915     return InvalidOperands(Loc, LHS, RHS);
5916   }
5917 
5918   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
5919   if (LHS.isInvalid() || RHS.isInvalid())
5920     return QualType();
5921 
5922   if (!LHS.get()->getType()->isIntegerType() ||
5923       !RHS.get()->getType()->isIntegerType())
5924     return InvalidOperands(Loc, LHS, RHS);
5925 
5926   // Check for remainder by zero.
5927   if (RHS.get()->isNullPointerConstant(Context,
5928                                        Expr::NPC_ValueDependentIsNotNull))
5929     DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_remainder_by_zero)
5930                                  << RHS.get()->getSourceRange());
5931 
5932   return compType;
5933 }
5934 
5935 /// \brief Diagnose invalid arithmetic on two void pointers.
5936 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
5937                                                 Expr *LHSExpr, Expr *RHSExpr) {
5938   S.Diag(Loc, S.getLangOptions().CPlusPlus
5939                 ? diag::err_typecheck_pointer_arith_void_type
5940                 : diag::ext_gnu_void_ptr)
5941     << 1 /* two pointers */ << LHSExpr->getSourceRange()
5942                             << RHSExpr->getSourceRange();
5943 }
5944 
5945 /// \brief Diagnose invalid arithmetic on a void pointer.
5946 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
5947                                             Expr *Pointer) {
5948   S.Diag(Loc, S.getLangOptions().CPlusPlus
5949                 ? diag::err_typecheck_pointer_arith_void_type
5950                 : diag::ext_gnu_void_ptr)
5951     << 0 /* one pointer */ << Pointer->getSourceRange();
5952 }
5953 
5954 /// \brief Diagnose invalid arithmetic on two function pointers.
5955 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
5956                                                     Expr *LHS, Expr *RHS) {
5957   assert(LHS->getType()->isAnyPointerType());
5958   assert(RHS->getType()->isAnyPointerType());
5959   S.Diag(Loc, S.getLangOptions().CPlusPlus
5960                 ? diag::err_typecheck_pointer_arith_function_type
5961                 : diag::ext_gnu_ptr_func_arith)
5962     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
5963     // We only show the second type if it differs from the first.
5964     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
5965                                                    RHS->getType())
5966     << RHS->getType()->getPointeeType()
5967     << LHS->getSourceRange() << RHS->getSourceRange();
5968 }
5969 
5970 /// \brief Diagnose invalid arithmetic on a function pointer.
5971 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
5972                                                 Expr *Pointer) {
5973   assert(Pointer->getType()->isAnyPointerType());
5974   S.Diag(Loc, S.getLangOptions().CPlusPlus
5975                 ? diag::err_typecheck_pointer_arith_function_type
5976                 : diag::ext_gnu_ptr_func_arith)
5977     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
5978     << 0 /* one pointer, so only one type */
5979     << Pointer->getSourceRange();
5980 }
5981 
5982 /// \brief Emit error if Operand is incomplete pointer type
5983 ///
5984 /// \returns True if pointer has incomplete type
5985 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
5986                                                  Expr *Operand) {
5987   if ((Operand->getType()->isPointerType() &&
5988        !Operand->getType()->isDependentType()) ||
5989       Operand->getType()->isObjCObjectPointerType()) {
5990     QualType PointeeTy = Operand->getType()->getPointeeType();
5991     if (S.RequireCompleteType(
5992           Loc, PointeeTy,
5993           S.PDiag(diag::err_typecheck_arithmetic_incomplete_type)
5994             << PointeeTy << Operand->getSourceRange()))
5995       return true;
5996   }
5997   return false;
5998 }
5999 
6000 /// \brief Check the validity of an arithmetic pointer operand.
6001 ///
6002 /// If the operand has pointer type, this code will check for pointer types
6003 /// which are invalid in arithmetic operations. These will be diagnosed
6004 /// appropriately, including whether or not the use is supported as an
6005 /// extension.
6006 ///
6007 /// \returns True when the operand is valid to use (even if as an extension).
6008 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
6009                                             Expr *Operand) {
6010   if (!Operand->getType()->isAnyPointerType()) return true;
6011 
6012   QualType PointeeTy = Operand->getType()->getPointeeType();
6013   if (PointeeTy->isVoidType()) {
6014     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
6015     return !S.getLangOptions().CPlusPlus;
6016   }
6017   if (PointeeTy->isFunctionType()) {
6018     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
6019     return !S.getLangOptions().CPlusPlus;
6020   }
6021 
6022   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
6023 
6024   return true;
6025 }
6026 
6027 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
6028 /// operands.
6029 ///
6030 /// This routine will diagnose any invalid arithmetic on pointer operands much
6031 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
6032 /// for emitting a single diagnostic even for operations where both LHS and RHS
6033 /// are (potentially problematic) pointers.
6034 ///
6035 /// \returns True when the operand is valid to use (even if as an extension).
6036 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
6037                                                 Expr *LHSExpr, Expr *RHSExpr) {
6038   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
6039   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
6040   if (!isLHSPointer && !isRHSPointer) return true;
6041 
6042   QualType LHSPointeeTy, RHSPointeeTy;
6043   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
6044   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
6045 
6046   // Check for arithmetic on pointers to incomplete types.
6047   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
6048   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
6049   if (isLHSVoidPtr || isRHSVoidPtr) {
6050     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
6051     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
6052     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
6053 
6054     return !S.getLangOptions().CPlusPlus;
6055   }
6056 
6057   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
6058   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
6059   if (isLHSFuncPtr || isRHSFuncPtr) {
6060     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
6061     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
6062                                                                 RHSExpr);
6063     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
6064 
6065     return !S.getLangOptions().CPlusPlus;
6066   }
6067 
6068   if (checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) return false;
6069   if (checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) return false;
6070 
6071   return true;
6072 }
6073 
6074 /// \brief Check bad cases where we step over interface counts.
6075 static bool checkArithmethicPointerOnNonFragileABI(Sema &S,
6076                                                    SourceLocation OpLoc,
6077                                                    Expr *Op) {
6078   assert(Op->getType()->isAnyPointerType());
6079   QualType PointeeTy = Op->getType()->getPointeeType();
6080   if (!PointeeTy->isObjCObjectType() || !S.LangOpts.ObjCNonFragileABI)
6081     return true;
6082 
6083   S.Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
6084     << PointeeTy << Op->getSourceRange();
6085   return false;
6086 }
6087 
6088 /// \brief Emit error when two pointers are incompatible.
6089 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
6090                                            Expr *LHSExpr, Expr *RHSExpr) {
6091   assert(LHSExpr->getType()->isAnyPointerType());
6092   assert(RHSExpr->getType()->isAnyPointerType());
6093   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
6094     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
6095     << RHSExpr->getSourceRange();
6096 }
6097 
6098 QualType Sema::CheckAdditionOperands( // C99 6.5.6
6099   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, QualType* CompLHSTy) {
6100   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6101 
6102   if (LHS.get()->getType()->isVectorType() ||
6103       RHS.get()->getType()->isVectorType()) {
6104     QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
6105     if (CompLHSTy) *CompLHSTy = compType;
6106     return compType;
6107   }
6108 
6109   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6110   if (LHS.isInvalid() || RHS.isInvalid())
6111     return QualType();
6112 
6113   // handle the common case first (both operands are arithmetic).
6114   if (LHS.get()->getType()->isArithmeticType() &&
6115       RHS.get()->getType()->isArithmeticType()) {
6116     if (CompLHSTy) *CompLHSTy = compType;
6117     return compType;
6118   }
6119 
6120   // Put any potential pointer into PExp
6121   Expr* PExp = LHS.get(), *IExp = RHS.get();
6122   if (IExp->getType()->isAnyPointerType())
6123     std::swap(PExp, IExp);
6124 
6125   if (!PExp->getType()->isAnyPointerType())
6126     return InvalidOperands(Loc, LHS, RHS);
6127 
6128   if (!IExp->getType()->isIntegerType())
6129     return InvalidOperands(Loc, LHS, RHS);
6130 
6131   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
6132     return QualType();
6133 
6134   // Diagnose bad cases where we step over interface counts.
6135   if (!checkArithmethicPointerOnNonFragileABI(*this, Loc, PExp))
6136     return QualType();
6137 
6138   // Check array bounds for pointer arithemtic
6139   CheckArrayAccess(PExp, IExp);
6140 
6141   if (CompLHSTy) {
6142     QualType LHSTy = Context.isPromotableBitField(LHS.get());
6143     if (LHSTy.isNull()) {
6144       LHSTy = LHS.get()->getType();
6145       if (LHSTy->isPromotableIntegerType())
6146         LHSTy = Context.getPromotedIntegerType(LHSTy);
6147     }
6148     *CompLHSTy = LHSTy;
6149   }
6150 
6151   return PExp->getType();
6152 }
6153 
6154 // C99 6.5.6
6155 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
6156                                         SourceLocation Loc,
6157                                         QualType* CompLHSTy) {
6158   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6159 
6160   if (LHS.get()->getType()->isVectorType() ||
6161       RHS.get()->getType()->isVectorType()) {
6162     QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
6163     if (CompLHSTy) *CompLHSTy = compType;
6164     return compType;
6165   }
6166 
6167   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6168   if (LHS.isInvalid() || RHS.isInvalid())
6169     return QualType();
6170 
6171   // Enforce type constraints: C99 6.5.6p3.
6172 
6173   // Handle the common case first (both operands are arithmetic).
6174   if (LHS.get()->getType()->isArithmeticType() &&
6175       RHS.get()->getType()->isArithmeticType()) {
6176     if (CompLHSTy) *CompLHSTy = compType;
6177     return compType;
6178   }
6179 
6180   // Either ptr - int   or   ptr - ptr.
6181   if (LHS.get()->getType()->isAnyPointerType()) {
6182     QualType lpointee = LHS.get()->getType()->getPointeeType();
6183 
6184     // Diagnose bad cases where we step over interface counts.
6185     if (!checkArithmethicPointerOnNonFragileABI(*this, Loc, LHS.get()))
6186       return QualType();
6187 
6188     // The result type of a pointer-int computation is the pointer type.
6189     if (RHS.get()->getType()->isIntegerType()) {
6190       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
6191         return QualType();
6192 
6193       Expr *IExpr = RHS.get()->IgnoreParenCasts();
6194       UnaryOperator negRex(IExpr, UO_Minus, IExpr->getType(), VK_RValue,
6195                            OK_Ordinary, IExpr->getExprLoc());
6196       // Check array bounds for pointer arithemtic
6197       CheckArrayAccess(LHS.get()->IgnoreParenCasts(), &negRex);
6198 
6199       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
6200       return LHS.get()->getType();
6201     }
6202 
6203     // Handle pointer-pointer subtractions.
6204     if (const PointerType *RHSPTy
6205           = RHS.get()->getType()->getAs<PointerType>()) {
6206       QualType rpointee = RHSPTy->getPointeeType();
6207 
6208       if (getLangOptions().CPlusPlus) {
6209         // Pointee types must be the same: C++ [expr.add]
6210         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
6211           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
6212         }
6213       } else {
6214         // Pointee types must be compatible C99 6.5.6p3
6215         if (!Context.typesAreCompatible(
6216                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
6217                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
6218           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
6219           return QualType();
6220         }
6221       }
6222 
6223       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
6224                                                LHS.get(), RHS.get()))
6225         return QualType();
6226 
6227       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
6228       return Context.getPointerDiffType();
6229     }
6230   }
6231 
6232   return InvalidOperands(Loc, LHS, RHS);
6233 }
6234 
6235 static bool isScopedEnumerationType(QualType T) {
6236   if (const EnumType *ET = dyn_cast<EnumType>(T))
6237     return ET->getDecl()->isScoped();
6238   return false;
6239 }
6240 
6241 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
6242                                    SourceLocation Loc, unsigned Opc,
6243                                    QualType LHSType) {
6244   llvm::APSInt Right;
6245   // Check right/shifter operand
6246   if (RHS.get()->isValueDependent() ||
6247       !RHS.get()->isIntegerConstantExpr(Right, S.Context))
6248     return;
6249 
6250   if (Right.isNegative()) {
6251     S.DiagRuntimeBehavior(Loc, RHS.get(),
6252                           S.PDiag(diag::warn_shift_negative)
6253                             << RHS.get()->getSourceRange());
6254     return;
6255   }
6256   llvm::APInt LeftBits(Right.getBitWidth(),
6257                        S.Context.getTypeSize(LHS.get()->getType()));
6258   if (Right.uge(LeftBits)) {
6259     S.DiagRuntimeBehavior(Loc, RHS.get(),
6260                           S.PDiag(diag::warn_shift_gt_typewidth)
6261                             << RHS.get()->getSourceRange());
6262     return;
6263   }
6264   if (Opc != BO_Shl)
6265     return;
6266 
6267   // When left shifting an ICE which is signed, we can check for overflow which
6268   // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
6269   // integers have defined behavior modulo one more than the maximum value
6270   // representable in the result type, so never warn for those.
6271   llvm::APSInt Left;
6272   if (LHS.get()->isValueDependent() ||
6273       !LHS.get()->isIntegerConstantExpr(Left, S.Context) ||
6274       LHSType->hasUnsignedIntegerRepresentation())
6275     return;
6276   llvm::APInt ResultBits =
6277       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
6278   if (LeftBits.uge(ResultBits))
6279     return;
6280   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
6281   Result = Result.shl(Right);
6282 
6283   // Print the bit representation of the signed integer as an unsigned
6284   // hexadecimal number.
6285   llvm::SmallString<40> HexResult;
6286   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
6287 
6288   // If we are only missing a sign bit, this is less likely to result in actual
6289   // bugs -- if the result is cast back to an unsigned type, it will have the
6290   // expected value. Thus we place this behind a different warning that can be
6291   // turned off separately if needed.
6292   if (LeftBits == ResultBits - 1) {
6293     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
6294         << HexResult.str() << LHSType
6295         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6296     return;
6297   }
6298 
6299   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
6300     << HexResult.str() << Result.getMinSignedBits() << LHSType
6301     << Left.getBitWidth() << LHS.get()->getSourceRange()
6302     << RHS.get()->getSourceRange();
6303 }
6304 
6305 // C99 6.5.7
6306 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
6307                                   SourceLocation Loc, unsigned Opc,
6308                                   bool IsCompAssign) {
6309   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6310 
6311   // C99 6.5.7p2: Each of the operands shall have integer type.
6312   if (!LHS.get()->getType()->hasIntegerRepresentation() ||
6313       !RHS.get()->getType()->hasIntegerRepresentation())
6314     return InvalidOperands(Loc, LHS, RHS);
6315 
6316   // C++0x: Don't allow scoped enums. FIXME: Use something better than
6317   // hasIntegerRepresentation() above instead of this.
6318   if (isScopedEnumerationType(LHS.get()->getType()) ||
6319       isScopedEnumerationType(RHS.get()->getType())) {
6320     return InvalidOperands(Loc, LHS, RHS);
6321   }
6322 
6323   // Vector shifts promote their scalar inputs to vector type.
6324   if (LHS.get()->getType()->isVectorType() ||
6325       RHS.get()->getType()->isVectorType())
6326     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
6327 
6328   // Shifts don't perform usual arithmetic conversions, they just do integer
6329   // promotions on each operand. C99 6.5.7p3
6330 
6331   // For the LHS, do usual unary conversions, but then reset them away
6332   // if this is a compound assignment.
6333   ExprResult OldLHS = LHS;
6334   LHS = UsualUnaryConversions(LHS.take());
6335   if (LHS.isInvalid())
6336     return QualType();
6337   QualType LHSType = LHS.get()->getType();
6338   if (IsCompAssign) LHS = OldLHS;
6339 
6340   // The RHS is simpler.
6341   RHS = UsualUnaryConversions(RHS.take());
6342   if (RHS.isInvalid())
6343     return QualType();
6344 
6345   // Sanity-check shift operands
6346   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
6347 
6348   // "The type of the result is that of the promoted left operand."
6349   return LHSType;
6350 }
6351 
6352 static bool IsWithinTemplateSpecialization(Decl *D) {
6353   if (DeclContext *DC = D->getDeclContext()) {
6354     if (isa<ClassTemplateSpecializationDecl>(DC))
6355       return true;
6356     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
6357       return FD->isFunctionTemplateSpecialization();
6358   }
6359   return false;
6360 }
6361 
6362 /// If two different enums are compared, raise a warning.
6363 static void checkEnumComparison(Sema &S, SourceLocation Loc, ExprResult &LHS,
6364                                 ExprResult &RHS) {
6365   QualType LHSStrippedType = LHS.get()->IgnoreParenImpCasts()->getType();
6366   QualType RHSStrippedType = RHS.get()->IgnoreParenImpCasts()->getType();
6367 
6368   const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
6369   if (!LHSEnumType)
6370     return;
6371   const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
6372   if (!RHSEnumType)
6373     return;
6374 
6375   // Ignore anonymous enums.
6376   if (!LHSEnumType->getDecl()->getIdentifier())
6377     return;
6378   if (!RHSEnumType->getDecl()->getIdentifier())
6379     return;
6380 
6381   if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
6382     return;
6383 
6384   S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
6385       << LHSStrippedType << RHSStrippedType
6386       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6387 }
6388 
6389 /// \brief Diagnose bad pointer comparisons.
6390 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
6391                                               ExprResult &LHS, ExprResult &RHS,
6392                                               bool IsError) {
6393   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
6394                       : diag::ext_typecheck_comparison_of_distinct_pointers)
6395     << LHS.get()->getType() << RHS.get()->getType()
6396     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6397 }
6398 
6399 /// \brief Returns false if the pointers are converted to a composite type,
6400 /// true otherwise.
6401 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
6402                                            ExprResult &LHS, ExprResult &RHS) {
6403   // C++ [expr.rel]p2:
6404   //   [...] Pointer conversions (4.10) and qualification
6405   //   conversions (4.4) are performed on pointer operands (or on
6406   //   a pointer operand and a null pointer constant) to bring
6407   //   them to their composite pointer type. [...]
6408   //
6409   // C++ [expr.eq]p1 uses the same notion for (in)equality
6410   // comparisons of pointers.
6411 
6412   // C++ [expr.eq]p2:
6413   //   In addition, pointers to members can be compared, or a pointer to
6414   //   member and a null pointer constant. Pointer to member conversions
6415   //   (4.11) and qualification conversions (4.4) are performed to bring
6416   //   them to a common type. If one operand is a null pointer constant,
6417   //   the common type is the type of the other operand. Otherwise, the
6418   //   common type is a pointer to member type similar (4.4) to the type
6419   //   of one of the operands, with a cv-qualification signature (4.4)
6420   //   that is the union of the cv-qualification signatures of the operand
6421   //   types.
6422 
6423   QualType LHSType = LHS.get()->getType();
6424   QualType RHSType = RHS.get()->getType();
6425   assert((LHSType->isPointerType() && RHSType->isPointerType()) ||
6426          (LHSType->isMemberPointerType() && RHSType->isMemberPointerType()));
6427 
6428   bool NonStandardCompositeType = false;
6429   bool *BoolPtr = S.isSFINAEContext() ? 0 : &NonStandardCompositeType;
6430   QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr);
6431   if (T.isNull()) {
6432     diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
6433     return true;
6434   }
6435 
6436   if (NonStandardCompositeType)
6437     S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
6438       << LHSType << RHSType << T << LHS.get()->getSourceRange()
6439       << RHS.get()->getSourceRange();
6440 
6441   LHS = S.ImpCastExprToType(LHS.take(), T, CK_BitCast);
6442   RHS = S.ImpCastExprToType(RHS.take(), T, CK_BitCast);
6443   return false;
6444 }
6445 
6446 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
6447                                                     ExprResult &LHS,
6448                                                     ExprResult &RHS,
6449                                                     bool IsError) {
6450   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
6451                       : diag::ext_typecheck_comparison_of_fptr_to_void)
6452     << LHS.get()->getType() << RHS.get()->getType()
6453     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6454 }
6455 
6456 // C99 6.5.8, C++ [expr.rel]
6457 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
6458                                     SourceLocation Loc, unsigned OpaqueOpc,
6459                                     bool IsRelational) {
6460   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
6461 
6462   BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
6463 
6464   // Handle vector comparisons separately.
6465   if (LHS.get()->getType()->isVectorType() ||
6466       RHS.get()->getType()->isVectorType())
6467     return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
6468 
6469   QualType LHSType = LHS.get()->getType();
6470   QualType RHSType = RHS.get()->getType();
6471 
6472   Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
6473   Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
6474 
6475   checkEnumComparison(*this, Loc, LHS, RHS);
6476 
6477   if (!LHSType->hasFloatingRepresentation() &&
6478       !(LHSType->isBlockPointerType() && IsRelational) &&
6479       !LHS.get()->getLocStart().isMacroID() &&
6480       !RHS.get()->getLocStart().isMacroID()) {
6481     // For non-floating point types, check for self-comparisons of the form
6482     // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
6483     // often indicate logic errors in the program.
6484     //
6485     // NOTE: Don't warn about comparison expressions resulting from macro
6486     // expansion. Also don't warn about comparisons which are only self
6487     // comparisons within a template specialization. The warnings should catch
6488     // obvious cases in the definition of the template anyways. The idea is to
6489     // warn when the typed comparison operator will always evaluate to the same
6490     // result.
6491     if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
6492       if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
6493         if (DRL->getDecl() == DRR->getDecl() &&
6494             !IsWithinTemplateSpecialization(DRL->getDecl())) {
6495           DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
6496                               << 0 // self-
6497                               << (Opc == BO_EQ
6498                                   || Opc == BO_LE
6499                                   || Opc == BO_GE));
6500         } else if (LHSType->isArrayType() && RHSType->isArrayType() &&
6501                    !DRL->getDecl()->getType()->isReferenceType() &&
6502                    !DRR->getDecl()->getType()->isReferenceType()) {
6503             // what is it always going to eval to?
6504             char always_evals_to;
6505             switch(Opc) {
6506             case BO_EQ: // e.g. array1 == array2
6507               always_evals_to = 0; // false
6508               break;
6509             case BO_NE: // e.g. array1 != array2
6510               always_evals_to = 1; // true
6511               break;
6512             default:
6513               // best we can say is 'a constant'
6514               always_evals_to = 2; // e.g. array1 <= array2
6515               break;
6516             }
6517             DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
6518                                 << 1 // array
6519                                 << always_evals_to);
6520         }
6521       }
6522     }
6523 
6524     if (isa<CastExpr>(LHSStripped))
6525       LHSStripped = LHSStripped->IgnoreParenCasts();
6526     if (isa<CastExpr>(RHSStripped))
6527       RHSStripped = RHSStripped->IgnoreParenCasts();
6528 
6529     // Warn about comparisons against a string constant (unless the other
6530     // operand is null), the user probably wants strcmp.
6531     Expr *literalString = 0;
6532     Expr *literalStringStripped = 0;
6533     if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
6534         !RHSStripped->isNullPointerConstant(Context,
6535                                             Expr::NPC_ValueDependentIsNull)) {
6536       literalString = LHS.get();
6537       literalStringStripped = LHSStripped;
6538     } else if ((isa<StringLiteral>(RHSStripped) ||
6539                 isa<ObjCEncodeExpr>(RHSStripped)) &&
6540                !LHSStripped->isNullPointerConstant(Context,
6541                                             Expr::NPC_ValueDependentIsNull)) {
6542       literalString = RHS.get();
6543       literalStringStripped = RHSStripped;
6544     }
6545 
6546     if (literalString) {
6547       std::string resultComparison;
6548       switch (Opc) {
6549       case BO_LT: resultComparison = ") < 0"; break;
6550       case BO_GT: resultComparison = ") > 0"; break;
6551       case BO_LE: resultComparison = ") <= 0"; break;
6552       case BO_GE: resultComparison = ") >= 0"; break;
6553       case BO_EQ: resultComparison = ") == 0"; break;
6554       case BO_NE: resultComparison = ") != 0"; break;
6555       default: llvm_unreachable("Invalid comparison operator");
6556       }
6557 
6558       DiagRuntimeBehavior(Loc, 0,
6559         PDiag(diag::warn_stringcompare)
6560           << isa<ObjCEncodeExpr>(literalStringStripped)
6561           << literalString->getSourceRange());
6562     }
6563   }
6564 
6565   // C99 6.5.8p3 / C99 6.5.9p4
6566   if (LHS.get()->getType()->isArithmeticType() &&
6567       RHS.get()->getType()->isArithmeticType()) {
6568     UsualArithmeticConversions(LHS, RHS);
6569     if (LHS.isInvalid() || RHS.isInvalid())
6570       return QualType();
6571   }
6572   else {
6573     LHS = UsualUnaryConversions(LHS.take());
6574     if (LHS.isInvalid())
6575       return QualType();
6576 
6577     RHS = UsualUnaryConversions(RHS.take());
6578     if (RHS.isInvalid())
6579       return QualType();
6580   }
6581 
6582   LHSType = LHS.get()->getType();
6583   RHSType = RHS.get()->getType();
6584 
6585   // The result of comparisons is 'bool' in C++, 'int' in C.
6586   QualType ResultTy = Context.getLogicalOperationType();
6587 
6588   if (IsRelational) {
6589     if (LHSType->isRealType() && RHSType->isRealType())
6590       return ResultTy;
6591   } else {
6592     // Check for comparisons of floating point operands using != and ==.
6593     if (LHSType->hasFloatingRepresentation())
6594       CheckFloatComparison(Loc, LHS.get(), RHS.get());
6595 
6596     if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
6597       return ResultTy;
6598   }
6599 
6600   bool LHSIsNull = LHS.get()->isNullPointerConstant(Context,
6601                                               Expr::NPC_ValueDependentIsNull);
6602   bool RHSIsNull = RHS.get()->isNullPointerConstant(Context,
6603                                               Expr::NPC_ValueDependentIsNull);
6604 
6605   // All of the following pointer-related warnings are GCC extensions, except
6606   // when handling null pointer constants.
6607   if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2
6608     QualType LCanPointeeTy =
6609       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
6610     QualType RCanPointeeTy =
6611       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
6612 
6613     if (getLangOptions().CPlusPlus) {
6614       if (LCanPointeeTy == RCanPointeeTy)
6615         return ResultTy;
6616       if (!IsRelational &&
6617           (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6618         // Valid unless comparison between non-null pointer and function pointer
6619         // This is a gcc extension compatibility comparison.
6620         // In a SFINAE context, we treat this as a hard error to maintain
6621         // conformance with the C++ standard.
6622         if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
6623             && !LHSIsNull && !RHSIsNull) {
6624           diagnoseFunctionPointerToVoidComparison(
6625               *this, Loc, LHS, RHS, /*isError*/ isSFINAEContext());
6626 
6627           if (isSFINAEContext())
6628             return QualType();
6629 
6630           RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
6631           return ResultTy;
6632         }
6633       }
6634 
6635       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
6636         return QualType();
6637       else
6638         return ResultTy;
6639     }
6640     // C99 6.5.9p2 and C99 6.5.8p2
6641     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
6642                                    RCanPointeeTy.getUnqualifiedType())) {
6643       // Valid unless a relational comparison of function pointers
6644       if (IsRelational && LCanPointeeTy->isFunctionType()) {
6645         Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
6646           << LHSType << RHSType << LHS.get()->getSourceRange()
6647           << RHS.get()->getSourceRange();
6648       }
6649     } else if (!IsRelational &&
6650                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6651       // Valid unless comparison between non-null pointer and function pointer
6652       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
6653           && !LHSIsNull && !RHSIsNull)
6654         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
6655                                                 /*isError*/false);
6656     } else {
6657       // Invalid
6658       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
6659     }
6660     if (LCanPointeeTy != RCanPointeeTy) {
6661       if (LHSIsNull && !RHSIsNull)
6662         LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
6663       else
6664         RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
6665     }
6666     return ResultTy;
6667   }
6668 
6669   if (getLangOptions().CPlusPlus) {
6670     // Comparison of nullptr_t with itself.
6671     if (LHSType->isNullPtrType() && RHSType->isNullPtrType())
6672       return ResultTy;
6673 
6674     // Comparison of pointers with null pointer constants and equality
6675     // comparisons of member pointers to null pointer constants.
6676     if (RHSIsNull &&
6677         ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) ||
6678          (!IsRelational &&
6679           (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) {
6680       RHS = ImpCastExprToType(RHS.take(), LHSType,
6681                         LHSType->isMemberPointerType()
6682                           ? CK_NullToMemberPointer
6683                           : CK_NullToPointer);
6684       return ResultTy;
6685     }
6686     if (LHSIsNull &&
6687         ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) ||
6688          (!IsRelational &&
6689           (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) {
6690       LHS = ImpCastExprToType(LHS.take(), RHSType,
6691                         RHSType->isMemberPointerType()
6692                           ? CK_NullToMemberPointer
6693                           : CK_NullToPointer);
6694       return ResultTy;
6695     }
6696 
6697     // Comparison of member pointers.
6698     if (!IsRelational &&
6699         LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) {
6700       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
6701         return QualType();
6702       else
6703         return ResultTy;
6704     }
6705 
6706     // Handle scoped enumeration types specifically, since they don't promote
6707     // to integers.
6708     if (LHS.get()->getType()->isEnumeralType() &&
6709         Context.hasSameUnqualifiedType(LHS.get()->getType(),
6710                                        RHS.get()->getType()))
6711       return ResultTy;
6712   }
6713 
6714   // Handle block pointer types.
6715   if (!IsRelational && LHSType->isBlockPointerType() &&
6716       RHSType->isBlockPointerType()) {
6717     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
6718     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
6719 
6720     if (!LHSIsNull && !RHSIsNull &&
6721         !Context.typesAreCompatible(lpointee, rpointee)) {
6722       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
6723         << LHSType << RHSType << LHS.get()->getSourceRange()
6724         << RHS.get()->getSourceRange();
6725     }
6726     RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
6727     return ResultTy;
6728   }
6729 
6730   // Allow block pointers to be compared with null pointer constants.
6731   if (!IsRelational
6732       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
6733           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
6734     if (!LHSIsNull && !RHSIsNull) {
6735       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
6736              ->getPointeeType()->isVoidType())
6737             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
6738                 ->getPointeeType()->isVoidType())))
6739         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
6740           << LHSType << RHSType << LHS.get()->getSourceRange()
6741           << RHS.get()->getSourceRange();
6742     }
6743     if (LHSIsNull && !RHSIsNull)
6744       LHS = ImpCastExprToType(LHS.take(), RHSType,
6745                               RHSType->isPointerType() ? CK_BitCast
6746                                 : CK_AnyPointerToBlockPointerCast);
6747     else
6748       RHS = ImpCastExprToType(RHS.take(), LHSType,
6749                               LHSType->isPointerType() ? CK_BitCast
6750                                 : CK_AnyPointerToBlockPointerCast);
6751     return ResultTy;
6752   }
6753 
6754   if (LHSType->isObjCObjectPointerType() ||
6755       RHSType->isObjCObjectPointerType()) {
6756     const PointerType *LPT = LHSType->getAs<PointerType>();
6757     const PointerType *RPT = RHSType->getAs<PointerType>();
6758     if (LPT || RPT) {
6759       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
6760       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
6761 
6762       if (!LPtrToVoid && !RPtrToVoid &&
6763           !Context.typesAreCompatible(LHSType, RHSType)) {
6764         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
6765                                           /*isError*/false);
6766       }
6767       if (LHSIsNull && !RHSIsNull)
6768         LHS = ImpCastExprToType(LHS.take(), RHSType,
6769                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
6770       else
6771         RHS = ImpCastExprToType(RHS.take(), LHSType,
6772                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
6773       return ResultTy;
6774     }
6775     if (LHSType->isObjCObjectPointerType() &&
6776         RHSType->isObjCObjectPointerType()) {
6777       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
6778         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
6779                                           /*isError*/false);
6780       if (LHSIsNull && !RHSIsNull)
6781         LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
6782       else
6783         RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
6784       return ResultTy;
6785     }
6786   }
6787   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
6788       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
6789     unsigned DiagID = 0;
6790     bool isError = false;
6791     if ((LHSIsNull && LHSType->isIntegerType()) ||
6792         (RHSIsNull && RHSType->isIntegerType())) {
6793       if (IsRelational && !getLangOptions().CPlusPlus)
6794         DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
6795     } else if (IsRelational && !getLangOptions().CPlusPlus)
6796       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
6797     else if (getLangOptions().CPlusPlus) {
6798       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
6799       isError = true;
6800     } else
6801       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
6802 
6803     if (DiagID) {
6804       Diag(Loc, DiagID)
6805         << LHSType << RHSType << LHS.get()->getSourceRange()
6806         << RHS.get()->getSourceRange();
6807       if (isError)
6808         return QualType();
6809     }
6810 
6811     if (LHSType->isIntegerType())
6812       LHS = ImpCastExprToType(LHS.take(), RHSType,
6813                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
6814     else
6815       RHS = ImpCastExprToType(RHS.take(), LHSType,
6816                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
6817     return ResultTy;
6818   }
6819 
6820   // Handle block pointers.
6821   if (!IsRelational && RHSIsNull
6822       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
6823     RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
6824     return ResultTy;
6825   }
6826   if (!IsRelational && LHSIsNull
6827       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
6828     LHS = ImpCastExprToType(LHS.take(), RHSType, CK_NullToPointer);
6829     return ResultTy;
6830   }
6831 
6832   return InvalidOperands(Loc, LHS, RHS);
6833 }
6834 
6835 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
6836 /// operates on extended vector types.  Instead of producing an IntTy result,
6837 /// like a scalar comparison, a vector comparison produces a vector of integer
6838 /// types.
6839 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
6840                                           SourceLocation Loc,
6841                                           bool IsRelational) {
6842   // Check to make sure we're operating on vectors of the same type and width,
6843   // Allowing one side to be a scalar of element type.
6844   QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false);
6845   if (vType.isNull())
6846     return vType;
6847 
6848   QualType LHSType = LHS.get()->getType();
6849   QualType RHSType = RHS.get()->getType();
6850 
6851   // If AltiVec, the comparison results in a numeric type, i.e.
6852   // bool for C++, int for C
6853   if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
6854     return Context.getLogicalOperationType();
6855 
6856   // For non-floating point types, check for self-comparisons of the form
6857   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
6858   // often indicate logic errors in the program.
6859   if (!LHSType->hasFloatingRepresentation()) {
6860     if (DeclRefExpr* DRL
6861           = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
6862       if (DeclRefExpr* DRR
6863             = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
6864         if (DRL->getDecl() == DRR->getDecl())
6865           DiagRuntimeBehavior(Loc, 0,
6866                               PDiag(diag::warn_comparison_always)
6867                                 << 0 // self-
6868                                 << 2 // "a constant"
6869                               );
6870   }
6871 
6872   // Check for comparisons of floating point operands using != and ==.
6873   if (!IsRelational && LHSType->hasFloatingRepresentation()) {
6874     assert (RHSType->hasFloatingRepresentation());
6875     CheckFloatComparison(Loc, LHS.get(), RHS.get());
6876   }
6877 
6878   // Return a signed type that is of identical size and number of elements.
6879   // For floating point vectors, return an integer type of identical size
6880   // and number of elements.
6881   const VectorType *VTy = LHSType->getAs<VectorType>();
6882   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
6883   if (TypeSize == Context.getTypeSize(Context.CharTy))
6884     return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
6885   else if (TypeSize == Context.getTypeSize(Context.ShortTy))
6886     return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
6887   else if (TypeSize == Context.getTypeSize(Context.IntTy))
6888     return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
6889   else if (TypeSize == Context.getTypeSize(Context.LongTy))
6890     return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
6891   assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
6892          "Unhandled vector element size in vector compare");
6893   return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
6894 }
6895 
6896 inline QualType Sema::CheckBitwiseOperands(
6897   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
6898   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6899 
6900   if (LHS.get()->getType()->isVectorType() ||
6901       RHS.get()->getType()->isVectorType()) {
6902     if (LHS.get()->getType()->hasIntegerRepresentation() &&
6903         RHS.get()->getType()->hasIntegerRepresentation())
6904       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
6905 
6906     return InvalidOperands(Loc, LHS, RHS);
6907   }
6908 
6909   ExprResult LHSResult = Owned(LHS), RHSResult = Owned(RHS);
6910   QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
6911                                                  IsCompAssign);
6912   if (LHSResult.isInvalid() || RHSResult.isInvalid())
6913     return QualType();
6914   LHS = LHSResult.take();
6915   RHS = RHSResult.take();
6916 
6917   if (LHS.get()->getType()->isIntegralOrUnscopedEnumerationType() &&
6918       RHS.get()->getType()->isIntegralOrUnscopedEnumerationType())
6919     return compType;
6920   return InvalidOperands(Loc, LHS, RHS);
6921 }
6922 
6923 inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
6924   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) {
6925 
6926   // Diagnose cases where the user write a logical and/or but probably meant a
6927   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
6928   // is a constant.
6929   if (LHS.get()->getType()->isIntegerType() &&
6930       !LHS.get()->getType()->isBooleanType() &&
6931       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
6932       // Don't warn in macros or template instantiations.
6933       !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
6934     // If the RHS can be constant folded, and if it constant folds to something
6935     // that isn't 0 or 1 (which indicate a potential logical operation that
6936     // happened to fold to true/false) then warn.
6937     // Parens on the RHS are ignored.
6938     llvm::APSInt Result;
6939     if (RHS.get()->EvaluateAsInt(Result, Context))
6940       if ((getLangOptions().Bool && !RHS.get()->getType()->isBooleanType()) ||
6941           (Result != 0 && Result != 1)) {
6942         Diag(Loc, diag::warn_logical_instead_of_bitwise)
6943           << RHS.get()->getSourceRange()
6944           << (Opc == BO_LAnd ? "&&" : "||");
6945         // Suggest replacing the logical operator with the bitwise version
6946         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
6947             << (Opc == BO_LAnd ? "&" : "|")
6948             << FixItHint::CreateReplacement(SourceRange(
6949                 Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(),
6950                                                 getLangOptions())),
6951                                             Opc == BO_LAnd ? "&" : "|");
6952         if (Opc == BO_LAnd)
6953           // Suggest replacing "Foo() && kNonZero" with "Foo()"
6954           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
6955               << FixItHint::CreateRemoval(
6956                   SourceRange(
6957                       Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(),
6958                                                  0, getSourceManager(),
6959                                                  getLangOptions()),
6960                       RHS.get()->getLocEnd()));
6961       }
6962   }
6963 
6964   if (!Context.getLangOptions().CPlusPlus) {
6965     LHS = UsualUnaryConversions(LHS.take());
6966     if (LHS.isInvalid())
6967       return QualType();
6968 
6969     RHS = UsualUnaryConversions(RHS.take());
6970     if (RHS.isInvalid())
6971       return QualType();
6972 
6973     if (!LHS.get()->getType()->isScalarType() ||
6974         !RHS.get()->getType()->isScalarType())
6975       return InvalidOperands(Loc, LHS, RHS);
6976 
6977     return Context.IntTy;
6978   }
6979 
6980   // The following is safe because we only use this method for
6981   // non-overloadable operands.
6982 
6983   // C++ [expr.log.and]p1
6984   // C++ [expr.log.or]p1
6985   // The operands are both contextually converted to type bool.
6986   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
6987   if (LHSRes.isInvalid())
6988     return InvalidOperands(Loc, LHS, RHS);
6989   LHS = move(LHSRes);
6990 
6991   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
6992   if (RHSRes.isInvalid())
6993     return InvalidOperands(Loc, LHS, RHS);
6994   RHS = move(RHSRes);
6995 
6996   // C++ [expr.log.and]p2
6997   // C++ [expr.log.or]p2
6998   // The result is a bool.
6999   return Context.BoolTy;
7000 }
7001 
7002 /// IsReadonlyProperty - Verify that otherwise a valid l-value expression
7003 /// is a read-only property; return true if so. A readonly property expression
7004 /// depends on various declarations and thus must be treated specially.
7005 ///
7006 static bool IsReadonlyProperty(Expr *E, Sema &S) {
7007   const ObjCPropertyRefExpr *PropExpr = dyn_cast<ObjCPropertyRefExpr>(E);
7008   if (!PropExpr) return false;
7009   if (PropExpr->isImplicitProperty()) return false;
7010 
7011   ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
7012   QualType BaseType = PropExpr->isSuperReceiver() ?
7013                             PropExpr->getSuperReceiverType() :
7014                             PropExpr->getBase()->getType();
7015 
7016   if (const ObjCObjectPointerType *OPT =
7017       BaseType->getAsObjCInterfacePointerType())
7018     if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
7019       if (S.isPropertyReadonly(PDecl, IFace))
7020         return true;
7021   return false;
7022 }
7023 
7024 static bool IsConstProperty(Expr *E, Sema &S) {
7025   const ObjCPropertyRefExpr *PropExpr = dyn_cast<ObjCPropertyRefExpr>(E);
7026   if (!PropExpr) return false;
7027   if (PropExpr->isImplicitProperty()) return false;
7028 
7029   ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
7030   QualType T = PDecl->getType().getNonReferenceType();
7031   return T.isConstQualified();
7032 }
7033 
7034 static bool IsReadonlyMessage(Expr *E, Sema &S) {
7035   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
7036   if (!ME) return false;
7037   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
7038   ObjCMessageExpr *Base =
7039     dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts());
7040   if (!Base) return false;
7041   return Base->getMethodDecl() != 0;
7042 }
7043 
7044 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
7045 /// emit an error and return true.  If so, return false.
7046 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
7047   SourceLocation OrigLoc = Loc;
7048   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
7049                                                               &Loc);
7050   if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
7051     IsLV = Expr::MLV_ReadonlyProperty;
7052   else if (Expr::MLV_ConstQualified && IsConstProperty(E, S))
7053     IsLV = Expr::MLV_Valid;
7054   else if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
7055     IsLV = Expr::MLV_InvalidMessageExpression;
7056   if (IsLV == Expr::MLV_Valid)
7057     return false;
7058 
7059   unsigned Diag = 0;
7060   bool NeedType = false;
7061   switch (IsLV) { // C99 6.5.16p2
7062   case Expr::MLV_ConstQualified:
7063     Diag = diag::err_typecheck_assign_const;
7064 
7065     // In ARC, use some specialized diagnostics for occasions where we
7066     // infer 'const'.  These are always pseudo-strong variables.
7067     if (S.getLangOptions().ObjCAutoRefCount) {
7068       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
7069       if (declRef && isa<VarDecl>(declRef->getDecl())) {
7070         VarDecl *var = cast<VarDecl>(declRef->getDecl());
7071 
7072         // Use the normal diagnostic if it's pseudo-__strong but the
7073         // user actually wrote 'const'.
7074         if (var->isARCPseudoStrong() &&
7075             (!var->getTypeSourceInfo() ||
7076              !var->getTypeSourceInfo()->getType().isConstQualified())) {
7077           // There are two pseudo-strong cases:
7078           //  - self
7079           ObjCMethodDecl *method = S.getCurMethodDecl();
7080           if (method && var == method->getSelfDecl())
7081             Diag = method->isClassMethod()
7082               ? diag::err_typecheck_arc_assign_self_class_method
7083               : diag::err_typecheck_arc_assign_self;
7084 
7085           //  - fast enumeration variables
7086           else
7087             Diag = diag::err_typecheck_arr_assign_enumeration;
7088 
7089           SourceRange Assign;
7090           if (Loc != OrigLoc)
7091             Assign = SourceRange(OrigLoc, OrigLoc);
7092           S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
7093           // We need to preserve the AST regardless, so migration tool
7094           // can do its job.
7095           return false;
7096         }
7097       }
7098     }
7099 
7100     break;
7101   case Expr::MLV_ArrayType:
7102     Diag = diag::err_typecheck_array_not_modifiable_lvalue;
7103     NeedType = true;
7104     break;
7105   case Expr::MLV_NotObjectType:
7106     Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
7107     NeedType = true;
7108     break;
7109   case Expr::MLV_LValueCast:
7110     Diag = diag::err_typecheck_lvalue_casts_not_supported;
7111     break;
7112   case Expr::MLV_Valid:
7113     llvm_unreachable("did not take early return for MLV_Valid");
7114   case Expr::MLV_InvalidExpression:
7115   case Expr::MLV_MemberFunction:
7116   case Expr::MLV_ClassTemporary:
7117     Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
7118     break;
7119   case Expr::MLV_IncompleteType:
7120   case Expr::MLV_IncompleteVoidType:
7121     return S.RequireCompleteType(Loc, E->getType(),
7122               S.PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
7123                   << E->getSourceRange());
7124   case Expr::MLV_DuplicateVectorComponents:
7125     Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
7126     break;
7127   case Expr::MLV_NotBlockQualified:
7128     Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
7129     break;
7130   case Expr::MLV_ReadonlyProperty:
7131   case Expr::MLV_NoSetterProperty:
7132     llvm_unreachable("readonly properties should be processed differently");
7133     break;
7134   case Expr::MLV_InvalidMessageExpression:
7135     Diag = diag::error_readonly_message_assignment;
7136     break;
7137   case Expr::MLV_SubObjCPropertySetting:
7138     Diag = diag::error_no_subobject_property_setting;
7139     break;
7140   }
7141 
7142   SourceRange Assign;
7143   if (Loc != OrigLoc)
7144     Assign = SourceRange(OrigLoc, OrigLoc);
7145   if (NeedType)
7146     S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
7147   else
7148     S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
7149   return true;
7150 }
7151 
7152 
7153 
7154 // C99 6.5.16.1
7155 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
7156                                        SourceLocation Loc,
7157                                        QualType CompoundType) {
7158   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
7159 
7160   // Verify that LHS is a modifiable lvalue, and emit error if not.
7161   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
7162     return QualType();
7163 
7164   QualType LHSType = LHSExpr->getType();
7165   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
7166                                              CompoundType;
7167   AssignConvertType ConvTy;
7168   if (CompoundType.isNull()) {
7169     QualType LHSTy(LHSType);
7170     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
7171     if (RHS.isInvalid())
7172       return QualType();
7173     // Special case of NSObject attributes on c-style pointer types.
7174     if (ConvTy == IncompatiblePointer &&
7175         ((Context.isObjCNSObjectType(LHSType) &&
7176           RHSType->isObjCObjectPointerType()) ||
7177          (Context.isObjCNSObjectType(RHSType) &&
7178           LHSType->isObjCObjectPointerType())))
7179       ConvTy = Compatible;
7180 
7181     if (ConvTy == Compatible &&
7182         getLangOptions().ObjCNonFragileABI &&
7183         LHSType->isObjCObjectType())
7184       Diag(Loc, diag::err_assignment_requires_nonfragile_object)
7185         << LHSType;
7186 
7187     // If the RHS is a unary plus or minus, check to see if they = and + are
7188     // right next to each other.  If so, the user may have typo'd "x =+ 4"
7189     // instead of "x += 4".
7190     Expr *RHSCheck = RHS.get();
7191     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
7192       RHSCheck = ICE->getSubExpr();
7193     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
7194       if ((UO->getOpcode() == UO_Plus ||
7195            UO->getOpcode() == UO_Minus) &&
7196           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
7197           // Only if the two operators are exactly adjacent.
7198           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
7199           // And there is a space or other character before the subexpr of the
7200           // unary +/-.  We don't want to warn on "x=-1".
7201           Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
7202           UO->getSubExpr()->getLocStart().isFileID()) {
7203         Diag(Loc, diag::warn_not_compound_assign)
7204           << (UO->getOpcode() == UO_Plus ? "+" : "-")
7205           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
7206       }
7207     }
7208 
7209     if (ConvTy == Compatible) {
7210       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong)
7211         checkRetainCycles(LHSExpr, RHS.get());
7212       else if (getLangOptions().ObjCAutoRefCount)
7213         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
7214     }
7215   } else {
7216     // Compound assignment "x += y"
7217     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
7218   }
7219 
7220   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
7221                                RHS.get(), AA_Assigning))
7222     return QualType();
7223 
7224   CheckForNullPointerDereference(*this, LHSExpr);
7225 
7226   // C99 6.5.16p3: The type of an assignment expression is the type of the
7227   // left operand unless the left operand has qualified type, in which case
7228   // it is the unqualified version of the type of the left operand.
7229   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
7230   // is converted to the type of the assignment expression (above).
7231   // C++ 5.17p1: the type of the assignment expression is that of its left
7232   // operand.
7233   return (getLangOptions().CPlusPlus
7234           ? LHSType : LHSType.getUnqualifiedType());
7235 }
7236 
7237 // C99 6.5.17
7238 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
7239                                    SourceLocation Loc) {
7240   S.DiagnoseUnusedExprResult(LHS.get());
7241 
7242   LHS = S.CheckPlaceholderExpr(LHS.take());
7243   RHS = S.CheckPlaceholderExpr(RHS.take());
7244   if (LHS.isInvalid() || RHS.isInvalid())
7245     return QualType();
7246 
7247   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
7248   // operands, but not unary promotions.
7249   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
7250 
7251   // So we treat the LHS as a ignored value, and in C++ we allow the
7252   // containing site to determine what should be done with the RHS.
7253   LHS = S.IgnoredValueConversions(LHS.take());
7254   if (LHS.isInvalid())
7255     return QualType();
7256 
7257   if (!S.getLangOptions().CPlusPlus) {
7258     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take());
7259     if (RHS.isInvalid())
7260       return QualType();
7261     if (!RHS.get()->getType()->isVoidType())
7262       S.RequireCompleteType(Loc, RHS.get()->getType(),
7263                             diag::err_incomplete_type);
7264   }
7265 
7266   return RHS.get()->getType();
7267 }
7268 
7269 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
7270 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
7271 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
7272                                                ExprValueKind &VK,
7273                                                SourceLocation OpLoc,
7274                                                bool IsInc, bool IsPrefix) {
7275   if (Op->isTypeDependent())
7276     return S.Context.DependentTy;
7277 
7278   QualType ResType = Op->getType();
7279   assert(!ResType.isNull() && "no type for increment/decrement expression");
7280 
7281   if (S.getLangOptions().CPlusPlus && ResType->isBooleanType()) {
7282     // Decrement of bool is not allowed.
7283     if (!IsInc) {
7284       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
7285       return QualType();
7286     }
7287     // Increment of bool sets it to true, but is deprecated.
7288     S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
7289   } else if (ResType->isRealType()) {
7290     // OK!
7291   } else if (ResType->isAnyPointerType()) {
7292     // C99 6.5.2.4p2, 6.5.6p2
7293     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
7294       return QualType();
7295 
7296     // Diagnose bad cases where we step over interface counts.
7297     else if (!checkArithmethicPointerOnNonFragileABI(S, OpLoc, Op))
7298       return QualType();
7299   } else if (ResType->isAnyComplexType()) {
7300     // C99 does not support ++/-- on complex types, we allow as an extension.
7301     S.Diag(OpLoc, diag::ext_integer_increment_complex)
7302       << ResType << Op->getSourceRange();
7303   } else if (ResType->isPlaceholderType()) {
7304     ExprResult PR = S.CheckPlaceholderExpr(Op);
7305     if (PR.isInvalid()) return QualType();
7306     return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
7307                                           IsInc, IsPrefix);
7308   } else if (S.getLangOptions().AltiVec && ResType->isVectorType()) {
7309     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
7310   } else {
7311     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
7312       << ResType << int(IsInc) << Op->getSourceRange();
7313     return QualType();
7314   }
7315   // At this point, we know we have a real, complex or pointer type.
7316   // Now make sure the operand is a modifiable lvalue.
7317   if (CheckForModifiableLvalue(Op, OpLoc, S))
7318     return QualType();
7319   // In C++, a prefix increment is the same type as the operand. Otherwise
7320   // (in C or with postfix), the increment is the unqualified type of the
7321   // operand.
7322   if (IsPrefix && S.getLangOptions().CPlusPlus) {
7323     VK = VK_LValue;
7324     return ResType;
7325   } else {
7326     VK = VK_RValue;
7327     return ResType.getUnqualifiedType();
7328   }
7329 }
7330 
7331 
7332 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
7333 /// This routine allows us to typecheck complex/recursive expressions
7334 /// where the declaration is needed for type checking. We only need to
7335 /// handle cases when the expression references a function designator
7336 /// or is an lvalue. Here are some examples:
7337 ///  - &(x) => x
7338 ///  - &*****f => f for f a function designator.
7339 ///  - &s.xx => s
7340 ///  - &s.zz[1].yy -> s, if zz is an array
7341 ///  - *(x + 1) -> x, if x is an array
7342 ///  - &"123"[2] -> 0
7343 ///  - & __real__ x -> x
7344 static ValueDecl *getPrimaryDecl(Expr *E) {
7345   switch (E->getStmtClass()) {
7346   case Stmt::DeclRefExprClass:
7347     return cast<DeclRefExpr>(E)->getDecl();
7348   case Stmt::MemberExprClass:
7349     // If this is an arrow operator, the address is an offset from
7350     // the base's value, so the object the base refers to is
7351     // irrelevant.
7352     if (cast<MemberExpr>(E)->isArrow())
7353       return 0;
7354     // Otherwise, the expression refers to a part of the base
7355     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
7356   case Stmt::ArraySubscriptExprClass: {
7357     // FIXME: This code shouldn't be necessary!  We should catch the implicit
7358     // promotion of register arrays earlier.
7359     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
7360     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
7361       if (ICE->getSubExpr()->getType()->isArrayType())
7362         return getPrimaryDecl(ICE->getSubExpr());
7363     }
7364     return 0;
7365   }
7366   case Stmt::UnaryOperatorClass: {
7367     UnaryOperator *UO = cast<UnaryOperator>(E);
7368 
7369     switch(UO->getOpcode()) {
7370     case UO_Real:
7371     case UO_Imag:
7372     case UO_Extension:
7373       return getPrimaryDecl(UO->getSubExpr());
7374     default:
7375       return 0;
7376     }
7377   }
7378   case Stmt::ParenExprClass:
7379     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
7380   case Stmt::ImplicitCastExprClass:
7381     // If the result of an implicit cast is an l-value, we care about
7382     // the sub-expression; otherwise, the result here doesn't matter.
7383     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
7384   default:
7385     return 0;
7386   }
7387 }
7388 
7389 namespace {
7390   enum {
7391     AO_Bit_Field = 0,
7392     AO_Vector_Element = 1,
7393     AO_Property_Expansion = 2,
7394     AO_Register_Variable = 3,
7395     AO_No_Error = 4
7396   };
7397 }
7398 /// \brief Diagnose invalid operand for address of operations.
7399 ///
7400 /// \param Type The type of operand which cannot have its address taken.
7401 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
7402                                          Expr *E, unsigned Type) {
7403   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
7404 }
7405 
7406 /// CheckAddressOfOperand - The operand of & must be either a function
7407 /// designator or an lvalue designating an object. If it is an lvalue, the
7408 /// object cannot be declared with storage class register or be a bit field.
7409 /// Note: The usual conversions are *not* applied to the operand of the &
7410 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
7411 /// In C++, the operand might be an overloaded function name, in which case
7412 /// we allow the '&' but retain the overloaded-function type.
7413 static QualType CheckAddressOfOperand(Sema &S, ExprResult &OrigOp,
7414                                       SourceLocation OpLoc) {
7415   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
7416     if (PTy->getKind() == BuiltinType::Overload) {
7417       if (!isa<OverloadExpr>(OrigOp.get()->IgnoreParens())) {
7418         S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
7419           << OrigOp.get()->getSourceRange();
7420         return QualType();
7421       }
7422 
7423       return S.Context.OverloadTy;
7424     }
7425 
7426     if (PTy->getKind() == BuiltinType::UnknownAny)
7427       return S.Context.UnknownAnyTy;
7428 
7429     if (PTy->getKind() == BuiltinType::BoundMember) {
7430       S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
7431         << OrigOp.get()->getSourceRange();
7432       return QualType();
7433     }
7434 
7435     OrigOp = S.CheckPlaceholderExpr(OrigOp.take());
7436     if (OrigOp.isInvalid()) return QualType();
7437   }
7438 
7439   if (OrigOp.get()->isTypeDependent())
7440     return S.Context.DependentTy;
7441 
7442   assert(!OrigOp.get()->getType()->isPlaceholderType());
7443 
7444   // Make sure to ignore parentheses in subsequent checks
7445   Expr *op = OrigOp.get()->IgnoreParens();
7446 
7447   if (S.getLangOptions().C99) {
7448     // Implement C99-only parts of addressof rules.
7449     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
7450       if (uOp->getOpcode() == UO_Deref)
7451         // Per C99 6.5.3.2, the address of a deref always returns a valid result
7452         // (assuming the deref expression is valid).
7453         return uOp->getSubExpr()->getType();
7454     }
7455     // Technically, there should be a check for array subscript
7456     // expressions here, but the result of one is always an lvalue anyway.
7457   }
7458   ValueDecl *dcl = getPrimaryDecl(op);
7459   Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
7460   unsigned AddressOfError = AO_No_Error;
7461 
7462   if (lval == Expr::LV_ClassTemporary) {
7463     bool sfinae = S.isSFINAEContext();
7464     S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
7465                          : diag::ext_typecheck_addrof_class_temporary)
7466       << op->getType() << op->getSourceRange();
7467     if (sfinae)
7468       return QualType();
7469   } else if (isa<ObjCSelectorExpr>(op)) {
7470     return S.Context.getPointerType(op->getType());
7471   } else if (lval == Expr::LV_MemberFunction) {
7472     // If it's an instance method, make a member pointer.
7473     // The expression must have exactly the form &A::foo.
7474 
7475     // If the underlying expression isn't a decl ref, give up.
7476     if (!isa<DeclRefExpr>(op)) {
7477       S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
7478         << OrigOp.get()->getSourceRange();
7479       return QualType();
7480     }
7481     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
7482     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
7483 
7484     // The id-expression was parenthesized.
7485     if (OrigOp.get() != DRE) {
7486       S.Diag(OpLoc, diag::err_parens_pointer_member_function)
7487         << OrigOp.get()->getSourceRange();
7488 
7489     // The method was named without a qualifier.
7490     } else if (!DRE->getQualifier()) {
7491       S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
7492         << op->getSourceRange();
7493     }
7494 
7495     return S.Context.getMemberPointerType(op->getType(),
7496               S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
7497   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
7498     // C99 6.5.3.2p1
7499     // The operand must be either an l-value or a function designator
7500     if (!op->getType()->isFunctionType()) {
7501       // Use a special diagnostic for loads from property references.
7502       if (isa<PseudoObjectExpr>(op)) {
7503         AddressOfError = AO_Property_Expansion;
7504       } else {
7505         // FIXME: emit more specific diag...
7506         S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
7507           << op->getSourceRange();
7508         return QualType();
7509       }
7510     }
7511   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
7512     // The operand cannot be a bit-field
7513     AddressOfError = AO_Bit_Field;
7514   } else if (op->getObjectKind() == OK_VectorComponent) {
7515     // The operand cannot be an element of a vector
7516     AddressOfError = AO_Vector_Element;
7517   } else if (dcl) { // C99 6.5.3.2p1
7518     // We have an lvalue with a decl. Make sure the decl is not declared
7519     // with the register storage-class specifier.
7520     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
7521       // in C++ it is not error to take address of a register
7522       // variable (c++03 7.1.1P3)
7523       if (vd->getStorageClass() == SC_Register &&
7524           !S.getLangOptions().CPlusPlus) {
7525         AddressOfError = AO_Register_Variable;
7526       }
7527     } else if (isa<FunctionTemplateDecl>(dcl)) {
7528       return S.Context.OverloadTy;
7529     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
7530       // Okay: we can take the address of a field.
7531       // Could be a pointer to member, though, if there is an explicit
7532       // scope qualifier for the class.
7533       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
7534         DeclContext *Ctx = dcl->getDeclContext();
7535         if (Ctx && Ctx->isRecord()) {
7536           if (dcl->getType()->isReferenceType()) {
7537             S.Diag(OpLoc,
7538                    diag::err_cannot_form_pointer_to_member_of_reference_type)
7539               << dcl->getDeclName() << dcl->getType();
7540             return QualType();
7541           }
7542 
7543           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
7544             Ctx = Ctx->getParent();
7545           return S.Context.getMemberPointerType(op->getType(),
7546                 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
7547         }
7548       }
7549     } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl))
7550       llvm_unreachable("Unknown/unexpected decl type");
7551   }
7552 
7553   if (AddressOfError != AO_No_Error) {
7554     diagnoseAddressOfInvalidType(S, OpLoc, op, AddressOfError);
7555     return QualType();
7556   }
7557 
7558   if (lval == Expr::LV_IncompleteVoidType) {
7559     // Taking the address of a void variable is technically illegal, but we
7560     // allow it in cases which are otherwise valid.
7561     // Example: "extern void x; void* y = &x;".
7562     S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
7563   }
7564 
7565   // If the operand has type "type", the result has type "pointer to type".
7566   if (op->getType()->isObjCObjectType())
7567     return S.Context.getObjCObjectPointerType(op->getType());
7568   return S.Context.getPointerType(op->getType());
7569 }
7570 
7571 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
7572 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
7573                                         SourceLocation OpLoc) {
7574   if (Op->isTypeDependent())
7575     return S.Context.DependentTy;
7576 
7577   ExprResult ConvResult = S.UsualUnaryConversions(Op);
7578   if (ConvResult.isInvalid())
7579     return QualType();
7580   Op = ConvResult.take();
7581   QualType OpTy = Op->getType();
7582   QualType Result;
7583 
7584   if (isa<CXXReinterpretCastExpr>(Op)) {
7585     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
7586     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
7587                                      Op->getSourceRange());
7588   }
7589 
7590   // Note that per both C89 and C99, indirection is always legal, even if OpTy
7591   // is an incomplete type or void.  It would be possible to warn about
7592   // dereferencing a void pointer, but it's completely well-defined, and such a
7593   // warning is unlikely to catch any mistakes.
7594   if (const PointerType *PT = OpTy->getAs<PointerType>())
7595     Result = PT->getPointeeType();
7596   else if (const ObjCObjectPointerType *OPT =
7597              OpTy->getAs<ObjCObjectPointerType>())
7598     Result = OPT->getPointeeType();
7599   else {
7600     ExprResult PR = S.CheckPlaceholderExpr(Op);
7601     if (PR.isInvalid()) return QualType();
7602     if (PR.take() != Op)
7603       return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
7604   }
7605 
7606   if (Result.isNull()) {
7607     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
7608       << OpTy << Op->getSourceRange();
7609     return QualType();
7610   }
7611 
7612   // Dereferences are usually l-values...
7613   VK = VK_LValue;
7614 
7615   // ...except that certain expressions are never l-values in C.
7616   if (!S.getLangOptions().CPlusPlus && Result.isCForbiddenLValueType())
7617     VK = VK_RValue;
7618 
7619   return Result;
7620 }
7621 
7622 static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
7623   tok::TokenKind Kind) {
7624   BinaryOperatorKind Opc;
7625   switch (Kind) {
7626   default: llvm_unreachable("Unknown binop!");
7627   case tok::periodstar:           Opc = BO_PtrMemD; break;
7628   case tok::arrowstar:            Opc = BO_PtrMemI; break;
7629   case tok::star:                 Opc = BO_Mul; break;
7630   case tok::slash:                Opc = BO_Div; break;
7631   case tok::percent:              Opc = BO_Rem; break;
7632   case tok::plus:                 Opc = BO_Add; break;
7633   case tok::minus:                Opc = BO_Sub; break;
7634   case tok::lessless:             Opc = BO_Shl; break;
7635   case tok::greatergreater:       Opc = BO_Shr; break;
7636   case tok::lessequal:            Opc = BO_LE; break;
7637   case tok::less:                 Opc = BO_LT; break;
7638   case tok::greaterequal:         Opc = BO_GE; break;
7639   case tok::greater:              Opc = BO_GT; break;
7640   case tok::exclaimequal:         Opc = BO_NE; break;
7641   case tok::equalequal:           Opc = BO_EQ; break;
7642   case tok::amp:                  Opc = BO_And; break;
7643   case tok::caret:                Opc = BO_Xor; break;
7644   case tok::pipe:                 Opc = BO_Or; break;
7645   case tok::ampamp:               Opc = BO_LAnd; break;
7646   case tok::pipepipe:             Opc = BO_LOr; break;
7647   case tok::equal:                Opc = BO_Assign; break;
7648   case tok::starequal:            Opc = BO_MulAssign; break;
7649   case tok::slashequal:           Opc = BO_DivAssign; break;
7650   case tok::percentequal:         Opc = BO_RemAssign; break;
7651   case tok::plusequal:            Opc = BO_AddAssign; break;
7652   case tok::minusequal:           Opc = BO_SubAssign; break;
7653   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
7654   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
7655   case tok::ampequal:             Opc = BO_AndAssign; break;
7656   case tok::caretequal:           Opc = BO_XorAssign; break;
7657   case tok::pipeequal:            Opc = BO_OrAssign; break;
7658   case tok::comma:                Opc = BO_Comma; break;
7659   }
7660   return Opc;
7661 }
7662 
7663 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
7664   tok::TokenKind Kind) {
7665   UnaryOperatorKind Opc;
7666   switch (Kind) {
7667   default: llvm_unreachable("Unknown unary op!");
7668   case tok::plusplus:     Opc = UO_PreInc; break;
7669   case tok::minusminus:   Opc = UO_PreDec; break;
7670   case tok::amp:          Opc = UO_AddrOf; break;
7671   case tok::star:         Opc = UO_Deref; break;
7672   case tok::plus:         Opc = UO_Plus; break;
7673   case tok::minus:        Opc = UO_Minus; break;
7674   case tok::tilde:        Opc = UO_Not; break;
7675   case tok::exclaim:      Opc = UO_LNot; break;
7676   case tok::kw___real:    Opc = UO_Real; break;
7677   case tok::kw___imag:    Opc = UO_Imag; break;
7678   case tok::kw___extension__: Opc = UO_Extension; break;
7679   }
7680   return Opc;
7681 }
7682 
7683 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
7684 /// This warning is only emitted for builtin assignment operations. It is also
7685 /// suppressed in the event of macro expansions.
7686 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
7687                                    SourceLocation OpLoc) {
7688   if (!S.ActiveTemplateInstantiations.empty())
7689     return;
7690   if (OpLoc.isInvalid() || OpLoc.isMacroID())
7691     return;
7692   LHSExpr = LHSExpr->IgnoreParenImpCasts();
7693   RHSExpr = RHSExpr->IgnoreParenImpCasts();
7694   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
7695   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
7696   if (!LHSDeclRef || !RHSDeclRef ||
7697       LHSDeclRef->getLocation().isMacroID() ||
7698       RHSDeclRef->getLocation().isMacroID())
7699     return;
7700   const ValueDecl *LHSDecl =
7701     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
7702   const ValueDecl *RHSDecl =
7703     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
7704   if (LHSDecl != RHSDecl)
7705     return;
7706   if (LHSDecl->getType().isVolatileQualified())
7707     return;
7708   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
7709     if (RefTy->getPointeeType().isVolatileQualified())
7710       return;
7711 
7712   S.Diag(OpLoc, diag::warn_self_assignment)
7713       << LHSDeclRef->getType()
7714       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
7715 }
7716 
7717 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
7718 /// operator @p Opc at location @c TokLoc. This routine only supports
7719 /// built-in operations; ActOnBinOp handles overloaded operators.
7720 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
7721                                     BinaryOperatorKind Opc,
7722                                     Expr *LHSExpr, Expr *RHSExpr) {
7723   ExprResult LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
7724   QualType ResultTy;     // Result type of the binary operator.
7725   // The following two variables are used for compound assignment operators
7726   QualType CompLHSTy;    // Type of LHS after promotions for computation
7727   QualType CompResultTy; // Type of computation result
7728   ExprValueKind VK = VK_RValue;
7729   ExprObjectKind OK = OK_Ordinary;
7730 
7731   switch (Opc) {
7732   case BO_Assign:
7733     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
7734     if (getLangOptions().CPlusPlus &&
7735         LHS.get()->getObjectKind() != OK_ObjCProperty) {
7736       VK = LHS.get()->getValueKind();
7737       OK = LHS.get()->getObjectKind();
7738     }
7739     if (!ResultTy.isNull())
7740       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
7741     break;
7742   case BO_PtrMemD:
7743   case BO_PtrMemI:
7744     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
7745                                             Opc == BO_PtrMemI);
7746     break;
7747   case BO_Mul:
7748   case BO_Div:
7749     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
7750                                            Opc == BO_Div);
7751     break;
7752   case BO_Rem:
7753     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
7754     break;
7755   case BO_Add:
7756     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc);
7757     break;
7758   case BO_Sub:
7759     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
7760     break;
7761   case BO_Shl:
7762   case BO_Shr:
7763     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
7764     break;
7765   case BO_LE:
7766   case BO_LT:
7767   case BO_GE:
7768   case BO_GT:
7769     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
7770     break;
7771   case BO_EQ:
7772   case BO_NE:
7773     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
7774     break;
7775   case BO_And:
7776   case BO_Xor:
7777   case BO_Or:
7778     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc);
7779     break;
7780   case BO_LAnd:
7781   case BO_LOr:
7782     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
7783     break;
7784   case BO_MulAssign:
7785   case BO_DivAssign:
7786     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
7787                                                Opc == BO_DivAssign);
7788     CompLHSTy = CompResultTy;
7789     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7790       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
7791     break;
7792   case BO_RemAssign:
7793     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
7794     CompLHSTy = CompResultTy;
7795     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7796       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
7797     break;
7798   case BO_AddAssign:
7799     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, &CompLHSTy);
7800     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7801       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
7802     break;
7803   case BO_SubAssign:
7804     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
7805     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7806       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
7807     break;
7808   case BO_ShlAssign:
7809   case BO_ShrAssign:
7810     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
7811     CompLHSTy = CompResultTy;
7812     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7813       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
7814     break;
7815   case BO_AndAssign:
7816   case BO_XorAssign:
7817   case BO_OrAssign:
7818     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true);
7819     CompLHSTy = CompResultTy;
7820     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7821       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
7822     break;
7823   case BO_Comma:
7824     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
7825     if (getLangOptions().CPlusPlus && !RHS.isInvalid()) {
7826       VK = RHS.get()->getValueKind();
7827       OK = RHS.get()->getObjectKind();
7828     }
7829     break;
7830   }
7831   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
7832     return ExprError();
7833 
7834   // Check for array bounds violations for both sides of the BinaryOperator
7835   CheckArrayAccess(LHS.get());
7836   CheckArrayAccess(RHS.get());
7837 
7838   if (CompResultTy.isNull())
7839     return Owned(new (Context) BinaryOperator(LHS.take(), RHS.take(), Opc,
7840                                               ResultTy, VK, OK, OpLoc));
7841   if (getLangOptions().CPlusPlus && LHS.get()->getObjectKind() !=
7842       OK_ObjCProperty) {
7843     VK = VK_LValue;
7844     OK = LHS.get()->getObjectKind();
7845   }
7846   return Owned(new (Context) CompoundAssignOperator(LHS.take(), RHS.take(), Opc,
7847                                                     ResultTy, VK, OK, CompLHSTy,
7848                                                     CompResultTy, OpLoc));
7849 }
7850 
7851 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
7852 /// operators are mixed in a way that suggests that the programmer forgot that
7853 /// comparison operators have higher precedence. The most typical example of
7854 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
7855 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
7856                                       SourceLocation OpLoc, Expr *LHSExpr,
7857                                       Expr *RHSExpr) {
7858   typedef BinaryOperator BinOp;
7859   BinOp::Opcode LHSopc = static_cast<BinOp::Opcode>(-1),
7860                 RHSopc = static_cast<BinOp::Opcode>(-1);
7861   if (BinOp *BO = dyn_cast<BinOp>(LHSExpr))
7862     LHSopc = BO->getOpcode();
7863   if (BinOp *BO = dyn_cast<BinOp>(RHSExpr))
7864     RHSopc = BO->getOpcode();
7865 
7866   // Subs are not binary operators.
7867   if (LHSopc == -1 && RHSopc == -1)
7868     return;
7869 
7870   // Bitwise operations are sometimes used as eager logical ops.
7871   // Don't diagnose this.
7872   if ((BinOp::isComparisonOp(LHSopc) || BinOp::isBitwiseOp(LHSopc)) &&
7873       (BinOp::isComparisonOp(RHSopc) || BinOp::isBitwiseOp(RHSopc)))
7874     return;
7875 
7876   bool isLeftComp = BinOp::isComparisonOp(LHSopc);
7877   bool isRightComp = BinOp::isComparisonOp(RHSopc);
7878   if (!isLeftComp && !isRightComp) return;
7879 
7880   SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
7881                                                    OpLoc)
7882                                      : SourceRange(OpLoc, RHSExpr->getLocEnd());
7883   std::string OpStr = isLeftComp ? BinOp::getOpcodeStr(LHSopc)
7884                                  : BinOp::getOpcodeStr(RHSopc);
7885   SourceRange ParensRange = isLeftComp ?
7886       SourceRange(cast<BinOp>(LHSExpr)->getRHS()->getLocStart(),
7887                   RHSExpr->getLocEnd())
7888     : SourceRange(LHSExpr->getLocStart(),
7889                   cast<BinOp>(RHSExpr)->getLHS()->getLocStart());
7890 
7891   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
7892     << DiagRange << BinOp::getOpcodeStr(Opc) << OpStr;
7893   SuggestParentheses(Self, OpLoc,
7894     Self.PDiag(diag::note_precedence_bitwise_silence) << OpStr,
7895     RHSExpr->getSourceRange());
7896   SuggestParentheses(Self, OpLoc,
7897     Self.PDiag(diag::note_precedence_bitwise_first) << BinOp::getOpcodeStr(Opc),
7898     ParensRange);
7899 }
7900 
7901 /// \brief It accepts a '&' expr that is inside a '|' one.
7902 /// Emit a diagnostic together with a fixit hint that wraps the '&' expression
7903 /// in parentheses.
7904 static void
7905 EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc,
7906                                        BinaryOperator *Bop) {
7907   assert(Bop->getOpcode() == BO_And);
7908   Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or)
7909       << Bop->getSourceRange() << OpLoc;
7910   SuggestParentheses(Self, Bop->getOperatorLoc(),
7911     Self.PDiag(diag::note_bitwise_and_in_bitwise_or_silence),
7912     Bop->getSourceRange());
7913 }
7914 
7915 /// \brief It accepts a '&&' expr that is inside a '||' one.
7916 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
7917 /// in parentheses.
7918 static void
7919 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
7920                                        BinaryOperator *Bop) {
7921   assert(Bop->getOpcode() == BO_LAnd);
7922   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
7923       << Bop->getSourceRange() << OpLoc;
7924   SuggestParentheses(Self, Bop->getOperatorLoc(),
7925     Self.PDiag(diag::note_logical_and_in_logical_or_silence),
7926     Bop->getSourceRange());
7927 }
7928 
7929 /// \brief Returns true if the given expression can be evaluated as a constant
7930 /// 'true'.
7931 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
7932   bool Res;
7933   return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
7934 }
7935 
7936 /// \brief Returns true if the given expression can be evaluated as a constant
7937 /// 'false'.
7938 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
7939   bool Res;
7940   return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
7941 }
7942 
7943 /// \brief Look for '&&' in the left hand of a '||' expr.
7944 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
7945                                              Expr *LHSExpr, Expr *RHSExpr) {
7946   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
7947     if (Bop->getOpcode() == BO_LAnd) {
7948       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
7949       if (EvaluatesAsFalse(S, RHSExpr))
7950         return;
7951       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
7952       if (!EvaluatesAsTrue(S, Bop->getLHS()))
7953         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
7954     } else if (Bop->getOpcode() == BO_LOr) {
7955       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
7956         // If it's "a || b && 1 || c" we didn't warn earlier for
7957         // "a || b && 1", but warn now.
7958         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
7959           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
7960       }
7961     }
7962   }
7963 }
7964 
7965 /// \brief Look for '&&' in the right hand of a '||' expr.
7966 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
7967                                              Expr *LHSExpr, Expr *RHSExpr) {
7968   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
7969     if (Bop->getOpcode() == BO_LAnd) {
7970       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
7971       if (EvaluatesAsFalse(S, LHSExpr))
7972         return;
7973       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
7974       if (!EvaluatesAsTrue(S, Bop->getRHS()))
7975         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
7976     }
7977   }
7978 }
7979 
7980 /// \brief Look for '&' in the left or right hand of a '|' expr.
7981 static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc,
7982                                              Expr *OrArg) {
7983   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) {
7984     if (Bop->getOpcode() == BO_And)
7985       return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop);
7986   }
7987 }
7988 
7989 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
7990 /// precedence.
7991 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
7992                                     SourceLocation OpLoc, Expr *LHSExpr,
7993                                     Expr *RHSExpr){
7994   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
7995   if (BinaryOperator::isBitwiseOp(Opc))
7996     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
7997 
7998   // Diagnose "arg1 & arg2 | arg3"
7999   if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) {
8000     DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr);
8001     DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr);
8002   }
8003 
8004   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
8005   // We don't warn for 'assert(a || b && "bad")' since this is safe.
8006   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
8007     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
8008     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
8009   }
8010 }
8011 
8012 // Binary Operators.  'Tok' is the token for the operator.
8013 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
8014                             tok::TokenKind Kind,
8015                             Expr *LHSExpr, Expr *RHSExpr) {
8016   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
8017   assert((LHSExpr != 0) && "ActOnBinOp(): missing left expression");
8018   assert((RHSExpr != 0) && "ActOnBinOp(): missing right expression");
8019 
8020   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
8021   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
8022 
8023   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
8024 }
8025 
8026 /// Build an overloaded binary operator expression in the given scope.
8027 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
8028                                        BinaryOperatorKind Opc,
8029                                        Expr *LHS, Expr *RHS) {
8030   // Find all of the overloaded operators visible from this
8031   // point. We perform both an operator-name lookup from the local
8032   // scope and an argument-dependent lookup based on the types of
8033   // the arguments.
8034   UnresolvedSet<16> Functions;
8035   OverloadedOperatorKind OverOp
8036     = BinaryOperator::getOverloadedOperator(Opc);
8037   if (Sc && OverOp != OO_None)
8038     S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
8039                                    RHS->getType(), Functions);
8040 
8041   // Build the (potentially-overloaded, potentially-dependent)
8042   // binary operation.
8043   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
8044 }
8045 
8046 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
8047                             BinaryOperatorKind Opc,
8048                             Expr *LHSExpr, Expr *RHSExpr) {
8049   // We want to end up calling one of checkPseudoObjectAssignment
8050   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
8051   // both expressions are overloadable or either is type-dependent),
8052   // or CreateBuiltinBinOp (in any other case).  We also want to get
8053   // any placeholder types out of the way.
8054 
8055   // Handle pseudo-objects in the LHS.
8056   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
8057     // Assignments with a pseudo-object l-value need special analysis.
8058     if (pty->getKind() == BuiltinType::PseudoObject &&
8059         BinaryOperator::isAssignmentOp(Opc))
8060       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
8061 
8062     // Don't resolve overloads if the other type is overloadable.
8063     if (pty->getKind() == BuiltinType::Overload) {
8064       // We can't actually test that if we still have a placeholder,
8065       // though.  Fortunately, none of the exceptions we see in that
8066       // code below are valid when the LHS is an overload set.  Note
8067       // that an overload set can be dependently-typed, but it never
8068       // instantiates to having an overloadable type.
8069       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
8070       if (resolvedRHS.isInvalid()) return ExprError();
8071       RHSExpr = resolvedRHS.take();
8072 
8073       if (RHSExpr->isTypeDependent() ||
8074           RHSExpr->getType()->isOverloadableType())
8075         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8076     }
8077 
8078     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
8079     if (LHS.isInvalid()) return ExprError();
8080     LHSExpr = LHS.take();
8081   }
8082 
8083   // Handle pseudo-objects in the RHS.
8084   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
8085     // An overload in the RHS can potentially be resolved by the type
8086     // being assigned to.
8087     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
8088       if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
8089         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8090 
8091       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
8092     }
8093 
8094     // Don't resolve overloads if the other type is overloadable.
8095     if (pty->getKind() == BuiltinType::Overload &&
8096         LHSExpr->getType()->isOverloadableType())
8097       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8098 
8099     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
8100     if (!resolvedRHS.isUsable()) return ExprError();
8101     RHSExpr = resolvedRHS.take();
8102   }
8103 
8104   if (getLangOptions().CPlusPlus) {
8105     // If either expression is type-dependent, always build an
8106     // overloaded op.
8107     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
8108       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8109 
8110     // Otherwise, build an overloaded op if either expression has an
8111     // overloadable type.
8112     if (LHSExpr->getType()->isOverloadableType() ||
8113         RHSExpr->getType()->isOverloadableType())
8114       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8115   }
8116 
8117   // Build a built-in binary operation.
8118   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
8119 }
8120 
8121 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
8122                                       UnaryOperatorKind Opc,
8123                                       Expr *InputExpr) {
8124   ExprResult Input = Owned(InputExpr);
8125   ExprValueKind VK = VK_RValue;
8126   ExprObjectKind OK = OK_Ordinary;
8127   QualType resultType;
8128   switch (Opc) {
8129   case UO_PreInc:
8130   case UO_PreDec:
8131   case UO_PostInc:
8132   case UO_PostDec:
8133     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc,
8134                                                 Opc == UO_PreInc ||
8135                                                 Opc == UO_PostInc,
8136                                                 Opc == UO_PreInc ||
8137                                                 Opc == UO_PreDec);
8138     break;
8139   case UO_AddrOf:
8140     resultType = CheckAddressOfOperand(*this, Input, OpLoc);
8141     break;
8142   case UO_Deref: {
8143     Input = DefaultFunctionArrayLvalueConversion(Input.take());
8144     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
8145     break;
8146   }
8147   case UO_Plus:
8148   case UO_Minus:
8149     Input = UsualUnaryConversions(Input.take());
8150     if (Input.isInvalid()) return ExprError();
8151     resultType = Input.get()->getType();
8152     if (resultType->isDependentType())
8153       break;
8154     if (resultType->isArithmeticType() || // C99 6.5.3.3p1
8155         resultType->isVectorType())
8156       break;
8157     else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
8158              resultType->isEnumeralType())
8159       break;
8160     else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
8161              Opc == UO_Plus &&
8162              resultType->isPointerType())
8163       break;
8164 
8165     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
8166       << resultType << Input.get()->getSourceRange());
8167 
8168   case UO_Not: // bitwise complement
8169     Input = UsualUnaryConversions(Input.take());
8170     if (Input.isInvalid()) return ExprError();
8171     resultType = Input.get()->getType();
8172     if (resultType->isDependentType())
8173       break;
8174     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
8175     if (resultType->isComplexType() || resultType->isComplexIntegerType())
8176       // C99 does not support '~' for complex conjugation.
8177       Diag(OpLoc, diag::ext_integer_complement_complex)
8178         << resultType << Input.get()->getSourceRange();
8179     else if (resultType->hasIntegerRepresentation())
8180       break;
8181     else {
8182       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
8183         << resultType << Input.get()->getSourceRange());
8184     }
8185     break;
8186 
8187   case UO_LNot: // logical negation
8188     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
8189     Input = DefaultFunctionArrayLvalueConversion(Input.take());
8190     if (Input.isInvalid()) return ExprError();
8191     resultType = Input.get()->getType();
8192 
8193     // Though we still have to promote half FP to float...
8194     if (resultType->isHalfType()) {
8195       Input = ImpCastExprToType(Input.take(), Context.FloatTy, CK_FloatingCast).take();
8196       resultType = Context.FloatTy;
8197     }
8198 
8199     if (resultType->isDependentType())
8200       break;
8201     if (resultType->isScalarType()) {
8202       // C99 6.5.3.3p1: ok, fallthrough;
8203       if (Context.getLangOptions().CPlusPlus) {
8204         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
8205         // operand contextually converted to bool.
8206         Input = ImpCastExprToType(Input.take(), Context.BoolTy,
8207                                   ScalarTypeToBooleanCastKind(resultType));
8208       }
8209     } else {
8210       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
8211         << resultType << Input.get()->getSourceRange());
8212     }
8213 
8214     // LNot always has type int. C99 6.5.3.3p5.
8215     // In C++, it's bool. C++ 5.3.1p8
8216     resultType = Context.getLogicalOperationType();
8217     break;
8218   case UO_Real:
8219   case UO_Imag:
8220     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
8221     // _Real and _Imag map ordinary l-values into ordinary l-values.
8222     if (Input.isInvalid()) return ExprError();
8223     if (Input.get()->getValueKind() != VK_RValue &&
8224         Input.get()->getObjectKind() == OK_Ordinary)
8225       VK = Input.get()->getValueKind();
8226     break;
8227   case UO_Extension:
8228     resultType = Input.get()->getType();
8229     VK = Input.get()->getValueKind();
8230     OK = Input.get()->getObjectKind();
8231     break;
8232   }
8233   if (resultType.isNull() || Input.isInvalid())
8234     return ExprError();
8235 
8236   // Check for array bounds violations in the operand of the UnaryOperator,
8237   // except for the '*' and '&' operators that have to be handled specially
8238   // by CheckArrayAccess (as there are special cases like &array[arraysize]
8239   // that are explicitly defined as valid by the standard).
8240   if (Opc != UO_AddrOf && Opc != UO_Deref)
8241     CheckArrayAccess(Input.get());
8242 
8243   return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType,
8244                                            VK, OK, OpLoc));
8245 }
8246 
8247 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
8248                               UnaryOperatorKind Opc, Expr *Input) {
8249   // First things first: handle placeholders so that the
8250   // overloaded-operator check considers the right type.
8251   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
8252     // Increment and decrement of pseudo-object references.
8253     if (pty->getKind() == BuiltinType::PseudoObject &&
8254         UnaryOperator::isIncrementDecrementOp(Opc))
8255       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
8256 
8257     // extension is always a builtin operator.
8258     if (Opc == UO_Extension)
8259       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
8260 
8261     // & gets special logic for several kinds of placeholder.
8262     // The builtin code knows what to do.
8263     if (Opc == UO_AddrOf &&
8264         (pty->getKind() == BuiltinType::Overload ||
8265          pty->getKind() == BuiltinType::UnknownAny ||
8266          pty->getKind() == BuiltinType::BoundMember))
8267       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
8268 
8269     // Anything else needs to be handled now.
8270     ExprResult Result = CheckPlaceholderExpr(Input);
8271     if (Result.isInvalid()) return ExprError();
8272     Input = Result.take();
8273   }
8274 
8275   if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
8276       UnaryOperator::getOverloadedOperator(Opc) != OO_None) {
8277     // Find all of the overloaded operators visible from this
8278     // point. We perform both an operator-name lookup from the local
8279     // scope and an argument-dependent lookup based on the types of
8280     // the arguments.
8281     UnresolvedSet<16> Functions;
8282     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
8283     if (S && OverOp != OO_None)
8284       LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
8285                                    Functions);
8286 
8287     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
8288   }
8289 
8290   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
8291 }
8292 
8293 // Unary Operators.  'Tok' is the token for the operator.
8294 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
8295                               tok::TokenKind Op, Expr *Input) {
8296   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
8297 }
8298 
8299 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
8300 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
8301                                 LabelDecl *TheDecl) {
8302   TheDecl->setUsed();
8303   // Create the AST node.  The address of a label always has type 'void*'.
8304   return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
8305                                        Context.getPointerType(Context.VoidTy)));
8306 }
8307 
8308 /// Given the last statement in a statement-expression, check whether
8309 /// the result is a producing expression (like a call to an
8310 /// ns_returns_retained function) and, if so, rebuild it to hoist the
8311 /// release out of the full-expression.  Otherwise, return null.
8312 /// Cannot fail.
8313 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
8314   // Should always be wrapped with one of these.
8315   ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
8316   if (!cleanups) return 0;
8317 
8318   ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
8319   if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
8320     return 0;
8321 
8322   // Splice out the cast.  This shouldn't modify any interesting
8323   // features of the statement.
8324   Expr *producer = cast->getSubExpr();
8325   assert(producer->getType() == cast->getType());
8326   assert(producer->getValueKind() == cast->getValueKind());
8327   cleanups->setSubExpr(producer);
8328   return cleanups;
8329 }
8330 
8331 ExprResult
8332 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
8333                     SourceLocation RPLoc) { // "({..})"
8334   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
8335   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
8336 
8337   bool isFileScope
8338     = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
8339   if (isFileScope)
8340     return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
8341 
8342   // FIXME: there are a variety of strange constraints to enforce here, for
8343   // example, it is not possible to goto into a stmt expression apparently.
8344   // More semantic analysis is needed.
8345 
8346   // If there are sub stmts in the compound stmt, take the type of the last one
8347   // as the type of the stmtexpr.
8348   QualType Ty = Context.VoidTy;
8349   bool StmtExprMayBindToTemp = false;
8350   if (!Compound->body_empty()) {
8351     Stmt *LastStmt = Compound->body_back();
8352     LabelStmt *LastLabelStmt = 0;
8353     // If LastStmt is a label, skip down through into the body.
8354     while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
8355       LastLabelStmt = Label;
8356       LastStmt = Label->getSubStmt();
8357     }
8358 
8359     if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
8360       // Do function/array conversion on the last expression, but not
8361       // lvalue-to-rvalue.  However, initialize an unqualified type.
8362       ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
8363       if (LastExpr.isInvalid())
8364         return ExprError();
8365       Ty = LastExpr.get()->getType().getUnqualifiedType();
8366 
8367       if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
8368         // In ARC, if the final expression ends in a consume, splice
8369         // the consume out and bind it later.  In the alternate case
8370         // (when dealing with a retainable type), the result
8371         // initialization will create a produce.  In both cases the
8372         // result will be +1, and we'll need to balance that out with
8373         // a bind.
8374         if (Expr *rebuiltLastStmt
8375               = maybeRebuildARCConsumingStmt(LastExpr.get())) {
8376           LastExpr = rebuiltLastStmt;
8377         } else {
8378           LastExpr = PerformCopyInitialization(
8379                             InitializedEntity::InitializeResult(LPLoc,
8380                                                                 Ty,
8381                                                                 false),
8382                                                    SourceLocation(),
8383                                                LastExpr);
8384         }
8385 
8386         if (LastExpr.isInvalid())
8387           return ExprError();
8388         if (LastExpr.get() != 0) {
8389           if (!LastLabelStmt)
8390             Compound->setLastStmt(LastExpr.take());
8391           else
8392             LastLabelStmt->setSubStmt(LastExpr.take());
8393           StmtExprMayBindToTemp = true;
8394         }
8395       }
8396     }
8397   }
8398 
8399   // FIXME: Check that expression type is complete/non-abstract; statement
8400   // expressions are not lvalues.
8401   Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
8402   if (StmtExprMayBindToTemp)
8403     return MaybeBindToTemporary(ResStmtExpr);
8404   return Owned(ResStmtExpr);
8405 }
8406 
8407 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
8408                                       TypeSourceInfo *TInfo,
8409                                       OffsetOfComponent *CompPtr,
8410                                       unsigned NumComponents,
8411                                       SourceLocation RParenLoc) {
8412   QualType ArgTy = TInfo->getType();
8413   bool Dependent = ArgTy->isDependentType();
8414   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
8415 
8416   // We must have at least one component that refers to the type, and the first
8417   // one is known to be a field designator.  Verify that the ArgTy represents
8418   // a struct/union/class.
8419   if (!Dependent && !ArgTy->isRecordType())
8420     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
8421                        << ArgTy << TypeRange);
8422 
8423   // Type must be complete per C99 7.17p3 because a declaring a variable
8424   // with an incomplete type would be ill-formed.
8425   if (!Dependent
8426       && RequireCompleteType(BuiltinLoc, ArgTy,
8427                              PDiag(diag::err_offsetof_incomplete_type)
8428                                << TypeRange))
8429     return ExprError();
8430 
8431   // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
8432   // GCC extension, diagnose them.
8433   // FIXME: This diagnostic isn't actually visible because the location is in
8434   // a system header!
8435   if (NumComponents != 1)
8436     Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
8437       << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
8438 
8439   bool DidWarnAboutNonPOD = false;
8440   QualType CurrentType = ArgTy;
8441   typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
8442   SmallVector<OffsetOfNode, 4> Comps;
8443   SmallVector<Expr*, 4> Exprs;
8444   for (unsigned i = 0; i != NumComponents; ++i) {
8445     const OffsetOfComponent &OC = CompPtr[i];
8446     if (OC.isBrackets) {
8447       // Offset of an array sub-field.  TODO: Should we allow vector elements?
8448       if (!CurrentType->isDependentType()) {
8449         const ArrayType *AT = Context.getAsArrayType(CurrentType);
8450         if(!AT)
8451           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
8452                            << CurrentType);
8453         CurrentType = AT->getElementType();
8454       } else
8455         CurrentType = Context.DependentTy;
8456 
8457       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
8458       if (IdxRval.isInvalid())
8459         return ExprError();
8460       Expr *Idx = IdxRval.take();
8461 
8462       // The expression must be an integral expression.
8463       // FIXME: An integral constant expression?
8464       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
8465           !Idx->getType()->isIntegerType())
8466         return ExprError(Diag(Idx->getLocStart(),
8467                               diag::err_typecheck_subscript_not_integer)
8468                          << Idx->getSourceRange());
8469 
8470       // Record this array index.
8471       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
8472       Exprs.push_back(Idx);
8473       continue;
8474     }
8475 
8476     // Offset of a field.
8477     if (CurrentType->isDependentType()) {
8478       // We have the offset of a field, but we can't look into the dependent
8479       // type. Just record the identifier of the field.
8480       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
8481       CurrentType = Context.DependentTy;
8482       continue;
8483     }
8484 
8485     // We need to have a complete type to look into.
8486     if (RequireCompleteType(OC.LocStart, CurrentType,
8487                             diag::err_offsetof_incomplete_type))
8488       return ExprError();
8489 
8490     // Look for the designated field.
8491     const RecordType *RC = CurrentType->getAs<RecordType>();
8492     if (!RC)
8493       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
8494                        << CurrentType);
8495     RecordDecl *RD = RC->getDecl();
8496 
8497     // C++ [lib.support.types]p5:
8498     //   The macro offsetof accepts a restricted set of type arguments in this
8499     //   International Standard. type shall be a POD structure or a POD union
8500     //   (clause 9).
8501     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
8502       if (!CRD->isPOD() && !DidWarnAboutNonPOD &&
8503           DiagRuntimeBehavior(BuiltinLoc, 0,
8504                               PDiag(diag::warn_offsetof_non_pod_type)
8505                               << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
8506                               << CurrentType))
8507         DidWarnAboutNonPOD = true;
8508     }
8509 
8510     // Look for the field.
8511     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
8512     LookupQualifiedName(R, RD);
8513     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
8514     IndirectFieldDecl *IndirectMemberDecl = 0;
8515     if (!MemberDecl) {
8516       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
8517         MemberDecl = IndirectMemberDecl->getAnonField();
8518     }
8519 
8520     if (!MemberDecl)
8521       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
8522                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
8523                                                               OC.LocEnd));
8524 
8525     // C99 7.17p3:
8526     //   (If the specified member is a bit-field, the behavior is undefined.)
8527     //
8528     // We diagnose this as an error.
8529     if (MemberDecl->isBitField()) {
8530       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
8531         << MemberDecl->getDeclName()
8532         << SourceRange(BuiltinLoc, RParenLoc);
8533       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
8534       return ExprError();
8535     }
8536 
8537     RecordDecl *Parent = MemberDecl->getParent();
8538     if (IndirectMemberDecl)
8539       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
8540 
8541     // If the member was found in a base class, introduce OffsetOfNodes for
8542     // the base class indirections.
8543     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
8544                        /*DetectVirtual=*/false);
8545     if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
8546       CXXBasePath &Path = Paths.front();
8547       for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
8548            B != BEnd; ++B)
8549         Comps.push_back(OffsetOfNode(B->Base));
8550     }
8551 
8552     if (IndirectMemberDecl) {
8553       for (IndirectFieldDecl::chain_iterator FI =
8554            IndirectMemberDecl->chain_begin(),
8555            FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
8556         assert(isa<FieldDecl>(*FI));
8557         Comps.push_back(OffsetOfNode(OC.LocStart,
8558                                      cast<FieldDecl>(*FI), OC.LocEnd));
8559       }
8560     } else
8561       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
8562 
8563     CurrentType = MemberDecl->getType().getNonReferenceType();
8564   }
8565 
8566   return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
8567                                     TInfo, Comps.data(), Comps.size(),
8568                                     Exprs.data(), Exprs.size(), RParenLoc));
8569 }
8570 
8571 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
8572                                       SourceLocation BuiltinLoc,
8573                                       SourceLocation TypeLoc,
8574                                       ParsedType ParsedArgTy,
8575                                       OffsetOfComponent *CompPtr,
8576                                       unsigned NumComponents,
8577                                       SourceLocation RParenLoc) {
8578 
8579   TypeSourceInfo *ArgTInfo;
8580   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
8581   if (ArgTy.isNull())
8582     return ExprError();
8583 
8584   if (!ArgTInfo)
8585     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
8586 
8587   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
8588                               RParenLoc);
8589 }
8590 
8591 
8592 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
8593                                  Expr *CondExpr,
8594                                  Expr *LHSExpr, Expr *RHSExpr,
8595                                  SourceLocation RPLoc) {
8596   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
8597 
8598   ExprValueKind VK = VK_RValue;
8599   ExprObjectKind OK = OK_Ordinary;
8600   QualType resType;
8601   bool ValueDependent = false;
8602   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
8603     resType = Context.DependentTy;
8604     ValueDependent = true;
8605   } else {
8606     // The conditional expression is required to be a constant expression.
8607     llvm::APSInt condEval(32);
8608     SourceLocation ExpLoc;
8609     if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
8610       return ExprError(Diag(ExpLoc,
8611                        diag::err_typecheck_choose_expr_requires_constant)
8612         << CondExpr->getSourceRange());
8613 
8614     // If the condition is > zero, then the AST type is the same as the LSHExpr.
8615     Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
8616 
8617     resType = ActiveExpr->getType();
8618     ValueDependent = ActiveExpr->isValueDependent();
8619     VK = ActiveExpr->getValueKind();
8620     OK = ActiveExpr->getObjectKind();
8621   }
8622 
8623   return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
8624                                         resType, VK, OK, RPLoc,
8625                                         resType->isDependentType(),
8626                                         ValueDependent));
8627 }
8628 
8629 //===----------------------------------------------------------------------===//
8630 // Clang Extensions.
8631 //===----------------------------------------------------------------------===//
8632 
8633 /// ActOnBlockStart - This callback is invoked when a block literal is started.
8634 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
8635   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
8636   PushBlockScope(CurScope, Block);
8637   CurContext->addDecl(Block);
8638   if (CurScope)
8639     PushDeclContext(CurScope, Block);
8640   else
8641     CurContext = Block;
8642 
8643   // Enter a new evaluation context to insulate the block from any
8644   // cleanups from the enclosing full-expression.
8645   PushExpressionEvaluationContext(PotentiallyEvaluated);
8646 }
8647 
8648 void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
8649   assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
8650   assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
8651   BlockScopeInfo *CurBlock = getCurBlock();
8652 
8653   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
8654   QualType T = Sig->getType();
8655 
8656   // GetTypeForDeclarator always produces a function type for a block
8657   // literal signature.  Furthermore, it is always a FunctionProtoType
8658   // unless the function was written with a typedef.
8659   assert(T->isFunctionType() &&
8660          "GetTypeForDeclarator made a non-function block signature");
8661 
8662   // Look for an explicit signature in that function type.
8663   FunctionProtoTypeLoc ExplicitSignature;
8664 
8665   TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
8666   if (isa<FunctionProtoTypeLoc>(tmp)) {
8667     ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp);
8668 
8669     // Check whether that explicit signature was synthesized by
8670     // GetTypeForDeclarator.  If so, don't save that as part of the
8671     // written signature.
8672     if (ExplicitSignature.getLocalRangeBegin() ==
8673         ExplicitSignature.getLocalRangeEnd()) {
8674       // This would be much cheaper if we stored TypeLocs instead of
8675       // TypeSourceInfos.
8676       TypeLoc Result = ExplicitSignature.getResultLoc();
8677       unsigned Size = Result.getFullDataSize();
8678       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
8679       Sig->getTypeLoc().initializeFullCopy(Result, Size);
8680 
8681       ExplicitSignature = FunctionProtoTypeLoc();
8682     }
8683   }
8684 
8685   CurBlock->TheDecl->setSignatureAsWritten(Sig);
8686   CurBlock->FunctionType = T;
8687 
8688   const FunctionType *Fn = T->getAs<FunctionType>();
8689   QualType RetTy = Fn->getResultType();
8690   bool isVariadic =
8691     (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
8692 
8693   CurBlock->TheDecl->setIsVariadic(isVariadic);
8694 
8695   // Don't allow returning a objc interface by value.
8696   if (RetTy->isObjCObjectType()) {
8697     Diag(ParamInfo.getSourceRange().getBegin(),
8698          diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
8699     return;
8700   }
8701 
8702   // Context.DependentTy is used as a placeholder for a missing block
8703   // return type.  TODO:  what should we do with declarators like:
8704   //   ^ * { ... }
8705   // If the answer is "apply template argument deduction"....
8706   if (RetTy != Context.DependentTy)
8707     CurBlock->ReturnType = RetTy;
8708 
8709   // Push block parameters from the declarator if we had them.
8710   SmallVector<ParmVarDecl*, 8> Params;
8711   if (ExplicitSignature) {
8712     for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
8713       ParmVarDecl *Param = ExplicitSignature.getArg(I);
8714       if (Param->getIdentifier() == 0 &&
8715           !Param->isImplicit() &&
8716           !Param->isInvalidDecl() &&
8717           !getLangOptions().CPlusPlus)
8718         Diag(Param->getLocation(), diag::err_parameter_name_omitted);
8719       Params.push_back(Param);
8720     }
8721 
8722   // Fake up parameter variables if we have a typedef, like
8723   //   ^ fntype { ... }
8724   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
8725     for (FunctionProtoType::arg_type_iterator
8726            I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
8727       ParmVarDecl *Param =
8728         BuildParmVarDeclForTypedef(CurBlock->TheDecl,
8729                                    ParamInfo.getSourceRange().getBegin(),
8730                                    *I);
8731       Params.push_back(Param);
8732     }
8733   }
8734 
8735   // Set the parameters on the block decl.
8736   if (!Params.empty()) {
8737     CurBlock->TheDecl->setParams(Params);
8738     CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
8739                              CurBlock->TheDecl->param_end(),
8740                              /*CheckParameterNames=*/false);
8741   }
8742 
8743   // Finally we can process decl attributes.
8744   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
8745 
8746   if (!isVariadic && CurBlock->TheDecl->getAttr<SentinelAttr>()) {
8747     Diag(ParamInfo.getAttributes()->getLoc(),
8748          diag::warn_attribute_sentinel_not_variadic) << 1;
8749     // FIXME: remove the attribute.
8750   }
8751 
8752   // Put the parameter variables in scope.  We can bail out immediately
8753   // if we don't have any.
8754   if (Params.empty())
8755     return;
8756 
8757   for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
8758          E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
8759     (*AI)->setOwningFunction(CurBlock->TheDecl);
8760 
8761     // If this has an identifier, add it to the scope stack.
8762     if ((*AI)->getIdentifier()) {
8763       CheckShadow(CurBlock->TheScope, *AI);
8764 
8765       PushOnScopeChains(*AI, CurBlock->TheScope);
8766     }
8767   }
8768 }
8769 
8770 /// ActOnBlockError - If there is an error parsing a block, this callback
8771 /// is invoked to pop the information about the block from the action impl.
8772 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
8773   // Leave the expression-evaluation context.
8774   DiscardCleanupsInEvaluationContext();
8775   PopExpressionEvaluationContext();
8776 
8777   // Pop off CurBlock, handle nested blocks.
8778   PopDeclContext();
8779   PopFunctionOrBlockScope();
8780 }
8781 
8782 /// ActOnBlockStmtExpr - This is called when the body of a block statement
8783 /// literal was successfully completed.  ^(int x){...}
8784 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
8785                                     Stmt *Body, Scope *CurScope) {
8786   // If blocks are disabled, emit an error.
8787   if (!LangOpts.Blocks)
8788     Diag(CaretLoc, diag::err_blocks_disable);
8789 
8790   // Leave the expression-evaluation context.
8791   assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!");
8792   PopExpressionEvaluationContext();
8793 
8794   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
8795 
8796   PopDeclContext();
8797 
8798   QualType RetTy = Context.VoidTy;
8799   if (!BSI->ReturnType.isNull())
8800     RetTy = BSI->ReturnType;
8801 
8802   bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
8803   QualType BlockTy;
8804 
8805   // Set the captured variables on the block.
8806   BSI->TheDecl->setCaptures(Context, BSI->Captures.begin(), BSI->Captures.end(),
8807                             BSI->CapturesCXXThis);
8808 
8809   // If the user wrote a function type in some form, try to use that.
8810   if (!BSI->FunctionType.isNull()) {
8811     const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
8812 
8813     FunctionType::ExtInfo Ext = FTy->getExtInfo();
8814     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
8815 
8816     // Turn protoless block types into nullary block types.
8817     if (isa<FunctionNoProtoType>(FTy)) {
8818       FunctionProtoType::ExtProtoInfo EPI;
8819       EPI.ExtInfo = Ext;
8820       BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
8821 
8822     // Otherwise, if we don't need to change anything about the function type,
8823     // preserve its sugar structure.
8824     } else if (FTy->getResultType() == RetTy &&
8825                (!NoReturn || FTy->getNoReturnAttr())) {
8826       BlockTy = BSI->FunctionType;
8827 
8828     // Otherwise, make the minimal modifications to the function type.
8829     } else {
8830       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
8831       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8832       EPI.TypeQuals = 0; // FIXME: silently?
8833       EPI.ExtInfo = Ext;
8834       BlockTy = Context.getFunctionType(RetTy,
8835                                         FPT->arg_type_begin(),
8836                                         FPT->getNumArgs(),
8837                                         EPI);
8838     }
8839 
8840   // If we don't have a function type, just build one from nothing.
8841   } else {
8842     FunctionProtoType::ExtProtoInfo EPI;
8843     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
8844     BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
8845   }
8846 
8847   DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
8848                            BSI->TheDecl->param_end());
8849   BlockTy = Context.getBlockPointerType(BlockTy);
8850 
8851   // If needed, diagnose invalid gotos and switches in the block.
8852   if (getCurFunction()->NeedsScopeChecking() &&
8853       !hasAnyUnrecoverableErrorsInThisFunction())
8854     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
8855 
8856   BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
8857 
8858   for (BlockDecl::capture_const_iterator ci = BSI->TheDecl->capture_begin(),
8859        ce = BSI->TheDecl->capture_end(); ci != ce; ++ci) {
8860     const VarDecl *variable = ci->getVariable();
8861     QualType T = variable->getType();
8862     QualType::DestructionKind destructKind = T.isDestructedType();
8863     if (destructKind != QualType::DK_none)
8864       getCurFunction()->setHasBranchProtectedScope();
8865   }
8866 
8867   computeNRVO(Body, getCurBlock());
8868 
8869   BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
8870   const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy();
8871   PopFunctionOrBlockScope(&WP, Result->getBlockDecl(), Result);
8872 
8873   // If the block isn't obviously global, i.e. it captures anything at
8874   // all, mark this full-expression as needing a cleanup.
8875   if (Result->getBlockDecl()->hasCaptures()) {
8876     ExprCleanupObjects.push_back(Result->getBlockDecl());
8877     ExprNeedsCleanups = true;
8878   }
8879 
8880   return Owned(Result);
8881 }
8882 
8883 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
8884                                         Expr *E, ParsedType Ty,
8885                                         SourceLocation RPLoc) {
8886   TypeSourceInfo *TInfo;
8887   GetTypeFromParser(Ty, &TInfo);
8888   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
8889 }
8890 
8891 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
8892                                 Expr *E, TypeSourceInfo *TInfo,
8893                                 SourceLocation RPLoc) {
8894   Expr *OrigExpr = E;
8895 
8896   // Get the va_list type
8897   QualType VaListType = Context.getBuiltinVaListType();
8898   if (VaListType->isArrayType()) {
8899     // Deal with implicit array decay; for example, on x86-64,
8900     // va_list is an array, but it's supposed to decay to
8901     // a pointer for va_arg.
8902     VaListType = Context.getArrayDecayedType(VaListType);
8903     // Make sure the input expression also decays appropriately.
8904     ExprResult Result = UsualUnaryConversions(E);
8905     if (Result.isInvalid())
8906       return ExprError();
8907     E = Result.take();
8908   } else {
8909     // Otherwise, the va_list argument must be an l-value because
8910     // it is modified by va_arg.
8911     if (!E->isTypeDependent() &&
8912         CheckForModifiableLvalue(E, BuiltinLoc, *this))
8913       return ExprError();
8914   }
8915 
8916   if (!E->isTypeDependent() &&
8917       !Context.hasSameType(VaListType, E->getType())) {
8918     return ExprError(Diag(E->getLocStart(),
8919                          diag::err_first_argument_to_va_arg_not_of_type_va_list)
8920       << OrigExpr->getType() << E->getSourceRange());
8921   }
8922 
8923   if (!TInfo->getType()->isDependentType()) {
8924     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
8925           PDiag(diag::err_second_parameter_to_va_arg_incomplete)
8926           << TInfo->getTypeLoc().getSourceRange()))
8927       return ExprError();
8928 
8929     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
8930           TInfo->getType(),
8931           PDiag(diag::err_second_parameter_to_va_arg_abstract)
8932           << TInfo->getTypeLoc().getSourceRange()))
8933       return ExprError();
8934 
8935     if (!TInfo->getType().isPODType(Context)) {
8936       Diag(TInfo->getTypeLoc().getBeginLoc(),
8937            TInfo->getType()->isObjCLifetimeType()
8938              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
8939              : diag::warn_second_parameter_to_va_arg_not_pod)
8940         << TInfo->getType()
8941         << TInfo->getTypeLoc().getSourceRange();
8942     }
8943 
8944     // Check for va_arg where arguments of the given type will be promoted
8945     // (i.e. this va_arg is guaranteed to have undefined behavior).
8946     QualType PromoteType;
8947     if (TInfo->getType()->isPromotableIntegerType()) {
8948       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
8949       if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
8950         PromoteType = QualType();
8951     }
8952     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
8953       PromoteType = Context.DoubleTy;
8954     if (!PromoteType.isNull())
8955       Diag(TInfo->getTypeLoc().getBeginLoc(),
8956           diag::warn_second_parameter_to_va_arg_never_compatible)
8957         << TInfo->getType()
8958         << PromoteType
8959         << TInfo->getTypeLoc().getSourceRange();
8960   }
8961 
8962   QualType T = TInfo->getType().getNonLValueExprType(Context);
8963   return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
8964 }
8965 
8966 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
8967   // The type of __null will be int or long, depending on the size of
8968   // pointers on the target.
8969   QualType Ty;
8970   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
8971   if (pw == Context.getTargetInfo().getIntWidth())
8972     Ty = Context.IntTy;
8973   else if (pw == Context.getTargetInfo().getLongWidth())
8974     Ty = Context.LongTy;
8975   else if (pw == Context.getTargetInfo().getLongLongWidth())
8976     Ty = Context.LongLongTy;
8977   else {
8978     llvm_unreachable("I don't know size of pointer!");
8979   }
8980 
8981   return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
8982 }
8983 
8984 static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
8985                                            Expr *SrcExpr, FixItHint &Hint) {
8986   if (!SemaRef.getLangOptions().ObjC1)
8987     return;
8988 
8989   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
8990   if (!PT)
8991     return;
8992 
8993   // Check if the destination is of type 'id'.
8994   if (!PT->isObjCIdType()) {
8995     // Check if the destination is the 'NSString' interface.
8996     const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
8997     if (!ID || !ID->getIdentifier()->isStr("NSString"))
8998       return;
8999   }
9000 
9001   // Ignore any parens, implicit casts (should only be
9002   // array-to-pointer decays), and not-so-opaque values.  The last is
9003   // important for making this trigger for property assignments.
9004   SrcExpr = SrcExpr->IgnoreParenImpCasts();
9005   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
9006     if (OV->getSourceExpr())
9007       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
9008 
9009   StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
9010   if (!SL || !SL->isAscii())
9011     return;
9012 
9013   Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
9014 }
9015 
9016 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
9017                                     SourceLocation Loc,
9018                                     QualType DstType, QualType SrcType,
9019                                     Expr *SrcExpr, AssignmentAction Action,
9020                                     bool *Complained) {
9021   if (Complained)
9022     *Complained = false;
9023 
9024   // Decode the result (notice that AST's are still created for extensions).
9025   bool CheckInferredResultType = false;
9026   bool isInvalid = false;
9027   unsigned DiagKind;
9028   FixItHint Hint;
9029   ConversionFixItGenerator ConvHints;
9030   bool MayHaveConvFixit = false;
9031 
9032   switch (ConvTy) {
9033   default: llvm_unreachable("Unknown conversion type");
9034   case Compatible: return false;
9035   case PointerToInt:
9036     DiagKind = diag::ext_typecheck_convert_pointer_int;
9037     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9038     MayHaveConvFixit = true;
9039     break;
9040   case IntToPointer:
9041     DiagKind = diag::ext_typecheck_convert_int_pointer;
9042     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9043     MayHaveConvFixit = true;
9044     break;
9045   case IncompatiblePointer:
9046     MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
9047     DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
9048     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
9049       SrcType->isObjCObjectPointerType();
9050     if (Hint.isNull() && !CheckInferredResultType) {
9051       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9052     }
9053     MayHaveConvFixit = true;
9054     break;
9055   case IncompatiblePointerSign:
9056     DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
9057     break;
9058   case FunctionVoidPointer:
9059     DiagKind = diag::ext_typecheck_convert_pointer_void_func;
9060     break;
9061   case IncompatiblePointerDiscardsQualifiers: {
9062     // Perform array-to-pointer decay if necessary.
9063     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
9064 
9065     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
9066     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
9067     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
9068       DiagKind = diag::err_typecheck_incompatible_address_space;
9069       break;
9070 
9071 
9072     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
9073       DiagKind = diag::err_typecheck_incompatible_ownership;
9074       break;
9075     }
9076 
9077     llvm_unreachable("unknown error case for discarding qualifiers!");
9078     // fallthrough
9079   }
9080   case CompatiblePointerDiscardsQualifiers:
9081     // If the qualifiers lost were because we were applying the
9082     // (deprecated) C++ conversion from a string literal to a char*
9083     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
9084     // Ideally, this check would be performed in
9085     // checkPointerTypesForAssignment. However, that would require a
9086     // bit of refactoring (so that the second argument is an
9087     // expression, rather than a type), which should be done as part
9088     // of a larger effort to fix checkPointerTypesForAssignment for
9089     // C++ semantics.
9090     if (getLangOptions().CPlusPlus &&
9091         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
9092       return false;
9093     DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
9094     break;
9095   case IncompatibleNestedPointerQualifiers:
9096     DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
9097     break;
9098   case IntToBlockPointer:
9099     DiagKind = diag::err_int_to_block_pointer;
9100     break;
9101   case IncompatibleBlockPointer:
9102     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
9103     break;
9104   case IncompatibleObjCQualifiedId:
9105     // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
9106     // it can give a more specific diagnostic.
9107     DiagKind = diag::warn_incompatible_qualified_id;
9108     break;
9109   case IncompatibleVectors:
9110     DiagKind = diag::warn_incompatible_vectors;
9111     break;
9112   case IncompatibleObjCWeakRef:
9113     DiagKind = diag::err_arc_weak_unavailable_assign;
9114     break;
9115   case Incompatible:
9116     DiagKind = diag::err_typecheck_convert_incompatible;
9117     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9118     MayHaveConvFixit = true;
9119     isInvalid = true;
9120     break;
9121   }
9122 
9123   QualType FirstType, SecondType;
9124   switch (Action) {
9125   case AA_Assigning:
9126   case AA_Initializing:
9127     // The destination type comes first.
9128     FirstType = DstType;
9129     SecondType = SrcType;
9130     break;
9131 
9132   case AA_Returning:
9133   case AA_Passing:
9134   case AA_Converting:
9135   case AA_Sending:
9136   case AA_Casting:
9137     // The source type comes first.
9138     FirstType = SrcType;
9139     SecondType = DstType;
9140     break;
9141   }
9142 
9143   PartialDiagnostic FDiag = PDiag(DiagKind);
9144   FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
9145 
9146   // If we can fix the conversion, suggest the FixIts.
9147   assert(ConvHints.isNull() || Hint.isNull());
9148   if (!ConvHints.isNull()) {
9149     for (llvm::SmallVector<FixItHint, 1>::iterator
9150         HI = ConvHints.Hints.begin(), HE = ConvHints.Hints.end();
9151         HI != HE; ++HI)
9152       FDiag << *HI;
9153   } else {
9154     FDiag << Hint;
9155   }
9156   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
9157 
9158   Diag(Loc, FDiag);
9159 
9160   if (CheckInferredResultType)
9161     EmitRelatedResultTypeNote(SrcExpr);
9162 
9163   if (Complained)
9164     *Complained = true;
9165   return isInvalid;
9166 }
9167 
9168 bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
9169   llvm::APSInt ICEResult;
9170   if (E->isIntegerConstantExpr(ICEResult, Context)) {
9171     if (Result)
9172       *Result = ICEResult;
9173     return false;
9174   }
9175 
9176   Expr::EvalResult EvalResult;
9177 
9178   if (!E->EvaluateAsRValue(EvalResult, Context) || !EvalResult.Val.isInt() ||
9179       EvalResult.HasSideEffects) {
9180     Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
9181 
9182     if (EvalResult.Diag) {
9183       // We only show the note if it's not the usual "invalid subexpression"
9184       // or if it's actually in a subexpression.
9185       if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
9186           E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
9187         Diag(EvalResult.DiagLoc, EvalResult.Diag);
9188     }
9189 
9190     return true;
9191   }
9192 
9193   Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
9194     E->getSourceRange();
9195 
9196   if (EvalResult.Diag &&
9197       Diags.getDiagnosticLevel(diag::ext_expr_not_ice, EvalResult.DiagLoc)
9198           != DiagnosticsEngine::Ignored)
9199     Diag(EvalResult.DiagLoc, EvalResult.Diag);
9200 
9201   if (Result)
9202     *Result = EvalResult.Val.getInt();
9203   return false;
9204 }
9205 
9206 void
9207 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
9208   ExprEvalContexts.push_back(
9209              ExpressionEvaluationContextRecord(NewContext,
9210                                                ExprCleanupObjects.size(),
9211                                                ExprNeedsCleanups));
9212   ExprNeedsCleanups = false;
9213 }
9214 
9215 void Sema::PopExpressionEvaluationContext() {
9216   // Pop the current expression evaluation context off the stack.
9217   ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back();
9218   ExprEvalContexts.pop_back();
9219 
9220   if (Rec.Context == PotentiallyPotentiallyEvaluated) {
9221     if (Rec.PotentiallyReferenced) {
9222       // Mark any remaining declarations in the current position of the stack
9223       // as "referenced". If they were not meant to be referenced, semantic
9224       // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
9225       for (PotentiallyReferencedDecls::iterator
9226              I = Rec.PotentiallyReferenced->begin(),
9227              IEnd = Rec.PotentiallyReferenced->end();
9228            I != IEnd; ++I)
9229         MarkDeclarationReferenced(I->first, I->second);
9230     }
9231 
9232     if (Rec.PotentiallyDiagnosed) {
9233       // Emit any pending diagnostics.
9234       for (PotentiallyEmittedDiagnostics::iterator
9235                 I = Rec.PotentiallyDiagnosed->begin(),
9236              IEnd = Rec.PotentiallyDiagnosed->end();
9237            I != IEnd; ++I)
9238         Diag(I->first, I->second);
9239     }
9240   }
9241 
9242   // When are coming out of an unevaluated context, clear out any
9243   // temporaries that we may have created as part of the evaluation of
9244   // the expression in that context: they aren't relevant because they
9245   // will never be constructed.
9246   if (Rec.Context == Unevaluated) {
9247     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
9248                              ExprCleanupObjects.end());
9249     ExprNeedsCleanups = Rec.ParentNeedsCleanups;
9250 
9251   // Otherwise, merge the contexts together.
9252   } else {
9253     ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
9254   }
9255 
9256   // Destroy the popped expression evaluation record.
9257   Rec.Destroy();
9258 }
9259 
9260 void Sema::DiscardCleanupsInEvaluationContext() {
9261   ExprCleanupObjects.erase(
9262          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
9263          ExprCleanupObjects.end());
9264   ExprNeedsCleanups = false;
9265 }
9266 
9267 /// \brief Note that the given declaration was referenced in the source code.
9268 ///
9269 /// This routine should be invoke whenever a given declaration is referenced
9270 /// in the source code, and where that reference occurred. If this declaration
9271 /// reference means that the the declaration is used (C++ [basic.def.odr]p2,
9272 /// C99 6.9p3), then the declaration will be marked as used.
9273 ///
9274 /// \param Loc the location where the declaration was referenced.
9275 ///
9276 /// \param D the declaration that has been referenced by the source code.
9277 void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
9278   assert(D && "No declaration?");
9279 
9280   D->setReferenced();
9281 
9282   if (D->isUsed(false))
9283     return;
9284 
9285   // Mark a parameter or variable declaration "used", regardless of whether
9286   // we're in a template or not. The reason for this is that unevaluated
9287   // expressions (e.g. (void)sizeof()) constitute a use for warning purposes
9288   // (-Wunused-variables and -Wunused-parameters)
9289   if (isa<ParmVarDecl>(D) ||
9290       (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod())) {
9291     D->setUsed();
9292     return;
9293   }
9294 
9295   if (!isa<VarDecl>(D) && !isa<FunctionDecl>(D))
9296     return;
9297 
9298   // Do not mark anything as "used" within a dependent context; wait for
9299   // an instantiation.
9300   if (CurContext->isDependentContext())
9301     return;
9302 
9303   switch (ExprEvalContexts.back().Context) {
9304     case Unevaluated:
9305       // We are in an expression that is not potentially evaluated; do nothing.
9306       return;
9307 
9308     case PotentiallyEvaluated:
9309       // We are in a potentially-evaluated expression, so this declaration is
9310       // "used"; handle this below.
9311       break;
9312 
9313     case PotentiallyPotentiallyEvaluated:
9314       // We are in an expression that may be potentially evaluated; queue this
9315       // declaration reference until we know whether the expression is
9316       // potentially evaluated.
9317       ExprEvalContexts.back().addReferencedDecl(Loc, D);
9318       return;
9319 
9320     case PotentiallyEvaluatedIfUsed:
9321       // Referenced declarations will only be used if the construct in the
9322       // containing expression is used.
9323       return;
9324   }
9325 
9326   // Note that this declaration has been used.
9327   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
9328     if (Constructor->isDefaulted()) {
9329       if (Constructor->isDefaultConstructor()) {
9330         if (Constructor->isTrivial())
9331           return;
9332         if (!Constructor->isUsed(false))
9333           DefineImplicitDefaultConstructor(Loc, Constructor);
9334       } else if (Constructor->isCopyConstructor()) {
9335         if (!Constructor->isUsed(false))
9336           DefineImplicitCopyConstructor(Loc, Constructor);
9337       } else if (Constructor->isMoveConstructor()) {
9338         if (!Constructor->isUsed(false))
9339           DefineImplicitMoveConstructor(Loc, Constructor);
9340       }
9341     }
9342 
9343     MarkVTableUsed(Loc, Constructor->getParent());
9344   } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
9345     if (Destructor->isDefaulted() && !Destructor->isUsed(false))
9346       DefineImplicitDestructor(Loc, Destructor);
9347     if (Destructor->isVirtual())
9348       MarkVTableUsed(Loc, Destructor->getParent());
9349   } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
9350     if (MethodDecl->isDefaulted() && MethodDecl->isOverloadedOperator() &&
9351         MethodDecl->getOverloadedOperator() == OO_Equal) {
9352       if (!MethodDecl->isUsed(false)) {
9353         if (MethodDecl->isCopyAssignmentOperator())
9354           DefineImplicitCopyAssignment(Loc, MethodDecl);
9355         else
9356           DefineImplicitMoveAssignment(Loc, MethodDecl);
9357       }
9358     } else if (MethodDecl->isVirtual())
9359       MarkVTableUsed(Loc, MethodDecl->getParent());
9360   }
9361   if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
9362     // Recursive functions should be marked when used from another function.
9363     if (CurContext == Function) return;
9364 
9365     // Implicit instantiation of function templates and member functions of
9366     // class templates.
9367     if (Function->isImplicitlyInstantiable()) {
9368       bool AlreadyInstantiated = false;
9369       if (FunctionTemplateSpecializationInfo *SpecInfo
9370                                 = Function->getTemplateSpecializationInfo()) {
9371         if (SpecInfo->getPointOfInstantiation().isInvalid())
9372           SpecInfo->setPointOfInstantiation(Loc);
9373         else if (SpecInfo->getTemplateSpecializationKind()
9374                    == TSK_ImplicitInstantiation)
9375           AlreadyInstantiated = true;
9376       } else if (MemberSpecializationInfo *MSInfo
9377                                   = Function->getMemberSpecializationInfo()) {
9378         if (MSInfo->getPointOfInstantiation().isInvalid())
9379           MSInfo->setPointOfInstantiation(Loc);
9380         else if (MSInfo->getTemplateSpecializationKind()
9381                    == TSK_ImplicitInstantiation)
9382           AlreadyInstantiated = true;
9383       }
9384 
9385       if (!AlreadyInstantiated) {
9386         if (isa<CXXRecordDecl>(Function->getDeclContext()) &&
9387             cast<CXXRecordDecl>(Function->getDeclContext())->isLocalClass())
9388           PendingLocalImplicitInstantiations.push_back(std::make_pair(Function,
9389                                                                       Loc));
9390         else
9391           PendingInstantiations.push_back(std::make_pair(Function, Loc));
9392       }
9393     } else {
9394       // Walk redefinitions, as some of them may be instantiable.
9395       for (FunctionDecl::redecl_iterator i(Function->redecls_begin()),
9396            e(Function->redecls_end()); i != e; ++i) {
9397         if (!i->isUsed(false) && i->isImplicitlyInstantiable())
9398           MarkDeclarationReferenced(Loc, *i);
9399       }
9400     }
9401 
9402     // Keep track of used but undefined functions.
9403     if (!Function->isPure() && !Function->hasBody() &&
9404         Function->getLinkage() != ExternalLinkage) {
9405       SourceLocation &old = UndefinedInternals[Function->getCanonicalDecl()];
9406       if (old.isInvalid()) old = Loc;
9407     }
9408 
9409     Function->setUsed(true);
9410     return;
9411   }
9412 
9413   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
9414     // Implicit instantiation of static data members of class templates.
9415     if (Var->isStaticDataMember() &&
9416         Var->getInstantiatedFromStaticDataMember()) {
9417       MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
9418       assert(MSInfo && "Missing member specialization information?");
9419       if (MSInfo->getPointOfInstantiation().isInvalid() &&
9420           MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
9421         MSInfo->setPointOfInstantiation(Loc);
9422         // This is a modification of an existing AST node. Notify listeners.
9423         if (ASTMutationListener *L = getASTMutationListener())
9424           L->StaticDataMemberInstantiated(Var);
9425         PendingInstantiations.push_back(std::make_pair(Var, Loc));
9426       }
9427     }
9428 
9429     // Keep track of used but undefined variables.  We make a hole in
9430     // the warning for static const data members with in-line
9431     // initializers.
9432     if (Var->hasDefinition() == VarDecl::DeclarationOnly
9433         && Var->getLinkage() != ExternalLinkage
9434         && !(Var->isStaticDataMember() && Var->hasInit())) {
9435       SourceLocation &old = UndefinedInternals[Var->getCanonicalDecl()];
9436       if (old.isInvalid()) old = Loc;
9437     }
9438 
9439     D->setUsed(true);
9440     return;
9441   }
9442 }
9443 
9444 namespace {
9445   // Mark all of the declarations referenced
9446   // FIXME: Not fully implemented yet! We need to have a better understanding
9447   // of when we're entering
9448   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
9449     Sema &S;
9450     SourceLocation Loc;
9451 
9452   public:
9453     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
9454 
9455     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
9456 
9457     bool TraverseTemplateArgument(const TemplateArgument &Arg);
9458     bool TraverseRecordType(RecordType *T);
9459   };
9460 }
9461 
9462 bool MarkReferencedDecls::TraverseTemplateArgument(
9463   const TemplateArgument &Arg) {
9464   if (Arg.getKind() == TemplateArgument::Declaration) {
9465     S.MarkDeclarationReferenced(Loc, Arg.getAsDecl());
9466   }
9467 
9468   return Inherited::TraverseTemplateArgument(Arg);
9469 }
9470 
9471 bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
9472   if (ClassTemplateSpecializationDecl *Spec
9473                   = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
9474     const TemplateArgumentList &Args = Spec->getTemplateArgs();
9475     return TraverseTemplateArguments(Args.data(), Args.size());
9476   }
9477 
9478   return true;
9479 }
9480 
9481 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
9482   MarkReferencedDecls Marker(*this, Loc);
9483   Marker.TraverseType(Context.getCanonicalType(T));
9484 }
9485 
9486 namespace {
9487   /// \brief Helper class that marks all of the declarations referenced by
9488   /// potentially-evaluated subexpressions as "referenced".
9489   class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
9490     Sema &S;
9491 
9492   public:
9493     typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
9494 
9495     explicit EvaluatedExprMarker(Sema &S) : Inherited(S.Context), S(S) { }
9496 
9497     void VisitDeclRefExpr(DeclRefExpr *E) {
9498       S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9499     }
9500 
9501     void VisitMemberExpr(MemberExpr *E) {
9502       S.MarkDeclarationReferenced(E->getMemberLoc(), E->getMemberDecl());
9503       Inherited::VisitMemberExpr(E);
9504     }
9505 
9506     void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
9507       S.MarkDeclarationReferenced(E->getLocStart(),
9508             const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
9509       Visit(E->getSubExpr());
9510     }
9511 
9512     void VisitCXXNewExpr(CXXNewExpr *E) {
9513       if (E->getConstructor())
9514         S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
9515       if (E->getOperatorNew())
9516         S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorNew());
9517       if (E->getOperatorDelete())
9518         S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
9519       Inherited::VisitCXXNewExpr(E);
9520     }
9521 
9522     void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
9523       if (E->getOperatorDelete())
9524         S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
9525       QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
9526       if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
9527         CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
9528         S.MarkDeclarationReferenced(E->getLocStart(),
9529                                     S.LookupDestructor(Record));
9530       }
9531 
9532       Inherited::VisitCXXDeleteExpr(E);
9533     }
9534 
9535     void VisitCXXConstructExpr(CXXConstructExpr *E) {
9536       S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
9537       Inherited::VisitCXXConstructExpr(E);
9538     }
9539 
9540     void VisitBlockDeclRefExpr(BlockDeclRefExpr *E) {
9541       S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9542     }
9543 
9544     void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
9545       Visit(E->getExpr());
9546     }
9547   };
9548 }
9549 
9550 /// \brief Mark any declarations that appear within this expression or any
9551 /// potentially-evaluated subexpressions as "referenced".
9552 void Sema::MarkDeclarationsReferencedInExpr(Expr *E) {
9553   EvaluatedExprMarker(*this).Visit(E);
9554 }
9555 
9556 /// \brief Emit a diagnostic that describes an effect on the run-time behavior
9557 /// of the program being compiled.
9558 ///
9559 /// This routine emits the given diagnostic when the code currently being
9560 /// type-checked is "potentially evaluated", meaning that there is a
9561 /// possibility that the code will actually be executable. Code in sizeof()
9562 /// expressions, code used only during overload resolution, etc., are not
9563 /// potentially evaluated. This routine will suppress such diagnostics or,
9564 /// in the absolutely nutty case of potentially potentially evaluated
9565 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
9566 /// later.
9567 ///
9568 /// This routine should be used for all diagnostics that describe the run-time
9569 /// behavior of a program, such as passing a non-POD value through an ellipsis.
9570 /// Failure to do so will likely result in spurious diagnostics or failures
9571 /// during overload resolution or within sizeof/alignof/typeof/typeid.
9572 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
9573                                const PartialDiagnostic &PD) {
9574   switch (ExprEvalContexts.back().Context) {
9575   case Unevaluated:
9576     // The argument will never be evaluated, so don't complain.
9577     break;
9578 
9579   case PotentiallyEvaluated:
9580   case PotentiallyEvaluatedIfUsed:
9581     if (Statement && getCurFunctionOrMethodDecl()) {
9582       FunctionScopes.back()->PossiblyUnreachableDiags.
9583         push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
9584     }
9585     else
9586       Diag(Loc, PD);
9587 
9588     return true;
9589 
9590   case PotentiallyPotentiallyEvaluated:
9591     ExprEvalContexts.back().addDiagnostic(Loc, PD);
9592     break;
9593   }
9594 
9595   return false;
9596 }
9597 
9598 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
9599                                CallExpr *CE, FunctionDecl *FD) {
9600   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
9601     return false;
9602 
9603   PartialDiagnostic Note =
9604     FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
9605     << FD->getDeclName() : PDiag();
9606   SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
9607 
9608   if (RequireCompleteType(Loc, ReturnType,
9609                           FD ?
9610                           PDiag(diag::err_call_function_incomplete_return)
9611                             << CE->getSourceRange() << FD->getDeclName() :
9612                           PDiag(diag::err_call_incomplete_return)
9613                             << CE->getSourceRange(),
9614                           std::make_pair(NoteLoc, Note)))
9615     return true;
9616 
9617   return false;
9618 }
9619 
9620 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
9621 // will prevent this condition from triggering, which is what we want.
9622 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
9623   SourceLocation Loc;
9624 
9625   unsigned diagnostic = diag::warn_condition_is_assignment;
9626   bool IsOrAssign = false;
9627 
9628   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
9629     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
9630       return;
9631 
9632     IsOrAssign = Op->getOpcode() == BO_OrAssign;
9633 
9634     // Greylist some idioms by putting them into a warning subcategory.
9635     if (ObjCMessageExpr *ME
9636           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
9637       Selector Sel = ME->getSelector();
9638 
9639       // self = [<foo> init...]
9640       if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init"))
9641         diagnostic = diag::warn_condition_is_idiomatic_assignment;
9642 
9643       // <foo> = [<bar> nextObject]
9644       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
9645         diagnostic = diag::warn_condition_is_idiomatic_assignment;
9646     }
9647 
9648     Loc = Op->getOperatorLoc();
9649   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
9650     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
9651       return;
9652 
9653     IsOrAssign = Op->getOperator() == OO_PipeEqual;
9654     Loc = Op->getOperatorLoc();
9655   } else {
9656     // Not an assignment.
9657     return;
9658   }
9659 
9660   Diag(Loc, diagnostic) << E->getSourceRange();
9661 
9662   SourceLocation Open = E->getSourceRange().getBegin();
9663   SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
9664   Diag(Loc, diag::note_condition_assign_silence)
9665         << FixItHint::CreateInsertion(Open, "(")
9666         << FixItHint::CreateInsertion(Close, ")");
9667 
9668   if (IsOrAssign)
9669     Diag(Loc, diag::note_condition_or_assign_to_comparison)
9670       << FixItHint::CreateReplacement(Loc, "!=");
9671   else
9672     Diag(Loc, diag::note_condition_assign_to_comparison)
9673       << FixItHint::CreateReplacement(Loc, "==");
9674 }
9675 
9676 /// \brief Redundant parentheses over an equality comparison can indicate
9677 /// that the user intended an assignment used as condition.
9678 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
9679   // Don't warn if the parens came from a macro.
9680   SourceLocation parenLoc = ParenE->getLocStart();
9681   if (parenLoc.isInvalid() || parenLoc.isMacroID())
9682     return;
9683   // Don't warn for dependent expressions.
9684   if (ParenE->isTypeDependent())
9685     return;
9686 
9687   Expr *E = ParenE->IgnoreParens();
9688 
9689   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
9690     if (opE->getOpcode() == BO_EQ &&
9691         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
9692                                                            == Expr::MLV_Valid) {
9693       SourceLocation Loc = opE->getOperatorLoc();
9694 
9695       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
9696       Diag(Loc, diag::note_equality_comparison_silence)
9697         << FixItHint::CreateRemoval(ParenE->getSourceRange().getBegin())
9698         << FixItHint::CreateRemoval(ParenE->getSourceRange().getEnd());
9699       Diag(Loc, diag::note_equality_comparison_to_assign)
9700         << FixItHint::CreateReplacement(Loc, "=");
9701     }
9702 }
9703 
9704 ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
9705   DiagnoseAssignmentAsCondition(E);
9706   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
9707     DiagnoseEqualityWithExtraParens(parenE);
9708 
9709   ExprResult result = CheckPlaceholderExpr(E);
9710   if (result.isInvalid()) return ExprError();
9711   E = result.take();
9712 
9713   if (!E->isTypeDependent()) {
9714     if (getLangOptions().CPlusPlus)
9715       return CheckCXXBooleanCondition(E); // C++ 6.4p4
9716 
9717     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
9718     if (ERes.isInvalid())
9719       return ExprError();
9720     E = ERes.take();
9721 
9722     QualType T = E->getType();
9723     if (!T->isScalarType()) { // C99 6.8.4.1p1
9724       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
9725         << T << E->getSourceRange();
9726       return ExprError();
9727     }
9728   }
9729 
9730   return Owned(E);
9731 }
9732 
9733 ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
9734                                        Expr *SubExpr) {
9735   if (!SubExpr)
9736     return ExprError();
9737 
9738   return CheckBooleanCondition(SubExpr, Loc);
9739 }
9740 
9741 namespace {
9742   /// A visitor for rebuilding a call to an __unknown_any expression
9743   /// to have an appropriate type.
9744   struct RebuildUnknownAnyFunction
9745     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
9746 
9747     Sema &S;
9748 
9749     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
9750 
9751     ExprResult VisitStmt(Stmt *S) {
9752       llvm_unreachable("unexpected statement!");
9753       return ExprError();
9754     }
9755 
9756     ExprResult VisitExpr(Expr *E) {
9757       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
9758         << E->getSourceRange();
9759       return ExprError();
9760     }
9761 
9762     /// Rebuild an expression which simply semantically wraps another
9763     /// expression which it shares the type and value kind of.
9764     template <class T> ExprResult rebuildSugarExpr(T *E) {
9765       ExprResult SubResult = Visit(E->getSubExpr());
9766       if (SubResult.isInvalid()) return ExprError();
9767 
9768       Expr *SubExpr = SubResult.take();
9769       E->setSubExpr(SubExpr);
9770       E->setType(SubExpr->getType());
9771       E->setValueKind(SubExpr->getValueKind());
9772       assert(E->getObjectKind() == OK_Ordinary);
9773       return E;
9774     }
9775 
9776     ExprResult VisitParenExpr(ParenExpr *E) {
9777       return rebuildSugarExpr(E);
9778     }
9779 
9780     ExprResult VisitUnaryExtension(UnaryOperator *E) {
9781       return rebuildSugarExpr(E);
9782     }
9783 
9784     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
9785       ExprResult SubResult = Visit(E->getSubExpr());
9786       if (SubResult.isInvalid()) return ExprError();
9787 
9788       Expr *SubExpr = SubResult.take();
9789       E->setSubExpr(SubExpr);
9790       E->setType(S.Context.getPointerType(SubExpr->getType()));
9791       assert(E->getValueKind() == VK_RValue);
9792       assert(E->getObjectKind() == OK_Ordinary);
9793       return E;
9794     }
9795 
9796     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
9797       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
9798 
9799       E->setType(VD->getType());
9800 
9801       assert(E->getValueKind() == VK_RValue);
9802       if (S.getLangOptions().CPlusPlus &&
9803           !(isa<CXXMethodDecl>(VD) &&
9804             cast<CXXMethodDecl>(VD)->isInstance()))
9805         E->setValueKind(VK_LValue);
9806 
9807       return E;
9808     }
9809 
9810     ExprResult VisitMemberExpr(MemberExpr *E) {
9811       return resolveDecl(E, E->getMemberDecl());
9812     }
9813 
9814     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
9815       return resolveDecl(E, E->getDecl());
9816     }
9817   };
9818 }
9819 
9820 /// Given a function expression of unknown-any type, try to rebuild it
9821 /// to have a function type.
9822 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
9823   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
9824   if (Result.isInvalid()) return ExprError();
9825   return S.DefaultFunctionArrayConversion(Result.take());
9826 }
9827 
9828 namespace {
9829   /// A visitor for rebuilding an expression of type __unknown_anytype
9830   /// into one which resolves the type directly on the referring
9831   /// expression.  Strict preservation of the original source
9832   /// structure is not a goal.
9833   struct RebuildUnknownAnyExpr
9834     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
9835 
9836     Sema &S;
9837 
9838     /// The current destination type.
9839     QualType DestType;
9840 
9841     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
9842       : S(S), DestType(CastType) {}
9843 
9844     ExprResult VisitStmt(Stmt *S) {
9845       llvm_unreachable("unexpected statement!");
9846       return ExprError();
9847     }
9848 
9849     ExprResult VisitExpr(Expr *E) {
9850       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
9851         << E->getSourceRange();
9852       return ExprError();
9853     }
9854 
9855     ExprResult VisitCallExpr(CallExpr *E);
9856     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
9857 
9858     /// Rebuild an expression which simply semantically wraps another
9859     /// expression which it shares the type and value kind of.
9860     template <class T> ExprResult rebuildSugarExpr(T *E) {
9861       ExprResult SubResult = Visit(E->getSubExpr());
9862       if (SubResult.isInvalid()) return ExprError();
9863       Expr *SubExpr = SubResult.take();
9864       E->setSubExpr(SubExpr);
9865       E->setType(SubExpr->getType());
9866       E->setValueKind(SubExpr->getValueKind());
9867       assert(E->getObjectKind() == OK_Ordinary);
9868       return E;
9869     }
9870 
9871     ExprResult VisitParenExpr(ParenExpr *E) {
9872       return rebuildSugarExpr(E);
9873     }
9874 
9875     ExprResult VisitUnaryExtension(UnaryOperator *E) {
9876       return rebuildSugarExpr(E);
9877     }
9878 
9879     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
9880       const PointerType *Ptr = DestType->getAs<PointerType>();
9881       if (!Ptr) {
9882         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
9883           << E->getSourceRange();
9884         return ExprError();
9885       }
9886       assert(E->getValueKind() == VK_RValue);
9887       assert(E->getObjectKind() == OK_Ordinary);
9888       E->setType(DestType);
9889 
9890       // Build the sub-expression as if it were an object of the pointee type.
9891       DestType = Ptr->getPointeeType();
9892       ExprResult SubResult = Visit(E->getSubExpr());
9893       if (SubResult.isInvalid()) return ExprError();
9894       E->setSubExpr(SubResult.take());
9895       return E;
9896     }
9897 
9898     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
9899 
9900     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
9901 
9902     ExprResult VisitMemberExpr(MemberExpr *E) {
9903       return resolveDecl(E, E->getMemberDecl());
9904     }
9905 
9906     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
9907       return resolveDecl(E, E->getDecl());
9908     }
9909   };
9910 }
9911 
9912 /// Rebuilds a call expression which yielded __unknown_anytype.
9913 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
9914   Expr *CalleeExpr = E->getCallee();
9915 
9916   enum FnKind {
9917     FK_MemberFunction,
9918     FK_FunctionPointer,
9919     FK_BlockPointer
9920   };
9921 
9922   FnKind Kind;
9923   QualType CalleeType = CalleeExpr->getType();
9924   if (CalleeType == S.Context.BoundMemberTy) {
9925     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
9926     Kind = FK_MemberFunction;
9927     CalleeType = Expr::findBoundMemberType(CalleeExpr);
9928   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
9929     CalleeType = Ptr->getPointeeType();
9930     Kind = FK_FunctionPointer;
9931   } else {
9932     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
9933     Kind = FK_BlockPointer;
9934   }
9935   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
9936 
9937   // Verify that this is a legal result type of a function.
9938   if (DestType->isArrayType() || DestType->isFunctionType()) {
9939     unsigned diagID = diag::err_func_returning_array_function;
9940     if (Kind == FK_BlockPointer)
9941       diagID = diag::err_block_returning_array_function;
9942 
9943     S.Diag(E->getExprLoc(), diagID)
9944       << DestType->isFunctionType() << DestType;
9945     return ExprError();
9946   }
9947 
9948   // Otherwise, go ahead and set DestType as the call's result.
9949   E->setType(DestType.getNonLValueExprType(S.Context));
9950   E->setValueKind(Expr::getValueKindForType(DestType));
9951   assert(E->getObjectKind() == OK_Ordinary);
9952 
9953   // Rebuild the function type, replacing the result type with DestType.
9954   if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType))
9955     DestType = S.Context.getFunctionType(DestType,
9956                                          Proto->arg_type_begin(),
9957                                          Proto->getNumArgs(),
9958                                          Proto->getExtProtoInfo());
9959   else
9960     DestType = S.Context.getFunctionNoProtoType(DestType,
9961                                                 FnType->getExtInfo());
9962 
9963   // Rebuild the appropriate pointer-to-function type.
9964   switch (Kind) {
9965   case FK_MemberFunction:
9966     // Nothing to do.
9967     break;
9968 
9969   case FK_FunctionPointer:
9970     DestType = S.Context.getPointerType(DestType);
9971     break;
9972 
9973   case FK_BlockPointer:
9974     DestType = S.Context.getBlockPointerType(DestType);
9975     break;
9976   }
9977 
9978   // Finally, we can recurse.
9979   ExprResult CalleeResult = Visit(CalleeExpr);
9980   if (!CalleeResult.isUsable()) return ExprError();
9981   E->setCallee(CalleeResult.take());
9982 
9983   // Bind a temporary if necessary.
9984   return S.MaybeBindToTemporary(E);
9985 }
9986 
9987 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
9988   // Verify that this is a legal result type of a call.
9989   if (DestType->isArrayType() || DestType->isFunctionType()) {
9990     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
9991       << DestType->isFunctionType() << DestType;
9992     return ExprError();
9993   }
9994 
9995   // Rewrite the method result type if available.
9996   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
9997     assert(Method->getResultType() == S.Context.UnknownAnyTy);
9998     Method->setResultType(DestType);
9999   }
10000 
10001   // Change the type of the message.
10002   E->setType(DestType.getNonReferenceType());
10003   E->setValueKind(Expr::getValueKindForType(DestType));
10004 
10005   return S.MaybeBindToTemporary(E);
10006 }
10007 
10008 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
10009   // The only case we should ever see here is a function-to-pointer decay.
10010   assert(E->getCastKind() == CK_FunctionToPointerDecay);
10011   assert(E->getValueKind() == VK_RValue);
10012   assert(E->getObjectKind() == OK_Ordinary);
10013 
10014   E->setType(DestType);
10015 
10016   // Rebuild the sub-expression as the pointee (function) type.
10017   DestType = DestType->castAs<PointerType>()->getPointeeType();
10018 
10019   ExprResult Result = Visit(E->getSubExpr());
10020   if (!Result.isUsable()) return ExprError();
10021 
10022   E->setSubExpr(Result.take());
10023   return S.Owned(E);
10024 }
10025 
10026 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
10027   ExprValueKind ValueKind = VK_LValue;
10028   QualType Type = DestType;
10029 
10030   // We know how to make this work for certain kinds of decls:
10031 
10032   //  - functions
10033   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
10034     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
10035       DestType = Ptr->getPointeeType();
10036       ExprResult Result = resolveDecl(E, VD);
10037       if (Result.isInvalid()) return ExprError();
10038       return S.ImpCastExprToType(Result.take(), Type,
10039                                  CK_FunctionToPointerDecay, VK_RValue);
10040     }
10041 
10042     if (!Type->isFunctionType()) {
10043       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
10044         << VD << E->getSourceRange();
10045       return ExprError();
10046     }
10047 
10048     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
10049       if (MD->isInstance()) {
10050         ValueKind = VK_RValue;
10051         Type = S.Context.BoundMemberTy;
10052       }
10053 
10054     // Function references aren't l-values in C.
10055     if (!S.getLangOptions().CPlusPlus)
10056       ValueKind = VK_RValue;
10057 
10058   //  - variables
10059   } else if (isa<VarDecl>(VD)) {
10060     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
10061       Type = RefTy->getPointeeType();
10062     } else if (Type->isFunctionType()) {
10063       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
10064         << VD << E->getSourceRange();
10065       return ExprError();
10066     }
10067 
10068   //  - nothing else
10069   } else {
10070     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
10071       << VD << E->getSourceRange();
10072     return ExprError();
10073   }
10074 
10075   VD->setType(DestType);
10076   E->setType(Type);
10077   E->setValueKind(ValueKind);
10078   return S.Owned(E);
10079 }
10080 
10081 /// Check a cast of an unknown-any type.  We intentionally only
10082 /// trigger this for C-style casts.
10083 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
10084                                      Expr *CastExpr, CastKind &CastKind,
10085                                      ExprValueKind &VK, CXXCastPath &Path) {
10086   // Rewrite the casted expression from scratch.
10087   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
10088   if (!result.isUsable()) return ExprError();
10089 
10090   CastExpr = result.take();
10091   VK = CastExpr->getValueKind();
10092   CastKind = CK_NoOp;
10093 
10094   return CastExpr;
10095 }
10096 
10097 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
10098   Expr *orig = E;
10099   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
10100   while (true) {
10101     E = E->IgnoreParenImpCasts();
10102     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
10103       E = call->getCallee();
10104       diagID = diag::err_uncasted_call_of_unknown_any;
10105     } else {
10106       break;
10107     }
10108   }
10109 
10110   SourceLocation loc;
10111   NamedDecl *d;
10112   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
10113     loc = ref->getLocation();
10114     d = ref->getDecl();
10115   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
10116     loc = mem->getMemberLoc();
10117     d = mem->getMemberDecl();
10118   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
10119     diagID = diag::err_uncasted_call_of_unknown_any;
10120     loc = msg->getSelectorStartLoc();
10121     d = msg->getMethodDecl();
10122     if (!d) {
10123       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
10124         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
10125         << orig->getSourceRange();
10126       return ExprError();
10127     }
10128   } else {
10129     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
10130       << E->getSourceRange();
10131     return ExprError();
10132   }
10133 
10134   S.Diag(loc, diagID) << d << orig->getSourceRange();
10135 
10136   // Never recoverable.
10137   return ExprError();
10138 }
10139 
10140 /// Check for operands with placeholder types and complain if found.
10141 /// Returns true if there was an error and no recovery was possible.
10142 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
10143   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
10144   if (!placeholderType) return Owned(E);
10145 
10146   switch (placeholderType->getKind()) {
10147 
10148   // Overloaded expressions.
10149   case BuiltinType::Overload: {
10150     // Try to resolve a single function template specialization.
10151     // This is obligatory.
10152     ExprResult result = Owned(E);
10153     if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) {
10154       return result;
10155 
10156     // If that failed, try to recover with a call.
10157     } else {
10158       tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable),
10159                            /*complain*/ true);
10160       return result;
10161     }
10162   }
10163 
10164   // Bound member functions.
10165   case BuiltinType::BoundMember: {
10166     ExprResult result = Owned(E);
10167     tryToRecoverWithCall(result, PDiag(diag::err_bound_member_function),
10168                          /*complain*/ true);
10169     return result;
10170   }
10171 
10172   // ARC unbridged casts.
10173   case BuiltinType::ARCUnbridgedCast: {
10174     Expr *realCast = stripARCUnbridgedCast(E);
10175     diagnoseARCUnbridgedCast(realCast);
10176     return Owned(realCast);
10177   }
10178 
10179   // Expressions of unknown type.
10180   case BuiltinType::UnknownAny:
10181     return diagnoseUnknownAnyExpr(*this, E);
10182 
10183   // Pseudo-objects.
10184   case BuiltinType::PseudoObject:
10185     return checkPseudoObjectRValue(E);
10186 
10187   // Everything else should be impossible.
10188 #define BUILTIN_TYPE(Id, SingletonId) \
10189   case BuiltinType::Id:
10190 #define PLACEHOLDER_TYPE(Id, SingletonId)
10191 #include "clang/AST/BuiltinTypes.def"
10192     break;
10193   }
10194 
10195   llvm_unreachable("invalid placeholder type!");
10196 }
10197 
10198 bool Sema::CheckCaseExpression(Expr *E) {
10199   if (E->isTypeDependent())
10200     return true;
10201   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
10202     return E->getType()->isIntegralOrEnumerationType();
10203   return false;
10204 }
10205