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