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 "TreeTransform.h"
     16 #include "clang/AST/ASTConsumer.h"
     17 #include "clang/AST/ASTContext.h"
     18 #include "clang/AST/ASTLambda.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/ExprOpenMP.h"
     28 #include "clang/AST/RecursiveASTVisitor.h"
     29 #include "clang/AST/TypeLoc.h"
     30 #include "clang/Basic/PartialDiagnostic.h"
     31 #include "clang/Basic/SourceManager.h"
     32 #include "clang/Basic/TargetInfo.h"
     33 #include "clang/Lex/LiteralSupport.h"
     34 #include "clang/Lex/Preprocessor.h"
     35 #include "clang/Sema/AnalysisBasedWarnings.h"
     36 #include "clang/Sema/DeclSpec.h"
     37 #include "clang/Sema/DelayedDiagnostic.h"
     38 #include "clang/Sema/Designator.h"
     39 #include "clang/Sema/Initialization.h"
     40 #include "clang/Sema/Lookup.h"
     41 #include "clang/Sema/ParsedTemplate.h"
     42 #include "clang/Sema/Scope.h"
     43 #include "clang/Sema/ScopeInfo.h"
     44 #include "clang/Sema/SemaFixItUtils.h"
     45 #include "clang/Sema/Template.h"
     46 #include "llvm/Support/ConvertUTF.h"
     47 using namespace clang;
     48 using namespace sema;
     49 
     50 /// \brief Determine whether the use of this declaration is valid, without
     51 /// emitting diagnostics.
     52 bool Sema::CanUseDecl(NamedDecl *D) {
     53   // See if this is an auto-typed variable whose initializer we are parsing.
     54   if (ParsingInitForAutoVars.count(D))
     55     return false;
     56 
     57   // See if this is a deleted function.
     58   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
     59     if (FD->isDeleted())
     60       return false;
     61 
     62     // If the function has a deduced return type, and we can't deduce it,
     63     // then we can't use it either.
     64     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
     65         DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
     66       return false;
     67   }
     68 
     69   // See if this function is unavailable.
     70   if (D->getAvailability() == AR_Unavailable &&
     71       cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
     72     return false;
     73 
     74   return true;
     75 }
     76 
     77 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
     78   // Warn if this is used but marked unused.
     79   if (D->hasAttr<UnusedAttr>()) {
     80     const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
     81     if (DC && !DC->hasAttr<UnusedAttr>())
     82       S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
     83   }
     84 }
     85 
     86 static bool HasRedeclarationWithoutAvailabilityInCategory(const Decl *D) {
     87   const auto *OMD = dyn_cast<ObjCMethodDecl>(D);
     88   if (!OMD)
     89     return false;
     90   const ObjCInterfaceDecl *OID = OMD->getClassInterface();
     91   if (!OID)
     92     return false;
     93 
     94   for (const ObjCCategoryDecl *Cat : OID->visible_categories())
     95     if (ObjCMethodDecl *CatMeth =
     96             Cat->getMethod(OMD->getSelector(), OMD->isInstanceMethod()))
     97       if (!CatMeth->hasAttr<AvailabilityAttr>())
     98         return true;
     99   return false;
    100 }
    101 
    102 static AvailabilityResult
    103 DiagnoseAvailabilityOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc,
    104                            const ObjCInterfaceDecl *UnknownObjCClass,
    105                            bool ObjCPropertyAccess) {
    106   // See if this declaration is unavailable or deprecated.
    107   std::string Message;
    108   AvailabilityResult Result = D->getAvailability(&Message);
    109 
    110   // For typedefs, if the typedef declaration appears available look
    111   // to the underlying type to see if it is more restrictive.
    112   while (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
    113     if (Result == AR_Available) {
    114       if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
    115         D = TT->getDecl();
    116         Result = D->getAvailability(&Message);
    117         continue;
    118       }
    119     }
    120     break;
    121   }
    122 
    123   // Forward class declarations get their attributes from their definition.
    124   if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(D)) {
    125     if (IDecl->getDefinition()) {
    126       D = IDecl->getDefinition();
    127       Result = D->getAvailability(&Message);
    128     }
    129   }
    130 
    131   if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D))
    132     if (Result == AR_Available) {
    133       const DeclContext *DC = ECD->getDeclContext();
    134       if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC))
    135         Result = TheEnumDecl->getAvailability(&Message);
    136     }
    137 
    138   const ObjCPropertyDecl *ObjCPDecl = nullptr;
    139   if (Result == AR_Deprecated || Result == AR_Unavailable ||
    140       AR_NotYetIntroduced) {
    141     if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
    142       if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) {
    143         AvailabilityResult PDeclResult = PD->getAvailability(nullptr);
    144         if (PDeclResult == Result)
    145           ObjCPDecl = PD;
    146       }
    147     }
    148   }
    149 
    150   switch (Result) {
    151     case AR_Available:
    152       break;
    153 
    154     case AR_Deprecated:
    155       if (S.getCurContextAvailability() != AR_Deprecated)
    156         S.EmitAvailabilityWarning(Sema::AD_Deprecation,
    157                                   D, Message, Loc, UnknownObjCClass, ObjCPDecl,
    158                                   ObjCPropertyAccess);
    159       break;
    160 
    161     case AR_NotYetIntroduced: {
    162       // Don't do this for enums, they can't be redeclared.
    163       if (isa<EnumConstantDecl>(D) || isa<EnumDecl>(D))
    164         break;
    165 
    166       bool Warn = !D->getAttr<AvailabilityAttr>()->isInherited();
    167       // Objective-C method declarations in categories are not modelled as
    168       // redeclarations, so manually look for a redeclaration in a category
    169       // if necessary.
    170       if (Warn && HasRedeclarationWithoutAvailabilityInCategory(D))
    171         Warn = false;
    172       // In general, D will point to the most recent redeclaration. However,
    173       // for `@class A;` decls, this isn't true -- manually go through the
    174       // redecl chain in that case.
    175       if (Warn && isa<ObjCInterfaceDecl>(D))
    176         for (Decl *Redecl = D->getMostRecentDecl(); Redecl && Warn;
    177              Redecl = Redecl->getPreviousDecl())
    178           if (!Redecl->hasAttr<AvailabilityAttr>() ||
    179               Redecl->getAttr<AvailabilityAttr>()->isInherited())
    180             Warn = false;
    181 
    182       if (Warn)
    183         S.EmitAvailabilityWarning(Sema::AD_Partial, D, Message, Loc,
    184                                   UnknownObjCClass, ObjCPDecl,
    185                                   ObjCPropertyAccess);
    186       break;
    187     }
    188 
    189     case AR_Unavailable:
    190       if (S.getCurContextAvailability() != AR_Unavailable)
    191         S.EmitAvailabilityWarning(Sema::AD_Unavailable,
    192                                   D, Message, Loc, UnknownObjCClass, ObjCPDecl,
    193                                   ObjCPropertyAccess);
    194       break;
    195 
    196     }
    197     return Result;
    198 }
    199 
    200 /// \brief Emit a note explaining that this function is deleted.
    201 void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
    202   assert(Decl->isDeleted());
    203 
    204   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
    205 
    206   if (Method && Method->isDeleted() && Method->isDefaulted()) {
    207     // If the method was explicitly defaulted, point at that declaration.
    208     if (!Method->isImplicit())
    209       Diag(Decl->getLocation(), diag::note_implicitly_deleted);
    210 
    211     // Try to diagnose why this special member function was implicitly
    212     // deleted. This might fail, if that reason no longer applies.
    213     CXXSpecialMember CSM = getSpecialMember(Method);
    214     if (CSM != CXXInvalid)
    215       ShouldDeleteSpecialMember(Method, CSM, /*Diagnose=*/true);
    216 
    217     return;
    218   }
    219 
    220   if (CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Decl)) {
    221     if (CXXConstructorDecl *BaseCD =
    222             const_cast<CXXConstructorDecl*>(CD->getInheritedConstructor())) {
    223       Diag(Decl->getLocation(), diag::note_inherited_deleted_here);
    224       if (BaseCD->isDeleted()) {
    225         NoteDeletedFunction(BaseCD);
    226       } else {
    227         // FIXME: An explanation of why exactly it can't be inherited
    228         // would be nice.
    229         Diag(BaseCD->getLocation(), diag::note_cannot_inherit);
    230       }
    231       return;
    232     }
    233   }
    234 
    235   Diag(Decl->getLocation(), diag::note_availability_specified_here)
    236     << Decl << true;
    237 }
    238 
    239 /// \brief Determine whether a FunctionDecl was ever declared with an
    240 /// explicit storage class.
    241 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
    242   for (auto I : D->redecls()) {
    243     if (I->getStorageClass() != SC_None)
    244       return true;
    245   }
    246   return false;
    247 }
    248 
    249 /// \brief Check whether we're in an extern inline function and referring to a
    250 /// variable or function with internal linkage (C11 6.7.4p3).
    251 ///
    252 /// This is only a warning because we used to silently accept this code, but
    253 /// in many cases it will not behave correctly. This is not enabled in C++ mode
    254 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
    255 /// and so while there may still be user mistakes, most of the time we can't
    256 /// prove that there are errors.
    257 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
    258                                                       const NamedDecl *D,
    259                                                       SourceLocation Loc) {
    260   // This is disabled under C++; there are too many ways for this to fire in
    261   // contexts where the warning is a false positive, or where it is technically
    262   // correct but benign.
    263   if (S.getLangOpts().CPlusPlus)
    264     return;
    265 
    266   // Check if this is an inlined function or method.
    267   FunctionDecl *Current = S.getCurFunctionDecl();
    268   if (!Current)
    269     return;
    270   if (!Current->isInlined())
    271     return;
    272   if (!Current->isExternallyVisible())
    273     return;
    274 
    275   // Check if the decl has internal linkage.
    276   if (D->getFormalLinkage() != InternalLinkage)
    277     return;
    278 
    279   // Downgrade from ExtWarn to Extension if
    280   //  (1) the supposedly external inline function is in the main file,
    281   //      and probably won't be included anywhere else.
    282   //  (2) the thing we're referencing is a pure function.
    283   //  (3) the thing we're referencing is another inline function.
    284   // This last can give us false negatives, but it's better than warning on
    285   // wrappers for simple C library functions.
    286   const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
    287   bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
    288   if (!DowngradeWarning && UsedFn)
    289     DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
    290 
    291   S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
    292                                : diag::ext_internal_in_extern_inline)
    293     << /*IsVar=*/!UsedFn << D;
    294 
    295   S.MaybeSuggestAddingStaticToDecl(Current);
    296 
    297   S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
    298       << D;
    299 }
    300 
    301 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
    302   const FunctionDecl *First = Cur->getFirstDecl();
    303 
    304   // Suggest "static" on the function, if possible.
    305   if (!hasAnyExplicitStorageClass(First)) {
    306     SourceLocation DeclBegin = First->getSourceRange().getBegin();
    307     Diag(DeclBegin, diag::note_convert_inline_to_static)
    308       << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
    309   }
    310 }
    311 
    312 /// \brief Determine whether the use of this declaration is valid, and
    313 /// emit any corresponding diagnostics.
    314 ///
    315 /// This routine diagnoses various problems with referencing
    316 /// declarations that can occur when using a declaration. For example,
    317 /// it might warn if a deprecated or unavailable declaration is being
    318 /// used, or produce an error (and return true) if a C++0x deleted
    319 /// function is being used.
    320 ///
    321 /// \returns true if there was an error (this declaration cannot be
    322 /// referenced), false otherwise.
    323 ///
    324 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
    325                              const ObjCInterfaceDecl *UnknownObjCClass,
    326                              bool ObjCPropertyAccess) {
    327   if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
    328     // If there were any diagnostics suppressed by template argument deduction,
    329     // emit them now.
    330     auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
    331     if (Pos != SuppressedDiagnostics.end()) {
    332       for (const PartialDiagnosticAt &Suppressed : Pos->second)
    333         Diag(Suppressed.first, Suppressed.second);
    334 
    335       // Clear out the list of suppressed diagnostics, so that we don't emit
    336       // them again for this specialization. However, we don't obsolete this
    337       // entry from the table, because we want to avoid ever emitting these
    338       // diagnostics again.
    339       Pos->second.clear();
    340     }
    341 
    342     // C++ [basic.start.main]p3:
    343     //   The function 'main' shall not be used within a program.
    344     if (cast<FunctionDecl>(D)->isMain())
    345       Diag(Loc, diag::ext_main_used);
    346   }
    347 
    348   // See if this is an auto-typed variable whose initializer we are parsing.
    349   if (ParsingInitForAutoVars.count(D)) {
    350     const AutoType *AT = cast<VarDecl>(D)->getType()->getContainedAutoType();
    351 
    352     Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
    353       << D->getDeclName() << (unsigned)AT->getKeyword();
    354     return true;
    355   }
    356 
    357   // See if this is a deleted function.
    358   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
    359     if (FD->isDeleted()) {
    360       Diag(Loc, diag::err_deleted_function_use);
    361       NoteDeletedFunction(FD);
    362       return true;
    363     }
    364 
    365     // If the function has a deduced return type, and we can't deduce it,
    366     // then we can't use it either.
    367     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
    368         DeduceReturnType(FD, Loc))
    369       return true;
    370   }
    371   DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass,
    372                              ObjCPropertyAccess);
    373 
    374   DiagnoseUnusedOfDecl(*this, D, Loc);
    375 
    376   diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
    377 
    378   return false;
    379 }
    380 
    381 /// \brief Retrieve the message suffix that should be added to a
    382 /// diagnostic complaining about the given function being deleted or
    383 /// unavailable.
    384 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
    385   std::string Message;
    386   if (FD->getAvailability(&Message))
    387     return ": " + Message;
    388 
    389   return std::string();
    390 }
    391 
    392 /// DiagnoseSentinelCalls - This routine checks whether a call or
    393 /// message-send is to a declaration with the sentinel attribute, and
    394 /// if so, it checks that the requirements of the sentinel are
    395 /// satisfied.
    396 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
    397                                  ArrayRef<Expr *> Args) {
    398   const SentinelAttr *attr = D->getAttr<SentinelAttr>();
    399   if (!attr)
    400     return;
    401 
    402   // The number of formal parameters of the declaration.
    403   unsigned numFormalParams;
    404 
    405   // The kind of declaration.  This is also an index into a %select in
    406   // the diagnostic.
    407   enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
    408 
    409   if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
    410     numFormalParams = MD->param_size();
    411     calleeType = CT_Method;
    412   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
    413     numFormalParams = FD->param_size();
    414     calleeType = CT_Function;
    415   } else if (isa<VarDecl>(D)) {
    416     QualType type = cast<ValueDecl>(D)->getType();
    417     const FunctionType *fn = nullptr;
    418     if (const PointerType *ptr = type->getAs<PointerType>()) {
    419       fn = ptr->getPointeeType()->getAs<FunctionType>();
    420       if (!fn) return;
    421       calleeType = CT_Function;
    422     } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
    423       fn = ptr->getPointeeType()->castAs<FunctionType>();
    424       calleeType = CT_Block;
    425     } else {
    426       return;
    427     }
    428 
    429     if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
    430       numFormalParams = proto->getNumParams();
    431     } else {
    432       numFormalParams = 0;
    433     }
    434   } else {
    435     return;
    436   }
    437 
    438   // "nullPos" is the number of formal parameters at the end which
    439   // effectively count as part of the variadic arguments.  This is
    440   // useful if you would prefer to not have *any* formal parameters,
    441   // but the language forces you to have at least one.
    442   unsigned nullPos = attr->getNullPos();
    443   assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
    444   numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
    445 
    446   // The number of arguments which should follow the sentinel.
    447   unsigned numArgsAfterSentinel = attr->getSentinel();
    448 
    449   // If there aren't enough arguments for all the formal parameters,
    450   // the sentinel, and the args after the sentinel, complain.
    451   if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
    452     Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
    453     Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
    454     return;
    455   }
    456 
    457   // Otherwise, find the sentinel expression.
    458   Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
    459   if (!sentinelExpr) return;
    460   if (sentinelExpr->isValueDependent()) return;
    461   if (Context.isSentinelNullExpr(sentinelExpr)) return;
    462 
    463   // Pick a reasonable string to insert.  Optimistically use 'nil', 'nullptr',
    464   // or 'NULL' if those are actually defined in the context.  Only use
    465   // 'nil' for ObjC methods, where it's much more likely that the
    466   // variadic arguments form a list of object pointers.
    467   SourceLocation MissingNilLoc
    468     = getLocForEndOfToken(sentinelExpr->getLocEnd());
    469   std::string NullValue;
    470   if (calleeType == CT_Method && PP.isMacroDefined("nil"))
    471     NullValue = "nil";
    472   else if (getLangOpts().CPlusPlus11)
    473     NullValue = "nullptr";
    474   else if (PP.isMacroDefined("NULL"))
    475     NullValue = "NULL";
    476   else
    477     NullValue = "(void*) 0";
    478 
    479   if (MissingNilLoc.isInvalid())
    480     Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
    481   else
    482     Diag(MissingNilLoc, diag::warn_missing_sentinel)
    483       << int(calleeType)
    484       << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
    485   Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
    486 }
    487 
    488 SourceRange Sema::getExprRange(Expr *E) const {
    489   return E ? E->getSourceRange() : SourceRange();
    490 }
    491 
    492 //===----------------------------------------------------------------------===//
    493 //  Standard Promotions and Conversions
    494 //===----------------------------------------------------------------------===//
    495 
    496 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
    497 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
    498   // Handle any placeholder expressions which made it here.
    499   if (E->getType()->isPlaceholderType()) {
    500     ExprResult result = CheckPlaceholderExpr(E);
    501     if (result.isInvalid()) return ExprError();
    502     E = result.get();
    503   }
    504 
    505   QualType Ty = E->getType();
    506   assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
    507 
    508   if (Ty->isFunctionType()) {
    509     // If we are here, we are not calling a function but taking
    510     // its address (which is not allowed in OpenCL v1.0 s6.8.a.3).
    511     if (getLangOpts().OpenCL) {
    512       if (Diagnose)
    513         Diag(E->getExprLoc(), diag::err_opencl_taking_function_address);
    514       return ExprError();
    515     }
    516 
    517     if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
    518       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
    519         if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
    520           return ExprError();
    521 
    522     E = ImpCastExprToType(E, Context.getPointerType(Ty),
    523                           CK_FunctionToPointerDecay).get();
    524   } else if (Ty->isArrayType()) {
    525     // In C90 mode, arrays only promote to pointers if the array expression is
    526     // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
    527     // type 'array of type' is converted to an expression that has type 'pointer
    528     // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
    529     // that has type 'array of type' ...".  The relevant change is "an lvalue"
    530     // (C90) to "an expression" (C99).
    531     //
    532     // C++ 4.2p1:
    533     // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
    534     // T" can be converted to an rvalue of type "pointer to T".
    535     //
    536     if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
    537       E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
    538                             CK_ArrayToPointerDecay).get();
    539   }
    540   return E;
    541 }
    542 
    543 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
    544   // Check to see if we are dereferencing a null pointer.  If so,
    545   // and if not volatile-qualified, this is undefined behavior that the
    546   // optimizer will delete, so warn about it.  People sometimes try to use this
    547   // to get a deterministic trap and are surprised by clang's behavior.  This
    548   // only handles the pattern "*null", which is a very syntactic check.
    549   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
    550     if (UO->getOpcode() == UO_Deref &&
    551         UO->getSubExpr()->IgnoreParenCasts()->
    552           isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
    553         !UO->getType().isVolatileQualified()) {
    554     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
    555                           S.PDiag(diag::warn_indirection_through_null)
    556                             << UO->getSubExpr()->getSourceRange());
    557     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
    558                         S.PDiag(diag::note_indirection_through_null));
    559   }
    560 }
    561 
    562 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
    563                                     SourceLocation AssignLoc,
    564                                     const Expr* RHS) {
    565   const ObjCIvarDecl *IV = OIRE->getDecl();
    566   if (!IV)
    567     return;
    568 
    569   DeclarationName MemberName = IV->getDeclName();
    570   IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
    571   if (!Member || !Member->isStr("isa"))
    572     return;
    573 
    574   const Expr *Base = OIRE->getBase();
    575   QualType BaseType = Base->getType();
    576   if (OIRE->isArrow())
    577     BaseType = BaseType->getPointeeType();
    578   if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
    579     if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
    580       ObjCInterfaceDecl *ClassDeclared = nullptr;
    581       ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
    582       if (!ClassDeclared->getSuperClass()
    583           && (*ClassDeclared->ivar_begin()) == IV) {
    584         if (RHS) {
    585           NamedDecl *ObjectSetClass =
    586             S.LookupSingleName(S.TUScope,
    587                                &S.Context.Idents.get("object_setClass"),
    588                                SourceLocation(), S.LookupOrdinaryName);
    589           if (ObjectSetClass) {
    590             SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getLocEnd());
    591             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) <<
    592             FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") <<
    593             FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(),
    594                                                      AssignLoc), ",") <<
    595             FixItHint::CreateInsertion(RHSLocEnd, ")");
    596           }
    597           else
    598             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
    599         } else {
    600           NamedDecl *ObjectGetClass =
    601             S.LookupSingleName(S.TUScope,
    602                                &S.Context.Idents.get("object_getClass"),
    603                                SourceLocation(), S.LookupOrdinaryName);
    604           if (ObjectGetClass)
    605             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) <<
    606             FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") <<
    607             FixItHint::CreateReplacement(
    608                                          SourceRange(OIRE->getOpLoc(),
    609                                                      OIRE->getLocEnd()), ")");
    610           else
    611             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
    612         }
    613         S.Diag(IV->getLocation(), diag::note_ivar_decl);
    614       }
    615     }
    616 }
    617 
    618 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
    619   // Handle any placeholder expressions which made it here.
    620   if (E->getType()->isPlaceholderType()) {
    621     ExprResult result = CheckPlaceholderExpr(E);
    622     if (result.isInvalid()) return ExprError();
    623     E = result.get();
    624   }
    625 
    626   // C++ [conv.lval]p1:
    627   //   A glvalue of a non-function, non-array type T can be
    628   //   converted to a prvalue.
    629   if (!E->isGLValue()) return E;
    630 
    631   QualType T = E->getType();
    632   assert(!T.isNull() && "r-value conversion on typeless expression?");
    633 
    634   // We don't want to throw lvalue-to-rvalue casts on top of
    635   // expressions of certain types in C++.
    636   if (getLangOpts().CPlusPlus &&
    637       (E->getType() == Context.OverloadTy ||
    638        T->isDependentType() ||
    639        T->isRecordType()))
    640     return E;
    641 
    642   // The C standard is actually really unclear on this point, and
    643   // DR106 tells us what the result should be but not why.  It's
    644   // generally best to say that void types just doesn't undergo
    645   // lvalue-to-rvalue at all.  Note that expressions of unqualified
    646   // 'void' type are never l-values, but qualified void can be.
    647   if (T->isVoidType())
    648     return E;
    649 
    650   // OpenCL usually rejects direct accesses to values of 'half' type.
    651   if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16 &&
    652       T->isHalfType()) {
    653     Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
    654       << 0 << T;
    655     return ExprError();
    656   }
    657 
    658   CheckForNullPointerDereference(*this, E);
    659   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
    660     NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
    661                                      &Context.Idents.get("object_getClass"),
    662                                      SourceLocation(), LookupOrdinaryName);
    663     if (ObjectGetClass)
    664       Diag(E->getExprLoc(), diag::warn_objc_isa_use) <<
    665         FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") <<
    666         FixItHint::CreateReplacement(
    667                     SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
    668     else
    669       Diag(E->getExprLoc(), diag::warn_objc_isa_use);
    670   }
    671   else if (const ObjCIvarRefExpr *OIRE =
    672             dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
    673     DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
    674 
    675   // C++ [conv.lval]p1:
    676   //   [...] If T is a non-class type, the type of the prvalue is the
    677   //   cv-unqualified version of T. Otherwise, the type of the
    678   //   rvalue is T.
    679   //
    680   // C99 6.3.2.1p2:
    681   //   If the lvalue has qualified type, the value has the unqualified
    682   //   version of the type of the lvalue; otherwise, the value has the
    683   //   type of the lvalue.
    684   if (T.hasQualifiers())
    685     T = T.getUnqualifiedType();
    686 
    687   // Under the MS ABI, lock down the inheritance model now.
    688   if (T->isMemberPointerType() &&
    689       Context.getTargetInfo().getCXXABI().isMicrosoft())
    690     (void)isCompleteType(E->getExprLoc(), T);
    691 
    692   UpdateMarkingForLValueToRValue(E);
    693 
    694   // Loading a __weak object implicitly retains the value, so we need a cleanup to
    695   // balance that.
    696   if (getLangOpts().ObjCAutoRefCount &&
    697       E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
    698     ExprNeedsCleanups = true;
    699 
    700   ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E,
    701                                             nullptr, VK_RValue);
    702 
    703   // C11 6.3.2.1p2:
    704   //   ... if the lvalue has atomic type, the value has the non-atomic version
    705   //   of the type of the lvalue ...
    706   if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
    707     T = Atomic->getValueType().getUnqualifiedType();
    708     Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
    709                                    nullptr, VK_RValue);
    710   }
    711 
    712   return Res;
    713 }
    714 
    715 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
    716   ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
    717   if (Res.isInvalid())
    718     return ExprError();
    719   Res = DefaultLvalueConversion(Res.get());
    720   if (Res.isInvalid())
    721     return ExprError();
    722   return Res;
    723 }
    724 
    725 /// CallExprUnaryConversions - a special case of an unary conversion
    726 /// performed on a function designator of a call expression.
    727 ExprResult Sema::CallExprUnaryConversions(Expr *E) {
    728   QualType Ty = E->getType();
    729   ExprResult Res = E;
    730   // Only do implicit cast for a function type, but not for a pointer
    731   // to function type.
    732   if (Ty->isFunctionType()) {
    733     Res = ImpCastExprToType(E, Context.getPointerType(Ty),
    734                             CK_FunctionToPointerDecay).get();
    735     if (Res.isInvalid())
    736       return ExprError();
    737   }
    738   Res = DefaultLvalueConversion(Res.get());
    739   if (Res.isInvalid())
    740     return ExprError();
    741   return Res.get();
    742 }
    743 
    744 /// UsualUnaryConversions - Performs various conversions that are common to most
    745 /// operators (C99 6.3). The conversions of array and function types are
    746 /// sometimes suppressed. For example, the array->pointer conversion doesn't
    747 /// apply if the array is an argument to the sizeof or address (&) operators.
    748 /// In these instances, this routine should *not* be called.
    749 ExprResult Sema::UsualUnaryConversions(Expr *E) {
    750   // First, convert to an r-value.
    751   ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
    752   if (Res.isInvalid())
    753     return ExprError();
    754   E = Res.get();
    755 
    756   QualType Ty = E->getType();
    757   assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
    758 
    759   // Half FP have to be promoted to float unless it is natively supported
    760   if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
    761     return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
    762 
    763   // Try to perform integral promotions if the object has a theoretically
    764   // promotable type.
    765   if (Ty->isIntegralOrUnscopedEnumerationType()) {
    766     // C99 6.3.1.1p2:
    767     //
    768     //   The following may be used in an expression wherever an int or
    769     //   unsigned int may be used:
    770     //     - an object or expression with an integer type whose integer
    771     //       conversion rank is less than or equal to the rank of int
    772     //       and unsigned int.
    773     //     - A bit-field of type _Bool, int, signed int, or unsigned int.
    774     //
    775     //   If an int can represent all values of the original type, the
    776     //   value is converted to an int; otherwise, it is converted to an
    777     //   unsigned int. These are called the integer promotions. All
    778     //   other types are unchanged by the integer promotions.
    779 
    780     QualType PTy = Context.isPromotableBitField(E);
    781     if (!PTy.isNull()) {
    782       E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
    783       return E;
    784     }
    785     if (Ty->isPromotableIntegerType()) {
    786       QualType PT = Context.getPromotedIntegerType(Ty);
    787       E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
    788       return E;
    789     }
    790   }
    791   return E;
    792 }
    793 
    794 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
    795 /// do not have a prototype. Arguments that have type float or __fp16
    796 /// are promoted to double. All other argument types are converted by
    797 /// UsualUnaryConversions().
    798 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
    799   QualType Ty = E->getType();
    800   assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
    801 
    802   ExprResult Res = UsualUnaryConversions(E);
    803   if (Res.isInvalid())
    804     return ExprError();
    805   E = Res.get();
    806 
    807   // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to
    808   // double.
    809   const BuiltinType *BTy = Ty->getAs<BuiltinType>();
    810   if (BTy && (BTy->getKind() == BuiltinType::Half ||
    811               BTy->getKind() == BuiltinType::Float))
    812     E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
    813 
    814   // C++ performs lvalue-to-rvalue conversion as a default argument
    815   // promotion, even on class types, but note:
    816   //   C++11 [conv.lval]p2:
    817   //     When an lvalue-to-rvalue conversion occurs in an unevaluated
    818   //     operand or a subexpression thereof the value contained in the
    819   //     referenced object is not accessed. Otherwise, if the glvalue
    820   //     has a class type, the conversion copy-initializes a temporary
    821   //     of type T from the glvalue and the result of the conversion
    822   //     is a prvalue for the temporary.
    823   // FIXME: add some way to gate this entire thing for correctness in
    824   // potentially potentially evaluated contexts.
    825   if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
    826     ExprResult Temp = PerformCopyInitialization(
    827                        InitializedEntity::InitializeTemporary(E->getType()),
    828                                                 E->getExprLoc(), E);
    829     if (Temp.isInvalid())
    830       return ExprError();
    831     E = Temp.get();
    832   }
    833 
    834   return E;
    835 }
    836 
    837 /// Determine the degree of POD-ness for an expression.
    838 /// Incomplete types are considered POD, since this check can be performed
    839 /// when we're in an unevaluated context.
    840 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
    841   if (Ty->isIncompleteType()) {
    842     // C++11 [expr.call]p7:
    843     //   After these conversions, if the argument does not have arithmetic,
    844     //   enumeration, pointer, pointer to member, or class type, the program
    845     //   is ill-formed.
    846     //
    847     // Since we've already performed array-to-pointer and function-to-pointer
    848     // decay, the only such type in C++ is cv void. This also handles
    849     // initializer lists as variadic arguments.
    850     if (Ty->isVoidType())
    851       return VAK_Invalid;
    852 
    853     if (Ty->isObjCObjectType())
    854       return VAK_Invalid;
    855     return VAK_Valid;
    856   }
    857 
    858   if (Ty.isCXX98PODType(Context))
    859     return VAK_Valid;
    860 
    861   // C++11 [expr.call]p7:
    862   //   Passing a potentially-evaluated argument of class type (Clause 9)
    863   //   having a non-trivial copy constructor, a non-trivial move constructor,
    864   //   or a non-trivial destructor, with no corresponding parameter,
    865   //   is conditionally-supported with implementation-defined semantics.
    866   if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
    867     if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
    868       if (!Record->hasNonTrivialCopyConstructor() &&
    869           !Record->hasNonTrivialMoveConstructor() &&
    870           !Record->hasNonTrivialDestructor())
    871         return VAK_ValidInCXX11;
    872 
    873   if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
    874     return VAK_Valid;
    875 
    876   if (Ty->isObjCObjectType())
    877     return VAK_Invalid;
    878 
    879   if (getLangOpts().MSVCCompat)
    880     return VAK_MSVCUndefined;
    881 
    882   // FIXME: In C++11, these cases are conditionally-supported, meaning we're
    883   // permitted to reject them. We should consider doing so.
    884   return VAK_Undefined;
    885 }
    886 
    887 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
    888   // Don't allow one to pass an Objective-C interface to a vararg.
    889   const QualType &Ty = E->getType();
    890   VarArgKind VAK = isValidVarArgType(Ty);
    891 
    892   // Complain about passing non-POD types through varargs.
    893   switch (VAK) {
    894   case VAK_ValidInCXX11:
    895     DiagRuntimeBehavior(
    896         E->getLocStart(), nullptr,
    897         PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
    898           << Ty << CT);
    899     // Fall through.
    900   case VAK_Valid:
    901     if (Ty->isRecordType()) {
    902       // This is unlikely to be what the user intended. If the class has a
    903       // 'c_str' member function, the user probably meant to call that.
    904       DiagRuntimeBehavior(E->getLocStart(), nullptr,
    905                           PDiag(diag::warn_pass_class_arg_to_vararg)
    906                             << Ty << CT << hasCStrMethod(E) << ".c_str()");
    907     }
    908     break;
    909 
    910   case VAK_Undefined:
    911   case VAK_MSVCUndefined:
    912     DiagRuntimeBehavior(
    913         E->getLocStart(), nullptr,
    914         PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
    915           << getLangOpts().CPlusPlus11 << Ty << CT);
    916     break;
    917 
    918   case VAK_Invalid:
    919     if (Ty->isObjCObjectType())
    920       DiagRuntimeBehavior(
    921           E->getLocStart(), nullptr,
    922           PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
    923             << Ty << CT);
    924     else
    925       Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg)
    926         << isa<InitListExpr>(E) << Ty << CT;
    927     break;
    928   }
    929 }
    930 
    931 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
    932 /// will create a trap if the resulting type is not a POD type.
    933 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
    934                                                   FunctionDecl *FDecl) {
    935   if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
    936     // Strip the unbridged-cast placeholder expression off, if applicable.
    937     if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
    938         (CT == VariadicMethod ||
    939          (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
    940       E = stripARCUnbridgedCast(E);
    941 
    942     // Otherwise, do normal placeholder checking.
    943     } else {
    944       ExprResult ExprRes = CheckPlaceholderExpr(E);
    945       if (ExprRes.isInvalid())
    946         return ExprError();
    947       E = ExprRes.get();
    948     }
    949   }
    950 
    951   ExprResult ExprRes = DefaultArgumentPromotion(E);
    952   if (ExprRes.isInvalid())
    953     return ExprError();
    954   E = ExprRes.get();
    955 
    956   // Diagnostics regarding non-POD argument types are
    957   // emitted along with format string checking in Sema::CheckFunctionCall().
    958   if (isValidVarArgType(E->getType()) == VAK_Undefined) {
    959     // Turn this into a trap.
    960     CXXScopeSpec SS;
    961     SourceLocation TemplateKWLoc;
    962     UnqualifiedId Name;
    963     Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
    964                        E->getLocStart());
    965     ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
    966                                           Name, true, false);
    967     if (TrapFn.isInvalid())
    968       return ExprError();
    969 
    970     ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(),
    971                                     E->getLocStart(), None,
    972                                     E->getLocEnd());
    973     if (Call.isInvalid())
    974       return ExprError();
    975 
    976     ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
    977                                   Call.get(), E);
    978     if (Comma.isInvalid())
    979       return ExprError();
    980     return Comma.get();
    981   }
    982 
    983   if (!getLangOpts().CPlusPlus &&
    984       RequireCompleteType(E->getExprLoc(), E->getType(),
    985                           diag::err_call_incomplete_argument))
    986     return ExprError();
    987 
    988   return E;
    989 }
    990 
    991 /// \brief Converts an integer to complex float type.  Helper function of
    992 /// UsualArithmeticConversions()
    993 ///
    994 /// \return false if the integer expression is an integer type and is
    995 /// successfully converted to the complex type.
    996 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
    997                                                   ExprResult &ComplexExpr,
    998                                                   QualType IntTy,
    999                                                   QualType ComplexTy,
   1000                                                   bool SkipCast) {
   1001   if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
   1002   if (SkipCast) return false;
   1003   if (IntTy->isIntegerType()) {
   1004     QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
   1005     IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
   1006     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
   1007                                   CK_FloatingRealToComplex);
   1008   } else {
   1009     assert(IntTy->isComplexIntegerType());
   1010     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
   1011                                   CK_IntegralComplexToFloatingComplex);
   1012   }
   1013   return false;
   1014 }
   1015 
   1016 /// \brief Handle arithmetic conversion with complex types.  Helper function of
   1017 /// UsualArithmeticConversions()
   1018 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
   1019                                              ExprResult &RHS, QualType LHSType,
   1020                                              QualType RHSType,
   1021                                              bool IsCompAssign) {
   1022   // if we have an integer operand, the result is the complex type.
   1023   if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
   1024                                              /*skipCast*/false))
   1025     return LHSType;
   1026   if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
   1027                                              /*skipCast*/IsCompAssign))
   1028     return RHSType;
   1029 
   1030   // This handles complex/complex, complex/float, or float/complex.
   1031   // When both operands are complex, the shorter operand is converted to the
   1032   // type of the longer, and that is the type of the result. This corresponds
   1033   // to what is done when combining two real floating-point operands.
   1034   // The fun begins when size promotion occur across type domains.
   1035   // From H&S 6.3.4: When one operand is complex and the other is a real
   1036   // floating-point type, the less precise type is converted, within it's
   1037   // real or complex domain, to the precision of the other type. For example,
   1038   // when combining a "long double" with a "double _Complex", the
   1039   // "double _Complex" is promoted to "long double _Complex".
   1040 
   1041   // Compute the rank of the two types, regardless of whether they are complex.
   1042   int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
   1043 
   1044   auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
   1045   auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
   1046   QualType LHSElementType =
   1047       LHSComplexType ? LHSComplexType->getElementType() : LHSType;
   1048   QualType RHSElementType =
   1049       RHSComplexType ? RHSComplexType->getElementType() : RHSType;
   1050 
   1051   QualType ResultType = S.Context.getComplexType(LHSElementType);
   1052   if (Order < 0) {
   1053     // Promote the precision of the LHS if not an assignment.
   1054     ResultType = S.Context.getComplexType(RHSElementType);
   1055     if (!IsCompAssign) {
   1056       if (LHSComplexType)
   1057         LHS =
   1058             S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
   1059       else
   1060         LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
   1061     }
   1062   } else if (Order > 0) {
   1063     // Promote the precision of the RHS.
   1064     if (RHSComplexType)
   1065       RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
   1066     else
   1067       RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
   1068   }
   1069   return ResultType;
   1070 }
   1071 
   1072 /// \brief Hande arithmetic conversion from integer to float.  Helper function
   1073 /// of UsualArithmeticConversions()
   1074 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
   1075                                            ExprResult &IntExpr,
   1076                                            QualType FloatTy, QualType IntTy,
   1077                                            bool ConvertFloat, bool ConvertInt) {
   1078   if (IntTy->isIntegerType()) {
   1079     if (ConvertInt)
   1080       // Convert intExpr to the lhs floating point type.
   1081       IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
   1082                                     CK_IntegralToFloating);
   1083     return FloatTy;
   1084   }
   1085 
   1086   // Convert both sides to the appropriate complex float.
   1087   assert(IntTy->isComplexIntegerType());
   1088   QualType result = S.Context.getComplexType(FloatTy);
   1089 
   1090   // _Complex int -> _Complex float
   1091   if (ConvertInt)
   1092     IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
   1093                                   CK_IntegralComplexToFloatingComplex);
   1094 
   1095   // float -> _Complex float
   1096   if (ConvertFloat)
   1097     FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
   1098                                     CK_FloatingRealToComplex);
   1099 
   1100   return result;
   1101 }
   1102 
   1103 /// \brief Handle arithmethic conversion with floating point types.  Helper
   1104 /// function of UsualArithmeticConversions()
   1105 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
   1106                                       ExprResult &RHS, QualType LHSType,
   1107                                       QualType RHSType, bool IsCompAssign) {
   1108   bool LHSFloat = LHSType->isRealFloatingType();
   1109   bool RHSFloat = RHSType->isRealFloatingType();
   1110 
   1111   // If we have two real floating types, convert the smaller operand
   1112   // to the bigger result.
   1113   if (LHSFloat && RHSFloat) {
   1114     int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
   1115     if (order > 0) {
   1116       RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
   1117       return LHSType;
   1118     }
   1119 
   1120     assert(order < 0 && "illegal float comparison");
   1121     if (!IsCompAssign)
   1122       LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
   1123     return RHSType;
   1124   }
   1125 
   1126   if (LHSFloat) {
   1127     // Half FP has to be promoted to float unless it is natively supported
   1128     if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
   1129       LHSType = S.Context.FloatTy;
   1130 
   1131     return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
   1132                                       /*convertFloat=*/!IsCompAssign,
   1133                                       /*convertInt=*/ true);
   1134   }
   1135   assert(RHSFloat);
   1136   return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
   1137                                     /*convertInt=*/ true,
   1138                                     /*convertFloat=*/!IsCompAssign);
   1139 }
   1140 
   1141 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
   1142 
   1143 namespace {
   1144 /// These helper callbacks are placed in an anonymous namespace to
   1145 /// permit their use as function template parameters.
   1146 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
   1147   return S.ImpCastExprToType(op, toType, CK_IntegralCast);
   1148 }
   1149 
   1150 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
   1151   return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
   1152                              CK_IntegralComplexCast);
   1153 }
   1154 }
   1155 
   1156 /// \brief Handle integer arithmetic conversions.  Helper function of
   1157 /// UsualArithmeticConversions()
   1158 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
   1159 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
   1160                                         ExprResult &RHS, QualType LHSType,
   1161                                         QualType RHSType, bool IsCompAssign) {
   1162   // The rules for this case are in C99 6.3.1.8
   1163   int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
   1164   bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
   1165   bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
   1166   if (LHSSigned == RHSSigned) {
   1167     // Same signedness; use the higher-ranked type
   1168     if (order >= 0) {
   1169       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
   1170       return LHSType;
   1171     } else if (!IsCompAssign)
   1172       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
   1173     return RHSType;
   1174   } else if (order != (LHSSigned ? 1 : -1)) {
   1175     // The unsigned type has greater than or equal rank to the
   1176     // signed type, so use the unsigned type
   1177     if (RHSSigned) {
   1178       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
   1179       return LHSType;
   1180     } else if (!IsCompAssign)
   1181       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
   1182     return RHSType;
   1183   } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
   1184     // The two types are different widths; if we are here, that
   1185     // means the signed type is larger than the unsigned type, so
   1186     // use the signed type.
   1187     if (LHSSigned) {
   1188       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
   1189       return LHSType;
   1190     } else if (!IsCompAssign)
   1191       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
   1192     return RHSType;
   1193   } else {
   1194     // The signed type is higher-ranked than the unsigned type,
   1195     // but isn't actually any bigger (like unsigned int and long
   1196     // on most 32-bit systems).  Use the unsigned type corresponding
   1197     // to the signed type.
   1198     QualType result =
   1199       S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
   1200     RHS = (*doRHSCast)(S, RHS.get(), result);
   1201     if (!IsCompAssign)
   1202       LHS = (*doLHSCast)(S, LHS.get(), result);
   1203     return result;
   1204   }
   1205 }
   1206 
   1207 /// \brief Handle conversions with GCC complex int extension.  Helper function
   1208 /// of UsualArithmeticConversions()
   1209 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
   1210                                            ExprResult &RHS, QualType LHSType,
   1211                                            QualType RHSType,
   1212                                            bool IsCompAssign) {
   1213   const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
   1214   const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
   1215 
   1216   if (LHSComplexInt && RHSComplexInt) {
   1217     QualType LHSEltType = LHSComplexInt->getElementType();
   1218     QualType RHSEltType = RHSComplexInt->getElementType();
   1219     QualType ScalarType =
   1220       handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
   1221         (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
   1222 
   1223     return S.Context.getComplexType(ScalarType);
   1224   }
   1225 
   1226   if (LHSComplexInt) {
   1227     QualType LHSEltType = LHSComplexInt->getElementType();
   1228     QualType ScalarType =
   1229       handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
   1230         (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
   1231     QualType ComplexType = S.Context.getComplexType(ScalarType);
   1232     RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
   1233                               CK_IntegralRealToComplex);
   1234 
   1235     return ComplexType;
   1236   }
   1237 
   1238   assert(RHSComplexInt);
   1239 
   1240   QualType RHSEltType = RHSComplexInt->getElementType();
   1241   QualType ScalarType =
   1242     handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
   1243       (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
   1244   QualType ComplexType = S.Context.getComplexType(ScalarType);
   1245 
   1246   if (!IsCompAssign)
   1247     LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
   1248                               CK_IntegralRealToComplex);
   1249   return ComplexType;
   1250 }
   1251 
   1252 /// UsualArithmeticConversions - Performs various conversions that are common to
   1253 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
   1254 /// routine returns the first non-arithmetic type found. The client is
   1255 /// responsible for emitting appropriate error diagnostics.
   1256 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
   1257                                           bool IsCompAssign) {
   1258   if (!IsCompAssign) {
   1259     LHS = UsualUnaryConversions(LHS.get());
   1260     if (LHS.isInvalid())
   1261       return QualType();
   1262   }
   1263 
   1264   RHS = UsualUnaryConversions(RHS.get());
   1265   if (RHS.isInvalid())
   1266     return QualType();
   1267 
   1268   // For conversion purposes, we ignore any qualifiers.
   1269   // For example, "const float" and "float" are equivalent.
   1270   QualType LHSType =
   1271     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
   1272   QualType RHSType =
   1273     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
   1274 
   1275   // For conversion purposes, we ignore any atomic qualifier on the LHS.
   1276   if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
   1277     LHSType = AtomicLHS->getValueType();
   1278 
   1279   // If both types are identical, no conversion is needed.
   1280   if (LHSType == RHSType)
   1281     return LHSType;
   1282 
   1283   // If either side is a non-arithmetic type (e.g. a pointer), we are done.
   1284   // The caller can deal with this (e.g. pointer + int).
   1285   if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
   1286     return QualType();
   1287 
   1288   // Apply unary and bitfield promotions to the LHS's type.
   1289   QualType LHSUnpromotedType = LHSType;
   1290   if (LHSType->isPromotableIntegerType())
   1291     LHSType = Context.getPromotedIntegerType(LHSType);
   1292   QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
   1293   if (!LHSBitfieldPromoteTy.isNull())
   1294     LHSType = LHSBitfieldPromoteTy;
   1295   if (LHSType != LHSUnpromotedType && !IsCompAssign)
   1296     LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
   1297 
   1298   // If both types are identical, no conversion is needed.
   1299   if (LHSType == RHSType)
   1300     return LHSType;
   1301 
   1302   // At this point, we have two different arithmetic types.
   1303 
   1304   // Handle complex types first (C99 6.3.1.8p1).
   1305   if (LHSType->isComplexType() || RHSType->isComplexType())
   1306     return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
   1307                                         IsCompAssign);
   1308 
   1309   // Now handle "real" floating types (i.e. float, double, long double).
   1310   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
   1311     return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
   1312                                  IsCompAssign);
   1313 
   1314   // Handle GCC complex int extension.
   1315   if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
   1316     return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
   1317                                       IsCompAssign);
   1318 
   1319   // Finally, we have two differing integer types.
   1320   return handleIntegerConversion<doIntegralCast, doIntegralCast>
   1321            (*this, LHS, RHS, LHSType, RHSType, IsCompAssign);
   1322 }
   1323 
   1324 
   1325 //===----------------------------------------------------------------------===//
   1326 //  Semantic Analysis for various Expression Types
   1327 //===----------------------------------------------------------------------===//
   1328 
   1329 
   1330 ExprResult
   1331 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
   1332                                 SourceLocation DefaultLoc,
   1333                                 SourceLocation RParenLoc,
   1334                                 Expr *ControllingExpr,
   1335                                 ArrayRef<ParsedType> ArgTypes,
   1336                                 ArrayRef<Expr *> ArgExprs) {
   1337   unsigned NumAssocs = ArgTypes.size();
   1338   assert(NumAssocs == ArgExprs.size());
   1339 
   1340   TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
   1341   for (unsigned i = 0; i < NumAssocs; ++i) {
   1342     if (ArgTypes[i])
   1343       (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
   1344     else
   1345       Types[i] = nullptr;
   1346   }
   1347 
   1348   ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
   1349                                              ControllingExpr,
   1350                                              llvm::makeArrayRef(Types, NumAssocs),
   1351                                              ArgExprs);
   1352   delete [] Types;
   1353   return ER;
   1354 }
   1355 
   1356 ExprResult
   1357 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
   1358                                  SourceLocation DefaultLoc,
   1359                                  SourceLocation RParenLoc,
   1360                                  Expr *ControllingExpr,
   1361                                  ArrayRef<TypeSourceInfo *> Types,
   1362                                  ArrayRef<Expr *> Exprs) {
   1363   unsigned NumAssocs = Types.size();
   1364   assert(NumAssocs == Exprs.size());
   1365 
   1366   // Decay and strip qualifiers for the controlling expression type, and handle
   1367   // placeholder type replacement. See committee discussion from WG14 DR423.
   1368   ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
   1369   if (R.isInvalid())
   1370     return ExprError();
   1371   ControllingExpr = R.get();
   1372 
   1373   // The controlling expression is an unevaluated operand, so side effects are
   1374   // likely unintended.
   1375   if (ActiveTemplateInstantiations.empty() &&
   1376       ControllingExpr->HasSideEffects(Context, false))
   1377     Diag(ControllingExpr->getExprLoc(),
   1378          diag::warn_side_effects_unevaluated_context);
   1379 
   1380   bool TypeErrorFound = false,
   1381        IsResultDependent = ControllingExpr->isTypeDependent(),
   1382        ContainsUnexpandedParameterPack
   1383          = ControllingExpr->containsUnexpandedParameterPack();
   1384 
   1385   for (unsigned i = 0; i < NumAssocs; ++i) {
   1386     if (Exprs[i]->containsUnexpandedParameterPack())
   1387       ContainsUnexpandedParameterPack = true;
   1388 
   1389     if (Types[i]) {
   1390       if (Types[i]->getType()->containsUnexpandedParameterPack())
   1391         ContainsUnexpandedParameterPack = true;
   1392 
   1393       if (Types[i]->getType()->isDependentType()) {
   1394         IsResultDependent = true;
   1395       } else {
   1396         // C11 6.5.1.1p2 "The type name in a generic association shall specify a
   1397         // complete object type other than a variably modified type."
   1398         unsigned D = 0;
   1399         if (Types[i]->getType()->isIncompleteType())
   1400           D = diag::err_assoc_type_incomplete;
   1401         else if (!Types[i]->getType()->isObjectType())
   1402           D = diag::err_assoc_type_nonobject;
   1403         else if (Types[i]->getType()->isVariablyModifiedType())
   1404           D = diag::err_assoc_type_variably_modified;
   1405 
   1406         if (D != 0) {
   1407           Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
   1408             << Types[i]->getTypeLoc().getSourceRange()
   1409             << Types[i]->getType();
   1410           TypeErrorFound = true;
   1411         }
   1412 
   1413         // C11 6.5.1.1p2 "No two generic associations in the same generic
   1414         // selection shall specify compatible types."
   1415         for (unsigned j = i+1; j < NumAssocs; ++j)
   1416           if (Types[j] && !Types[j]->getType()->isDependentType() &&
   1417               Context.typesAreCompatible(Types[i]->getType(),
   1418                                          Types[j]->getType())) {
   1419             Diag(Types[j]->getTypeLoc().getBeginLoc(),
   1420                  diag::err_assoc_compatible_types)
   1421               << Types[j]->getTypeLoc().getSourceRange()
   1422               << Types[j]->getType()
   1423               << Types[i]->getType();
   1424             Diag(Types[i]->getTypeLoc().getBeginLoc(),
   1425                  diag::note_compat_assoc)
   1426               << Types[i]->getTypeLoc().getSourceRange()
   1427               << Types[i]->getType();
   1428             TypeErrorFound = true;
   1429           }
   1430       }
   1431     }
   1432   }
   1433   if (TypeErrorFound)
   1434     return ExprError();
   1435 
   1436   // If we determined that the generic selection is result-dependent, don't
   1437   // try to compute the result expression.
   1438   if (IsResultDependent)
   1439     return new (Context) GenericSelectionExpr(
   1440         Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
   1441         ContainsUnexpandedParameterPack);
   1442 
   1443   SmallVector<unsigned, 1> CompatIndices;
   1444   unsigned DefaultIndex = -1U;
   1445   for (unsigned i = 0; i < NumAssocs; ++i) {
   1446     if (!Types[i])
   1447       DefaultIndex = i;
   1448     else if (Context.typesAreCompatible(ControllingExpr->getType(),
   1449                                         Types[i]->getType()))
   1450       CompatIndices.push_back(i);
   1451   }
   1452 
   1453   // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
   1454   // type compatible with at most one of the types named in its generic
   1455   // association list."
   1456   if (CompatIndices.size() > 1) {
   1457     // We strip parens here because the controlling expression is typically
   1458     // parenthesized in macro definitions.
   1459     ControllingExpr = ControllingExpr->IgnoreParens();
   1460     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
   1461       << ControllingExpr->getSourceRange() << ControllingExpr->getType()
   1462       << (unsigned) CompatIndices.size();
   1463     for (unsigned I : CompatIndices) {
   1464       Diag(Types[I]->getTypeLoc().getBeginLoc(),
   1465            diag::note_compat_assoc)
   1466         << Types[I]->getTypeLoc().getSourceRange()
   1467         << Types[I]->getType();
   1468     }
   1469     return ExprError();
   1470   }
   1471 
   1472   // C11 6.5.1.1p2 "If a generic selection has no default generic association,
   1473   // its controlling expression shall have type compatible with exactly one of
   1474   // the types named in its generic association list."
   1475   if (DefaultIndex == -1U && CompatIndices.size() == 0) {
   1476     // We strip parens here because the controlling expression is typically
   1477     // parenthesized in macro definitions.
   1478     ControllingExpr = ControllingExpr->IgnoreParens();
   1479     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
   1480       << ControllingExpr->getSourceRange() << ControllingExpr->getType();
   1481     return ExprError();
   1482   }
   1483 
   1484   // C11 6.5.1.1p3 "If a generic selection has a generic association with a
   1485   // type name that is compatible with the type of the controlling expression,
   1486   // then the result expression of the generic selection is the expression
   1487   // in that generic association. Otherwise, the result expression of the
   1488   // generic selection is the expression in the default generic association."
   1489   unsigned ResultIndex =
   1490     CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
   1491 
   1492   return new (Context) GenericSelectionExpr(
   1493       Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
   1494       ContainsUnexpandedParameterPack, ResultIndex);
   1495 }
   1496 
   1497 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
   1498 /// location of the token and the offset of the ud-suffix within it.
   1499 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
   1500                                      unsigned Offset) {
   1501   return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
   1502                                         S.getLangOpts());
   1503 }
   1504 
   1505 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
   1506 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
   1507 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
   1508                                                  IdentifierInfo *UDSuffix,
   1509                                                  SourceLocation UDSuffixLoc,
   1510                                                  ArrayRef<Expr*> Args,
   1511                                                  SourceLocation LitEndLoc) {
   1512   assert(Args.size() <= 2 && "too many arguments for literal operator");
   1513 
   1514   QualType ArgTy[2];
   1515   for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
   1516     ArgTy[ArgIdx] = Args[ArgIdx]->getType();
   1517     if (ArgTy[ArgIdx]->isArrayType())
   1518       ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
   1519   }
   1520 
   1521   DeclarationName OpName =
   1522     S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
   1523   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
   1524   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
   1525 
   1526   LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
   1527   if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
   1528                               /*AllowRaw*/false, /*AllowTemplate*/false,
   1529                               /*AllowStringTemplate*/false) == Sema::LOLR_Error)
   1530     return ExprError();
   1531 
   1532   return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
   1533 }
   1534 
   1535 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
   1536 /// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
   1537 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
   1538 /// multiple tokens.  However, the common case is that StringToks points to one
   1539 /// string.
   1540 ///
   1541 ExprResult
   1542 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
   1543   assert(!StringToks.empty() && "Must have at least one string!");
   1544 
   1545   StringLiteralParser Literal(StringToks, PP);
   1546   if (Literal.hadError)
   1547     return ExprError();
   1548 
   1549   SmallVector<SourceLocation, 4> StringTokLocs;
   1550   for (const Token &Tok : StringToks)
   1551     StringTokLocs.push_back(Tok.getLocation());
   1552 
   1553   QualType CharTy = Context.CharTy;
   1554   StringLiteral::StringKind Kind = StringLiteral::Ascii;
   1555   if (Literal.isWide()) {
   1556     CharTy = Context.getWideCharType();
   1557     Kind = StringLiteral::Wide;
   1558   } else if (Literal.isUTF8()) {
   1559     Kind = StringLiteral::UTF8;
   1560   } else if (Literal.isUTF16()) {
   1561     CharTy = Context.Char16Ty;
   1562     Kind = StringLiteral::UTF16;
   1563   } else if (Literal.isUTF32()) {
   1564     CharTy = Context.Char32Ty;
   1565     Kind = StringLiteral::UTF32;
   1566   } else if (Literal.isPascal()) {
   1567     CharTy = Context.UnsignedCharTy;
   1568   }
   1569 
   1570   QualType CharTyConst = CharTy;
   1571   // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
   1572   if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
   1573     CharTyConst.addConst();
   1574 
   1575   // Get an array type for the string, according to C99 6.4.5.  This includes
   1576   // the nul terminator character as well as the string length for pascal
   1577   // strings.
   1578   QualType StrTy = Context.getConstantArrayType(CharTyConst,
   1579                                  llvm::APInt(32, Literal.GetNumStringChars()+1),
   1580                                  ArrayType::Normal, 0);
   1581 
   1582   // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
   1583   if (getLangOpts().OpenCL) {
   1584     StrTy = Context.getAddrSpaceQualType(StrTy, LangAS::opencl_constant);
   1585   }
   1586 
   1587   // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
   1588   StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
   1589                                              Kind, Literal.Pascal, StrTy,
   1590                                              &StringTokLocs[0],
   1591                                              StringTokLocs.size());
   1592   if (Literal.getUDSuffix().empty())
   1593     return Lit;
   1594 
   1595   // We're building a user-defined literal.
   1596   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
   1597   SourceLocation UDSuffixLoc =
   1598     getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
   1599                    Literal.getUDSuffixOffset());
   1600 
   1601   // Make sure we're allowed user-defined literals here.
   1602   if (!UDLScope)
   1603     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
   1604 
   1605   // C++11 [lex.ext]p5: The literal L is treated as a call of the form
   1606   //   operator "" X (str, len)
   1607   QualType SizeType = Context.getSizeType();
   1608 
   1609   DeclarationName OpName =
   1610     Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
   1611   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
   1612   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
   1613 
   1614   QualType ArgTy[] = {
   1615     Context.getArrayDecayedType(StrTy), SizeType
   1616   };
   1617 
   1618   LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
   1619   switch (LookupLiteralOperator(UDLScope, R, ArgTy,
   1620                                 /*AllowRaw*/false, /*AllowTemplate*/false,
   1621                                 /*AllowStringTemplate*/true)) {
   1622 
   1623   case LOLR_Cooked: {
   1624     llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
   1625     IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
   1626                                                     StringTokLocs[0]);
   1627     Expr *Args[] = { Lit, LenArg };
   1628 
   1629     return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
   1630   }
   1631 
   1632   case LOLR_StringTemplate: {
   1633     TemplateArgumentListInfo ExplicitArgs;
   1634 
   1635     unsigned CharBits = Context.getIntWidth(CharTy);
   1636     bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
   1637     llvm::APSInt Value(CharBits, CharIsUnsigned);
   1638 
   1639     TemplateArgument TypeArg(CharTy);
   1640     TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
   1641     ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
   1642 
   1643     for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
   1644       Value = Lit->getCodeUnit(I);
   1645       TemplateArgument Arg(Context, Value, CharTy);
   1646       TemplateArgumentLocInfo ArgInfo;
   1647       ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
   1648     }
   1649     return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
   1650                                     &ExplicitArgs);
   1651   }
   1652   case LOLR_Raw:
   1653   case LOLR_Template:
   1654     llvm_unreachable("unexpected literal operator lookup result");
   1655   case LOLR_Error:
   1656     return ExprError();
   1657   }
   1658   llvm_unreachable("unexpected literal operator lookup result");
   1659 }
   1660 
   1661 ExprResult
   1662 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
   1663                        SourceLocation Loc,
   1664                        const CXXScopeSpec *SS) {
   1665   DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
   1666   return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
   1667 }
   1668 
   1669 /// BuildDeclRefExpr - Build an expression that references a
   1670 /// declaration that does not require a closure capture.
   1671 ExprResult
   1672 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
   1673                        const DeclarationNameInfo &NameInfo,
   1674                        const CXXScopeSpec *SS, NamedDecl *FoundD,
   1675                        const TemplateArgumentListInfo *TemplateArgs) {
   1676   if (getLangOpts().CUDA)
   1677     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
   1678       if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) {
   1679         if (CheckCUDATarget(Caller, Callee)) {
   1680           Diag(NameInfo.getLoc(), diag::err_ref_bad_target)
   1681             << IdentifyCUDATarget(Callee) << D->getIdentifier()
   1682             << IdentifyCUDATarget(Caller);
   1683           Diag(D->getLocation(), diag::note_previous_decl)
   1684             << D->getIdentifier();
   1685           return ExprError();
   1686         }
   1687       }
   1688 
   1689   bool RefersToCapturedVariable =
   1690       isa<VarDecl>(D) &&
   1691       NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
   1692 
   1693   DeclRefExpr *E;
   1694   if (isa<VarTemplateSpecializationDecl>(D)) {
   1695     VarTemplateSpecializationDecl *VarSpec =
   1696         cast<VarTemplateSpecializationDecl>(D);
   1697 
   1698     E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
   1699                                         : NestedNameSpecifierLoc(),
   1700                             VarSpec->getTemplateKeywordLoc(), D,
   1701                             RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK,
   1702                             FoundD, TemplateArgs);
   1703   } else {
   1704     assert(!TemplateArgs && "No template arguments for non-variable"
   1705                             " template specialization references");
   1706     E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
   1707                                         : NestedNameSpecifierLoc(),
   1708                             SourceLocation(), D, RefersToCapturedVariable,
   1709                             NameInfo, Ty, VK, FoundD);
   1710   }
   1711 
   1712   MarkDeclRefReferenced(E);
   1713 
   1714   if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
   1715       Ty.getObjCLifetime() == Qualifiers::OCL_Weak &&
   1716       !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getLocStart()))
   1717       recordUseOfEvaluatedWeak(E);
   1718 
   1719   // Just in case we're building an illegal pointer-to-member.
   1720   FieldDecl *FD = dyn_cast<FieldDecl>(D);
   1721   if (FD && FD->isBitField())
   1722     E->setObjectKind(OK_BitField);
   1723 
   1724   return E;
   1725 }
   1726 
   1727 /// Decomposes the given name into a DeclarationNameInfo, its location, and
   1728 /// possibly a list of template arguments.
   1729 ///
   1730 /// If this produces template arguments, it is permitted to call
   1731 /// DecomposeTemplateName.
   1732 ///
   1733 /// This actually loses a lot of source location information for
   1734 /// non-standard name kinds; we should consider preserving that in
   1735 /// some way.
   1736 void
   1737 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
   1738                              TemplateArgumentListInfo &Buffer,
   1739                              DeclarationNameInfo &NameInfo,
   1740                              const TemplateArgumentListInfo *&TemplateArgs) {
   1741   if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
   1742     Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
   1743     Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
   1744 
   1745     ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
   1746                                        Id.TemplateId->NumArgs);
   1747     translateTemplateArguments(TemplateArgsPtr, Buffer);
   1748 
   1749     TemplateName TName = Id.TemplateId->Template.get();
   1750     SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
   1751     NameInfo = Context.getNameForTemplate(TName, TNameLoc);
   1752     TemplateArgs = &Buffer;
   1753   } else {
   1754     NameInfo = GetNameFromUnqualifiedId(Id);
   1755     TemplateArgs = nullptr;
   1756   }
   1757 }
   1758 
   1759 static void emitEmptyLookupTypoDiagnostic(
   1760     const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
   1761     DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
   1762     unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
   1763   DeclContext *Ctx =
   1764       SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
   1765   if (!TC) {
   1766     // Emit a special diagnostic for failed member lookups.
   1767     // FIXME: computing the declaration context might fail here (?)
   1768     if (Ctx)
   1769       SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
   1770                                                  << SS.getRange();
   1771     else
   1772       SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
   1773     return;
   1774   }
   1775 
   1776   std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
   1777   bool DroppedSpecifier =
   1778       TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
   1779   unsigned NoteID =
   1780       (TC.getCorrectionDecl() && isa<ImplicitParamDecl>(TC.getCorrectionDecl()))
   1781           ? diag::note_implicit_param_decl
   1782           : diag::note_previous_decl;
   1783   if (!Ctx)
   1784     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
   1785                          SemaRef.PDiag(NoteID));
   1786   else
   1787     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
   1788                                  << Typo << Ctx << DroppedSpecifier
   1789                                  << SS.getRange(),
   1790                          SemaRef.PDiag(NoteID));
   1791 }
   1792 
   1793 /// Diagnose an empty lookup.
   1794 ///
   1795 /// \return false if new lookup candidates were found
   1796 bool
   1797 Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
   1798                           std::unique_ptr<CorrectionCandidateCallback> CCC,
   1799                           TemplateArgumentListInfo *ExplicitTemplateArgs,
   1800                           ArrayRef<Expr *> Args, TypoExpr **Out) {
   1801   DeclarationName Name = R.getLookupName();
   1802 
   1803   unsigned diagnostic = diag::err_undeclared_var_use;
   1804   unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
   1805   if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
   1806       Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
   1807       Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
   1808     diagnostic = diag::err_undeclared_use;
   1809     diagnostic_suggest = diag::err_undeclared_use_suggest;
   1810   }
   1811 
   1812   // If the original lookup was an unqualified lookup, fake an
   1813   // unqualified lookup.  This is useful when (for example) the
   1814   // original lookup would not have found something because it was a
   1815   // dependent name.
   1816   DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
   1817   while (DC) {
   1818     if (isa<CXXRecordDecl>(DC)) {
   1819       LookupQualifiedName(R, DC);
   1820 
   1821       if (!R.empty()) {
   1822         // Don't give errors about ambiguities in this lookup.
   1823         R.suppressDiagnostics();
   1824 
   1825         // During a default argument instantiation the CurContext points
   1826         // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
   1827         // function parameter list, hence add an explicit check.
   1828         bool isDefaultArgument = !ActiveTemplateInstantiations.empty() &&
   1829                               ActiveTemplateInstantiations.back().Kind ==
   1830             ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
   1831         CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
   1832         bool isInstance = CurMethod &&
   1833                           CurMethod->isInstance() &&
   1834                           DC == CurMethod->getParent() && !isDefaultArgument;
   1835 
   1836         // Give a code modification hint to insert 'this->'.
   1837         // TODO: fixit for inserting 'Base<T>::' in the other cases.
   1838         // Actually quite difficult!
   1839         if (getLangOpts().MSVCCompat)
   1840           diagnostic = diag::ext_found_via_dependent_bases_lookup;
   1841         if (isInstance) {
   1842           Diag(R.getNameLoc(), diagnostic) << Name
   1843             << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
   1844           CheckCXXThisCapture(R.getNameLoc());
   1845         } else {
   1846           Diag(R.getNameLoc(), diagnostic) << Name;
   1847         }
   1848 
   1849         // Do we really want to note all of these?
   1850         for (NamedDecl *D : R)
   1851           Diag(D->getLocation(), diag::note_dependent_var_use);
   1852 
   1853         // Return true if we are inside a default argument instantiation
   1854         // and the found name refers to an instance member function, otherwise
   1855         // the function calling DiagnoseEmptyLookup will try to create an
   1856         // implicit member call and this is wrong for default argument.
   1857         if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
   1858           Diag(R.getNameLoc(), diag::err_member_call_without_object);
   1859           return true;
   1860         }
   1861 
   1862         // Tell the callee to try to recover.
   1863         return false;
   1864       }
   1865 
   1866       R.clear();
   1867     }
   1868 
   1869     // In Microsoft mode, if we are performing lookup from within a friend
   1870     // function definition declared at class scope then we must set
   1871     // DC to the lexical parent to be able to search into the parent
   1872     // class.
   1873     if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) &&
   1874         cast<FunctionDecl>(DC)->getFriendObjectKind() &&
   1875         DC->getLexicalParent()->isRecord())
   1876       DC = DC->getLexicalParent();
   1877     else
   1878       DC = DC->getParent();
   1879   }
   1880 
   1881   // We didn't find anything, so try to correct for a typo.
   1882   TypoCorrection Corrected;
   1883   if (S && Out) {
   1884     SourceLocation TypoLoc = R.getNameLoc();
   1885     assert(!ExplicitTemplateArgs &&
   1886            "Diagnosing an empty lookup with explicit template args!");
   1887     *Out = CorrectTypoDelayed(
   1888         R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC),
   1889         [=](const TypoCorrection &TC) {
   1890           emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
   1891                                         diagnostic, diagnostic_suggest);
   1892         },
   1893         nullptr, CTK_ErrorRecovery);
   1894     if (*Out)
   1895       return true;
   1896   } else if (S && (Corrected =
   1897                        CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S,
   1898                                    &SS, std::move(CCC), CTK_ErrorRecovery))) {
   1899     std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
   1900     bool DroppedSpecifier =
   1901         Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
   1902     R.setLookupName(Corrected.getCorrection());
   1903 
   1904     bool AcceptableWithRecovery = false;
   1905     bool AcceptableWithoutRecovery = false;
   1906     NamedDecl *ND = Corrected.getCorrectionDecl();
   1907     if (ND) {
   1908       if (Corrected.isOverloaded()) {
   1909         OverloadCandidateSet OCS(R.getNameLoc(),
   1910                                  OverloadCandidateSet::CSK_Normal);
   1911         OverloadCandidateSet::iterator Best;
   1912         for (NamedDecl *CD : Corrected) {
   1913           if (FunctionTemplateDecl *FTD =
   1914                    dyn_cast<FunctionTemplateDecl>(CD))
   1915             AddTemplateOverloadCandidate(
   1916                 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
   1917                 Args, OCS);
   1918           else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
   1919             if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
   1920               AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
   1921                                    Args, OCS);
   1922         }
   1923         switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
   1924         case OR_Success:
   1925           ND = Best->Function;
   1926           Corrected.setCorrectionDecl(ND);
   1927           break;
   1928         default:
   1929           // FIXME: Arbitrarily pick the first declaration for the note.
   1930           Corrected.setCorrectionDecl(ND);
   1931           break;
   1932         }
   1933       }
   1934       R.addDecl(ND);
   1935       if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
   1936         CXXRecordDecl *Record = nullptr;
   1937         if (Corrected.getCorrectionSpecifier()) {
   1938           const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
   1939           Record = Ty->getAsCXXRecordDecl();
   1940         }
   1941         if (!Record)
   1942           Record = cast<CXXRecordDecl>(
   1943               ND->getDeclContext()->getRedeclContext());
   1944         R.setNamingClass(Record);
   1945       }
   1946 
   1947       AcceptableWithRecovery =
   1948           isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND);
   1949       // FIXME: If we ended up with a typo for a type name or
   1950       // Objective-C class name, we're in trouble because the parser
   1951       // is in the wrong place to recover. Suggest the typo
   1952       // correction, but don't make it a fix-it since we're not going
   1953       // to recover well anyway.
   1954       AcceptableWithoutRecovery =
   1955           isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
   1956     } else {
   1957       // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
   1958       // because we aren't able to recover.
   1959       AcceptableWithoutRecovery = true;
   1960     }
   1961 
   1962     if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
   1963       unsigned NoteID = (Corrected.getCorrectionDecl() &&
   1964                          isa<ImplicitParamDecl>(Corrected.getCorrectionDecl()))
   1965                             ? diag::note_implicit_param_decl
   1966                             : diag::note_previous_decl;
   1967       if (SS.isEmpty())
   1968         diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
   1969                      PDiag(NoteID), AcceptableWithRecovery);
   1970       else
   1971         diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
   1972                                   << Name << computeDeclContext(SS, false)
   1973                                   << DroppedSpecifier << SS.getRange(),
   1974                      PDiag(NoteID), AcceptableWithRecovery);
   1975 
   1976       // Tell the callee whether to try to recover.
   1977       return !AcceptableWithRecovery;
   1978     }
   1979   }
   1980   R.clear();
   1981 
   1982   // Emit a special diagnostic for failed member lookups.
   1983   // FIXME: computing the declaration context might fail here (?)
   1984   if (!SS.isEmpty()) {
   1985     Diag(R.getNameLoc(), diag::err_no_member)
   1986       << Name << computeDeclContext(SS, false)
   1987       << SS.getRange();
   1988     return true;
   1989   }
   1990 
   1991   // Give up, we can't recover.
   1992   Diag(R.getNameLoc(), diagnostic) << Name;
   1993   return true;
   1994 }
   1995 
   1996 /// In Microsoft mode, if we are inside a template class whose parent class has
   1997 /// dependent base classes, and we can't resolve an unqualified identifier, then
   1998 /// assume the identifier is a member of a dependent base class.  We can only
   1999 /// recover successfully in static methods, instance methods, and other contexts
   2000 /// where 'this' is available.  This doesn't precisely match MSVC's
   2001 /// instantiation model, but it's close enough.
   2002 static Expr *
   2003 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
   2004                                DeclarationNameInfo &NameInfo,
   2005                                SourceLocation TemplateKWLoc,
   2006                                const TemplateArgumentListInfo *TemplateArgs) {
   2007   // Only try to recover from lookup into dependent bases in static methods or
   2008   // contexts where 'this' is available.
   2009   QualType ThisType = S.getCurrentThisType();
   2010   const CXXRecordDecl *RD = nullptr;
   2011   if (!ThisType.isNull())
   2012     RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
   2013   else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
   2014     RD = MD->getParent();
   2015   if (!RD || !RD->hasAnyDependentBases())
   2016     return nullptr;
   2017 
   2018   // Diagnose this as unqualified lookup into a dependent base class.  If 'this'
   2019   // is available, suggest inserting 'this->' as a fixit.
   2020   SourceLocation Loc = NameInfo.getLoc();
   2021   auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
   2022   DB << NameInfo.getName() << RD;
   2023 
   2024   if (!ThisType.isNull()) {
   2025     DB << FixItHint::CreateInsertion(Loc, "this->");
   2026     return CXXDependentScopeMemberExpr::Create(
   2027         Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
   2028         /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
   2029         /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs);
   2030   }
   2031 
   2032   // Synthesize a fake NNS that points to the derived class.  This will
   2033   // perform name lookup during template instantiation.
   2034   CXXScopeSpec SS;
   2035   auto *NNS =
   2036       NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
   2037   SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
   2038   return DependentScopeDeclRefExpr::Create(
   2039       Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
   2040       TemplateArgs);
   2041 }
   2042 
   2043 ExprResult
   2044 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
   2045                         SourceLocation TemplateKWLoc, UnqualifiedId &Id,
   2046                         bool HasTrailingLParen, bool IsAddressOfOperand,
   2047                         std::unique_ptr<CorrectionCandidateCallback> CCC,
   2048                         bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
   2049   assert(!(IsAddressOfOperand && HasTrailingLParen) &&
   2050          "cannot be direct & operand and have a trailing lparen");
   2051   if (SS.isInvalid())
   2052     return ExprError();
   2053 
   2054   TemplateArgumentListInfo TemplateArgsBuffer;
   2055 
   2056   // Decompose the UnqualifiedId into the following data.
   2057   DeclarationNameInfo NameInfo;
   2058   const TemplateArgumentListInfo *TemplateArgs;
   2059   DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
   2060 
   2061   DeclarationName Name = NameInfo.getName();
   2062   IdentifierInfo *II = Name.getAsIdentifierInfo();
   2063   SourceLocation NameLoc = NameInfo.getLoc();
   2064 
   2065   // C++ [temp.dep.expr]p3:
   2066   //   An id-expression is type-dependent if it contains:
   2067   //     -- an identifier that was declared with a dependent type,
   2068   //        (note: handled after lookup)
   2069   //     -- a template-id that is dependent,
   2070   //        (note: handled in BuildTemplateIdExpr)
   2071   //     -- a conversion-function-id that specifies a dependent type,
   2072   //     -- a nested-name-specifier that contains a class-name that
   2073   //        names a dependent type.
   2074   // Determine whether this is a member of an unknown specialization;
   2075   // we need to handle these differently.
   2076   bool DependentID = false;
   2077   if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
   2078       Name.getCXXNameType()->isDependentType()) {
   2079     DependentID = true;
   2080   } else if (SS.isSet()) {
   2081     if (DeclContext *DC = computeDeclContext(SS, false)) {
   2082       if (RequireCompleteDeclContext(SS, DC))
   2083         return ExprError();
   2084     } else {
   2085       DependentID = true;
   2086     }
   2087   }
   2088 
   2089   if (DependentID)
   2090     return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
   2091                                       IsAddressOfOperand, TemplateArgs);
   2092 
   2093   // Perform the required lookup.
   2094   LookupResult R(*this, NameInfo,
   2095                  (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
   2096                   ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
   2097   if (TemplateArgs) {
   2098     // Lookup the template name again to correctly establish the context in
   2099     // which it was found. This is really unfortunate as we already did the
   2100     // lookup to determine that it was a template name in the first place. If
   2101     // this becomes a performance hit, we can work harder to preserve those
   2102     // results until we get here but it's likely not worth it.
   2103     bool MemberOfUnknownSpecialization;
   2104     LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
   2105                        MemberOfUnknownSpecialization);
   2106 
   2107     if (MemberOfUnknownSpecialization ||
   2108         (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
   2109       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
   2110                                         IsAddressOfOperand, TemplateArgs);
   2111   } else {
   2112     bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
   2113     LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
   2114 
   2115     // If the result might be in a dependent base class, this is a dependent
   2116     // id-expression.
   2117     if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
   2118       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
   2119                                         IsAddressOfOperand, TemplateArgs);
   2120 
   2121     // If this reference is in an Objective-C method, then we need to do
   2122     // some special Objective-C lookup, too.
   2123     if (IvarLookupFollowUp) {
   2124       ExprResult E(LookupInObjCMethod(R, S, II, true));
   2125       if (E.isInvalid())
   2126         return ExprError();
   2127 
   2128       if (Expr *Ex = E.getAs<Expr>())
   2129         return Ex;
   2130     }
   2131   }
   2132 
   2133   if (R.isAmbiguous())
   2134     return ExprError();
   2135 
   2136   // This could be an implicitly declared function reference (legal in C90,
   2137   // extension in C99, forbidden in C++).
   2138   if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
   2139     NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
   2140     if (D) R.addDecl(D);
   2141   }
   2142 
   2143   // Determine whether this name might be a candidate for
   2144   // argument-dependent lookup.
   2145   bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
   2146 
   2147   if (R.empty() && !ADL) {
   2148     if (SS.isEmpty() && getLangOpts().MSVCCompat) {
   2149       if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
   2150                                                    TemplateKWLoc, TemplateArgs))
   2151         return E;
   2152     }
   2153 
   2154     // Don't diagnose an empty lookup for inline assembly.
   2155     if (IsInlineAsmIdentifier)
   2156       return ExprError();
   2157 
   2158     // If this name wasn't predeclared and if this is not a function
   2159     // call, diagnose the problem.
   2160     TypoExpr *TE = nullptr;
   2161     auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>(
   2162         II, SS.isValid() ? SS.getScopeRep() : nullptr);
   2163     DefaultValidator->IsAddressOfOperand = IsAddressOfOperand;
   2164     assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
   2165            "Typo correction callback misconfigured");
   2166     if (CCC) {
   2167       // Make sure the callback knows what the typo being diagnosed is.
   2168       CCC->setTypoName(II);
   2169       if (SS.isValid())
   2170         CCC->setTypoNNS(SS.getScopeRep());
   2171     }
   2172     if (DiagnoseEmptyLookup(S, SS, R,
   2173                             CCC ? std::move(CCC) : std::move(DefaultValidator),
   2174                             nullptr, None, &TE)) {
   2175       if (TE && KeywordReplacement) {
   2176         auto &State = getTypoExprState(TE);
   2177         auto BestTC = State.Consumer->getNextCorrection();
   2178         if (BestTC.isKeyword()) {
   2179           auto *II = BestTC.getCorrectionAsIdentifierInfo();
   2180           if (State.DiagHandler)
   2181             State.DiagHandler(BestTC);
   2182           KeywordReplacement->startToken();
   2183           KeywordReplacement->setKind(II->getTokenID());
   2184           KeywordReplacement->setIdentifierInfo(II);
   2185           KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
   2186           // Clean up the state associated with the TypoExpr, since it has
   2187           // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
   2188           clearDelayedTypo(TE);
   2189           // Signal that a correction to a keyword was performed by returning a
   2190           // valid-but-null ExprResult.
   2191           return (Expr*)nullptr;
   2192         }
   2193         State.Consumer->resetCorrectionStream();
   2194       }
   2195       return TE ? TE : ExprError();
   2196     }
   2197 
   2198     assert(!R.empty() &&
   2199            "DiagnoseEmptyLookup returned false but added no results");
   2200 
   2201     // If we found an Objective-C instance variable, let
   2202     // LookupInObjCMethod build the appropriate expression to
   2203     // reference the ivar.
   2204     if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
   2205       R.clear();
   2206       ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
   2207       // In a hopelessly buggy code, Objective-C instance variable
   2208       // lookup fails and no expression will be built to reference it.
   2209       if (!E.isInvalid() && !E.get())
   2210         return ExprError();
   2211       return E;
   2212     }
   2213   }
   2214 
   2215   // This is guaranteed from this point on.
   2216   assert(!R.empty() || ADL);
   2217 
   2218   // Check whether this might be a C++ implicit instance member access.
   2219   // C++ [class.mfct.non-static]p3:
   2220   //   When an id-expression that is not part of a class member access
   2221   //   syntax and not used to form a pointer to member is used in the
   2222   //   body of a non-static member function of class X, if name lookup
   2223   //   resolves the name in the id-expression to a non-static non-type
   2224   //   member of some class C, the id-expression is transformed into a
   2225   //   class member access expression using (*this) as the
   2226   //   postfix-expression to the left of the . operator.
   2227   //
   2228   // But we don't actually need to do this for '&' operands if R
   2229   // resolved to a function or overloaded function set, because the
   2230   // expression is ill-formed if it actually works out to be a
   2231   // non-static member function:
   2232   //
   2233   // C++ [expr.ref]p4:
   2234   //   Otherwise, if E1.E2 refers to a non-static member function. . .
   2235   //   [t]he expression can be used only as the left-hand operand of a
   2236   //   member function call.
   2237   //
   2238   // There are other safeguards against such uses, but it's important
   2239   // to get this right here so that we don't end up making a
   2240   // spuriously dependent expression if we're inside a dependent
   2241   // instance method.
   2242   if (!R.empty() && (*R.begin())->isCXXClassMember()) {
   2243     bool MightBeImplicitMember;
   2244     if (!IsAddressOfOperand)
   2245       MightBeImplicitMember = true;
   2246     else if (!SS.isEmpty())
   2247       MightBeImplicitMember = false;
   2248     else if (R.isOverloadedResult())
   2249       MightBeImplicitMember = false;
   2250     else if (R.isUnresolvableResult())
   2251       MightBeImplicitMember = true;
   2252     else
   2253       MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
   2254                               isa<IndirectFieldDecl>(R.getFoundDecl()) ||
   2255                               isa<MSPropertyDecl>(R.getFoundDecl());
   2256 
   2257     if (MightBeImplicitMember)
   2258       return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
   2259                                              R, TemplateArgs, S);
   2260   }
   2261 
   2262   if (TemplateArgs || TemplateKWLoc.isValid()) {
   2263 
   2264     // In C++1y, if this is a variable template id, then check it
   2265     // in BuildTemplateIdExpr().
   2266     // The single lookup result must be a variable template declaration.
   2267     if (Id.getKind() == UnqualifiedId::IK_TemplateId && Id.TemplateId &&
   2268         Id.TemplateId->Kind == TNK_Var_template) {
   2269       assert(R.getAsSingle<VarTemplateDecl>() &&
   2270              "There should only be one declaration found.");
   2271     }
   2272 
   2273     return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
   2274   }
   2275 
   2276   return BuildDeclarationNameExpr(SS, R, ADL);
   2277 }
   2278 
   2279 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
   2280 /// declaration name, generally during template instantiation.
   2281 /// There's a large number of things which don't need to be done along
   2282 /// this path.
   2283 ExprResult Sema::BuildQualifiedDeclarationNameExpr(
   2284     CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
   2285     bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
   2286   DeclContext *DC = computeDeclContext(SS, false);
   2287   if (!DC)
   2288     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
   2289                                      NameInfo, /*TemplateArgs=*/nullptr);
   2290 
   2291   if (RequireCompleteDeclContext(SS, DC))
   2292     return ExprError();
   2293 
   2294   LookupResult R(*this, NameInfo, LookupOrdinaryName);
   2295   LookupQualifiedName(R, DC);
   2296 
   2297   if (R.isAmbiguous())
   2298     return ExprError();
   2299 
   2300   if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
   2301     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
   2302                                      NameInfo, /*TemplateArgs=*/nullptr);
   2303 
   2304   if (R.empty()) {
   2305     Diag(NameInfo.getLoc(), diag::err_no_member)
   2306       << NameInfo.getName() << DC << SS.getRange();
   2307     return ExprError();
   2308   }
   2309 
   2310   if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
   2311     // Diagnose a missing typename if this resolved unambiguously to a type in
   2312     // a dependent context.  If we can recover with a type, downgrade this to
   2313     // a warning in Microsoft compatibility mode.
   2314     unsigned DiagID = diag::err_typename_missing;
   2315     if (RecoveryTSI && getLangOpts().MSVCCompat)
   2316       DiagID = diag::ext_typename_missing;
   2317     SourceLocation Loc = SS.getBeginLoc();
   2318     auto D = Diag(Loc, DiagID);
   2319     D << SS.getScopeRep() << NameInfo.getName().getAsString()
   2320       << SourceRange(Loc, NameInfo.getEndLoc());
   2321 
   2322     // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
   2323     // context.
   2324     if (!RecoveryTSI)
   2325       return ExprError();
   2326 
   2327     // Only issue the fixit if we're prepared to recover.
   2328     D << FixItHint::CreateInsertion(Loc, "typename ");
   2329 
   2330     // Recover by pretending this was an elaborated type.
   2331     QualType Ty = Context.getTypeDeclType(TD);
   2332     TypeLocBuilder TLB;
   2333     TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
   2334 
   2335     QualType ET = getElaboratedType(ETK_None, SS, Ty);
   2336     ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
   2337     QTL.setElaboratedKeywordLoc(SourceLocation());
   2338     QTL.setQualifierLoc(SS.getWithLocInContext(Context));
   2339 
   2340     *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
   2341 
   2342     return ExprEmpty();
   2343   }
   2344 
   2345   // Defend against this resolving to an implicit member access. We usually
   2346   // won't get here if this might be a legitimate a class member (we end up in
   2347   // BuildMemberReferenceExpr instead), but this can be valid if we're forming
   2348   // a pointer-to-member or in an unevaluated context in C++11.
   2349   if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
   2350     return BuildPossibleImplicitMemberExpr(SS,
   2351                                            /*TemplateKWLoc=*/SourceLocation(),
   2352                                            R, /*TemplateArgs=*/nullptr, S);
   2353 
   2354   return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
   2355 }
   2356 
   2357 /// LookupInObjCMethod - The parser has read a name in, and Sema has
   2358 /// detected that we're currently inside an ObjC method.  Perform some
   2359 /// additional lookup.
   2360 ///
   2361 /// Ideally, most of this would be done by lookup, but there's
   2362 /// actually quite a lot of extra work involved.
   2363 ///
   2364 /// Returns a null sentinel to indicate trivial success.
   2365 ExprResult
   2366 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
   2367                          IdentifierInfo *II, bool AllowBuiltinCreation) {
   2368   SourceLocation Loc = Lookup.getNameLoc();
   2369   ObjCMethodDecl *CurMethod = getCurMethodDecl();
   2370 
   2371   // Check for error condition which is already reported.
   2372   if (!CurMethod)
   2373     return ExprError();
   2374 
   2375   // There are two cases to handle here.  1) scoped lookup could have failed,
   2376   // in which case we should look for an ivar.  2) scoped lookup could have
   2377   // found a decl, but that decl is outside the current instance method (i.e.
   2378   // a global variable).  In these two cases, we do a lookup for an ivar with
   2379   // this name, if the lookup sucedes, we replace it our current decl.
   2380 
   2381   // If we're in a class method, we don't normally want to look for
   2382   // ivars.  But if we don't find anything else, and there's an
   2383   // ivar, that's an error.
   2384   bool IsClassMethod = CurMethod->isClassMethod();
   2385 
   2386   bool LookForIvars;
   2387   if (Lookup.empty())
   2388     LookForIvars = true;
   2389   else if (IsClassMethod)
   2390     LookForIvars = false;
   2391   else
   2392     LookForIvars = (Lookup.isSingleResult() &&
   2393                     Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
   2394   ObjCInterfaceDecl *IFace = nullptr;
   2395   if (LookForIvars) {
   2396     IFace = CurMethod->getClassInterface();
   2397     ObjCInterfaceDecl *ClassDeclared;
   2398     ObjCIvarDecl *IV = nullptr;
   2399     if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
   2400       // Diagnose using an ivar in a class method.
   2401       if (IsClassMethod)
   2402         return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
   2403                          << IV->getDeclName());
   2404 
   2405       // If we're referencing an invalid decl, just return this as a silent
   2406       // error node.  The error diagnostic was already emitted on the decl.
   2407       if (IV->isInvalidDecl())
   2408         return ExprError();
   2409 
   2410       // Check if referencing a field with __attribute__((deprecated)).
   2411       if (DiagnoseUseOfDecl(IV, Loc))
   2412         return ExprError();
   2413 
   2414       // Diagnose the use of an ivar outside of the declaring class.
   2415       if (IV->getAccessControl() == ObjCIvarDecl::Private &&
   2416           !declaresSameEntity(ClassDeclared, IFace) &&
   2417           !getLangOpts().DebuggerSupport)
   2418         Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
   2419 
   2420       // FIXME: This should use a new expr for a direct reference, don't
   2421       // turn this into Self->ivar, just return a BareIVarExpr or something.
   2422       IdentifierInfo &II = Context.Idents.get("self");
   2423       UnqualifiedId SelfName;
   2424       SelfName.setIdentifier(&II, SourceLocation());
   2425       SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
   2426       CXXScopeSpec SelfScopeSpec;
   2427       SourceLocation TemplateKWLoc;
   2428       ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
   2429                                               SelfName, false, false);
   2430       if (SelfExpr.isInvalid())
   2431         return ExprError();
   2432 
   2433       SelfExpr = DefaultLvalueConversion(SelfExpr.get());
   2434       if (SelfExpr.isInvalid())
   2435         return ExprError();
   2436 
   2437       MarkAnyDeclReferenced(Loc, IV, true);
   2438 
   2439       ObjCMethodFamily MF = CurMethod->getMethodFamily();
   2440       if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
   2441           !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
   2442         Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
   2443 
   2444       ObjCIvarRefExpr *Result = new (Context)
   2445           ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
   2446                           IV->getLocation(), SelfExpr.get(), true, true);
   2447 
   2448       if (getLangOpts().ObjCAutoRefCount) {
   2449         if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
   2450           if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
   2451             recordUseOfEvaluatedWeak(Result);
   2452         }
   2453         if (CurContext->isClosure())
   2454           Diag(Loc, diag::warn_implicitly_retains_self)
   2455             << FixItHint::CreateInsertion(Loc, "self->");
   2456       }
   2457 
   2458       return Result;
   2459     }
   2460   } else if (CurMethod->isInstanceMethod()) {
   2461     // We should warn if a local variable hides an ivar.
   2462     if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
   2463       ObjCInterfaceDecl *ClassDeclared;
   2464       if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
   2465         if (IV->getAccessControl() != ObjCIvarDecl::Private ||
   2466             declaresSameEntity(IFace, ClassDeclared))
   2467           Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
   2468       }
   2469     }
   2470   } else if (Lookup.isSingleResult() &&
   2471              Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
   2472     // If accessing a stand-alone ivar in a class method, this is an error.
   2473     if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
   2474       return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
   2475                        << IV->getDeclName());
   2476   }
   2477 
   2478   if (Lookup.empty() && II && AllowBuiltinCreation) {
   2479     // FIXME. Consolidate this with similar code in LookupName.
   2480     if (unsigned BuiltinID = II->getBuiltinID()) {
   2481       if (!(getLangOpts().CPlusPlus &&
   2482             Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
   2483         NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
   2484                                            S, Lookup.isForRedeclaration(),
   2485                                            Lookup.getNameLoc());
   2486         if (D) Lookup.addDecl(D);
   2487       }
   2488     }
   2489   }
   2490   // Sentinel value saying that we didn't do anything special.
   2491   return ExprResult((Expr *)nullptr);
   2492 }
   2493 
   2494 /// \brief Cast a base object to a member's actual type.
   2495 ///
   2496 /// Logically this happens in three phases:
   2497 ///
   2498 /// * First we cast from the base type to the naming class.
   2499 ///   The naming class is the class into which we were looking
   2500 ///   when we found the member;  it's the qualifier type if a
   2501 ///   qualifier was provided, and otherwise it's the base type.
   2502 ///
   2503 /// * Next we cast from the naming class to the declaring class.
   2504 ///   If the member we found was brought into a class's scope by
   2505 ///   a using declaration, this is that class;  otherwise it's
   2506 ///   the class declaring the member.
   2507 ///
   2508 /// * Finally we cast from the declaring class to the "true"
   2509 ///   declaring class of the member.  This conversion does not
   2510 ///   obey access control.
   2511 ExprResult
   2512 Sema::PerformObjectMemberConversion(Expr *From,
   2513                                     NestedNameSpecifier *Qualifier,
   2514                                     NamedDecl *FoundDecl,
   2515                                     NamedDecl *Member) {
   2516   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
   2517   if (!RD)
   2518     return From;
   2519 
   2520   QualType DestRecordType;
   2521   QualType DestType;
   2522   QualType FromRecordType;
   2523   QualType FromType = From->getType();
   2524   bool PointerConversions = false;
   2525   if (isa<FieldDecl>(Member)) {
   2526     DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
   2527 
   2528     if (FromType->getAs<PointerType>()) {
   2529       DestType = Context.getPointerType(DestRecordType);
   2530       FromRecordType = FromType->getPointeeType();
   2531       PointerConversions = true;
   2532     } else {
   2533       DestType = DestRecordType;
   2534       FromRecordType = FromType;
   2535     }
   2536   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
   2537     if (Method->isStatic())
   2538       return From;
   2539 
   2540     DestType = Method->getThisType(Context);
   2541     DestRecordType = DestType->getPointeeType();
   2542 
   2543     if (FromType->getAs<PointerType>()) {
   2544       FromRecordType = FromType->getPointeeType();
   2545       PointerConversions = true;
   2546     } else {
   2547       FromRecordType = FromType;
   2548       DestType = DestRecordType;
   2549     }
   2550   } else {
   2551     // No conversion necessary.
   2552     return From;
   2553   }
   2554 
   2555   if (DestType->isDependentType() || FromType->isDependentType())
   2556     return From;
   2557 
   2558   // If the unqualified types are the same, no conversion is necessary.
   2559   if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
   2560     return From;
   2561 
   2562   SourceRange FromRange = From->getSourceRange();
   2563   SourceLocation FromLoc = FromRange.getBegin();
   2564 
   2565   ExprValueKind VK = From->getValueKind();
   2566 
   2567   // C++ [class.member.lookup]p8:
   2568   //   [...] Ambiguities can often be resolved by qualifying a name with its
   2569   //   class name.
   2570   //
   2571   // If the member was a qualified name and the qualified referred to a
   2572   // specific base subobject type, we'll cast to that intermediate type
   2573   // first and then to the object in which the member is declared. That allows
   2574   // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
   2575   //
   2576   //   class Base { public: int x; };
   2577   //   class Derived1 : public Base { };
   2578   //   class Derived2 : public Base { };
   2579   //   class VeryDerived : public Derived1, public Derived2 { void f(); };
   2580   //
   2581   //   void VeryDerived::f() {
   2582   //     x = 17; // error: ambiguous base subobjects
   2583   //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
   2584   //   }
   2585   if (Qualifier && Qualifier->getAsType()) {
   2586     QualType QType = QualType(Qualifier->getAsType(), 0);
   2587     assert(QType->isRecordType() && "lookup done with non-record type");
   2588 
   2589     QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
   2590 
   2591     // In C++98, the qualifier type doesn't actually have to be a base
   2592     // type of the object type, in which case we just ignore it.
   2593     // Otherwise build the appropriate casts.
   2594     if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
   2595       CXXCastPath BasePath;
   2596       if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
   2597                                        FromLoc, FromRange, &BasePath))
   2598         return ExprError();
   2599 
   2600       if (PointerConversions)
   2601         QType = Context.getPointerType(QType);
   2602       From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
   2603                                VK, &BasePath).get();
   2604 
   2605       FromType = QType;
   2606       FromRecordType = QRecordType;
   2607 
   2608       // If the qualifier type was the same as the destination type,
   2609       // we're done.
   2610       if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
   2611         return From;
   2612     }
   2613   }
   2614 
   2615   bool IgnoreAccess = false;
   2616 
   2617   // If we actually found the member through a using declaration, cast
   2618   // down to the using declaration's type.
   2619   //
   2620   // Pointer equality is fine here because only one declaration of a
   2621   // class ever has member declarations.
   2622   if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
   2623     assert(isa<UsingShadowDecl>(FoundDecl));
   2624     QualType URecordType = Context.getTypeDeclType(
   2625                            cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
   2626 
   2627     // We only need to do this if the naming-class to declaring-class
   2628     // conversion is non-trivial.
   2629     if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
   2630       assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType));
   2631       CXXCastPath BasePath;
   2632       if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
   2633                                        FromLoc, FromRange, &BasePath))
   2634         return ExprError();
   2635 
   2636       QualType UType = URecordType;
   2637       if (PointerConversions)
   2638         UType = Context.getPointerType(UType);
   2639       From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
   2640                                VK, &BasePath).get();
   2641       FromType = UType;
   2642       FromRecordType = URecordType;
   2643     }
   2644 
   2645     // We don't do access control for the conversion from the
   2646     // declaring class to the true declaring class.
   2647     IgnoreAccess = true;
   2648   }
   2649 
   2650   CXXCastPath BasePath;
   2651   if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
   2652                                    FromLoc, FromRange, &BasePath,
   2653                                    IgnoreAccess))
   2654     return ExprError();
   2655 
   2656   return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
   2657                            VK, &BasePath);
   2658 }
   2659 
   2660 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
   2661                                       const LookupResult &R,
   2662                                       bool HasTrailingLParen) {
   2663   // Only when used directly as the postfix-expression of a call.
   2664   if (!HasTrailingLParen)
   2665     return false;
   2666 
   2667   // Never if a scope specifier was provided.
   2668   if (SS.isSet())
   2669     return false;
   2670 
   2671   // Only in C++ or ObjC++.
   2672   if (!getLangOpts().CPlusPlus)
   2673     return false;
   2674 
   2675   // Turn off ADL when we find certain kinds of declarations during
   2676   // normal lookup:
   2677   for (NamedDecl *D : R) {
   2678     // C++0x [basic.lookup.argdep]p3:
   2679     //     -- a declaration of a class member
   2680     // Since using decls preserve this property, we check this on the
   2681     // original decl.
   2682     if (D->isCXXClassMember())
   2683       return false;
   2684 
   2685     // C++0x [basic.lookup.argdep]p3:
   2686     //     -- a block-scope function declaration that is not a
   2687     //        using-declaration
   2688     // NOTE: we also trigger this for function templates (in fact, we
   2689     // don't check the decl type at all, since all other decl types
   2690     // turn off ADL anyway).
   2691     if (isa<UsingShadowDecl>(D))
   2692       D = cast<UsingShadowDecl>(D)->getTargetDecl();
   2693     else if (D->getLexicalDeclContext()->isFunctionOrMethod())
   2694       return false;
   2695 
   2696     // C++0x [basic.lookup.argdep]p3:
   2697     //     -- a declaration that is neither a function or a function
   2698     //        template
   2699     // And also for builtin functions.
   2700     if (isa<FunctionDecl>(D)) {
   2701       FunctionDecl *FDecl = cast<FunctionDecl>(D);
   2702 
   2703       // But also builtin functions.
   2704       if (FDecl->getBuiltinID() && FDecl->isImplicit())
   2705         return false;
   2706     } else if (!isa<FunctionTemplateDecl>(D))
   2707       return false;
   2708   }
   2709 
   2710   return true;
   2711 }
   2712 
   2713 
   2714 /// Diagnoses obvious problems with the use of the given declaration
   2715 /// as an expression.  This is only actually called for lookups that
   2716 /// were not overloaded, and it doesn't promise that the declaration
   2717 /// will in fact be used.
   2718 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
   2719   if (isa<TypedefNameDecl>(D)) {
   2720     S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
   2721     return true;
   2722   }
   2723 
   2724   if (isa<ObjCInterfaceDecl>(D)) {
   2725     S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
   2726     return true;
   2727   }
   2728 
   2729   if (isa<NamespaceDecl>(D)) {
   2730     S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
   2731     return true;
   2732   }
   2733 
   2734   return false;
   2735 }
   2736 
   2737 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
   2738                                           LookupResult &R, bool NeedsADL,
   2739                                           bool AcceptInvalidDecl) {
   2740   // If this is a single, fully-resolved result and we don't need ADL,
   2741   // just build an ordinary singleton decl ref.
   2742   if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
   2743     return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
   2744                                     R.getRepresentativeDecl(), nullptr,
   2745                                     AcceptInvalidDecl);
   2746 
   2747   // We only need to check the declaration if there's exactly one
   2748   // result, because in the overloaded case the results can only be
   2749   // functions and function templates.
   2750   if (R.isSingleResult() &&
   2751       CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
   2752     return ExprError();
   2753 
   2754   // Otherwise, just build an unresolved lookup expression.  Suppress
   2755   // any lookup-related diagnostics; we'll hash these out later, when
   2756   // we've picked a target.
   2757   R.suppressDiagnostics();
   2758 
   2759   UnresolvedLookupExpr *ULE
   2760     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
   2761                                    SS.getWithLocInContext(Context),
   2762                                    R.getLookupNameInfo(),
   2763                                    NeedsADL, R.isOverloadedResult(),
   2764                                    R.begin(), R.end());
   2765 
   2766   return ULE;
   2767 }
   2768 
   2769 /// \brief Complete semantic analysis for a reference to the given declaration.
   2770 ExprResult Sema::BuildDeclarationNameExpr(
   2771     const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
   2772     NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
   2773     bool AcceptInvalidDecl) {
   2774   assert(D && "Cannot refer to a NULL declaration");
   2775   assert(!isa<FunctionTemplateDecl>(D) &&
   2776          "Cannot refer unambiguously to a function template");
   2777 
   2778   SourceLocation Loc = NameInfo.getLoc();
   2779   if (CheckDeclInExpr(*this, Loc, D))
   2780     return ExprError();
   2781 
   2782   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
   2783     // Specifically diagnose references to class templates that are missing
   2784     // a template argument list.
   2785     Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0)
   2786                                            << Template << SS.getRange();
   2787     Diag(Template->getLocation(), diag::note_template_decl_here);
   2788     return ExprError();
   2789   }
   2790 
   2791   // Make sure that we're referring to a value.
   2792   ValueDecl *VD = dyn_cast<ValueDecl>(D);
   2793   if (!VD) {
   2794     Diag(Loc, diag::err_ref_non_value)
   2795       << D << SS.getRange();
   2796     Diag(D->getLocation(), diag::note_declared_at);
   2797     return ExprError();
   2798   }
   2799 
   2800   // Check whether this declaration can be used. Note that we suppress
   2801   // this check when we're going to perform argument-dependent lookup
   2802   // on this function name, because this might not be the function
   2803   // that overload resolution actually selects.
   2804   if (DiagnoseUseOfDecl(VD, Loc))
   2805     return ExprError();
   2806 
   2807   // Only create DeclRefExpr's for valid Decl's.
   2808   if (VD->isInvalidDecl() && !AcceptInvalidDecl)
   2809     return ExprError();
   2810 
   2811   // Handle members of anonymous structs and unions.  If we got here,
   2812   // and the reference is to a class member indirect field, then this
   2813   // must be the subject of a pointer-to-member expression.
   2814   if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
   2815     if (!indirectField->isCXXClassMember())
   2816       return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
   2817                                                       indirectField);
   2818 
   2819   {
   2820     QualType type = VD->getType();
   2821     ExprValueKind valueKind = VK_RValue;
   2822 
   2823     switch (D->getKind()) {
   2824     // Ignore all the non-ValueDecl kinds.
   2825 #define ABSTRACT_DECL(kind)
   2826 #define VALUE(type, base)
   2827 #define DECL(type, base) \
   2828     case Decl::type:
   2829 #include "clang/AST/DeclNodes.inc"
   2830       llvm_unreachable("invalid value decl kind");
   2831 
   2832     // These shouldn't make it here.
   2833     case Decl::ObjCAtDefsField:
   2834     case Decl::ObjCIvar:
   2835       llvm_unreachable("forming non-member reference to ivar?");
   2836 
   2837     // Enum constants are always r-values and never references.
   2838     // Unresolved using declarations are dependent.
   2839     case Decl::EnumConstant:
   2840     case Decl::UnresolvedUsingValue:
   2841       valueKind = VK_RValue;
   2842       break;
   2843 
   2844     // Fields and indirect fields that got here must be for
   2845     // pointer-to-member expressions; we just call them l-values for
   2846     // internal consistency, because this subexpression doesn't really
   2847     // exist in the high-level semantics.
   2848     case Decl::Field:
   2849     case Decl::IndirectField:
   2850       assert(getLangOpts().CPlusPlus &&
   2851              "building reference to field in C?");
   2852 
   2853       // These can't have reference type in well-formed programs, but
   2854       // for internal consistency we do this anyway.
   2855       type = type.getNonReferenceType();
   2856       valueKind = VK_LValue;
   2857       break;
   2858 
   2859     // Non-type template parameters are either l-values or r-values
   2860     // depending on the type.
   2861     case Decl::NonTypeTemplateParm: {
   2862       if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
   2863         type = reftype->getPointeeType();
   2864         valueKind = VK_LValue; // even if the parameter is an r-value reference
   2865         break;
   2866       }
   2867 
   2868       // For non-references, we need to strip qualifiers just in case
   2869       // the template parameter was declared as 'const int' or whatever.
   2870       valueKind = VK_RValue;
   2871       type = type.getUnqualifiedType();
   2872       break;
   2873     }
   2874 
   2875     case Decl::Var:
   2876     case Decl::VarTemplateSpecialization:
   2877     case Decl::VarTemplatePartialSpecialization:
   2878       // In C, "extern void blah;" is valid and is an r-value.
   2879       if (!getLangOpts().CPlusPlus &&
   2880           !type.hasQualifiers() &&
   2881           type->isVoidType()) {
   2882         valueKind = VK_RValue;
   2883         break;
   2884       }
   2885       // fallthrough
   2886 
   2887     case Decl::ImplicitParam:
   2888     case Decl::ParmVar: {
   2889       // These are always l-values.
   2890       valueKind = VK_LValue;
   2891       type = type.getNonReferenceType();
   2892 
   2893       // FIXME: Does the addition of const really only apply in
   2894       // potentially-evaluated contexts? Since the variable isn't actually
   2895       // captured in an unevaluated context, it seems that the answer is no.
   2896       if (!isUnevaluatedContext()) {
   2897         QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
   2898         if (!CapturedType.isNull())
   2899           type = CapturedType;
   2900       }
   2901 
   2902       break;
   2903     }
   2904 
   2905     case Decl::Function: {
   2906       if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
   2907         if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
   2908           type = Context.BuiltinFnTy;
   2909           valueKind = VK_RValue;
   2910           break;
   2911         }
   2912       }
   2913 
   2914       const FunctionType *fty = type->castAs<FunctionType>();
   2915 
   2916       // If we're referring to a function with an __unknown_anytype
   2917       // result type, make the entire expression __unknown_anytype.
   2918       if (fty->getReturnType() == Context.UnknownAnyTy) {
   2919         type = Context.UnknownAnyTy;
   2920         valueKind = VK_RValue;
   2921         break;
   2922       }
   2923 
   2924       // Functions are l-values in C++.
   2925       if (getLangOpts().CPlusPlus) {
   2926         valueKind = VK_LValue;
   2927         break;
   2928       }
   2929 
   2930       // C99 DR 316 says that, if a function type comes from a
   2931       // function definition (without a prototype), that type is only
   2932       // used for checking compatibility. Therefore, when referencing
   2933       // the function, we pretend that we don't have the full function
   2934       // type.
   2935       if (!cast<FunctionDecl>(VD)->hasPrototype() &&
   2936           isa<FunctionProtoType>(fty))
   2937         type = Context.getFunctionNoProtoType(fty->getReturnType(),
   2938                                               fty->getExtInfo());
   2939 
   2940       // Functions are r-values in C.
   2941       valueKind = VK_RValue;
   2942       break;
   2943     }
   2944 
   2945     case Decl::MSProperty:
   2946       valueKind = VK_LValue;
   2947       break;
   2948 
   2949     case Decl::CXXMethod:
   2950       // If we're referring to a method with an __unknown_anytype
   2951       // result type, make the entire expression __unknown_anytype.
   2952       // This should only be possible with a type written directly.
   2953       if (const FunctionProtoType *proto
   2954             = dyn_cast<FunctionProtoType>(VD->getType()))
   2955         if (proto->getReturnType() == Context.UnknownAnyTy) {
   2956           type = Context.UnknownAnyTy;
   2957           valueKind = VK_RValue;
   2958           break;
   2959         }
   2960 
   2961       // C++ methods are l-values if static, r-values if non-static.
   2962       if (cast<CXXMethodDecl>(VD)->isStatic()) {
   2963         valueKind = VK_LValue;
   2964         break;
   2965       }
   2966       // fallthrough
   2967 
   2968     case Decl::CXXConversion:
   2969     case Decl::CXXDestructor:
   2970     case Decl::CXXConstructor:
   2971       valueKind = VK_RValue;
   2972       break;
   2973     }
   2974 
   2975     return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
   2976                             TemplateArgs);
   2977   }
   2978 }
   2979 
   2980 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
   2981                                     SmallString<32> &Target) {
   2982   Target.resize(CharByteWidth * (Source.size() + 1));
   2983   char *ResultPtr = &Target[0];
   2984   const UTF8 *ErrorPtr;
   2985   bool success = ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
   2986   (void)success;
   2987   assert(success);
   2988   Target.resize(ResultPtr - &Target[0]);
   2989 }
   2990 
   2991 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
   2992                                      PredefinedExpr::IdentType IT) {
   2993   // Pick the current block, lambda, captured statement or function.
   2994   Decl *currentDecl = nullptr;
   2995   if (const BlockScopeInfo *BSI = getCurBlock())
   2996     currentDecl = BSI->TheDecl;
   2997   else if (const LambdaScopeInfo *LSI = getCurLambda())
   2998     currentDecl = LSI->CallOperator;
   2999   else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
   3000     currentDecl = CSI->TheCapturedDecl;
   3001   else
   3002     currentDecl = getCurFunctionOrMethodDecl();
   3003 
   3004   if (!currentDecl) {
   3005     Diag(Loc, diag::ext_predef_outside_function);
   3006     currentDecl = Context.getTranslationUnitDecl();
   3007   }
   3008 
   3009   QualType ResTy;
   3010   StringLiteral *SL = nullptr;
   3011   if (cast<DeclContext>(currentDecl)->isDependentContext())
   3012     ResTy = Context.DependentTy;
   3013   else {
   3014     // Pre-defined identifiers are of type char[x], where x is the length of
   3015     // the string.
   3016     auto Str = PredefinedExpr::ComputeName(IT, currentDecl);
   3017     unsigned Length = Str.length();
   3018 
   3019     llvm::APInt LengthI(32, Length + 1);
   3020     if (IT == PredefinedExpr::LFunction) {
   3021       ResTy = Context.WideCharTy.withConst();
   3022       SmallString<32> RawChars;
   3023       ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
   3024                               Str, RawChars);
   3025       ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
   3026                                            /*IndexTypeQuals*/ 0);
   3027       SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
   3028                                  /*Pascal*/ false, ResTy, Loc);
   3029     } else {
   3030       ResTy = Context.CharTy.withConst();
   3031       ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
   3032                                            /*IndexTypeQuals*/ 0);
   3033       SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
   3034                                  /*Pascal*/ false, ResTy, Loc);
   3035     }
   3036   }
   3037 
   3038   return new (Context) PredefinedExpr(Loc, ResTy, IT, SL);
   3039 }
   3040 
   3041 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
   3042   PredefinedExpr::IdentType IT;
   3043 
   3044   switch (Kind) {
   3045   default: llvm_unreachable("Unknown simple primary expr!");
   3046   case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
   3047   case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
   3048   case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS]
   3049   case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS]
   3050   case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break;
   3051   case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
   3052   }
   3053 
   3054   return BuildPredefinedExpr(Loc, IT);
   3055 }
   3056 
   3057 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
   3058   SmallString<16> CharBuffer;
   3059   bool Invalid = false;
   3060   StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
   3061   if (Invalid)
   3062     return ExprError();
   3063 
   3064   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
   3065                             PP, Tok.getKind());
   3066   if (Literal.hadError())
   3067     return ExprError();
   3068 
   3069   QualType Ty;
   3070   if (Literal.isWide())
   3071     Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
   3072   else if (Literal.isUTF16())
   3073     Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
   3074   else if (Literal.isUTF32())
   3075     Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
   3076   else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
   3077     Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
   3078   else
   3079     Ty = Context.CharTy;  // 'x' -> char in C++
   3080 
   3081   CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
   3082   if (Literal.isWide())
   3083     Kind = CharacterLiteral::Wide;
   3084   else if (Literal.isUTF16())
   3085     Kind = CharacterLiteral::UTF16;
   3086   else if (Literal.isUTF32())
   3087     Kind = CharacterLiteral::UTF32;
   3088 
   3089   Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
   3090                                              Tok.getLocation());
   3091 
   3092   if (Literal.getUDSuffix().empty())
   3093     return Lit;
   3094 
   3095   // We're building a user-defined literal.
   3096   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
   3097   SourceLocation UDSuffixLoc =
   3098     getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
   3099 
   3100   // Make sure we're allowed user-defined literals here.
   3101   if (!UDLScope)
   3102     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
   3103 
   3104   // C++11 [lex.ext]p6: The literal L is treated as a call of the form
   3105   //   operator "" X (ch)
   3106   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
   3107                                         Lit, Tok.getLocation());
   3108 }
   3109 
   3110 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
   3111   unsigned IntSize = Context.getTargetInfo().getIntWidth();
   3112   return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
   3113                                 Context.IntTy, Loc);
   3114 }
   3115 
   3116 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
   3117                                   QualType Ty, SourceLocation Loc) {
   3118   const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
   3119 
   3120   using llvm::APFloat;
   3121   APFloat Val(Format);
   3122 
   3123   APFloat::opStatus result = Literal.GetFloatValue(Val);
   3124 
   3125   // Overflow is always an error, but underflow is only an error if
   3126   // we underflowed to zero (APFloat reports denormals as underflow).
   3127   if ((result & APFloat::opOverflow) ||
   3128       ((result & APFloat::opUnderflow) && Val.isZero())) {
   3129     unsigned diagnostic;
   3130     SmallString<20> buffer;
   3131     if (result & APFloat::opOverflow) {
   3132       diagnostic = diag::warn_float_overflow;
   3133       APFloat::getLargest(Format).toString(buffer);
   3134     } else {
   3135       diagnostic = diag::warn_float_underflow;
   3136       APFloat::getSmallest(Format).toString(buffer);
   3137     }
   3138 
   3139     S.Diag(Loc, diagnostic)
   3140       << Ty
   3141       << StringRef(buffer.data(), buffer.size());
   3142   }
   3143 
   3144   bool isExact = (result == APFloat::opOK);
   3145   return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
   3146 }
   3147 
   3148 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
   3149   assert(E && "Invalid expression");
   3150 
   3151   if (E->isValueDependent())
   3152     return false;
   3153 
   3154   QualType QT = E->getType();
   3155   if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
   3156     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
   3157     return true;
   3158   }
   3159 
   3160   llvm::APSInt ValueAPS;
   3161   ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
   3162 
   3163   if (R.isInvalid())
   3164     return true;
   3165 
   3166   bool ValueIsPositive = ValueAPS.isStrictlyPositive();
   3167   if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
   3168     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
   3169         << ValueAPS.toString(10) << ValueIsPositive;
   3170     return true;
   3171   }
   3172 
   3173   return false;
   3174 }
   3175 
   3176 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
   3177   // Fast path for a single digit (which is quite common).  A single digit
   3178   // cannot have a trigraph, escaped newline, radix prefix, or suffix.
   3179   if (Tok.getLength() == 1) {
   3180     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
   3181     return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
   3182   }
   3183 
   3184   SmallString<128> SpellingBuffer;
   3185   // NumericLiteralParser wants to overread by one character.  Add padding to
   3186   // the buffer in case the token is copied to the buffer.  If getSpelling()
   3187   // returns a StringRef to the memory buffer, it should have a null char at
   3188   // the EOF, so it is also safe.
   3189   SpellingBuffer.resize(Tok.getLength() + 1);
   3190 
   3191   // Get the spelling of the token, which eliminates trigraphs, etc.
   3192   bool Invalid = false;
   3193   StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
   3194   if (Invalid)
   3195     return ExprError();
   3196 
   3197   NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
   3198   if (Literal.hadError)
   3199     return ExprError();
   3200 
   3201   if (Literal.hasUDSuffix()) {
   3202     // We're building a user-defined literal.
   3203     IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
   3204     SourceLocation UDSuffixLoc =
   3205       getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
   3206 
   3207     // Make sure we're allowed user-defined literals here.
   3208     if (!UDLScope)
   3209       return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
   3210 
   3211     QualType CookedTy;
   3212     if (Literal.isFloatingLiteral()) {
   3213       // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
   3214       // long double, the literal is treated as a call of the form
   3215       //   operator "" X (f L)
   3216       CookedTy = Context.LongDoubleTy;
   3217     } else {
   3218       // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
   3219       // unsigned long long, the literal is treated as a call of the form
   3220       //   operator "" X (n ULL)
   3221       CookedTy = Context.UnsignedLongLongTy;
   3222     }
   3223 
   3224     DeclarationName OpName =
   3225       Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
   3226     DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
   3227     OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
   3228 
   3229     SourceLocation TokLoc = Tok.getLocation();
   3230 
   3231     // Perform literal operator lookup to determine if we're building a raw
   3232     // literal or a cooked one.
   3233     LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
   3234     switch (LookupLiteralOperator(UDLScope, R, CookedTy,
   3235                                   /*AllowRaw*/true, /*AllowTemplate*/true,
   3236                                   /*AllowStringTemplate*/false)) {
   3237     case LOLR_Error:
   3238       return ExprError();
   3239 
   3240     case LOLR_Cooked: {
   3241       Expr *Lit;
   3242       if (Literal.isFloatingLiteral()) {
   3243         Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
   3244       } else {
   3245         llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
   3246         if (Literal.GetIntegerValue(ResultVal))
   3247           Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
   3248               << /* Unsigned */ 1;
   3249         Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
   3250                                      Tok.getLocation());
   3251       }
   3252       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
   3253     }
   3254 
   3255     case LOLR_Raw: {
   3256       // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
   3257       // literal is treated as a call of the form
   3258       //   operator "" X ("n")
   3259       unsigned Length = Literal.getUDSuffixOffset();
   3260       QualType StrTy = Context.getConstantArrayType(
   3261           Context.CharTy.withConst(), llvm::APInt(32, Length + 1),
   3262           ArrayType::Normal, 0);
   3263       Expr *Lit = StringLiteral::Create(
   3264           Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
   3265           /*Pascal*/false, StrTy, &TokLoc, 1);
   3266       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
   3267     }
   3268 
   3269     case LOLR_Template: {
   3270       // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
   3271       // template), L is treated as a call fo the form
   3272       //   operator "" X <'c1', 'c2', ... 'ck'>()
   3273       // where n is the source character sequence c1 c2 ... ck.
   3274       TemplateArgumentListInfo ExplicitArgs;
   3275       unsigned CharBits = Context.getIntWidth(Context.CharTy);
   3276       bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
   3277       llvm::APSInt Value(CharBits, CharIsUnsigned);
   3278       for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
   3279         Value = TokSpelling[I];
   3280         TemplateArgument Arg(Context, Value, Context.CharTy);
   3281         TemplateArgumentLocInfo ArgInfo;
   3282         ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
   3283       }
   3284       return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
   3285                                       &ExplicitArgs);
   3286     }
   3287     case LOLR_StringTemplate:
   3288       llvm_unreachable("unexpected literal operator lookup result");
   3289     }
   3290   }
   3291 
   3292   Expr *Res;
   3293 
   3294   if (Literal.isFloatingLiteral()) {
   3295     QualType Ty;
   3296     if (Literal.isFloat)
   3297       Ty = Context.FloatTy;
   3298     else if (!Literal.isLong)
   3299       Ty = Context.DoubleTy;
   3300     else
   3301       Ty = Context.LongDoubleTy;
   3302 
   3303     Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
   3304 
   3305     if (Ty == Context.DoubleTy) {
   3306       if (getLangOpts().SinglePrecisionConstants) {
   3307         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
   3308       } else if (getLangOpts().OpenCL &&
   3309                  !((getLangOpts().OpenCLVersion >= 120) ||
   3310                    getOpenCLOptions().cl_khr_fp64)) {
   3311         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
   3312         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
   3313       }
   3314     }
   3315   } else if (!Literal.isIntegerLiteral()) {
   3316     return ExprError();
   3317   } else {
   3318     QualType Ty;
   3319 
   3320     // 'long long' is a C99 or C++11 feature.
   3321     if (!getLangOpts().C99 && Literal.isLongLong) {
   3322       if (getLangOpts().CPlusPlus)
   3323         Diag(Tok.getLocation(),
   3324              getLangOpts().CPlusPlus11 ?
   3325              diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
   3326       else
   3327         Diag(Tok.getLocation(), diag::ext_c99_longlong);
   3328     }
   3329 
   3330     // Get the value in the widest-possible width.
   3331     unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
   3332     llvm::APInt ResultVal(MaxWidth, 0);
   3333 
   3334     if (Literal.GetIntegerValue(ResultVal)) {
   3335       // If this value didn't fit into uintmax_t, error and force to ull.
   3336       Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
   3337           << /* Unsigned */ 1;
   3338       Ty = Context.UnsignedLongLongTy;
   3339       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
   3340              "long long is not intmax_t?");
   3341     } else {
   3342       // If this value fits into a ULL, try to figure out what else it fits into
   3343       // according to the rules of C99 6.4.4.1p5.
   3344 
   3345       // Octal, Hexadecimal, and integers with a U suffix are allowed to
   3346       // be an unsigned int.
   3347       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
   3348 
   3349       // Check from smallest to largest, picking the smallest type we can.
   3350       unsigned Width = 0;
   3351 
   3352       // Microsoft specific integer suffixes are explicitly sized.
   3353       if (Literal.MicrosoftInteger) {
   3354         if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
   3355           Width = 8;
   3356           Ty = Context.CharTy;
   3357         } else {
   3358           Width = Literal.MicrosoftInteger;
   3359           Ty = Context.getIntTypeForBitwidth(Width,
   3360                                              /*Signed=*/!Literal.isUnsigned);
   3361         }
   3362       }
   3363 
   3364       if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
   3365         // Are int/unsigned possibilities?
   3366         unsigned IntSize = Context.getTargetInfo().getIntWidth();
   3367 
   3368         // Does it fit in a unsigned int?
   3369         if (ResultVal.isIntN(IntSize)) {
   3370           // Does it fit in a signed int?
   3371           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
   3372             Ty = Context.IntTy;
   3373           else if (AllowUnsigned)
   3374             Ty = Context.UnsignedIntTy;
   3375           Width = IntSize;
   3376         }
   3377       }
   3378 
   3379       // Are long/unsigned long possibilities?
   3380       if (Ty.isNull() && !Literal.isLongLong) {
   3381         unsigned LongSize = Context.getTargetInfo().getLongWidth();
   3382 
   3383         // Does it fit in a unsigned long?
   3384         if (ResultVal.isIntN(LongSize)) {
   3385           // Does it fit in a signed long?
   3386           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
   3387             Ty = Context.LongTy;
   3388           else if (AllowUnsigned)
   3389             Ty = Context.UnsignedLongTy;
   3390           // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
   3391           // is compatible.
   3392           else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
   3393             const unsigned LongLongSize =
   3394                 Context.getTargetInfo().getLongLongWidth();
   3395             Diag(Tok.getLocation(),
   3396                  getLangOpts().CPlusPlus
   3397                      ? Literal.isLong
   3398                            ? diag::warn_old_implicitly_unsigned_long_cxx
   3399                            : /*C++98 UB*/ diag::
   3400                                  ext_old_implicitly_unsigned_long_cxx
   3401                      : diag::warn_old_implicitly_unsigned_long)
   3402                 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
   3403                                             : /*will be ill-formed*/ 1);
   3404             Ty = Context.UnsignedLongTy;
   3405           }
   3406           Width = LongSize;
   3407         }
   3408       }
   3409 
   3410       // Check long long if needed.
   3411       if (Ty.isNull()) {
   3412         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
   3413 
   3414         // Does it fit in a unsigned long long?
   3415         if (ResultVal.isIntN(LongLongSize)) {
   3416           // Does it fit in a signed long long?
   3417           // To be compatible with MSVC, hex integer literals ending with the
   3418           // LL or i64 suffix are always signed in Microsoft mode.
   3419           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
   3420               (getLangOpts().MicrosoftExt && Literal.isLongLong)))
   3421             Ty = Context.LongLongTy;
   3422           else if (AllowUnsigned)
   3423             Ty = Context.UnsignedLongLongTy;
   3424           Width = LongLongSize;
   3425         }
   3426       }
   3427 
   3428       // If we still couldn't decide a type, we probably have something that
   3429       // does not fit in a signed long long, but has no U suffix.
   3430       if (Ty.isNull()) {
   3431         Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
   3432         Ty = Context.UnsignedLongLongTy;
   3433         Width = Context.getTargetInfo().getLongLongWidth();
   3434       }
   3435 
   3436       if (ResultVal.getBitWidth() != Width)
   3437         ResultVal = ResultVal.trunc(Width);
   3438     }
   3439     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
   3440   }
   3441 
   3442   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
   3443   if (Literal.isImaginary)
   3444     Res = new (Context) ImaginaryLiteral(Res,
   3445                                         Context.getComplexType(Res->getType()));
   3446 
   3447   return Res;
   3448 }
   3449 
   3450 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
   3451   assert(E && "ActOnParenExpr() missing expr");
   3452   return new (Context) ParenExpr(L, R, E);
   3453 }
   3454 
   3455 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
   3456                                          SourceLocation Loc,
   3457                                          SourceRange ArgRange) {
   3458   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
   3459   // scalar or vector data type argument..."
   3460   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
   3461   // type (C99 6.2.5p18) or void.
   3462   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
   3463     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
   3464       << T << ArgRange;
   3465     return true;
   3466   }
   3467 
   3468   assert((T->isVoidType() || !T->isIncompleteType()) &&
   3469          "Scalar types should always be complete");
   3470   return false;
   3471 }
   3472 
   3473 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
   3474                                            SourceLocation Loc,
   3475                                            SourceRange ArgRange,
   3476                                            UnaryExprOrTypeTrait TraitKind) {
   3477   // Invalid types must be hard errors for SFINAE in C++.
   3478   if (S.LangOpts.CPlusPlus)
   3479     return true;
   3480 
   3481   // C99 6.5.3.4p1:
   3482   if (T->isFunctionType() &&
   3483       (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) {
   3484     // sizeof(function)/alignof(function) is allowed as an extension.
   3485     S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
   3486       << TraitKind << ArgRange;
   3487     return false;
   3488   }
   3489 
   3490   // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
   3491   // this is an error (OpenCL v1.1 s6.3.k)
   3492   if (T->isVoidType()) {
   3493     unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
   3494                                         : diag::ext_sizeof_alignof_void_type;
   3495     S.Diag(Loc, DiagID) << TraitKind << ArgRange;
   3496     return false;
   3497   }
   3498 
   3499   return true;
   3500 }
   3501 
   3502 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
   3503                                              SourceLocation Loc,
   3504                                              SourceRange ArgRange,
   3505                                              UnaryExprOrTypeTrait TraitKind) {
   3506   // Reject sizeof(interface) and sizeof(interface<proto>) if the
   3507   // runtime doesn't allow it.
   3508   if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
   3509     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
   3510       << T << (TraitKind == UETT_SizeOf)
   3511       << ArgRange;
   3512     return true;
   3513   }
   3514 
   3515   return false;
   3516 }
   3517 
   3518 /// \brief Check whether E is a pointer from a decayed array type (the decayed
   3519 /// pointer type is equal to T) and emit a warning if it is.
   3520 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
   3521                                      Expr *E) {
   3522   // Don't warn if the operation changed the type.
   3523   if (T != E->getType())
   3524     return;
   3525 
   3526   // Now look for array decays.
   3527   ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
   3528   if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
   3529     return;
   3530 
   3531   S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
   3532                                              << ICE->getType()
   3533                                              << ICE->getSubExpr()->getType();
   3534 }
   3535 
   3536 /// \brief Check the constraints on expression operands to unary type expression
   3537 /// and type traits.
   3538 ///
   3539 /// Completes any types necessary and validates the constraints on the operand
   3540 /// expression. The logic mostly mirrors the type-based overload, but may modify
   3541 /// the expression as it completes the type for that expression through template
   3542 /// instantiation, etc.
   3543 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
   3544                                             UnaryExprOrTypeTrait ExprKind) {
   3545   QualType ExprTy = E->getType();
   3546   assert(!ExprTy->isReferenceType());
   3547 
   3548   if (ExprKind == UETT_VecStep)
   3549     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
   3550                                         E->getSourceRange());
   3551 
   3552   // Whitelist some types as extensions
   3553   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
   3554                                       E->getSourceRange(), ExprKind))
   3555     return false;
   3556 
   3557   // 'alignof' applied to an expression only requires the base element type of
   3558   // the expression to be complete. 'sizeof' requires the expression's type to
   3559   // be complete (and will attempt to complete it if it's an array of unknown
   3560   // bound).
   3561   if (ExprKind == UETT_AlignOf) {
   3562     if (RequireCompleteType(E->getExprLoc(),
   3563                             Context.getBaseElementType(E->getType()),
   3564                             diag::err_sizeof_alignof_incomplete_type, ExprKind,
   3565                             E->getSourceRange()))
   3566       return true;
   3567   } else {
   3568     if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type,
   3569                                 ExprKind, E->getSourceRange()))
   3570       return true;
   3571   }
   3572 
   3573   // Completing the expression's type may have changed it.
   3574   ExprTy = E->getType();
   3575   assert(!ExprTy->isReferenceType());
   3576 
   3577   if (ExprTy->isFunctionType()) {
   3578     Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
   3579       << ExprKind << E->getSourceRange();
   3580     return true;
   3581   }
   3582 
   3583   // The operand for sizeof and alignof is in an unevaluated expression context,
   3584   // so side effects could result in unintended consequences.
   3585   if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf) &&
   3586       ActiveTemplateInstantiations.empty() && E->HasSideEffects(Context, false))
   3587     Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
   3588 
   3589   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
   3590                                        E->getSourceRange(), ExprKind))
   3591     return true;
   3592 
   3593   if (ExprKind == UETT_SizeOf) {
   3594     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
   3595       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
   3596         QualType OType = PVD->getOriginalType();
   3597         QualType Type = PVD->getType();
   3598         if (Type->isPointerType() && OType->isArrayType()) {
   3599           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
   3600             << Type << OType;
   3601           Diag(PVD->getLocation(), diag::note_declared_at);
   3602         }
   3603       }
   3604     }
   3605 
   3606     // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
   3607     // decays into a pointer and returns an unintended result. This is most
   3608     // likely a typo for "sizeof(array) op x".
   3609     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
   3610       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
   3611                                BO->getLHS());
   3612       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
   3613                                BO->getRHS());
   3614     }
   3615   }
   3616 
   3617   return false;
   3618 }
   3619 
   3620 /// \brief Check the constraints on operands to unary expression and type
   3621 /// traits.
   3622 ///
   3623 /// This will complete any types necessary, and validate the various constraints
   3624 /// on those operands.
   3625 ///
   3626 /// The UsualUnaryConversions() function is *not* called by this routine.
   3627 /// C99 6.3.2.1p[2-4] all state:
   3628 ///   Except when it is the operand of the sizeof operator ...
   3629 ///
   3630 /// C++ [expr.sizeof]p4
   3631 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
   3632 ///   standard conversions are not applied to the operand of sizeof.
   3633 ///
   3634 /// This policy is followed for all of the unary trait expressions.
   3635 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
   3636                                             SourceLocation OpLoc,
   3637                                             SourceRange ExprRange,
   3638                                             UnaryExprOrTypeTrait ExprKind) {
   3639   if (ExprType->isDependentType())
   3640     return false;
   3641 
   3642   // C++ [expr.sizeof]p2:
   3643   //     When applied to a reference or a reference type, the result
   3644   //     is the size of the referenced type.
   3645   // C++11 [expr.alignof]p3:
   3646   //     When alignof is applied to a reference type, the result
   3647   //     shall be the alignment of the referenced type.
   3648   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
   3649     ExprType = Ref->getPointeeType();
   3650 
   3651   // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
   3652   //   When alignof or _Alignof is applied to an array type, the result
   3653   //   is the alignment of the element type.
   3654   if (ExprKind == UETT_AlignOf || ExprKind == UETT_OpenMPRequiredSimdAlign)
   3655     ExprType = Context.getBaseElementType(ExprType);
   3656 
   3657   if (ExprKind == UETT_VecStep)
   3658     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
   3659 
   3660   // Whitelist some types as extensions
   3661   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
   3662                                       ExprKind))
   3663     return false;
   3664 
   3665   if (RequireCompleteType(OpLoc, ExprType,
   3666                           diag::err_sizeof_alignof_incomplete_type,
   3667                           ExprKind, ExprRange))
   3668     return true;
   3669 
   3670   if (ExprType->isFunctionType()) {
   3671     Diag(OpLoc, diag::err_sizeof_alignof_function_type)
   3672       << ExprKind << ExprRange;
   3673     return true;
   3674   }
   3675 
   3676   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
   3677                                        ExprKind))
   3678     return true;
   3679 
   3680   return false;
   3681 }
   3682 
   3683 static bool CheckAlignOfExpr(Sema &S, Expr *E) {
   3684   E = E->IgnoreParens();
   3685 
   3686   // Cannot know anything else if the expression is dependent.
   3687   if (E->isTypeDependent())
   3688     return false;
   3689 
   3690   if (E->getObjectKind() == OK_BitField) {
   3691     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
   3692        << 1 << E->getSourceRange();
   3693     return true;
   3694   }
   3695 
   3696   ValueDecl *D = nullptr;
   3697   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
   3698     D = DRE->getDecl();
   3699   } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
   3700     D = ME->getMemberDecl();
   3701   }
   3702 
   3703   // If it's a field, require the containing struct to have a
   3704   // complete definition so that we can compute the layout.
   3705   //
   3706   // This can happen in C++11 onwards, either by naming the member
   3707   // in a way that is not transformed into a member access expression
   3708   // (in an unevaluated operand, for instance), or by naming the member
   3709   // in a trailing-return-type.
   3710   //
   3711   // For the record, since __alignof__ on expressions is a GCC
   3712   // extension, GCC seems to permit this but always gives the
   3713   // nonsensical answer 0.
   3714   //
   3715   // We don't really need the layout here --- we could instead just
   3716   // directly check for all the appropriate alignment-lowing
   3717   // attributes --- but that would require duplicating a lot of
   3718   // logic that just isn't worth duplicating for such a marginal
   3719   // use-case.
   3720   if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
   3721     // Fast path this check, since we at least know the record has a
   3722     // definition if we can find a member of it.
   3723     if (!FD->getParent()->isCompleteDefinition()) {
   3724       S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
   3725         << E->getSourceRange();
   3726       return true;
   3727     }
   3728 
   3729     // Otherwise, if it's a field, and the field doesn't have
   3730     // reference type, then it must have a complete type (or be a
   3731     // flexible array member, which we explicitly want to
   3732     // white-list anyway), which makes the following checks trivial.
   3733     if (!FD->getType()->isReferenceType())
   3734       return false;
   3735   }
   3736 
   3737   return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
   3738 }
   3739 
   3740 bool Sema::CheckVecStepExpr(Expr *E) {
   3741   E = E->IgnoreParens();
   3742 
   3743   // Cannot know anything else if the expression is dependent.
   3744   if (E->isTypeDependent())
   3745     return false;
   3746 
   3747   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
   3748 }
   3749 
   3750 /// \brief Build a sizeof or alignof expression given a type operand.
   3751 ExprResult
   3752 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
   3753                                      SourceLocation OpLoc,
   3754                                      UnaryExprOrTypeTrait ExprKind,
   3755                                      SourceRange R) {
   3756   if (!TInfo)
   3757     return ExprError();
   3758 
   3759   QualType T = TInfo->getType();
   3760 
   3761   if (!T->isDependentType() &&
   3762       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
   3763     return ExprError();
   3764 
   3765   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
   3766   return new (Context) UnaryExprOrTypeTraitExpr(
   3767       ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
   3768 }
   3769 
   3770 /// \brief Build a sizeof or alignof expression given an expression
   3771 /// operand.
   3772 ExprResult
   3773 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
   3774                                      UnaryExprOrTypeTrait ExprKind) {
   3775   ExprResult PE = CheckPlaceholderExpr(E);
   3776   if (PE.isInvalid())
   3777     return ExprError();
   3778 
   3779   E = PE.get();
   3780 
   3781   // Verify that the operand is valid.
   3782   bool isInvalid = false;
   3783   if (E->isTypeDependent()) {
   3784     // Delay type-checking for type-dependent expressions.
   3785   } else if (ExprKind == UETT_AlignOf) {
   3786     isInvalid = CheckAlignOfExpr(*this, E);
   3787   } else if (ExprKind == UETT_VecStep) {
   3788     isInvalid = CheckVecStepExpr(E);
   3789   } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
   3790       Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
   3791       isInvalid = true;
   3792   } else if (E->refersToBitField()) {  // C99 6.5.3.4p1.
   3793     Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
   3794     isInvalid = true;
   3795   } else {
   3796     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
   3797   }
   3798 
   3799   if (isInvalid)
   3800     return ExprError();
   3801 
   3802   if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
   3803     PE = TransformToPotentiallyEvaluated(E);
   3804     if (PE.isInvalid()) return ExprError();
   3805     E = PE.get();
   3806   }
   3807 
   3808   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
   3809   return new (Context) UnaryExprOrTypeTraitExpr(
   3810       ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
   3811 }
   3812 
   3813 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
   3814 /// expr and the same for @c alignof and @c __alignof
   3815 /// Note that the ArgRange is invalid if isType is false.
   3816 ExprResult
   3817 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
   3818                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
   3819                                     void *TyOrEx, SourceRange ArgRange) {
   3820   // If error parsing type, ignore.
   3821   if (!TyOrEx) return ExprError();
   3822 
   3823   if (IsType) {
   3824     TypeSourceInfo *TInfo;
   3825     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
   3826     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
   3827   }
   3828 
   3829   Expr *ArgEx = (Expr *)TyOrEx;
   3830   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
   3831   return Result;
   3832 }
   3833 
   3834 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
   3835                                      bool IsReal) {
   3836   if (V.get()->isTypeDependent())
   3837     return S.Context.DependentTy;
   3838 
   3839   // _Real and _Imag are only l-values for normal l-values.
   3840   if (V.get()->getObjectKind() != OK_Ordinary) {
   3841     V = S.DefaultLvalueConversion(V.get());
   3842     if (V.isInvalid())
   3843       return QualType();
   3844   }
   3845 
   3846   // These operators return the element type of a complex type.
   3847   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
   3848     return CT->getElementType();
   3849 
   3850   // Otherwise they pass through real integer and floating point types here.
   3851   if (V.get()->getType()->isArithmeticType())
   3852     return V.get()->getType();
   3853 
   3854   // Test for placeholders.
   3855   ExprResult PR = S.CheckPlaceholderExpr(V.get());
   3856   if (PR.isInvalid()) return QualType();
   3857   if (PR.get() != V.get()) {
   3858     V = PR;
   3859     return CheckRealImagOperand(S, V, Loc, IsReal);
   3860   }
   3861 
   3862   // Reject anything else.
   3863   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
   3864     << (IsReal ? "__real" : "__imag");
   3865   return QualType();
   3866 }
   3867 
   3868 
   3869 
   3870 ExprResult
   3871 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
   3872                           tok::TokenKind Kind, Expr *Input) {
   3873   UnaryOperatorKind Opc;
   3874   switch (Kind) {
   3875   default: llvm_unreachable("Unknown unary op!");
   3876   case tok::plusplus:   Opc = UO_PostInc; break;
   3877   case tok::minusminus: Opc = UO_PostDec; break;
   3878   }
   3879 
   3880   // Since this might is a postfix expression, get rid of ParenListExprs.
   3881   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
   3882   if (Result.isInvalid()) return ExprError();
   3883   Input = Result.get();
   3884 
   3885   return BuildUnaryOp(S, OpLoc, Opc, Input);
   3886 }
   3887 
   3888 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal.
   3889 ///
   3890 /// \return true on error
   3891 static bool checkArithmeticOnObjCPointer(Sema &S,
   3892                                          SourceLocation opLoc,
   3893                                          Expr *op) {
   3894   assert(op->getType()->isObjCObjectPointerType());
   3895   if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
   3896       !S.LangOpts.ObjCSubscriptingLegacyRuntime)
   3897     return false;
   3898 
   3899   S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
   3900     << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
   3901     << op->getSourceRange();
   3902   return true;
   3903 }
   3904 
   3905 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
   3906   auto *BaseNoParens = Base->IgnoreParens();
   3907   if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
   3908     return MSProp->getPropertyDecl()->getType()->isArrayType();
   3909   return isa<MSPropertySubscriptExpr>(BaseNoParens);
   3910 }
   3911 
   3912 ExprResult
   3913 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
   3914                               Expr *idx, SourceLocation rbLoc) {
   3915   if (base && !base->getType().isNull() &&
   3916       base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
   3917     return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
   3918                                     /*Length=*/nullptr, rbLoc);
   3919 
   3920   // Since this might be a postfix expression, get rid of ParenListExprs.
   3921   if (isa<ParenListExpr>(base)) {
   3922     ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
   3923     if (result.isInvalid()) return ExprError();
   3924     base = result.get();
   3925   }
   3926 
   3927   // Handle any non-overload placeholder types in the base and index
   3928   // expressions.  We can't handle overloads here because the other
   3929   // operand might be an overloadable type, in which case the overload
   3930   // resolution for the operator overload should get the first crack
   3931   // at the overload.
   3932   bool IsMSPropertySubscript = false;
   3933   if (base->getType()->isNonOverloadPlaceholderType()) {
   3934     IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
   3935     if (!IsMSPropertySubscript) {
   3936       ExprResult result = CheckPlaceholderExpr(base);
   3937       if (result.isInvalid())
   3938         return ExprError();
   3939       base = result.get();
   3940     }
   3941   }
   3942   if (idx->getType()->isNonOverloadPlaceholderType()) {
   3943     ExprResult result = CheckPlaceholderExpr(idx);
   3944     if (result.isInvalid()) return ExprError();
   3945     idx = result.get();
   3946   }
   3947 
   3948   // Build an unanalyzed expression if either operand is type-dependent.
   3949   if (getLangOpts().CPlusPlus &&
   3950       (base->isTypeDependent() || idx->isTypeDependent())) {
   3951     return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
   3952                                             VK_LValue, OK_Ordinary, rbLoc);
   3953   }
   3954 
   3955   // MSDN, property (C++)
   3956   // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
   3957   // This attribute can also be used in the declaration of an empty array in a
   3958   // class or structure definition. For example:
   3959   // __declspec(property(get=GetX, put=PutX)) int x[];
   3960   // The above statement indicates that x[] can be used with one or more array
   3961   // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
   3962   // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
   3963   if (IsMSPropertySubscript) {
   3964     // Build MS property subscript expression if base is MS property reference
   3965     // or MS property subscript.
   3966     return new (Context) MSPropertySubscriptExpr(
   3967         base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
   3968   }
   3969 
   3970   // Use C++ overloaded-operator rules if either operand has record
   3971   // type.  The spec says to do this if either type is *overloadable*,
   3972   // but enum types can't declare subscript operators or conversion
   3973   // operators, so there's nothing interesting for overload resolution
   3974   // to do if there aren't any record types involved.
   3975   //
   3976   // ObjC pointers have their own subscripting logic that is not tied
   3977   // to overload resolution and so should not take this path.
   3978   if (getLangOpts().CPlusPlus &&
   3979       (base->getType()->isRecordType() ||
   3980        (!base->getType()->isObjCObjectPointerType() &&
   3981         idx->getType()->isRecordType()))) {
   3982     return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
   3983   }
   3984 
   3985   return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
   3986 }
   3987 
   3988 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
   3989                                           Expr *LowerBound,
   3990                                           SourceLocation ColonLoc, Expr *Length,
   3991                                           SourceLocation RBLoc) {
   3992   if (Base->getType()->isPlaceholderType() &&
   3993       !Base->getType()->isSpecificPlaceholderType(
   3994           BuiltinType::OMPArraySection)) {
   3995     ExprResult Result = CheckPlaceholderExpr(Base);
   3996     if (Result.isInvalid())
   3997       return ExprError();
   3998     Base = Result.get();
   3999   }
   4000   if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
   4001     ExprResult Result = CheckPlaceholderExpr(LowerBound);
   4002     if (Result.isInvalid())
   4003       return ExprError();
   4004     LowerBound = Result.get();
   4005   }
   4006   if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
   4007     ExprResult Result = CheckPlaceholderExpr(Length);
   4008     if (Result.isInvalid())
   4009       return ExprError();
   4010     Length = Result.get();
   4011   }
   4012 
   4013   // Build an unanalyzed expression if either operand is type-dependent.
   4014   if (Base->isTypeDependent() ||
   4015       (LowerBound &&
   4016        (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
   4017       (Length && (Length->isTypeDependent() || Length->isValueDependent()))) {
   4018     return new (Context)
   4019         OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy,
   4020                             VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
   4021   }
   4022 
   4023   // Perform default conversions.
   4024   QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
   4025   QualType ResultTy;
   4026   if (OriginalTy->isAnyPointerType()) {
   4027     ResultTy = OriginalTy->getPointeeType();
   4028   } else if (OriginalTy->isArrayType()) {
   4029     ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
   4030   } else {
   4031     return ExprError(
   4032         Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
   4033         << Base->getSourceRange());
   4034   }
   4035   // C99 6.5.2.1p1
   4036   if (LowerBound) {
   4037     auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
   4038                                                       LowerBound);
   4039     if (Res.isInvalid())
   4040       return ExprError(Diag(LowerBound->getExprLoc(),
   4041                             diag::err_omp_typecheck_section_not_integer)
   4042                        << 0 << LowerBound->getSourceRange());
   4043     LowerBound = Res.get();
   4044 
   4045     if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
   4046         LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
   4047       Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
   4048           << 0 << LowerBound->getSourceRange();
   4049   }
   4050   if (Length) {
   4051     auto Res =
   4052         PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
   4053     if (Res.isInvalid())
   4054       return ExprError(Diag(Length->getExprLoc(),
   4055                             diag::err_omp_typecheck_section_not_integer)
   4056                        << 1 << Length->getSourceRange());
   4057     Length = Res.get();
   4058 
   4059     if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
   4060         Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
   4061       Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
   4062           << 1 << Length->getSourceRange();
   4063   }
   4064 
   4065   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
   4066   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
   4067   // type. Note that functions are not objects, and that (in C99 parlance)
   4068   // incomplete types are not object types.
   4069   if (ResultTy->isFunctionType()) {
   4070     Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
   4071         << ResultTy << Base->getSourceRange();
   4072     return ExprError();
   4073   }
   4074 
   4075   if (RequireCompleteType(Base->getExprLoc(), ResultTy,
   4076                           diag::err_omp_section_incomplete_type, Base))
   4077     return ExprError();
   4078 
   4079   if (LowerBound) {
   4080     llvm::APSInt LowerBoundValue;
   4081     if (LowerBound->EvaluateAsInt(LowerBoundValue, Context)) {
   4082       // OpenMP 4.0, [2.4 Array Sections]
   4083       // The lower-bound and length must evaluate to non-negative integers.
   4084       if (LowerBoundValue.isNegative()) {
   4085         Diag(LowerBound->getExprLoc(), diag::err_omp_section_negative)
   4086             << 0 << LowerBoundValue.toString(/*Radix=*/10, /*Signed=*/true)
   4087             << LowerBound->getSourceRange();
   4088         return ExprError();
   4089       }
   4090     }
   4091   }
   4092 
   4093   if (Length) {
   4094     llvm::APSInt LengthValue;
   4095     if (Length->EvaluateAsInt(LengthValue, Context)) {
   4096       // OpenMP 4.0, [2.4 Array Sections]
   4097       // The lower-bound and length must evaluate to non-negative integers.
   4098       if (LengthValue.isNegative()) {
   4099         Diag(Length->getExprLoc(), diag::err_omp_section_negative)
   4100             << 1 << LengthValue.toString(/*Radix=*/10, /*Signed=*/true)
   4101             << Length->getSourceRange();
   4102         return ExprError();
   4103       }
   4104     }
   4105   } else if (ColonLoc.isValid() &&
   4106              (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
   4107                                       !OriginalTy->isVariableArrayType()))) {
   4108     // OpenMP 4.0, [2.4 Array Sections]
   4109     // When the size of the array dimension is not known, the length must be
   4110     // specified explicitly.
   4111     Diag(ColonLoc, diag::err_omp_section_length_undefined)
   4112         << (!OriginalTy.isNull() && OriginalTy->isArrayType());
   4113     return ExprError();
   4114   }
   4115 
   4116   return new (Context)
   4117       OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy,
   4118                           VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
   4119 }
   4120 
   4121 ExprResult
   4122 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
   4123                                       Expr *Idx, SourceLocation RLoc) {
   4124   Expr *LHSExp = Base;
   4125   Expr *RHSExp = Idx;
   4126 
   4127   // Perform default conversions.
   4128   if (!LHSExp->getType()->getAs<VectorType>()) {
   4129     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
   4130     if (Result.isInvalid())
   4131       return ExprError();
   4132     LHSExp = Result.get();
   4133   }
   4134   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
   4135   if (Result.isInvalid())
   4136     return ExprError();
   4137   RHSExp = Result.get();
   4138 
   4139   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
   4140   ExprValueKind VK = VK_LValue;
   4141   ExprObjectKind OK = OK_Ordinary;
   4142 
   4143   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
   4144   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
   4145   // in the subscript position. As a result, we need to derive the array base
   4146   // and index from the expression types.
   4147   Expr *BaseExpr, *IndexExpr;
   4148   QualType ResultType;
   4149   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
   4150     BaseExpr = LHSExp;
   4151     IndexExpr = RHSExp;
   4152     ResultType = Context.DependentTy;
   4153   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
   4154     BaseExpr = LHSExp;
   4155     IndexExpr = RHSExp;
   4156     ResultType = PTy->getPointeeType();
   4157   } else if (const ObjCObjectPointerType *PTy =
   4158                LHSTy->getAs<ObjCObjectPointerType>()) {
   4159     BaseExpr = LHSExp;
   4160     IndexExpr = RHSExp;
   4161 
   4162     // Use custom logic if this should be the pseudo-object subscript
   4163     // expression.
   4164     if (!LangOpts.isSubscriptPointerArithmetic())
   4165       return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
   4166                                           nullptr);
   4167 
   4168     ResultType = PTy->getPointeeType();
   4169   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
   4170      // Handle the uncommon case of "123[Ptr]".
   4171     BaseExpr = RHSExp;
   4172     IndexExpr = LHSExp;
   4173     ResultType = PTy->getPointeeType();
   4174   } else if (const ObjCObjectPointerType *PTy =
   4175                RHSTy->getAs<ObjCObjectPointerType>()) {
   4176      // Handle the uncommon case of "123[Ptr]".
   4177     BaseExpr = RHSExp;
   4178     IndexExpr = LHSExp;
   4179     ResultType = PTy->getPointeeType();
   4180     if (!LangOpts.isSubscriptPointerArithmetic()) {
   4181       Diag(LLoc, diag::err_subscript_nonfragile_interface)
   4182         << ResultType << BaseExpr->getSourceRange();
   4183       return ExprError();
   4184     }
   4185   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
   4186     BaseExpr = LHSExp;    // vectors: V[123]
   4187     IndexExpr = RHSExp;
   4188     VK = LHSExp->getValueKind();
   4189     if (VK != VK_RValue)
   4190       OK = OK_VectorComponent;
   4191 
   4192     // FIXME: need to deal with const...
   4193     ResultType = VTy->getElementType();
   4194   } else if (LHSTy->isArrayType()) {
   4195     // If we see an array that wasn't promoted by
   4196     // DefaultFunctionArrayLvalueConversion, it must be an array that
   4197     // wasn't promoted because of the C90 rule that doesn't
   4198     // allow promoting non-lvalue arrays.  Warn, then
   4199     // force the promotion here.
   4200     Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
   4201         LHSExp->getSourceRange();
   4202     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
   4203                                CK_ArrayToPointerDecay).get();
   4204     LHSTy = LHSExp->getType();
   4205 
   4206     BaseExpr = LHSExp;
   4207     IndexExpr = RHSExp;
   4208     ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
   4209   } else if (RHSTy->isArrayType()) {
   4210     // Same as previous, except for 123[f().a] case
   4211     Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
   4212         RHSExp->getSourceRange();
   4213     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
   4214                                CK_ArrayToPointerDecay).get();
   4215     RHSTy = RHSExp->getType();
   4216 
   4217     BaseExpr = RHSExp;
   4218     IndexExpr = LHSExp;
   4219     ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
   4220   } else {
   4221     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
   4222        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
   4223   }
   4224   // C99 6.5.2.1p1
   4225   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
   4226     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
   4227                      << IndexExpr->getSourceRange());
   4228 
   4229   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
   4230        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
   4231          && !IndexExpr->isTypeDependent())
   4232     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
   4233 
   4234   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
   4235   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
   4236   // type. Note that Functions are not objects, and that (in C99 parlance)
   4237   // incomplete types are not object types.
   4238   if (ResultType->isFunctionType()) {
   4239     Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
   4240       << ResultType << BaseExpr->getSourceRange();
   4241     return ExprError();
   4242   }
   4243 
   4244   if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
   4245     // GNU extension: subscripting on pointer to void
   4246     Diag(LLoc, diag::ext_gnu_subscript_void_type)
   4247       << BaseExpr->getSourceRange();
   4248 
   4249     // C forbids expressions of unqualified void type from being l-values.
   4250     // See IsCForbiddenLValueType.
   4251     if (!ResultType.hasQualifiers()) VK = VK_RValue;
   4252   } else if (!ResultType->isDependentType() &&
   4253       RequireCompleteType(LLoc, ResultType,
   4254                           diag::err_subscript_incomplete_type, BaseExpr))
   4255     return ExprError();
   4256 
   4257   assert(VK == VK_RValue || LangOpts.CPlusPlus ||
   4258          !ResultType.isCForbiddenLValueType());
   4259 
   4260   return new (Context)
   4261       ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
   4262 }
   4263 
   4264 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
   4265                                         FunctionDecl *FD,
   4266                                         ParmVarDecl *Param) {
   4267   if (Param->hasUnparsedDefaultArg()) {
   4268     Diag(CallLoc,
   4269          diag::err_use_of_default_argument_to_function_declared_later) <<
   4270       FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
   4271     Diag(UnparsedDefaultArgLocs[Param],
   4272          diag::note_default_argument_declared_here);
   4273     return ExprError();
   4274   }
   4275 
   4276   if (Param->hasUninstantiatedDefaultArg()) {
   4277     Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
   4278 
   4279     EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated,
   4280                                                  Param);
   4281 
   4282     // Instantiate the expression.
   4283     MultiLevelTemplateArgumentList MutiLevelArgList
   4284       = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
   4285 
   4286     InstantiatingTemplate Inst(*this, CallLoc, Param,
   4287                                MutiLevelArgList.getInnermost());
   4288     if (Inst.isInvalid())
   4289       return ExprError();
   4290 
   4291     ExprResult Result;
   4292     {
   4293       // C++ [dcl.fct.default]p5:
   4294       //   The names in the [default argument] expression are bound, and
   4295       //   the semantic constraints are checked, at the point where the
   4296       //   default argument expression appears.
   4297       ContextRAII SavedContext(*this, FD);
   4298       LocalInstantiationScope Local(*this);
   4299       Result = SubstExpr(UninstExpr, MutiLevelArgList);
   4300     }
   4301     if (Result.isInvalid())
   4302       return ExprError();
   4303 
   4304     // Check the expression as an initializer for the parameter.
   4305     InitializedEntity Entity
   4306       = InitializedEntity::InitializeParameter(Context, Param);
   4307     InitializationKind Kind
   4308       = InitializationKind::CreateCopy(Param->getLocation(),
   4309              /*FIXME:EqualLoc*/UninstExpr->getLocStart());
   4310     Expr *ResultE = Result.getAs<Expr>();
   4311 
   4312     InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
   4313     Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
   4314     if (Result.isInvalid())
   4315       return ExprError();
   4316 
   4317     Expr *Arg = Result.getAs<Expr>();
   4318     CheckCompletedExpr(Arg, Param->getOuterLocStart());
   4319     // Build the default argument expression.
   4320     return CXXDefaultArgExpr::Create(Context, CallLoc, Param, Arg);
   4321   }
   4322 
   4323   // If the default expression creates temporaries, we need to
   4324   // push them to the current stack of expression temporaries so they'll
   4325   // be properly destroyed.
   4326   // FIXME: We should really be rebuilding the default argument with new
   4327   // bound temporaries; see the comment in PR5810.
   4328   // We don't need to do that with block decls, though, because
   4329   // blocks in default argument expression can never capture anything.
   4330   if (isa<ExprWithCleanups>(Param->getInit())) {
   4331     // Set the "needs cleanups" bit regardless of whether there are
   4332     // any explicit objects.
   4333     ExprNeedsCleanups = true;
   4334 
   4335     // Append all the objects to the cleanup list.  Right now, this
   4336     // should always be a no-op, because blocks in default argument
   4337     // expressions should never be able to capture anything.
   4338     assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() &&
   4339            "default argument expression has capturing blocks?");
   4340   }
   4341 
   4342   // We already type-checked the argument, so we know it works.
   4343   // Just mark all of the declarations in this potentially-evaluated expression
   4344   // as being "referenced".
   4345   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
   4346                                    /*SkipLocalVariables=*/true);
   4347   return CXXDefaultArgExpr::Create(Context, CallLoc, Param);
   4348 }
   4349 
   4350 
   4351 Sema::VariadicCallType
   4352 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
   4353                           Expr *Fn) {
   4354   if (Proto && Proto->isVariadic()) {
   4355     if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
   4356       return VariadicConstructor;
   4357     else if (Fn && Fn->getType()->isBlockPointerType())
   4358       return VariadicBlock;
   4359     else if (FDecl) {
   4360       if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
   4361         if (Method->isInstance())
   4362           return VariadicMethod;
   4363     } else if (Fn && Fn->getType() == Context.BoundMemberTy)
   4364       return VariadicMethod;
   4365     return VariadicFunction;
   4366   }
   4367   return VariadicDoesNotApply;
   4368 }
   4369 
   4370 namespace {
   4371 class FunctionCallCCC : public FunctionCallFilterCCC {
   4372 public:
   4373   FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
   4374                   unsigned NumArgs, MemberExpr *ME)
   4375       : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
   4376         FunctionName(FuncName) {}
   4377 
   4378   bool ValidateCandidate(const TypoCorrection &candidate) override {
   4379     if (!candidate.getCorrectionSpecifier() ||
   4380         candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
   4381       return false;
   4382     }
   4383 
   4384     return FunctionCallFilterCCC::ValidateCandidate(candidate);
   4385   }
   4386 
   4387 private:
   4388   const IdentifierInfo *const FunctionName;
   4389 };
   4390 }
   4391 
   4392 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
   4393                                                FunctionDecl *FDecl,
   4394                                                ArrayRef<Expr *> Args) {
   4395   MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
   4396   DeclarationName FuncName = FDecl->getDeclName();
   4397   SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart();
   4398 
   4399   if (TypoCorrection Corrected = S.CorrectTypo(
   4400           DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
   4401           S.getScopeForContext(S.CurContext), nullptr,
   4402           llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(),
   4403                                              Args.size(), ME),
   4404           Sema::CTK_ErrorRecovery)) {
   4405     if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
   4406       if (Corrected.isOverloaded()) {
   4407         OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
   4408         OverloadCandidateSet::iterator Best;
   4409         for (NamedDecl *CD : Corrected) {
   4410           if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
   4411             S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
   4412                                    OCS);
   4413         }
   4414         switch (OCS.BestViableFunction(S, NameLoc, Best)) {
   4415         case OR_Success:
   4416           ND = Best->Function;
   4417           Corrected.setCorrectionDecl(ND);
   4418           break;
   4419         default:
   4420           break;
   4421         }
   4422       }
   4423       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
   4424         return Corrected;
   4425       }
   4426     }
   4427   }
   4428   return TypoCorrection();
   4429 }
   4430 
   4431 /// ConvertArgumentsForCall - Converts the arguments specified in
   4432 /// Args/NumArgs to the parameter types of the function FDecl with
   4433 /// function prototype Proto. Call is the call expression itself, and
   4434 /// Fn is the function expression. For a C++ member function, this
   4435 /// routine does not attempt to convert the object argument. Returns
   4436 /// true if the call is ill-formed.
   4437 bool
   4438 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
   4439                               FunctionDecl *FDecl,
   4440                               const FunctionProtoType *Proto,
   4441                               ArrayRef<Expr *> Args,
   4442                               SourceLocation RParenLoc,
   4443                               bool IsExecConfig) {
   4444   // Bail out early if calling a builtin with custom typechecking.
   4445   if (FDecl)
   4446     if (unsigned ID = FDecl->getBuiltinID())
   4447       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
   4448         return false;
   4449 
   4450   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
   4451   // assignment, to the types of the corresponding parameter, ...
   4452   unsigned NumParams = Proto->getNumParams();
   4453   bool Invalid = false;
   4454   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
   4455   unsigned FnKind = Fn->getType()->isBlockPointerType()
   4456                        ? 1 /* block */
   4457                        : (IsExecConfig ? 3 /* kernel function (exec config) */
   4458                                        : 0 /* function */);
   4459 
   4460   // If too few arguments are available (and we don't have default
   4461   // arguments for the remaining parameters), don't make the call.
   4462   if (Args.size() < NumParams) {
   4463     if (Args.size() < MinArgs) {
   4464       TypoCorrection TC;
   4465       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
   4466         unsigned diag_id =
   4467             MinArgs == NumParams && !Proto->isVariadic()
   4468                 ? diag::err_typecheck_call_too_few_args_suggest
   4469                 : diag::err_typecheck_call_too_few_args_at_least_suggest;
   4470         diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
   4471                                         << static_cast<unsigned>(Args.size())
   4472                                         << TC.getCorrectionRange());
   4473       } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
   4474         Diag(RParenLoc,
   4475              MinArgs == NumParams && !Proto->isVariadic()
   4476                  ? diag::err_typecheck_call_too_few_args_one
   4477                  : diag::err_typecheck_call_too_few_args_at_least_one)
   4478             << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
   4479       else
   4480         Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
   4481                             ? diag::err_typecheck_call_too_few_args
   4482                             : diag::err_typecheck_call_too_few_args_at_least)
   4483             << FnKind << MinArgs << static_cast<unsigned>(Args.size())
   4484             << Fn->getSourceRange();
   4485 
   4486       // Emit the location of the prototype.
   4487       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
   4488         Diag(FDecl->getLocStart(), diag::note_callee_decl)
   4489           << FDecl;
   4490 
   4491       return true;
   4492     }
   4493     Call->setNumArgs(Context, NumParams);
   4494   }
   4495 
   4496   // If too many are passed and not variadic, error on the extras and drop
   4497   // them.
   4498   if (Args.size() > NumParams) {
   4499     if (!Proto->isVariadic()) {
   4500       TypoCorrection TC;
   4501       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
   4502         unsigned diag_id =
   4503             MinArgs == NumParams && !Proto->isVariadic()
   4504                 ? diag::err_typecheck_call_too_many_args_suggest
   4505                 : diag::err_typecheck_call_too_many_args_at_most_suggest;
   4506         diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
   4507                                         << static_cast<unsigned>(Args.size())
   4508                                         << TC.getCorrectionRange());
   4509       } else if (NumParams == 1 && FDecl &&
   4510                  FDecl->getParamDecl(0)->getDeclName())
   4511         Diag(Args[NumParams]->getLocStart(),
   4512              MinArgs == NumParams
   4513                  ? diag::err_typecheck_call_too_many_args_one
   4514                  : diag::err_typecheck_call_too_many_args_at_most_one)
   4515             << FnKind << FDecl->getParamDecl(0)
   4516             << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
   4517             << SourceRange(Args[NumParams]->getLocStart(),
   4518                            Args.back()->getLocEnd());
   4519       else
   4520         Diag(Args[NumParams]->getLocStart(),
   4521              MinArgs == NumParams
   4522                  ? diag::err_typecheck_call_too_many_args
   4523                  : diag::err_typecheck_call_too_many_args_at_most)
   4524             << FnKind << NumParams << static_cast<unsigned>(Args.size())
   4525             << Fn->getSourceRange()
   4526             << SourceRange(Args[NumParams]->getLocStart(),
   4527                            Args.back()->getLocEnd());
   4528 
   4529       // Emit the location of the prototype.
   4530       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
   4531         Diag(FDecl->getLocStart(), diag::note_callee_decl)
   4532           << FDecl;
   4533 
   4534       // This deletes the extra arguments.
   4535       Call->setNumArgs(Context, NumParams);
   4536       return true;
   4537     }
   4538   }
   4539   SmallVector<Expr *, 8> AllArgs;
   4540   VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
   4541 
   4542   Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
   4543                                    Proto, 0, Args, AllArgs, CallType);
   4544   if (Invalid)
   4545     return true;
   4546   unsigned TotalNumArgs = AllArgs.size();
   4547   for (unsigned i = 0; i < TotalNumArgs; ++i)
   4548     Call->setArg(i, AllArgs[i]);
   4549 
   4550   return false;
   4551 }
   4552 
   4553 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
   4554                                   const FunctionProtoType *Proto,
   4555                                   unsigned FirstParam, ArrayRef<Expr *> Args,
   4556                                   SmallVectorImpl<Expr *> &AllArgs,
   4557                                   VariadicCallType CallType, bool AllowExplicit,
   4558                                   bool IsListInitialization) {
   4559   unsigned NumParams = Proto->getNumParams();
   4560   bool Invalid = false;
   4561   size_t ArgIx = 0;
   4562   // Continue to check argument types (even if we have too few/many args).
   4563   for (unsigned i = FirstParam; i < NumParams; i++) {
   4564     QualType ProtoArgType = Proto->getParamType(i);
   4565 
   4566     Expr *Arg;
   4567     ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
   4568     if (ArgIx < Args.size()) {
   4569       Arg = Args[ArgIx++];
   4570 
   4571       if (RequireCompleteType(Arg->getLocStart(),
   4572                               ProtoArgType,
   4573                               diag::err_call_incomplete_argument, Arg))
   4574         return true;
   4575 
   4576       // Strip the unbridged-cast placeholder expression off, if applicable.
   4577       bool CFAudited = false;
   4578       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
   4579           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
   4580           (!Param || !Param->hasAttr<CFConsumedAttr>()))
   4581         Arg = stripARCUnbridgedCast(Arg);
   4582       else if (getLangOpts().ObjCAutoRefCount &&
   4583                FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
   4584                (!Param || !Param->hasAttr<CFConsumedAttr>()))
   4585         CFAudited = true;
   4586 
   4587       InitializedEntity Entity =
   4588           Param ? InitializedEntity::InitializeParameter(Context, Param,
   4589                                                          ProtoArgType)
   4590                 : InitializedEntity::InitializeParameter(
   4591                       Context, ProtoArgType, Proto->isParamConsumed(i));
   4592 
   4593       // Remember that parameter belongs to a CF audited API.
   4594       if (CFAudited)
   4595         Entity.setParameterCFAudited();
   4596 
   4597       ExprResult ArgE = PerformCopyInitialization(
   4598           Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
   4599       if (ArgE.isInvalid())
   4600         return true;
   4601 
   4602       Arg = ArgE.getAs<Expr>();
   4603     } else {
   4604       assert(Param && "can't use default arguments without a known callee");
   4605 
   4606       ExprResult ArgExpr =
   4607         BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
   4608       if (ArgExpr.isInvalid())
   4609         return true;
   4610 
   4611       Arg = ArgExpr.getAs<Expr>();
   4612     }
   4613 
   4614     // Check for array bounds violations for each argument to the call. This
   4615     // check only triggers warnings when the argument isn't a more complex Expr
   4616     // with its own checking, such as a BinaryOperator.
   4617     CheckArrayAccess(Arg);
   4618 
   4619     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
   4620     CheckStaticArrayArgument(CallLoc, Param, Arg);
   4621 
   4622     AllArgs.push_back(Arg);
   4623   }
   4624 
   4625   // If this is a variadic call, handle args passed through "...".
   4626   if (CallType != VariadicDoesNotApply) {
   4627     // Assume that extern "C" functions with variadic arguments that
   4628     // return __unknown_anytype aren't *really* variadic.
   4629     if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
   4630         FDecl->isExternC()) {
   4631       for (Expr *A : Args.slice(ArgIx)) {
   4632         QualType paramType; // ignored
   4633         ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
   4634         Invalid |= arg.isInvalid();
   4635         AllArgs.push_back(arg.get());
   4636       }
   4637 
   4638     // Otherwise do argument promotion, (C99 6.5.2.2p7).
   4639     } else {
   4640       for (Expr *A : Args.slice(ArgIx)) {
   4641         ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
   4642         Invalid |= Arg.isInvalid();
   4643         AllArgs.push_back(Arg.get());
   4644       }
   4645     }
   4646 
   4647     // Check for array bounds violations.
   4648     for (Expr *A : Args.slice(ArgIx))
   4649       CheckArrayAccess(A);
   4650   }
   4651   return Invalid;
   4652 }
   4653 
   4654 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
   4655   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
   4656   if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
   4657     TL = DTL.getOriginalLoc();
   4658   if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
   4659     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
   4660       << ATL.getLocalSourceRange();
   4661 }
   4662 
   4663 /// CheckStaticArrayArgument - If the given argument corresponds to a static
   4664 /// array parameter, check that it is non-null, and that if it is formed by
   4665 /// array-to-pointer decay, the underlying array is sufficiently large.
   4666 ///
   4667 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
   4668 /// array type derivation, then for each call to the function, the value of the
   4669 /// corresponding actual argument shall provide access to the first element of
   4670 /// an array with at least as many elements as specified by the size expression.
   4671 void
   4672 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
   4673                                ParmVarDecl *Param,
   4674                                const Expr *ArgExpr) {
   4675   // Static array parameters are not supported in C++.
   4676   if (!Param || getLangOpts().CPlusPlus)
   4677     return;
   4678 
   4679   QualType OrigTy = Param->getOriginalType();
   4680 
   4681   const ArrayType *AT = Context.getAsArrayType(OrigTy);
   4682   if (!AT || AT->getSizeModifier() != ArrayType::Static)
   4683     return;
   4684 
   4685   if (ArgExpr->isNullPointerConstant(Context,
   4686                                      Expr::NPC_NeverValueDependent)) {
   4687     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
   4688     DiagnoseCalleeStaticArrayParam(*this, Param);
   4689     return;
   4690   }
   4691 
   4692   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
   4693   if (!CAT)
   4694     return;
   4695 
   4696   const ConstantArrayType *ArgCAT =
   4697     Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
   4698   if (!ArgCAT)
   4699     return;
   4700 
   4701   if (ArgCAT->getSize().ult(CAT->getSize())) {
   4702     Diag(CallLoc, diag::warn_static_array_too_small)
   4703       << ArgExpr->getSourceRange()
   4704       << (unsigned) ArgCAT->getSize().getZExtValue()
   4705       << (unsigned) CAT->getSize().getZExtValue();
   4706     DiagnoseCalleeStaticArrayParam(*this, Param);
   4707   }
   4708 }
   4709 
   4710 /// Given a function expression of unknown-any type, try to rebuild it
   4711 /// to have a function type.
   4712 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
   4713 
   4714 /// Is the given type a placeholder that we need to lower out
   4715 /// immediately during argument processing?
   4716 static bool isPlaceholderToRemoveAsArg(QualType type) {
   4717   // Placeholders are never sugared.
   4718   const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
   4719   if (!placeholder) return false;
   4720 
   4721   switch (placeholder->getKind()) {
   4722   // Ignore all the non-placeholder types.
   4723 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
   4724 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
   4725 #include "clang/AST/BuiltinTypes.def"
   4726     return false;
   4727 
   4728   // We cannot lower out overload sets; they might validly be resolved
   4729   // by the call machinery.
   4730   case BuiltinType::Overload:
   4731     return false;
   4732 
   4733   // Unbridged casts in ARC can be handled in some call positions and
   4734   // should be left in place.
   4735   case BuiltinType::ARCUnbridgedCast:
   4736     return false;
   4737 
   4738   // Pseudo-objects should be converted as soon as possible.
   4739   case BuiltinType::PseudoObject:
   4740     return true;
   4741 
   4742   // The debugger mode could theoretically but currently does not try
   4743   // to resolve unknown-typed arguments based on known parameter types.
   4744   case BuiltinType::UnknownAny:
   4745     return true;
   4746 
   4747   // These are always invalid as call arguments and should be reported.
   4748   case BuiltinType::BoundMember:
   4749   case BuiltinType::BuiltinFn:
   4750   case BuiltinType::OMPArraySection:
   4751     return true;
   4752 
   4753   }
   4754   llvm_unreachable("bad builtin type kind");
   4755 }
   4756 
   4757 /// Check an argument list for placeholders that we won't try to
   4758 /// handle later.
   4759 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
   4760   // Apply this processing to all the arguments at once instead of
   4761   // dying at the first failure.
   4762   bool hasInvalid = false;
   4763   for (size_t i = 0, e = args.size(); i != e; i++) {
   4764     if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
   4765       ExprResult result = S.CheckPlaceholderExpr(args[i]);
   4766       if (result.isInvalid()) hasInvalid = true;
   4767       else args[i] = result.get();
   4768     } else if (hasInvalid) {
   4769       (void)S.CorrectDelayedTyposInExpr(args[i]);
   4770     }
   4771   }
   4772   return hasInvalid;
   4773 }
   4774 
   4775 /// If a builtin function has a pointer argument with no explicit address
   4776 /// space, than it should be able to accept a pointer to any address
   4777 /// space as input.  In order to do this, we need to replace the
   4778 /// standard builtin declaration with one that uses the same address space
   4779 /// as the call.
   4780 ///
   4781 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
   4782 ///                  it does not contain any pointer arguments without
   4783 ///                  an address space qualifer.  Otherwise the rewritten
   4784 ///                  FunctionDecl is returned.
   4785 /// TODO: Handle pointer return types.
   4786 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
   4787                                                 const FunctionDecl *FDecl,
   4788                                                 MultiExprArg ArgExprs) {
   4789 
   4790   QualType DeclType = FDecl->getType();
   4791   const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
   4792 
   4793   if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) ||
   4794       !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams())
   4795     return nullptr;
   4796 
   4797   bool NeedsNewDecl = false;
   4798   unsigned i = 0;
   4799   SmallVector<QualType, 8> OverloadParams;
   4800 
   4801   for (QualType ParamType : FT->param_types()) {
   4802 
   4803     // Convert array arguments to pointer to simplify type lookup.
   4804     Expr *Arg = Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]).get();
   4805     QualType ArgType = Arg->getType();
   4806     if (!ParamType->isPointerType() ||
   4807         ParamType.getQualifiers().hasAddressSpace() ||
   4808         !ArgType->isPointerType() ||
   4809         !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) {
   4810       OverloadParams.push_back(ParamType);
   4811       continue;
   4812     }
   4813 
   4814     NeedsNewDecl = true;
   4815     unsigned AS = ArgType->getPointeeType().getQualifiers().getAddressSpace();
   4816 
   4817     QualType PointeeType = ParamType->getPointeeType();
   4818     PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
   4819     OverloadParams.push_back(Context.getPointerType(PointeeType));
   4820   }
   4821 
   4822   if (!NeedsNewDecl)
   4823     return nullptr;
   4824 
   4825   FunctionProtoType::ExtProtoInfo EPI;
   4826   QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
   4827                                                 OverloadParams, EPI);
   4828   DeclContext *Parent = Context.getTranslationUnitDecl();
   4829   FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
   4830                                                     FDecl->getLocation(),
   4831                                                     FDecl->getLocation(),
   4832                                                     FDecl->getIdentifier(),
   4833                                                     OverloadTy,
   4834                                                     /*TInfo=*/nullptr,
   4835                                                     SC_Extern, false,
   4836                                                     /*hasPrototype=*/true);
   4837   SmallVector<ParmVarDecl*, 16> Params;
   4838   FT = cast<FunctionProtoType>(OverloadTy);
   4839   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
   4840     QualType ParamType = FT->getParamType(i);
   4841     ParmVarDecl *Parm =
   4842         ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
   4843                                 SourceLocation(), nullptr, ParamType,
   4844                                 /*TInfo=*/nullptr, SC_None, nullptr);
   4845     Parm->setScopeInfo(0, i);
   4846     Params.push_back(Parm);
   4847   }
   4848   OverloadDecl->setParams(Params);
   4849   return OverloadDecl;
   4850 }
   4851 
   4852 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
   4853 /// This provides the location of the left/right parens and a list of comma
   4854 /// locations.
   4855 ExprResult
   4856 Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
   4857                     MultiExprArg ArgExprs, SourceLocation RParenLoc,
   4858                     Expr *ExecConfig, bool IsExecConfig) {
   4859   // Since this might be a postfix expression, get rid of ParenListExprs.
   4860   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
   4861   if (Result.isInvalid()) return ExprError();
   4862   Fn = Result.get();
   4863 
   4864   if (checkArgsForPlaceholders(*this, ArgExprs))
   4865     return ExprError();
   4866 
   4867   if (getLangOpts().CPlusPlus) {
   4868     // If this is a pseudo-destructor expression, build the call immediately.
   4869     if (isa<CXXPseudoDestructorExpr>(Fn)) {
   4870       if (!ArgExprs.empty()) {
   4871         // Pseudo-destructor calls should not have any arguments.
   4872         Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
   4873           << FixItHint::CreateRemoval(
   4874                                     SourceRange(ArgExprs.front()->getLocStart(),
   4875                                                 ArgExprs.back()->getLocEnd()));
   4876       }
   4877 
   4878       return new (Context)
   4879           CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc);
   4880     }
   4881     if (Fn->getType() == Context.PseudoObjectTy) {
   4882       ExprResult result = CheckPlaceholderExpr(Fn);
   4883       if (result.isInvalid()) return ExprError();
   4884       Fn = result.get();
   4885     }
   4886 
   4887     // Determine whether this is a dependent call inside a C++ template,
   4888     // in which case we won't do any semantic analysis now.
   4889     // FIXME: Will need to cache the results of name lookup (including ADL) in
   4890     // Fn.
   4891     bool Dependent = false;
   4892     if (Fn->isTypeDependent())
   4893       Dependent = true;
   4894     else if (Expr::hasAnyTypeDependentArguments(ArgExprs))
   4895       Dependent = true;
   4896 
   4897     if (Dependent) {
   4898       if (ExecConfig) {
   4899         return new (Context) CUDAKernelCallExpr(
   4900             Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
   4901             Context.DependentTy, VK_RValue, RParenLoc);
   4902       } else {
   4903         return new (Context) CallExpr(
   4904             Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc);
   4905       }
   4906     }
   4907 
   4908     // Determine whether this is a call to an object (C++ [over.call.object]).
   4909     if (Fn->getType()->isRecordType())
   4910       return BuildCallToObjectOfClassType(S, Fn, LParenLoc, ArgExprs,
   4911                                           RParenLoc);
   4912 
   4913     if (Fn->getType() == Context.UnknownAnyTy) {
   4914       ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
   4915       if (result.isInvalid()) return ExprError();
   4916       Fn = result.get();
   4917     }
   4918 
   4919     if (Fn->getType() == Context.BoundMemberTy) {
   4920       return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs, RParenLoc);
   4921     }
   4922   }
   4923 
   4924   // Check for overloaded calls.  This can happen even in C due to extensions.
   4925   if (Fn->getType() == Context.OverloadTy) {
   4926     OverloadExpr::FindResult find = OverloadExpr::find(Fn);
   4927 
   4928     // We aren't supposed to apply this logic for if there's an '&' involved.
   4929     if (!find.HasFormOfMemberPointer) {
   4930       OverloadExpr *ovl = find.Expression;
   4931       if (isa<UnresolvedLookupExpr>(ovl)) {
   4932         UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
   4933         return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, ArgExprs,
   4934                                        RParenLoc, ExecConfig);
   4935       } else {
   4936         return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs,
   4937                                          RParenLoc);
   4938       }
   4939     }
   4940   }
   4941 
   4942   // If we're directly calling a function, get the appropriate declaration.
   4943   if (Fn->getType() == Context.UnknownAnyTy) {
   4944     ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
   4945     if (result.isInvalid()) return ExprError();
   4946     Fn = result.get();
   4947   }
   4948 
   4949   Expr *NakedFn = Fn->IgnoreParens();
   4950 
   4951   NamedDecl *NDecl = nullptr;
   4952   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
   4953     if (UnOp->getOpcode() == UO_AddrOf)
   4954       NakedFn = UnOp->getSubExpr()->IgnoreParens();
   4955 
   4956   if (isa<DeclRefExpr>(NakedFn)) {
   4957     NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
   4958 
   4959     FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
   4960     if (FDecl && FDecl->getBuiltinID()) {
   4961       // Rewrite the function decl for this builtin by replacing paramaters
   4962       // with no explicit address space with the address space of the arguments
   4963       // in ArgExprs.
   4964       if ((FDecl = rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
   4965         NDecl = FDecl;
   4966         Fn = DeclRefExpr::Create(Context, FDecl->getQualifierLoc(),
   4967                            SourceLocation(), FDecl, false,
   4968                            SourceLocation(), FDecl->getType(),
   4969                            Fn->getValueKind(), FDecl);
   4970       }
   4971     }
   4972   } else if (isa<MemberExpr>(NakedFn))
   4973     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
   4974 
   4975   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
   4976     if (FD->hasAttr<EnableIfAttr>()) {
   4977       if (const EnableIfAttr *Attr = CheckEnableIf(FD, ArgExprs, true)) {
   4978         Diag(Fn->getLocStart(),
   4979              isa<CXXMethodDecl>(FD) ?
   4980                  diag::err_ovl_no_viable_member_function_in_call :
   4981                  diag::err_ovl_no_viable_function_in_call)
   4982           << FD << FD->getSourceRange();
   4983         Diag(FD->getLocation(),
   4984              diag::note_ovl_candidate_disabled_by_enable_if_attr)
   4985             << Attr->getCond()->getSourceRange() << Attr->getMessage();
   4986       }
   4987     }
   4988   }
   4989 
   4990   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
   4991                                ExecConfig, IsExecConfig);
   4992 }
   4993 
   4994 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
   4995 ///
   4996 /// __builtin_astype( value, dst type )
   4997 ///
   4998 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
   4999                                  SourceLocation BuiltinLoc,
   5000                                  SourceLocation RParenLoc) {
   5001   ExprValueKind VK = VK_RValue;
   5002   ExprObjectKind OK = OK_Ordinary;
   5003   QualType DstTy = GetTypeFromParser(ParsedDestTy);
   5004   QualType SrcTy = E->getType();
   5005   if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
   5006     return ExprError(Diag(BuiltinLoc,
   5007                           diag::err_invalid_astype_of_different_size)
   5008                      << DstTy
   5009                      << SrcTy
   5010                      << E->getSourceRange());
   5011   return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
   5012 }
   5013 
   5014 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
   5015 /// provided arguments.
   5016 ///
   5017 /// __builtin_convertvector( value, dst type )
   5018 ///
   5019 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
   5020                                         SourceLocation BuiltinLoc,
   5021                                         SourceLocation RParenLoc) {
   5022   TypeSourceInfo *TInfo;
   5023   GetTypeFromParser(ParsedDestTy, &TInfo);
   5024   return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
   5025 }
   5026 
   5027 /// BuildResolvedCallExpr - Build a call to a resolved expression,
   5028 /// i.e. an expression not of \p OverloadTy.  The expression should
   5029 /// unary-convert to an expression of function-pointer or
   5030 /// block-pointer type.
   5031 ///
   5032 /// \param NDecl the declaration being called, if available
   5033 ExprResult
   5034 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
   5035                             SourceLocation LParenLoc,
   5036                             ArrayRef<Expr *> Args,
   5037                             SourceLocation RParenLoc,
   5038                             Expr *Config, bool IsExecConfig) {
   5039   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
   5040   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
   5041 
   5042   // Promote the function operand.
   5043   // We special-case function promotion here because we only allow promoting
   5044   // builtin functions to function pointers in the callee of a call.
   5045   ExprResult Result;
   5046   if (BuiltinID &&
   5047       Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
   5048     Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()),
   5049                                CK_BuiltinFnToFnPtr).get();
   5050   } else {
   5051     Result = CallExprUnaryConversions(Fn);
   5052   }
   5053   if (Result.isInvalid())
   5054     return ExprError();
   5055   Fn = Result.get();
   5056 
   5057   // Make the call expr early, before semantic checks.  This guarantees cleanup
   5058   // of arguments and function on error.
   5059   CallExpr *TheCall;
   5060   if (Config)
   5061     TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
   5062                                                cast<CallExpr>(Config), Args,
   5063                                                Context.BoolTy, VK_RValue,
   5064                                                RParenLoc);
   5065   else
   5066     TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy,
   5067                                      VK_RValue, RParenLoc);
   5068 
   5069   if (!getLangOpts().CPlusPlus) {
   5070     // C cannot always handle TypoExpr nodes in builtin calls and direct
   5071     // function calls as their argument checking don't necessarily handle
   5072     // dependent types properly, so make sure any TypoExprs have been
   5073     // dealt with.
   5074     ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
   5075     if (!Result.isUsable()) return ExprError();
   5076     TheCall = dyn_cast<CallExpr>(Result.get());
   5077     if (!TheCall) return Result;
   5078     Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
   5079   }
   5080 
   5081   // Bail out early if calling a builtin with custom typechecking.
   5082   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
   5083     return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
   5084 
   5085  retry:
   5086   const FunctionType *FuncT;
   5087   if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
   5088     // C99 6.5.2.2p1 - "The expression that denotes the called function shall
   5089     // have type pointer to function".
   5090     FuncT = PT->getPointeeType()->getAs<FunctionType>();
   5091     if (!FuncT)
   5092       return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
   5093                          << Fn->getType() << Fn->getSourceRange());
   5094   } else if (const BlockPointerType *BPT =
   5095                Fn->getType()->getAs<BlockPointerType>()) {
   5096     FuncT = BPT->getPointeeType()->castAs<FunctionType>();
   5097   } else {
   5098     // Handle calls to expressions of unknown-any type.
   5099     if (Fn->getType() == Context.UnknownAnyTy) {
   5100       ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
   5101       if (rewrite.isInvalid()) return ExprError();
   5102       Fn = rewrite.get();
   5103       TheCall->setCallee(Fn);
   5104       goto retry;
   5105     }
   5106 
   5107     return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
   5108       << Fn->getType() << Fn->getSourceRange());
   5109   }
   5110 
   5111   if (getLangOpts().CUDA) {
   5112     if (Config) {
   5113       // CUDA: Kernel calls must be to global functions
   5114       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
   5115         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
   5116             << FDecl->getName() << Fn->getSourceRange());
   5117 
   5118       // CUDA: Kernel function must have 'void' return type
   5119       if (!FuncT->getReturnType()->isVoidType())
   5120         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
   5121             << Fn->getType() << Fn->getSourceRange());
   5122     } else {
   5123       // CUDA: Calls to global functions must be configured
   5124       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
   5125         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
   5126             << FDecl->getName() << Fn->getSourceRange());
   5127     }
   5128   }
   5129 
   5130   // Check for a valid return type
   5131   if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall,
   5132                           FDecl))
   5133     return ExprError();
   5134 
   5135   // We know the result type of the call, set it.
   5136   TheCall->setType(FuncT->getCallResultType(Context));
   5137   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
   5138 
   5139   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
   5140   if (Proto) {
   5141     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
   5142                                 IsExecConfig))
   5143       return ExprError();
   5144   } else {
   5145     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
   5146 
   5147     if (FDecl) {
   5148       // Check if we have too few/too many template arguments, based
   5149       // on our knowledge of the function definition.
   5150       const FunctionDecl *Def = nullptr;
   5151       if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
   5152         Proto = Def->getType()->getAs<FunctionProtoType>();
   5153        if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
   5154           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
   5155           << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
   5156       }
   5157 
   5158       // If the function we're calling isn't a function prototype, but we have
   5159       // a function prototype from a prior declaratiom, use that prototype.
   5160       if (!FDecl->hasPrototype())
   5161         Proto = FDecl->getType()->getAs<FunctionProtoType>();
   5162     }
   5163 
   5164     // Promote the arguments (C99 6.5.2.2p6).
   5165     for (unsigned i = 0, e = Args.size(); i != e; i++) {
   5166       Expr *Arg = Args[i];
   5167 
   5168       if (Proto && i < Proto->getNumParams()) {
   5169         InitializedEntity Entity = InitializedEntity::InitializeParameter(
   5170             Context, Proto->getParamType(i), Proto->isParamConsumed(i));
   5171         ExprResult ArgE =
   5172             PerformCopyInitialization(Entity, SourceLocation(), Arg);
   5173         if (ArgE.isInvalid())
   5174           return true;
   5175 
   5176         Arg = ArgE.getAs<Expr>();
   5177 
   5178       } else {
   5179         ExprResult ArgE = DefaultArgumentPromotion(Arg);
   5180 
   5181         if (ArgE.isInvalid())
   5182           return true;
   5183 
   5184         Arg = ArgE.getAs<Expr>();
   5185       }
   5186 
   5187       if (RequireCompleteType(Arg->getLocStart(),
   5188                               Arg->getType(),
   5189                               diag::err_call_incomplete_argument, Arg))
   5190         return ExprError();
   5191 
   5192       TheCall->setArg(i, Arg);
   5193     }
   5194   }
   5195 
   5196   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
   5197     if (!Method->isStatic())
   5198       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
   5199         << Fn->getSourceRange());
   5200 
   5201   // Check for sentinels
   5202   if (NDecl)
   5203     DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
   5204 
   5205   // Do special checking on direct calls to functions.
   5206   if (FDecl) {
   5207     if (CheckFunctionCall(FDecl, TheCall, Proto))
   5208       return ExprError();
   5209 
   5210     if (BuiltinID)
   5211       return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
   5212   } else if (NDecl) {
   5213     if (CheckPointerCall(NDecl, TheCall, Proto))
   5214       return ExprError();
   5215   } else {
   5216     if (CheckOtherCall(TheCall, Proto))
   5217       return ExprError();
   5218   }
   5219 
   5220   return MaybeBindToTemporary(TheCall);
   5221 }
   5222 
   5223 ExprResult
   5224 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
   5225                            SourceLocation RParenLoc, Expr *InitExpr) {
   5226   assert(Ty && "ActOnCompoundLiteral(): missing type");
   5227   assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
   5228 
   5229   TypeSourceInfo *TInfo;
   5230   QualType literalType = GetTypeFromParser(Ty, &TInfo);
   5231   if (!TInfo)
   5232     TInfo = Context.getTrivialTypeSourceInfo(literalType);
   5233 
   5234   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
   5235 }
   5236 
   5237 ExprResult
   5238 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
   5239                                SourceLocation RParenLoc, Expr *LiteralExpr) {
   5240   QualType literalType = TInfo->getType();
   5241 
   5242   if (literalType->isArrayType()) {
   5243     if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
   5244           diag::err_illegal_decl_array_incomplete_type,
   5245           SourceRange(LParenLoc,
   5246                       LiteralExpr->getSourceRange().getEnd())))
   5247       return ExprError();
   5248     if (literalType->isVariableArrayType())
   5249       return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
   5250         << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
   5251   } else if (!literalType->isDependentType() &&
   5252              RequireCompleteType(LParenLoc, literalType,
   5253                diag::err_typecheck_decl_incomplete_type,
   5254                SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
   5255     return ExprError();
   5256 
   5257   InitializedEntity Entity
   5258     = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
   5259   InitializationKind Kind
   5260     = InitializationKind::CreateCStyleCast(LParenLoc,
   5261                                            SourceRange(LParenLoc, RParenLoc),
   5262                                            /*InitList=*/true);
   5263   InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
   5264   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
   5265                                       &literalType);
   5266   if (Result.isInvalid())
   5267     return ExprError();
   5268   LiteralExpr = Result.get();
   5269 
   5270   bool isFileScope = getCurFunctionOrMethodDecl() == nullptr;
   5271   if (isFileScope &&
   5272       !LiteralExpr->isTypeDependent() &&
   5273       !LiteralExpr->isValueDependent() &&
   5274       !literalType->isDependentType()) { // 6.5.2.5p3
   5275     if (CheckForConstantInitializer(LiteralExpr, literalType))
   5276       return ExprError();
   5277   }
   5278 
   5279   // In C, compound literals are l-values for some reason.
   5280   ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue;
   5281 
   5282   return MaybeBindToTemporary(
   5283            new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
   5284                                              VK, LiteralExpr, isFileScope));
   5285 }
   5286 
   5287 ExprResult
   5288 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
   5289                     SourceLocation RBraceLoc) {
   5290   // Immediately handle non-overload placeholders.  Overloads can be
   5291   // resolved contextually, but everything else here can't.
   5292   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
   5293     if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
   5294       ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
   5295 
   5296       // Ignore failures; dropping the entire initializer list because
   5297       // of one failure would be terrible for indexing/etc.
   5298       if (result.isInvalid()) continue;
   5299 
   5300       InitArgList[I] = result.get();
   5301     }
   5302   }
   5303 
   5304   // Semantic analysis for initializers is done by ActOnDeclarator() and
   5305   // CheckInitializer() - it requires knowledge of the object being intialized.
   5306 
   5307   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
   5308                                                RBraceLoc);
   5309   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
   5310   return E;
   5311 }
   5312 
   5313 /// Do an explicit extend of the given block pointer if we're in ARC.
   5314 void Sema::maybeExtendBlockObject(ExprResult &E) {
   5315   assert(E.get()->getType()->isBlockPointerType());
   5316   assert(E.get()->isRValue());
   5317 
   5318   // Only do this in an r-value context.
   5319   if (!getLangOpts().ObjCAutoRefCount) return;
   5320 
   5321   E = ImplicitCastExpr::Create(Context, E.get()->getType(),
   5322                                CK_ARCExtendBlockObject, E.get(),
   5323                                /*base path*/ nullptr, VK_RValue);
   5324   ExprNeedsCleanups = true;
   5325 }
   5326 
   5327 /// Prepare a conversion of the given expression to an ObjC object
   5328 /// pointer type.
   5329 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
   5330   QualType type = E.get()->getType();
   5331   if (type->isObjCObjectPointerType()) {
   5332     return CK_BitCast;
   5333   } else if (type->isBlockPointerType()) {
   5334     maybeExtendBlockObject(E);
   5335     return CK_BlockPointerToObjCPointerCast;
   5336   } else {
   5337     assert(type->isPointerType());
   5338     return CK_CPointerToObjCPointerCast;
   5339   }
   5340 }
   5341 
   5342 /// Prepares for a scalar cast, performing all the necessary stages
   5343 /// except the final cast and returning the kind required.
   5344 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
   5345   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
   5346   // Also, callers should have filtered out the invalid cases with
   5347   // pointers.  Everything else should be possible.
   5348 
   5349   QualType SrcTy = Src.get()->getType();
   5350   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
   5351     return CK_NoOp;
   5352 
   5353   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
   5354   case Type::STK_MemberPointer:
   5355     llvm_unreachable("member pointer type in C");
   5356 
   5357   case Type::STK_CPointer:
   5358   case Type::STK_BlockPointer:
   5359   case Type::STK_ObjCObjectPointer:
   5360     switch (DestTy->getScalarTypeKind()) {
   5361     case Type::STK_CPointer: {
   5362       unsigned SrcAS = SrcTy->getPointeeType().getAddressSpace();
   5363       unsigned DestAS = DestTy->getPointeeType().getAddressSpace();
   5364       if (SrcAS != DestAS)
   5365         return CK_AddressSpaceConversion;
   5366       return CK_BitCast;
   5367     }
   5368     case Type::STK_BlockPointer:
   5369       return (SrcKind == Type::STK_BlockPointer
   5370                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
   5371     case Type::STK_ObjCObjectPointer:
   5372       if (SrcKind == Type::STK_ObjCObjectPointer)
   5373         return CK_BitCast;
   5374       if (SrcKind == Type::STK_CPointer)
   5375         return CK_CPointerToObjCPointerCast;
   5376       maybeExtendBlockObject(Src);
   5377       return CK_BlockPointerToObjCPointerCast;
   5378     case Type::STK_Bool:
   5379       return CK_PointerToBoolean;
   5380     case Type::STK_Integral:
   5381       return CK_PointerToIntegral;
   5382     case Type::STK_Floating:
   5383     case Type::STK_FloatingComplex:
   5384     case Type::STK_IntegralComplex:
   5385     case Type::STK_MemberPointer:
   5386       llvm_unreachable("illegal cast from pointer");
   5387     }
   5388     llvm_unreachable("Should have returned before this");
   5389 
   5390   case Type::STK_Bool: // casting from bool is like casting from an integer
   5391   case Type::STK_Integral:
   5392     switch (DestTy->getScalarTypeKind()) {
   5393     case Type::STK_CPointer:
   5394     case Type::STK_ObjCObjectPointer:
   5395     case Type::STK_BlockPointer:
   5396       if (Src.get()->isNullPointerConstant(Context,
   5397                                            Expr::NPC_ValueDependentIsNull))
   5398         return CK_NullToPointer;
   5399       return CK_IntegralToPointer;
   5400     case Type::STK_Bool:
   5401       return CK_IntegralToBoolean;
   5402     case Type::STK_Integral:
   5403       return CK_IntegralCast;
   5404     case Type::STK_Floating:
   5405       return CK_IntegralToFloating;
   5406     case Type::STK_IntegralComplex:
   5407       Src = ImpCastExprToType(Src.get(),
   5408                       DestTy->castAs<ComplexType>()->getElementType(),
   5409                       CK_IntegralCast);
   5410       return CK_IntegralRealToComplex;
   5411     case Type::STK_FloatingComplex:
   5412       Src = ImpCastExprToType(Src.get(),
   5413                       DestTy->castAs<ComplexType>()->getElementType(),
   5414                       CK_IntegralToFloating);
   5415       return CK_FloatingRealToComplex;
   5416     case Type::STK_MemberPointer:
   5417       llvm_unreachable("member pointer type in C");
   5418     }
   5419     llvm_unreachable("Should have returned before this");
   5420 
   5421   case Type::STK_Floating:
   5422     switch (DestTy->getScalarTypeKind()) {
   5423     case Type::STK_Floating:
   5424       return CK_FloatingCast;
   5425     case Type::STK_Bool:
   5426       return CK_FloatingToBoolean;
   5427     case Type::STK_Integral:
   5428       return CK_FloatingToIntegral;
   5429     case Type::STK_FloatingComplex:
   5430       Src = ImpCastExprToType(Src.get(),
   5431                               DestTy->castAs<ComplexType>()->getElementType(),
   5432                               CK_FloatingCast);
   5433       return CK_FloatingRealToComplex;
   5434     case Type::STK_IntegralComplex:
   5435       Src = ImpCastExprToType(Src.get(),
   5436                               DestTy->castAs<ComplexType>()->getElementType(),
   5437                               CK_FloatingToIntegral);
   5438       return CK_IntegralRealToComplex;
   5439     case Type::STK_CPointer:
   5440     case Type::STK_ObjCObjectPointer:
   5441     case Type::STK_BlockPointer:
   5442       llvm_unreachable("valid float->pointer cast?");
   5443     case Type::STK_MemberPointer:
   5444       llvm_unreachable("member pointer type in C");
   5445     }
   5446     llvm_unreachable("Should have returned before this");
   5447 
   5448   case Type::STK_FloatingComplex:
   5449     switch (DestTy->getScalarTypeKind()) {
   5450     case Type::STK_FloatingComplex:
   5451       return CK_FloatingComplexCast;
   5452     case Type::STK_IntegralComplex:
   5453       return CK_FloatingComplexToIntegralComplex;
   5454     case Type::STK_Floating: {
   5455       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
   5456       if (Context.hasSameType(ET, DestTy))
   5457         return CK_FloatingComplexToReal;
   5458       Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
   5459       return CK_FloatingCast;
   5460     }
   5461     case Type::STK_Bool:
   5462       return CK_FloatingComplexToBoolean;
   5463     case Type::STK_Integral:
   5464       Src = ImpCastExprToType(Src.get(),
   5465                               SrcTy->castAs<ComplexType>()->getElementType(),
   5466                               CK_FloatingComplexToReal);
   5467       return CK_FloatingToIntegral;
   5468     case Type::STK_CPointer:
   5469     case Type::STK_ObjCObjectPointer:
   5470     case Type::STK_BlockPointer:
   5471       llvm_unreachable("valid complex float->pointer cast?");
   5472     case Type::STK_MemberPointer:
   5473       llvm_unreachable("member pointer type in C");
   5474     }
   5475     llvm_unreachable("Should have returned before this");
   5476 
   5477   case Type::STK_IntegralComplex:
   5478     switch (DestTy->getScalarTypeKind()) {
   5479     case Type::STK_FloatingComplex:
   5480       return CK_IntegralComplexToFloatingComplex;
   5481     case Type::STK_IntegralComplex:
   5482       return CK_IntegralComplexCast;
   5483     case Type::STK_Integral: {
   5484       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
   5485       if (Context.hasSameType(ET, DestTy))
   5486         return CK_IntegralComplexToReal;
   5487       Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
   5488       return CK_IntegralCast;
   5489     }
   5490     case Type::STK_Bool:
   5491       return CK_IntegralComplexToBoolean;
   5492     case Type::STK_Floating:
   5493       Src = ImpCastExprToType(Src.get(),
   5494                               SrcTy->castAs<ComplexType>()->getElementType(),
   5495                               CK_IntegralComplexToReal);
   5496       return CK_IntegralToFloating;
   5497     case Type::STK_CPointer:
   5498     case Type::STK_ObjCObjectPointer:
   5499     case Type::STK_BlockPointer:
   5500       llvm_unreachable("valid complex int->pointer cast?");
   5501     case Type::STK_MemberPointer:
   5502       llvm_unreachable("member pointer type in C");
   5503     }
   5504     llvm_unreachable("Should have returned before this");
   5505   }
   5506 
   5507   llvm_unreachable("Unhandled scalar cast");
   5508 }
   5509 
   5510 static bool breakDownVectorType(QualType type, uint64_t &len,
   5511                                 QualType &eltType) {
   5512   // Vectors are simple.
   5513   if (const VectorType *vecType = type->getAs<VectorType>()) {
   5514     len = vecType->getNumElements();
   5515     eltType = vecType->getElementType();
   5516     assert(eltType->isScalarType());
   5517     return true;
   5518   }
   5519 
   5520   // We allow lax conversion to and from non-vector types, but only if
   5521   // they're real types (i.e. non-complex, non-pointer scalar types).
   5522   if (!type->isRealType()) return false;
   5523 
   5524   len = 1;
   5525   eltType = type;
   5526   return true;
   5527 }
   5528 
   5529 /// Are the two types lax-compatible vector types?  That is, given
   5530 /// that one of them is a vector, do they have equal storage sizes,
   5531 /// where the storage size is the number of elements times the element
   5532 /// size?
   5533 ///
   5534 /// This will also return false if either of the types is neither a
   5535 /// vector nor a real type.
   5536 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
   5537   assert(destTy->isVectorType() || srcTy->isVectorType());
   5538 
   5539   // Disallow lax conversions between scalars and ExtVectors (these
   5540   // conversions are allowed for other vector types because common headers
   5541   // depend on them).  Most scalar OP ExtVector cases are handled by the
   5542   // splat path anyway, which does what we want (convert, not bitcast).
   5543   // What this rules out for ExtVectors is crazy things like char4*float.
   5544   if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
   5545   if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
   5546 
   5547   uint64_t srcLen, destLen;
   5548   QualType srcEltTy, destEltTy;
   5549   if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false;
   5550   if (!breakDownVectorType(destTy, destLen, destEltTy)) return false;
   5551 
   5552   // ASTContext::getTypeSize will return the size rounded up to a
   5553   // power of 2, so instead of using that, we need to use the raw
   5554   // element size multiplied by the element count.
   5555   uint64_t srcEltSize = Context.getTypeSize(srcEltTy);
   5556   uint64_t destEltSize = Context.getTypeSize(destEltTy);
   5557 
   5558   return (srcLen * srcEltSize == destLen * destEltSize);
   5559 }
   5560 
   5561 /// Is this a legal conversion between two types, one of which is
   5562 /// known to be a vector type?
   5563 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
   5564   assert(destTy->isVectorType() || srcTy->isVectorType());
   5565 
   5566   if (!Context.getLangOpts().LaxVectorConversions)
   5567     return false;
   5568   return areLaxCompatibleVectorTypes(srcTy, destTy);
   5569 }
   5570 
   5571 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
   5572                            CastKind &Kind) {
   5573   assert(VectorTy->isVectorType() && "Not a vector type!");
   5574 
   5575   if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
   5576     if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
   5577       return Diag(R.getBegin(),
   5578                   Ty->isVectorType() ?
   5579                   diag::err_invalid_conversion_between_vectors :
   5580                   diag::err_invalid_conversion_between_vector_and_integer)
   5581         << VectorTy << Ty << R;
   5582   } else
   5583     return Diag(R.getBegin(),
   5584                 diag::err_invalid_conversion_between_vector_and_scalar)
   5585       << VectorTy << Ty << R;
   5586 
   5587   Kind = CK_BitCast;
   5588   return false;
   5589 }
   5590 
   5591 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
   5592                                     Expr *CastExpr, CastKind &Kind) {
   5593   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
   5594 
   5595   QualType SrcTy = CastExpr->getType();
   5596 
   5597   // If SrcTy is a VectorType, the total size must match to explicitly cast to
   5598   // an ExtVectorType.
   5599   // In OpenCL, casts between vectors of different types are not allowed.
   5600   // (See OpenCL 6.2).
   5601   if (SrcTy->isVectorType()) {
   5602     if (!areLaxCompatibleVectorTypes(SrcTy, DestTy)
   5603         || (getLangOpts().OpenCL &&
   5604             (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
   5605       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
   5606         << DestTy << SrcTy << R;
   5607       return ExprError();
   5608     }
   5609     Kind = CK_BitCast;
   5610     return CastExpr;
   5611   }
   5612 
   5613   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
   5614   // conversion will take place first from scalar to elt type, and then
   5615   // splat from elt type to vector.
   5616   if (SrcTy->isPointerType())
   5617     return Diag(R.getBegin(),
   5618                 diag::err_invalid_conversion_between_vector_and_scalar)
   5619       << DestTy << SrcTy << R;
   5620 
   5621   QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
   5622   ExprResult CastExprRes = CastExpr;
   5623   CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy);
   5624   if (CastExprRes.isInvalid())
   5625     return ExprError();
   5626   CastExpr = ImpCastExprToType(CastExprRes.get(), DestElemTy, CK).get();
   5627 
   5628   Kind = CK_VectorSplat;
   5629   return CastExpr;
   5630 }
   5631 
   5632 ExprResult
   5633 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
   5634                     Declarator &D, ParsedType &Ty,
   5635                     SourceLocation RParenLoc, Expr *CastExpr) {
   5636   assert(!D.isInvalidType() && (CastExpr != nullptr) &&
   5637          "ActOnCastExpr(): missing type or expr");
   5638 
   5639   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
   5640   if (D.isInvalidType())
   5641     return ExprError();
   5642 
   5643   if (getLangOpts().CPlusPlus) {
   5644     // Check that there are no default arguments (C++ only).
   5645     CheckExtraCXXDefaultArguments(D);
   5646   } else {
   5647     // Make sure any TypoExprs have been dealt with.
   5648     ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
   5649     if (!Res.isUsable())
   5650       return ExprError();
   5651     CastExpr = Res.get();
   5652   }
   5653 
   5654   checkUnusedDeclAttributes(D);
   5655 
   5656   QualType castType = castTInfo->getType();
   5657   Ty = CreateParsedType(castType, castTInfo);
   5658 
   5659   bool isVectorLiteral = false;
   5660 
   5661   // Check for an altivec or OpenCL literal,
   5662   // i.e. all the elements are integer constants.
   5663   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
   5664   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
   5665   if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
   5666        && castType->isVectorType() && (PE || PLE)) {
   5667     if (PLE && PLE->getNumExprs() == 0) {
   5668       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
   5669       return ExprError();
   5670     }
   5671     if (PE || PLE->getNumExprs() == 1) {
   5672       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
   5673       if (!E->getType()->isVectorType())
   5674         isVectorLiteral = true;
   5675     }
   5676     else
   5677       isVectorLiteral = true;
   5678   }
   5679 
   5680   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
   5681   // then handle it as such.
   5682   if (isVectorLiteral)
   5683     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
   5684 
   5685   // If the Expr being casted is a ParenListExpr, handle it specially.
   5686   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
   5687   // sequence of BinOp comma operators.
   5688   if (isa<ParenListExpr>(CastExpr)) {
   5689     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
   5690     if (Result.isInvalid()) return ExprError();
   5691     CastExpr = Result.get();
   5692   }
   5693 
   5694   if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
   5695       !getSourceManager().isInSystemMacro(LParenLoc))
   5696     Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
   5697 
   5698   CheckTollFreeBridgeCast(castType, CastExpr);
   5699 
   5700   CheckObjCBridgeRelatedCast(castType, CastExpr);
   5701 
   5702   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
   5703 }
   5704 
   5705 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
   5706                                     SourceLocation RParenLoc, Expr *E,
   5707                                     TypeSourceInfo *TInfo) {
   5708   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
   5709          "Expected paren or paren list expression");
   5710 
   5711   Expr **exprs;
   5712   unsigned numExprs;
   5713   Expr *subExpr;
   5714   SourceLocation LiteralLParenLoc, LiteralRParenLoc;
   5715   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
   5716     LiteralLParenLoc = PE->getLParenLoc();
   5717     LiteralRParenLoc = PE->getRParenLoc();
   5718     exprs = PE->getExprs();
   5719     numExprs = PE->getNumExprs();
   5720   } else { // isa<ParenExpr> by assertion at function entrance
   5721     LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
   5722     LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
   5723     subExpr = cast<ParenExpr>(E)->getSubExpr();
   5724     exprs = &subExpr;
   5725     numExprs = 1;
   5726   }
   5727 
   5728   QualType Ty = TInfo->getType();
   5729   assert(Ty->isVectorType() && "Expected vector type");
   5730 
   5731   SmallVector<Expr *, 8> initExprs;
   5732   const VectorType *VTy = Ty->getAs<VectorType>();
   5733   unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
   5734 
   5735   // '(...)' form of vector initialization in AltiVec: the number of
   5736   // initializers must be one or must match the size of the vector.
   5737   // If a single value is specified in the initializer then it will be
   5738   // replicated to all the components of the vector
   5739   if (VTy->getVectorKind() == VectorType::AltiVecVector) {
   5740     // The number of initializers must be one or must match the size of the
   5741     // vector. If a single value is specified in the initializer then it will
   5742     // be replicated to all the components of the vector
   5743     if (numExprs == 1) {
   5744       QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
   5745       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
   5746       if (Literal.isInvalid())
   5747         return ExprError();
   5748       Literal = ImpCastExprToType(Literal.get(), ElemTy,
   5749                                   PrepareScalarCast(Literal, ElemTy));
   5750       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
   5751     }
   5752     else if (numExprs < numElems) {
   5753       Diag(E->getExprLoc(),
   5754            diag::err_incorrect_number_of_vector_initializers);
   5755       return ExprError();
   5756     }
   5757     else
   5758       initExprs.append(exprs, exprs + numExprs);
   5759   }
   5760   else {
   5761     // For OpenCL, when the number of initializers is a single value,
   5762     // it will be replicated to all components of the vector.
   5763     if (getLangOpts().OpenCL &&
   5764         VTy->getVectorKind() == VectorType::GenericVector &&
   5765         numExprs == 1) {
   5766         QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
   5767         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
   5768         if (Literal.isInvalid())
   5769           return ExprError();
   5770         Literal = ImpCastExprToType(Literal.get(), ElemTy,
   5771                                     PrepareScalarCast(Literal, ElemTy));
   5772         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
   5773     }
   5774 
   5775     initExprs.append(exprs, exprs + numExprs);
   5776   }
   5777   // FIXME: This means that pretty-printing the final AST will produce curly
   5778   // braces instead of the original commas.
   5779   InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
   5780                                                    initExprs, LiteralRParenLoc);
   5781   initE->setType(Ty);
   5782   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
   5783 }
   5784 
   5785 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
   5786 /// the ParenListExpr into a sequence of comma binary operators.
   5787 ExprResult
   5788 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
   5789   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
   5790   if (!E)
   5791     return OrigExpr;
   5792 
   5793   ExprResult Result(E->getExpr(0));
   5794 
   5795   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
   5796     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
   5797                         E->getExpr(i));
   5798 
   5799   if (Result.isInvalid()) return ExprError();
   5800 
   5801   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
   5802 }
   5803 
   5804 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
   5805                                     SourceLocation R,
   5806                                     MultiExprArg Val) {
   5807   Expr *expr = new (Context) ParenListExpr(Context, L, Val, R);
   5808   return expr;
   5809 }
   5810 
   5811 /// \brief Emit a specialized diagnostic when one expression is a null pointer
   5812 /// constant and the other is not a pointer.  Returns true if a diagnostic is
   5813 /// emitted.
   5814 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
   5815                                       SourceLocation QuestionLoc) {
   5816   Expr *NullExpr = LHSExpr;
   5817   Expr *NonPointerExpr = RHSExpr;
   5818   Expr::NullPointerConstantKind NullKind =
   5819       NullExpr->isNullPointerConstant(Context,
   5820                                       Expr::NPC_ValueDependentIsNotNull);
   5821 
   5822   if (NullKind == Expr::NPCK_NotNull) {
   5823     NullExpr = RHSExpr;
   5824     NonPointerExpr = LHSExpr;
   5825     NullKind =
   5826         NullExpr->isNullPointerConstant(Context,
   5827                                         Expr::NPC_ValueDependentIsNotNull);
   5828   }
   5829 
   5830   if (NullKind == Expr::NPCK_NotNull)
   5831     return false;
   5832 
   5833   if (NullKind == Expr::NPCK_ZeroExpression)
   5834     return false;
   5835 
   5836   if (NullKind == Expr::NPCK_ZeroLiteral) {
   5837     // In this case, check to make sure that we got here from a "NULL"
   5838     // string in the source code.
   5839     NullExpr = NullExpr->IgnoreParenImpCasts();
   5840     SourceLocation loc = NullExpr->getExprLoc();
   5841     if (!findMacroSpelling(loc, "NULL"))
   5842       return false;
   5843   }
   5844 
   5845   int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
   5846   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
   5847       << NonPointerExpr->getType() << DiagType
   5848       << NonPointerExpr->getSourceRange();
   5849   return true;
   5850 }
   5851 
   5852 /// \brief Return false if the condition expression is valid, true otherwise.
   5853 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
   5854   QualType CondTy = Cond->getType();
   5855 
   5856   // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
   5857   if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
   5858     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
   5859       << CondTy << Cond->getSourceRange();
   5860     return true;
   5861   }
   5862 
   5863   // C99 6.5.15p2
   5864   if (CondTy->isScalarType()) return false;
   5865 
   5866   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
   5867     << CondTy << Cond->getSourceRange();
   5868   return true;
   5869 }
   5870 
   5871 /// \brief Handle when one or both operands are void type.
   5872 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
   5873                                          ExprResult &RHS) {
   5874     Expr *LHSExpr = LHS.get();
   5875     Expr *RHSExpr = RHS.get();
   5876 
   5877     if (!LHSExpr->getType()->isVoidType())
   5878       S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
   5879         << RHSExpr->getSourceRange();
   5880     if (!RHSExpr->getType()->isVoidType())
   5881       S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
   5882         << LHSExpr->getSourceRange();
   5883     LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
   5884     RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
   5885     return S.Context.VoidTy;
   5886 }
   5887 
   5888 /// \brief Return false if the NullExpr can be promoted to PointerTy,
   5889 /// true otherwise.
   5890 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
   5891                                         QualType PointerTy) {
   5892   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
   5893       !NullExpr.get()->isNullPointerConstant(S.Context,
   5894                                             Expr::NPC_ValueDependentIsNull))
   5895     return true;
   5896 
   5897   NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
   5898   return false;
   5899 }
   5900 
   5901 /// \brief Checks compatibility between two pointers and return the resulting
   5902 /// type.
   5903 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
   5904                                                      ExprResult &RHS,
   5905                                                      SourceLocation Loc) {
   5906   QualType LHSTy = LHS.get()->getType();
   5907   QualType RHSTy = RHS.get()->getType();
   5908 
   5909   if (S.Context.hasSameType(LHSTy, RHSTy)) {
   5910     // Two identical pointers types are always compatible.
   5911     return LHSTy;
   5912   }
   5913 
   5914   QualType lhptee, rhptee;
   5915 
   5916   // Get the pointee types.
   5917   bool IsBlockPointer = false;
   5918   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
   5919     lhptee = LHSBTy->getPointeeType();
   5920     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
   5921     IsBlockPointer = true;
   5922   } else {
   5923     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
   5924     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
   5925   }
   5926 
   5927   // C99 6.5.15p6: If both operands are pointers to compatible types or to
   5928   // differently qualified versions of compatible types, the result type is
   5929   // a pointer to an appropriately qualified version of the composite
   5930   // type.
   5931 
   5932   // Only CVR-qualifiers exist in the standard, and the differently-qualified
   5933   // clause doesn't make sense for our extensions. E.g. address space 2 should
   5934   // be incompatible with address space 3: they may live on different devices or
   5935   // anything.
   5936   Qualifiers lhQual = lhptee.getQualifiers();
   5937   Qualifiers rhQual = rhptee.getQualifiers();
   5938 
   5939   unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
   5940   lhQual.removeCVRQualifiers();
   5941   rhQual.removeCVRQualifiers();
   5942 
   5943   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
   5944   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
   5945 
   5946   QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
   5947 
   5948   if (CompositeTy.isNull()) {
   5949     S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
   5950       << LHSTy << RHSTy << LHS.get()->getSourceRange()
   5951       << RHS.get()->getSourceRange();
   5952     // In this situation, we assume void* type. No especially good
   5953     // reason, but this is what gcc does, and we do have to pick
   5954     // to get a consistent AST.
   5955     QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy);
   5956     LHS = S.ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
   5957     RHS = S.ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
   5958     return incompatTy;
   5959   }
   5960 
   5961   // The pointer types are compatible.
   5962   QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual);
   5963   if (IsBlockPointer)
   5964     ResultTy = S.Context.getBlockPointerType(ResultTy);
   5965   else
   5966     ResultTy = S.Context.getPointerType(ResultTy);
   5967 
   5968   LHS = S.ImpCastExprToType(LHS.get(), ResultTy, CK_BitCast);
   5969   RHS = S.ImpCastExprToType(RHS.get(), ResultTy, CK_BitCast);
   5970   return ResultTy;
   5971 }
   5972 
   5973 /// \brief Return the resulting type when the operands are both block pointers.
   5974 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
   5975                                                           ExprResult &LHS,
   5976                                                           ExprResult &RHS,
   5977                                                           SourceLocation Loc) {
   5978   QualType LHSTy = LHS.get()->getType();
   5979   QualType RHSTy = RHS.get()->getType();
   5980 
   5981   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
   5982     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
   5983       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
   5984       LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
   5985       RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
   5986       return destType;
   5987     }
   5988     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
   5989       << LHSTy << RHSTy << LHS.get()->getSourceRange()
   5990       << RHS.get()->getSourceRange();
   5991     return QualType();
   5992   }
   5993 
   5994   // We have 2 block pointer types.
   5995   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
   5996 }
   5997 
   5998 /// \brief Return the resulting type when the operands are both pointers.
   5999 static QualType
   6000 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
   6001                                             ExprResult &RHS,
   6002                                             SourceLocation Loc) {
   6003   // get the pointer types
   6004   QualType LHSTy = LHS.get()->getType();
   6005   QualType RHSTy = RHS.get()->getType();
   6006 
   6007   // get the "pointed to" types
   6008   QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
   6009   QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
   6010 
   6011   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
   6012   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
   6013     // Figure out necessary qualifiers (C99 6.5.15p6)
   6014     QualType destPointee
   6015       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
   6016     QualType destType = S.Context.getPointerType(destPointee);
   6017     // Add qualifiers if necessary.
   6018     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
   6019     // Promote to void*.
   6020     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
   6021     return destType;
   6022   }
   6023   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
   6024     QualType destPointee
   6025       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
   6026     QualType destType = S.Context.getPointerType(destPointee);
   6027     // Add qualifiers if necessary.
   6028     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
   6029     // Promote to void*.
   6030     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
   6031     return destType;
   6032   }
   6033 
   6034   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
   6035 }
   6036 
   6037 /// \brief Return false if the first expression is not an integer and the second
   6038 /// expression is not a pointer, true otherwise.
   6039 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
   6040                                         Expr* PointerExpr, SourceLocation Loc,
   6041                                         bool IsIntFirstExpr) {
   6042   if (!PointerExpr->getType()->isPointerType() ||
   6043       !Int.get()->getType()->isIntegerType())
   6044     return false;
   6045 
   6046   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
   6047   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
   6048 
   6049   S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
   6050     << Expr1->getType() << Expr2->getType()
   6051     << Expr1->getSourceRange() << Expr2->getSourceRange();
   6052   Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
   6053                             CK_IntegralToPointer);
   6054   return true;
   6055 }
   6056 
   6057 /// \brief Simple conversion between integer and floating point types.
   6058 ///
   6059 /// Used when handling the OpenCL conditional operator where the
   6060 /// condition is a vector while the other operands are scalar.
   6061 ///
   6062 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
   6063 /// types are either integer or floating type. Between the two
   6064 /// operands, the type with the higher rank is defined as the "result
   6065 /// type". The other operand needs to be promoted to the same type. No
   6066 /// other type promotion is allowed. We cannot use
   6067 /// UsualArithmeticConversions() for this purpose, since it always
   6068 /// promotes promotable types.
   6069 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
   6070                                             ExprResult &RHS,
   6071                                             SourceLocation QuestionLoc) {
   6072   LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
   6073   if (LHS.isInvalid())
   6074     return QualType();
   6075   RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
   6076   if (RHS.isInvalid())
   6077     return QualType();
   6078 
   6079   // For conversion purposes, we ignore any qualifiers.
   6080   // For example, "const float" and "float" are equivalent.
   6081   QualType LHSType =
   6082     S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
   6083   QualType RHSType =
   6084     S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
   6085 
   6086   if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
   6087     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
   6088       << LHSType << LHS.get()->getSourceRange();
   6089     return QualType();
   6090   }
   6091 
   6092   if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
   6093     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
   6094       << RHSType << RHS.get()->getSourceRange();
   6095     return QualType();
   6096   }
   6097 
   6098   // If both types are identical, no conversion is needed.
   6099   if (LHSType == RHSType)
   6100     return LHSType;
   6101 
   6102   // Now handle "real" floating types (i.e. float, double, long double).
   6103   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
   6104     return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
   6105                                  /*IsCompAssign = */ false);
   6106 
   6107   // Finally, we have two differing integer types.
   6108   return handleIntegerConversion<doIntegralCast, doIntegralCast>
   6109   (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
   6110 }
   6111 
   6112 /// \brief Convert scalar operands to a vector that matches the
   6113 ///        condition in length.
   6114 ///
   6115 /// Used when handling the OpenCL conditional operator where the
   6116 /// condition is a vector while the other operands are scalar.
   6117 ///
   6118 /// We first compute the "result type" for the scalar operands
   6119 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
   6120 /// into a vector of that type where the length matches the condition
   6121 /// vector type. s6.11.6 requires that the element types of the result
   6122 /// and the condition must have the same number of bits.
   6123 static QualType
   6124 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
   6125                               QualType CondTy, SourceLocation QuestionLoc) {
   6126   QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
   6127   if (ResTy.isNull()) return QualType();
   6128 
   6129   const VectorType *CV = CondTy->getAs<VectorType>();
   6130   assert(CV);
   6131 
   6132   // Determine the vector result type
   6133   unsigned NumElements = CV->getNumElements();
   6134   QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
   6135 
   6136   // Ensure that all types have the same number of bits
   6137   if (S.Context.getTypeSize(CV->getElementType())
   6138       != S.Context.getTypeSize(ResTy)) {
   6139     // Since VectorTy is created internally, it does not pretty print
   6140     // with an OpenCL name. Instead, we just print a description.
   6141     std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
   6142     SmallString<64> Str;
   6143     llvm::raw_svector_ostream OS(Str);
   6144     OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
   6145     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
   6146       << CondTy << OS.str();
   6147     return QualType();
   6148   }
   6149 
   6150   // Convert operands to the vector result type
   6151   LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
   6152   RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
   6153 
   6154   return VectorTy;
   6155 }
   6156 
   6157 /// \brief Return false if this is a valid OpenCL condition vector
   6158 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
   6159                                        SourceLocation QuestionLoc) {
   6160   // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
   6161   // integral type.
   6162   const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
   6163   assert(CondTy);
   6164   QualType EleTy = CondTy->getElementType();
   6165   if (EleTy->isIntegerType()) return false;
   6166 
   6167   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
   6168     << Cond->getType() << Cond->getSourceRange();
   6169   return true;
   6170 }
   6171 
   6172 /// \brief Return false if the vector condition type and the vector
   6173 ///        result type are compatible.
   6174 ///
   6175 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
   6176 /// number of elements, and their element types have the same number
   6177 /// of bits.
   6178 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
   6179                               SourceLocation QuestionLoc) {
   6180   const VectorType *CV = CondTy->getAs<VectorType>();
   6181   const VectorType *RV = VecResTy->getAs<VectorType>();
   6182   assert(CV && RV);
   6183 
   6184   if (CV->getNumElements() != RV->getNumElements()) {
   6185     S.Diag(QuestionLoc, diag::err_conditional_vector_size)
   6186       << CondTy << VecResTy;
   6187     return true;
   6188   }
   6189 
   6190   QualType CVE = CV->getElementType();
   6191   QualType RVE = RV->getElementType();
   6192 
   6193   if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
   6194     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
   6195       << CondTy << VecResTy;
   6196     return true;
   6197   }
   6198 
   6199   return false;
   6200 }
   6201 
   6202 /// \brief Return the resulting type for the conditional operator in
   6203 ///        OpenCL (aka "ternary selection operator", OpenCL v1.1
   6204 ///        s6.3.i) when the condition is a vector type.
   6205 static QualType
   6206 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
   6207                              ExprResult &LHS, ExprResult &RHS,
   6208                              SourceLocation QuestionLoc) {
   6209   Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
   6210   if (Cond.isInvalid())
   6211     return QualType();
   6212   QualType CondTy = Cond.get()->getType();
   6213 
   6214   if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
   6215     return QualType();
   6216 
   6217   // If either operand is a vector then find the vector type of the
   6218   // result as specified in OpenCL v1.1 s6.3.i.
   6219   if (LHS.get()->getType()->isVectorType() ||
   6220       RHS.get()->getType()->isVectorType()) {
   6221     QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
   6222                                               /*isCompAssign*/false,
   6223                                               /*AllowBothBool*/true,
   6224                                               /*AllowBoolConversions*/false);
   6225     if (VecResTy.isNull()) return QualType();
   6226     // The result type must match the condition type as specified in
   6227     // OpenCL v1.1 s6.11.6.
   6228     if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
   6229       return QualType();
   6230     return VecResTy;
   6231   }
   6232 
   6233   // Both operands are scalar.
   6234   return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
   6235 }
   6236 
   6237 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
   6238 /// In that case, LHS = cond.
   6239 /// C99 6.5.15
   6240 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
   6241                                         ExprResult &RHS, ExprValueKind &VK,
   6242                                         ExprObjectKind &OK,
   6243                                         SourceLocation QuestionLoc) {
   6244 
   6245   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
   6246   if (!LHSResult.isUsable()) return QualType();
   6247   LHS = LHSResult;
   6248 
   6249   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
   6250   if (!RHSResult.isUsable()) return QualType();
   6251   RHS = RHSResult;
   6252 
   6253   // C++ is sufficiently different to merit its own checker.
   6254   if (getLangOpts().CPlusPlus)
   6255     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
   6256 
   6257   VK = VK_RValue;
   6258   OK = OK_Ordinary;
   6259 
   6260   // The OpenCL operator with a vector condition is sufficiently
   6261   // different to merit its own checker.
   6262   if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType())
   6263     return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
   6264 
   6265   // First, check the condition.
   6266   Cond = UsualUnaryConversions(Cond.get());
   6267   if (Cond.isInvalid())
   6268     return QualType();
   6269   if (checkCondition(*this, Cond.get(), QuestionLoc))
   6270     return QualType();
   6271 
   6272   // Now check the two expressions.
   6273   if (LHS.get()->getType()->isVectorType() ||
   6274       RHS.get()->getType()->isVectorType())
   6275     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
   6276                                /*AllowBothBool*/true,
   6277                                /*AllowBoolConversions*/false);
   6278 
   6279   QualType ResTy = UsualArithmeticConversions(LHS, RHS);
   6280   if (LHS.isInvalid() || RHS.isInvalid())
   6281     return QualType();
   6282 
   6283   QualType LHSTy = LHS.get()->getType();
   6284   QualType RHSTy = RHS.get()->getType();
   6285 
   6286   // If both operands have arithmetic type, do the usual arithmetic conversions
   6287   // to find a common type: C99 6.5.15p3,5.
   6288   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
   6289     LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
   6290     RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
   6291 
   6292     return ResTy;
   6293   }
   6294 
   6295   // If both operands are the same structure or union type, the result is that
   6296   // type.
   6297   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
   6298     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
   6299       if (LHSRT->getDecl() == RHSRT->getDecl())
   6300         // "If both the operands have structure or union type, the result has
   6301         // that type."  This implies that CV qualifiers are dropped.
   6302         return LHSTy.getUnqualifiedType();
   6303     // FIXME: Type of conditional expression must be complete in C mode.
   6304   }
   6305 
   6306   // C99 6.5.15p5: "If both operands have void type, the result has void type."
   6307   // The following || allows only one side to be void (a GCC-ism).
   6308   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
   6309     return checkConditionalVoidType(*this, LHS, RHS);
   6310   }
   6311 
   6312   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
   6313   // the type of the other operand."
   6314   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
   6315   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
   6316 
   6317   // All objective-c pointer type analysis is done here.
   6318   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
   6319                                                         QuestionLoc);
   6320   if (LHS.isInvalid() || RHS.isInvalid())
   6321     return QualType();
   6322   if (!compositeType.isNull())
   6323     return compositeType;
   6324 
   6325 
   6326   // Handle block pointer types.
   6327   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
   6328     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
   6329                                                      QuestionLoc);
   6330 
   6331   // Check constraints for C object pointers types (C99 6.5.15p3,6).
   6332   if (LHSTy->isPointerType() && RHSTy->isPointerType())
   6333     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
   6334                                                        QuestionLoc);
   6335 
   6336   // GCC compatibility: soften pointer/integer mismatch.  Note that
   6337   // null pointers have been filtered out by this point.
   6338   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
   6339       /*isIntFirstExpr=*/true))
   6340     return RHSTy;
   6341   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
   6342       /*isIntFirstExpr=*/false))
   6343     return LHSTy;
   6344 
   6345   // Emit a better diagnostic if one of the expressions is a null pointer
   6346   // constant and the other is not a pointer type. In this case, the user most
   6347   // likely forgot to take the address of the other expression.
   6348   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
   6349     return QualType();
   6350 
   6351   // Otherwise, the operands are not compatible.
   6352   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
   6353     << LHSTy << RHSTy << LHS.get()->getSourceRange()
   6354     << RHS.get()->getSourceRange();
   6355   return QualType();
   6356 }
   6357 
   6358 /// FindCompositeObjCPointerType - Helper method to find composite type of
   6359 /// two objective-c pointer types of the two input expressions.
   6360 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
   6361                                             SourceLocation QuestionLoc) {
   6362   QualType LHSTy = LHS.get()->getType();
   6363   QualType RHSTy = RHS.get()->getType();
   6364 
   6365   // Handle things like Class and struct objc_class*.  Here we case the result
   6366   // to the pseudo-builtin, because that will be implicitly cast back to the
   6367   // redefinition type if an attempt is made to access its fields.
   6368   if (LHSTy->isObjCClassType() &&
   6369       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
   6370     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
   6371     return LHSTy;
   6372   }
   6373   if (RHSTy->isObjCClassType() &&
   6374       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
   6375     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
   6376     return RHSTy;
   6377   }
   6378   // And the same for struct objc_object* / id
   6379   if (LHSTy->isObjCIdType() &&
   6380       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
   6381     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
   6382     return LHSTy;
   6383   }
   6384   if (RHSTy->isObjCIdType() &&
   6385       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
   6386     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
   6387     return RHSTy;
   6388   }
   6389   // And the same for struct objc_selector* / SEL
   6390   if (Context.isObjCSelType(LHSTy) &&
   6391       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
   6392     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
   6393     return LHSTy;
   6394   }
   6395   if (Context.isObjCSelType(RHSTy) &&
   6396       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
   6397     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
   6398     return RHSTy;
   6399   }
   6400   // Check constraints for Objective-C object pointers types.
   6401   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
   6402 
   6403     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
   6404       // Two identical object pointer types are always compatible.
   6405       return LHSTy;
   6406     }
   6407     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
   6408     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
   6409     QualType compositeType = LHSTy;
   6410 
   6411     // If both operands are interfaces and either operand can be
   6412     // assigned to the other, use that type as the composite
   6413     // type. This allows
   6414     //   xxx ? (A*) a : (B*) b
   6415     // where B is a subclass of A.
   6416     //
   6417     // Additionally, as for assignment, if either type is 'id'
   6418     // allow silent coercion. Finally, if the types are
   6419     // incompatible then make sure to use 'id' as the composite
   6420     // type so the result is acceptable for sending messages to.
   6421 
   6422     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
   6423     // It could return the composite type.
   6424     if (!(compositeType =
   6425           Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
   6426       // Nothing more to do.
   6427     } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
   6428       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
   6429     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
   6430       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
   6431     } else if ((LHSTy->isObjCQualifiedIdType() ||
   6432                 RHSTy->isObjCQualifiedIdType()) &&
   6433                Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
   6434       // Need to handle "id<xx>" explicitly.
   6435       // GCC allows qualified id and any Objective-C type to devolve to
   6436       // id. Currently localizing to here until clear this should be
   6437       // part of ObjCQualifiedIdTypesAreCompatible.
   6438       compositeType = Context.getObjCIdType();
   6439     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
   6440       compositeType = Context.getObjCIdType();
   6441     } else {
   6442       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
   6443       << LHSTy << RHSTy
   6444       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
   6445       QualType incompatTy = Context.getObjCIdType();
   6446       LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
   6447       RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
   6448       return incompatTy;
   6449     }
   6450     // The object pointer types are compatible.
   6451     LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
   6452     RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
   6453     return compositeType;
   6454   }
   6455   // Check Objective-C object pointer types and 'void *'
   6456   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
   6457     if (getLangOpts().ObjCAutoRefCount) {
   6458       // ARC forbids the implicit conversion of object pointers to 'void *',
   6459       // so these types are not compatible.
   6460       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
   6461           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
   6462       LHS = RHS = true;
   6463       return QualType();
   6464     }
   6465     QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
   6466     QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
   6467     QualType destPointee
   6468     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
   6469     QualType destType = Context.getPointerType(destPointee);
   6470     // Add qualifiers if necessary.
   6471     LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
   6472     // Promote to void*.
   6473     RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
   6474     return destType;
   6475   }
   6476   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
   6477     if (getLangOpts().ObjCAutoRefCount) {
   6478       // ARC forbids the implicit conversion of object pointers to 'void *',
   6479       // so these types are not compatible.
   6480       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
   6481           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
   6482       LHS = RHS = true;
   6483       return QualType();
   6484     }
   6485     QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
   6486     QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
   6487     QualType destPointee
   6488     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
   6489     QualType destType = Context.getPointerType(destPointee);
   6490     // Add qualifiers if necessary.
   6491     RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
   6492     // Promote to void*.
   6493     LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
   6494     return destType;
   6495   }
   6496   return QualType();
   6497 }
   6498 
   6499 /// SuggestParentheses - Emit a note with a fixit hint that wraps
   6500 /// ParenRange in parentheses.
   6501 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
   6502                                const PartialDiagnostic &Note,
   6503                                SourceRange ParenRange) {
   6504   SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
   6505   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
   6506       EndLoc.isValid()) {
   6507     Self.Diag(Loc, Note)
   6508       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
   6509       << FixItHint::CreateInsertion(EndLoc, ")");
   6510   } else {
   6511     // We can't display the parentheses, so just show the bare note.
   6512     Self.Diag(Loc, Note) << ParenRange;
   6513   }
   6514 }
   6515 
   6516 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
   6517   return BinaryOperator::isAdditiveOp(Opc) ||
   6518          BinaryOperator::isMultiplicativeOp(Opc) ||
   6519          BinaryOperator::isShiftOp(Opc);
   6520 }
   6521 
   6522 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
   6523 /// expression, either using a built-in or overloaded operator,
   6524 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
   6525 /// expression.
   6526 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
   6527                                    Expr **RHSExprs) {
   6528   // Don't strip parenthesis: we should not warn if E is in parenthesis.
   6529   E = E->IgnoreImpCasts();
   6530   E = E->IgnoreConversionOperator();
   6531   E = E->IgnoreImpCasts();
   6532 
   6533   // Built-in binary operator.
   6534   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
   6535     if (IsArithmeticOp(OP->getOpcode())) {
   6536       *Opcode = OP->getOpcode();
   6537       *RHSExprs = OP->getRHS();
   6538       return true;
   6539     }
   6540   }
   6541 
   6542   // Overloaded operator.
   6543   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
   6544     if (Call->getNumArgs() != 2)
   6545       return false;
   6546 
   6547     // Make sure this is really a binary operator that is safe to pass into
   6548     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
   6549     OverloadedOperatorKind OO = Call->getOperator();
   6550     if (OO < OO_Plus || OO > OO_Arrow ||
   6551         OO == OO_PlusPlus || OO == OO_MinusMinus)
   6552       return false;
   6553 
   6554     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
   6555     if (IsArithmeticOp(OpKind)) {
   6556       *Opcode = OpKind;
   6557       *RHSExprs = Call->getArg(1);
   6558       return true;
   6559     }
   6560   }
   6561 
   6562   return false;
   6563 }
   6564 
   6565 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
   6566 /// or is a logical expression such as (x==y) which has int type, but is
   6567 /// commonly interpreted as boolean.
   6568 static bool ExprLooksBoolean(Expr *E) {
   6569   E = E->IgnoreParenImpCasts();
   6570 
   6571   if (E->getType()->isBooleanType())
   6572     return true;
   6573   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
   6574     return OP->isComparisonOp() || OP->isLogicalOp();
   6575   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
   6576     return OP->getOpcode() == UO_LNot;
   6577   if (E->getType()->isPointerType())
   6578     return true;
   6579 
   6580   return false;
   6581 }
   6582 
   6583 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
   6584 /// and binary operator are mixed in a way that suggests the programmer assumed
   6585 /// the conditional operator has higher precedence, for example:
   6586 /// "int x = a + someBinaryCondition ? 1 : 2".
   6587 static void DiagnoseConditionalPrecedence(Sema &Self,
   6588                                           SourceLocation OpLoc,
   6589                                           Expr *Condition,
   6590                                           Expr *LHSExpr,
   6591                                           Expr *RHSExpr) {
   6592   BinaryOperatorKind CondOpcode;
   6593   Expr *CondRHS;
   6594 
   6595   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
   6596     return;
   6597   if (!ExprLooksBoolean(CondRHS))
   6598     return;
   6599 
   6600   // The condition is an arithmetic binary expression, with a right-
   6601   // hand side that looks boolean, so warn.
   6602 
   6603   Self.Diag(OpLoc, diag::warn_precedence_conditional)
   6604       << Condition->getSourceRange()
   6605       << BinaryOperator::getOpcodeStr(CondOpcode);
   6606 
   6607   SuggestParentheses(Self, OpLoc,
   6608     Self.PDiag(diag::note_precedence_silence)
   6609       << BinaryOperator::getOpcodeStr(CondOpcode),
   6610     SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
   6611 
   6612   SuggestParentheses(Self, OpLoc,
   6613     Self.PDiag(diag::note_precedence_conditional_first),
   6614     SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
   6615 }
   6616 
   6617 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
   6618 /// in the case of a the GNU conditional expr extension.
   6619 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
   6620                                     SourceLocation ColonLoc,
   6621                                     Expr *CondExpr, Expr *LHSExpr,
   6622                                     Expr *RHSExpr) {
   6623   if (!getLangOpts().CPlusPlus) {
   6624     // C cannot handle TypoExpr nodes in the condition because it
   6625     // doesn't handle dependent types properly, so make sure any TypoExprs have
   6626     // been dealt with before checking the operands.
   6627     ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
   6628     if (!CondResult.isUsable()) return ExprError();
   6629     CondExpr = CondResult.get();
   6630   }
   6631 
   6632   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
   6633   // was the condition.
   6634   OpaqueValueExpr *opaqueValue = nullptr;
   6635   Expr *commonExpr = nullptr;
   6636   if (!LHSExpr) {
   6637     commonExpr = CondExpr;
   6638     // Lower out placeholder types first.  This is important so that we don't
   6639     // try to capture a placeholder. This happens in few cases in C++; such
   6640     // as Objective-C++'s dictionary subscripting syntax.
   6641     if (commonExpr->hasPlaceholderType()) {
   6642       ExprResult result = CheckPlaceholderExpr(commonExpr);
   6643       if (!result.isUsable()) return ExprError();
   6644       commonExpr = result.get();
   6645     }
   6646     // We usually want to apply unary conversions *before* saving, except
   6647     // in the special case of a C++ l-value conditional.
   6648     if (!(getLangOpts().CPlusPlus
   6649           && !commonExpr->isTypeDependent()
   6650           && commonExpr->getValueKind() == RHSExpr->getValueKind()
   6651           && commonExpr->isGLValue()
   6652           && commonExpr->isOrdinaryOrBitFieldObject()
   6653           && RHSExpr->isOrdinaryOrBitFieldObject()
   6654           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
   6655       ExprResult commonRes = UsualUnaryConversions(commonExpr);
   6656       if (commonRes.isInvalid())
   6657         return ExprError();
   6658       commonExpr = commonRes.get();
   6659     }
   6660 
   6661     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
   6662                                                 commonExpr->getType(),
   6663                                                 commonExpr->getValueKind(),
   6664                                                 commonExpr->getObjectKind(),
   6665                                                 commonExpr);
   6666     LHSExpr = CondExpr = opaqueValue;
   6667   }
   6668 
   6669   ExprValueKind VK = VK_RValue;
   6670   ExprObjectKind OK = OK_Ordinary;
   6671   ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
   6672   QualType result = CheckConditionalOperands(Cond, LHS, RHS,
   6673                                              VK, OK, QuestionLoc);
   6674   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
   6675       RHS.isInvalid())
   6676     return ExprError();
   6677 
   6678   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
   6679                                 RHS.get());
   6680 
   6681   CheckBoolLikeConversion(Cond.get(), QuestionLoc);
   6682 
   6683   if (!commonExpr)
   6684     return new (Context)
   6685         ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
   6686                             RHS.get(), result, VK, OK);
   6687 
   6688   return new (Context) BinaryConditionalOperator(
   6689       commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
   6690       ColonLoc, result, VK, OK);
   6691 }
   6692 
   6693 // checkPointerTypesForAssignment - This is a very tricky routine (despite
   6694 // being closely modeled after the C99 spec:-). The odd characteristic of this
   6695 // routine is it effectively iqnores the qualifiers on the top level pointee.
   6696 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
   6697 // FIXME: add a couple examples in this comment.
   6698 static Sema::AssignConvertType
   6699 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
   6700   assert(LHSType.isCanonical() && "LHS not canonicalized!");
   6701   assert(RHSType.isCanonical() && "RHS not canonicalized!");
   6702 
   6703   // get the "pointed to" type (ignoring qualifiers at the top level)
   6704   const Type *lhptee, *rhptee;
   6705   Qualifiers lhq, rhq;
   6706   std::tie(lhptee, lhq) =
   6707       cast<PointerType>(LHSType)->getPointeeType().split().asPair();
   6708   std::tie(rhptee, rhq) =
   6709       cast<PointerType>(RHSType)->getPointeeType().split().asPair();
   6710 
   6711   Sema::AssignConvertType ConvTy = Sema::Compatible;
   6712 
   6713   // C99 6.5.16.1p1: This following citation is common to constraints
   6714   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
   6715   // qualifiers of the type *pointed to* by the right;
   6716 
   6717   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
   6718   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
   6719       lhq.compatiblyIncludesObjCLifetime(rhq)) {
   6720     // Ignore lifetime for further calculation.
   6721     lhq.removeObjCLifetime();
   6722     rhq.removeObjCLifetime();
   6723   }
   6724 
   6725   if (!lhq.compatiblyIncludes(rhq)) {
   6726     // Treat address-space mismatches as fatal.  TODO: address subspaces
   6727     if (!lhq.isAddressSpaceSupersetOf(rhq))
   6728       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
   6729 
   6730     // It's okay to add or remove GC or lifetime qualifiers when converting to
   6731     // and from void*.
   6732     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
   6733                         .compatiblyIncludes(
   6734                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
   6735              && (lhptee->isVoidType() || rhptee->isVoidType()))
   6736       ; // keep old
   6737 
   6738     // Treat lifetime mismatches as fatal.
   6739     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
   6740       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
   6741 
   6742     // For GCC compatibility, other qualifier mismatches are treated
   6743     // as still compatible in C.
   6744     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
   6745   }
   6746 
   6747   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
   6748   // incomplete type and the other is a pointer to a qualified or unqualified
   6749   // version of void...
   6750   if (lhptee->isVoidType()) {
   6751     if (rhptee->isIncompleteOrObjectType())
   6752       return ConvTy;
   6753 
   6754     // As an extension, we allow cast to/from void* to function pointer.
   6755     assert(rhptee->isFunctionType());
   6756     return Sema::FunctionVoidPointer;
   6757   }
   6758 
   6759   if (rhptee->isVoidType()) {
   6760     if (lhptee->isIncompleteOrObjectType())
   6761       return ConvTy;
   6762 
   6763     // As an extension, we allow cast to/from void* to function pointer.
   6764     assert(lhptee->isFunctionType());
   6765     return Sema::FunctionVoidPointer;
   6766   }
   6767 
   6768   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
   6769   // unqualified versions of compatible types, ...
   6770   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
   6771   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
   6772     // Check if the pointee types are compatible ignoring the sign.
   6773     // We explicitly check for char so that we catch "char" vs
   6774     // "unsigned char" on systems where "char" is unsigned.
   6775     if (lhptee->isCharType())
   6776       ltrans = S.Context.UnsignedCharTy;
   6777     else if (lhptee->hasSignedIntegerRepresentation())
   6778       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
   6779 
   6780     if (rhptee->isCharType())
   6781       rtrans = S.Context.UnsignedCharTy;
   6782     else if (rhptee->hasSignedIntegerRepresentation())
   6783       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
   6784 
   6785     if (ltrans == rtrans) {
   6786       // Types are compatible ignoring the sign. Qualifier incompatibility
   6787       // takes priority over sign incompatibility because the sign
   6788       // warning can be disabled.
   6789       if (ConvTy != Sema::Compatible)
   6790         return ConvTy;
   6791 
   6792       return Sema::IncompatiblePointerSign;
   6793     }
   6794 
   6795     // If we are a multi-level pointer, it's possible that our issue is simply
   6796     // one of qualification - e.g. char ** -> const char ** is not allowed. If
   6797     // the eventual target type is the same and the pointers have the same
   6798     // level of indirection, this must be the issue.
   6799     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
   6800       do {
   6801         lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
   6802         rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
   6803       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
   6804 
   6805       if (lhptee == rhptee)
   6806         return Sema::IncompatibleNestedPointerQualifiers;
   6807     }
   6808 
   6809     // General pointer incompatibility takes priority over qualifiers.
   6810     return Sema::IncompatiblePointer;
   6811   }
   6812   if (!S.getLangOpts().CPlusPlus &&
   6813       S.IsNoReturnConversion(ltrans, rtrans, ltrans))
   6814     return Sema::IncompatiblePointer;
   6815   return ConvTy;
   6816 }
   6817 
   6818 /// checkBlockPointerTypesForAssignment - This routine determines whether two
   6819 /// block pointer types are compatible or whether a block and normal pointer
   6820 /// are compatible. It is more restrict than comparing two function pointer
   6821 // types.
   6822 static Sema::AssignConvertType
   6823 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
   6824                                     QualType RHSType) {
   6825   assert(LHSType.isCanonical() && "LHS not canonicalized!");
   6826   assert(RHSType.isCanonical() && "RHS not canonicalized!");
   6827 
   6828   QualType lhptee, rhptee;
   6829 
   6830   // get the "pointed to" type (ignoring qualifiers at the top level)
   6831   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
   6832   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
   6833 
   6834   // In C++, the types have to match exactly.
   6835   if (S.getLangOpts().CPlusPlus)
   6836     return Sema::IncompatibleBlockPointer;
   6837 
   6838   Sema::AssignConvertType ConvTy = Sema::Compatible;
   6839 
   6840   // For blocks we enforce that qualifiers are identical.
   6841   if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
   6842     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
   6843 
   6844   if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
   6845     return Sema::IncompatibleBlockPointer;
   6846 
   6847   return ConvTy;
   6848 }
   6849 
   6850 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
   6851 /// for assignment compatibility.
   6852 static Sema::AssignConvertType
   6853 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
   6854                                    QualType RHSType) {
   6855   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
   6856   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
   6857 
   6858   if (LHSType->isObjCBuiltinType()) {
   6859     // Class is not compatible with ObjC object pointers.
   6860     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
   6861         !RHSType->isObjCQualifiedClassType())
   6862       return Sema::IncompatiblePointer;
   6863     return Sema::Compatible;
   6864   }
   6865   if (RHSType->isObjCBuiltinType()) {
   6866     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
   6867         !LHSType->isObjCQualifiedClassType())
   6868       return Sema::IncompatiblePointer;
   6869     return Sema::Compatible;
   6870   }
   6871   QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
   6872   QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
   6873 
   6874   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
   6875       // make an exception for id<P>
   6876       !LHSType->isObjCQualifiedIdType())
   6877     return Sema::CompatiblePointerDiscardsQualifiers;
   6878 
   6879   if (S.Context.typesAreCompatible(LHSType, RHSType))
   6880     return Sema::Compatible;
   6881   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
   6882     return Sema::IncompatibleObjCQualifiedId;
   6883   return Sema::IncompatiblePointer;
   6884 }
   6885 
   6886 Sema::AssignConvertType
   6887 Sema::CheckAssignmentConstraints(SourceLocation Loc,
   6888                                  QualType LHSType, QualType RHSType) {
   6889   // Fake up an opaque expression.  We don't actually care about what
   6890   // cast operations are required, so if CheckAssignmentConstraints
   6891   // adds casts to this they'll be wasted, but fortunately that doesn't
   6892   // usually happen on valid code.
   6893   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
   6894   ExprResult RHSPtr = &RHSExpr;
   6895   CastKind K = CK_Invalid;
   6896 
   6897   return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
   6898 }
   6899 
   6900 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
   6901 /// has code to accommodate several GCC extensions when type checking
   6902 /// pointers. Here are some objectionable examples that GCC considers warnings:
   6903 ///
   6904 ///  int a, *pint;
   6905 ///  short *pshort;
   6906 ///  struct foo *pfoo;
   6907 ///
   6908 ///  pint = pshort; // warning: assignment from incompatible pointer type
   6909 ///  a = pint; // warning: assignment makes integer from pointer without a cast
   6910 ///  pint = a; // warning: assignment makes pointer from integer without a cast
   6911 ///  pint = pfoo; // warning: assignment from incompatible pointer type
   6912 ///
   6913 /// As a result, the code for dealing with pointers is more complex than the
   6914 /// C99 spec dictates.
   6915 ///
   6916 /// Sets 'Kind' for any result kind except Incompatible.
   6917 Sema::AssignConvertType
   6918 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
   6919                                  CastKind &Kind, bool ConvertRHS) {
   6920   QualType RHSType = RHS.get()->getType();
   6921   QualType OrigLHSType = LHSType;
   6922 
   6923   // Get canonical types.  We're not formatting these types, just comparing
   6924   // them.
   6925   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
   6926   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
   6927 
   6928   // Common case: no conversion required.
   6929   if (LHSType == RHSType) {
   6930     Kind = CK_NoOp;
   6931     return Compatible;
   6932   }
   6933 
   6934   // If we have an atomic type, try a non-atomic assignment, then just add an
   6935   // atomic qualification step.
   6936   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
   6937     Sema::AssignConvertType result =
   6938       CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
   6939     if (result != Compatible)
   6940       return result;
   6941     if (Kind != CK_NoOp && ConvertRHS)
   6942       RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
   6943     Kind = CK_NonAtomicToAtomic;
   6944     return Compatible;
   6945   }
   6946 
   6947   // If the left-hand side is a reference type, then we are in a
   6948   // (rare!) case where we've allowed the use of references in C,
   6949   // e.g., as a parameter type in a built-in function. In this case,
   6950   // just make sure that the type referenced is compatible with the
   6951   // right-hand side type. The caller is responsible for adjusting
   6952   // LHSType so that the resulting expression does not have reference
   6953   // type.
   6954   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
   6955     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
   6956       Kind = CK_LValueBitCast;
   6957       return Compatible;
   6958     }
   6959     return Incompatible;
   6960   }
   6961 
   6962   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
   6963   // to the same ExtVector type.
   6964   if (LHSType->isExtVectorType()) {
   6965     if (RHSType->isExtVectorType())
   6966       return Incompatible;
   6967     if (RHSType->isArithmeticType()) {
   6968       // CK_VectorSplat does T -> vector T, so first cast to the
   6969       // element type.
   6970       QualType elType = cast<ExtVectorType>(LHSType)->getElementType();
   6971       if (elType != RHSType && ConvertRHS) {
   6972         Kind = PrepareScalarCast(RHS, elType);
   6973         RHS = ImpCastExprToType(RHS.get(), elType, Kind);
   6974       }
   6975       Kind = CK_VectorSplat;
   6976       return Compatible;
   6977     }
   6978   }
   6979 
   6980   // Conversions to or from vector type.
   6981   if (LHSType->isVectorType() || RHSType->isVectorType()) {
   6982     if (LHSType->isVectorType() && RHSType->isVectorType()) {
   6983       // Allow assignments of an AltiVec vector type to an equivalent GCC
   6984       // vector type and vice versa
   6985       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
   6986         Kind = CK_BitCast;
   6987         return Compatible;
   6988       }
   6989 
   6990       // If we are allowing lax vector conversions, and LHS and RHS are both
   6991       // vectors, the total size only needs to be the same. This is a bitcast;
   6992       // no bits are changed but the result type is different.
   6993       if (isLaxVectorConversion(RHSType, LHSType)) {
   6994         Kind = CK_BitCast;
   6995         return IncompatibleVectors;
   6996       }
   6997     }
   6998     return Incompatible;
   6999   }
   7000 
   7001   // Arithmetic conversions.
   7002   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
   7003       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
   7004     if (ConvertRHS)
   7005       Kind = PrepareScalarCast(RHS, LHSType);
   7006     return Compatible;
   7007   }
   7008 
   7009   // Conversions to normal pointers.
   7010   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
   7011     // U* -> T*
   7012     if (isa<PointerType>(RHSType)) {
   7013       unsigned AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
   7014       unsigned AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
   7015       Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
   7016       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
   7017     }
   7018 
   7019     // int -> T*
   7020     if (RHSType->isIntegerType()) {
   7021       Kind = CK_IntegralToPointer; // FIXME: null?
   7022       return IntToPointer;
   7023     }
   7024 
   7025     // C pointers are not compatible with ObjC object pointers,
   7026     // with two exceptions:
   7027     if (isa<ObjCObjectPointerType>(RHSType)) {
   7028       //  - conversions to void*
   7029       if (LHSPointer->getPointeeType()->isVoidType()) {
   7030         Kind = CK_BitCast;
   7031         return Compatible;
   7032       }
   7033 
   7034       //  - conversions from 'Class' to the redefinition type
   7035       if (RHSType->isObjCClassType() &&
   7036           Context.hasSameType(LHSType,
   7037                               Context.getObjCClassRedefinitionType())) {
   7038         Kind = CK_BitCast;
   7039         return Compatible;
   7040       }
   7041 
   7042       Kind = CK_BitCast;
   7043       return IncompatiblePointer;
   7044     }
   7045 
   7046     // U^ -> void*
   7047     if (RHSType->getAs<BlockPointerType>()) {
   7048       if (LHSPointer->getPointeeType()->isVoidType()) {
   7049         Kind = CK_BitCast;
   7050         return Compatible;
   7051       }
   7052     }
   7053 
   7054     return Incompatible;
   7055   }
   7056 
   7057   // Conversions to block pointers.
   7058   if (isa<BlockPointerType>(LHSType)) {
   7059     // U^ -> T^
   7060     if (RHSType->isBlockPointerType()) {
   7061       Kind = CK_BitCast;
   7062       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
   7063     }
   7064 
   7065     // int or null -> T^
   7066     if (RHSType->isIntegerType()) {
   7067       Kind = CK_IntegralToPointer; // FIXME: null
   7068       return IntToBlockPointer;
   7069     }
   7070 
   7071     // id -> T^
   7072     if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
   7073       Kind = CK_AnyPointerToBlockPointerCast;
   7074       return Compatible;
   7075     }
   7076 
   7077     // void* -> T^
   7078     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
   7079       if (RHSPT->getPointeeType()->isVoidType()) {
   7080         Kind = CK_AnyPointerToBlockPointerCast;
   7081         return Compatible;
   7082       }
   7083 
   7084     return Incompatible;
   7085   }
   7086 
   7087   // Conversions to Objective-C pointers.
   7088   if (isa<ObjCObjectPointerType>(LHSType)) {
   7089     // A* -> B*
   7090     if (RHSType->isObjCObjectPointerType()) {
   7091       Kind = CK_BitCast;
   7092       Sema::AssignConvertType result =
   7093         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
   7094       if (getLangOpts().ObjCAutoRefCount &&
   7095           result == Compatible &&
   7096           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
   7097         result = IncompatibleObjCWeakRef;
   7098       return result;
   7099     }
   7100 
   7101     // int or null -> A*
   7102     if (RHSType->isIntegerType()) {
   7103       Kind = CK_IntegralToPointer; // FIXME: null
   7104       return IntToPointer;
   7105     }
   7106 
   7107     // In general, C pointers are not compatible with ObjC object pointers,
   7108     // with two exceptions:
   7109     if (isa<PointerType>(RHSType)) {
   7110       Kind = CK_CPointerToObjCPointerCast;
   7111 
   7112       //  - conversions from 'void*'
   7113       if (RHSType->isVoidPointerType()) {
   7114         return Compatible;
   7115       }
   7116 
   7117       //  - conversions to 'Class' from its redefinition type
   7118       if (LHSType->isObjCClassType() &&
   7119           Context.hasSameType(RHSType,
   7120                               Context.getObjCClassRedefinitionType())) {
   7121         return Compatible;
   7122       }
   7123 
   7124       return IncompatiblePointer;
   7125     }
   7126 
   7127     // Only under strict condition T^ is compatible with an Objective-C pointer.
   7128     if (RHSType->isBlockPointerType() &&
   7129         LHSType->isBlockCompatibleObjCPointerType(Context)) {
   7130       if (ConvertRHS)
   7131         maybeExtendBlockObject(RHS);
   7132       Kind = CK_BlockPointerToObjCPointerCast;
   7133       return Compatible;
   7134     }
   7135 
   7136     return Incompatible;
   7137   }
   7138 
   7139   // Conversions from pointers that are not covered by the above.
   7140   if (isa<PointerType>(RHSType)) {
   7141     // T* -> _Bool
   7142     if (LHSType == Context.BoolTy) {
   7143       Kind = CK_PointerToBoolean;
   7144       return Compatible;
   7145     }
   7146 
   7147     // T* -> int
   7148     if (LHSType->isIntegerType()) {
   7149       Kind = CK_PointerToIntegral;
   7150       return PointerToInt;
   7151     }
   7152 
   7153     return Incompatible;
   7154   }
   7155 
   7156   // Conversions from Objective-C pointers that are not covered by the above.
   7157   if (isa<ObjCObjectPointerType>(RHSType)) {
   7158     // T* -> _Bool
   7159     if (LHSType == Context.BoolTy) {
   7160       Kind = CK_PointerToBoolean;
   7161       return Compatible;
   7162     }
   7163 
   7164     // T* -> int
   7165     if (LHSType->isIntegerType()) {
   7166       Kind = CK_PointerToIntegral;
   7167       return PointerToInt;
   7168     }
   7169 
   7170     return Incompatible;
   7171   }
   7172 
   7173   // struct A -> struct B
   7174   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
   7175     if (Context.typesAreCompatible(LHSType, RHSType)) {
   7176       Kind = CK_NoOp;
   7177       return Compatible;
   7178     }
   7179   }
   7180 
   7181   return Incompatible;
   7182 }
   7183 
   7184 /// \brief Constructs a transparent union from an expression that is
   7185 /// used to initialize the transparent union.
   7186 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
   7187                                       ExprResult &EResult, QualType UnionType,
   7188                                       FieldDecl *Field) {
   7189   // Build an initializer list that designates the appropriate member
   7190   // of the transparent union.
   7191   Expr *E = EResult.get();
   7192   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
   7193                                                    E, SourceLocation());
   7194   Initializer->setType(UnionType);
   7195   Initializer->setInitializedFieldInUnion(Field);
   7196 
   7197   // Build a compound literal constructing a value of the transparent
   7198   // union type from this initializer list.
   7199   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
   7200   EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
   7201                                         VK_RValue, Initializer, false);
   7202 }
   7203 
   7204 Sema::AssignConvertType
   7205 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
   7206                                                ExprResult &RHS) {
   7207   QualType RHSType = RHS.get()->getType();
   7208 
   7209   // If the ArgType is a Union type, we want to handle a potential
   7210   // transparent_union GCC extension.
   7211   const RecordType *UT = ArgType->getAsUnionType();
   7212   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
   7213     return Incompatible;
   7214 
   7215   // The field to initialize within the transparent union.
   7216   RecordDecl *UD = UT->getDecl();
   7217   FieldDecl *InitField = nullptr;
   7218   // It's compatible if the expression matches any of the fields.
   7219   for (auto *it : UD->fields()) {
   7220     if (it->getType()->isPointerType()) {
   7221       // If the transparent union contains a pointer type, we allow:
   7222       // 1) void pointer
   7223       // 2) null pointer constant
   7224       if (RHSType->isPointerType())
   7225         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
   7226           RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
   7227           InitField = it;
   7228           break;
   7229         }
   7230 
   7231       if (RHS.get()->isNullPointerConstant(Context,
   7232                                            Expr::NPC_ValueDependentIsNull)) {
   7233         RHS = ImpCastExprToType(RHS.get(), it->getType(),
   7234                                 CK_NullToPointer);
   7235         InitField = it;
   7236         break;
   7237       }
   7238     }
   7239 
   7240     CastKind Kind = CK_Invalid;
   7241     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
   7242           == Compatible) {
   7243       RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
   7244       InitField = it;
   7245       break;
   7246     }
   7247   }
   7248 
   7249   if (!InitField)
   7250     return Incompatible;
   7251 
   7252   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
   7253   return Compatible;
   7254 }
   7255 
   7256 Sema::AssignConvertType
   7257 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
   7258                                        bool Diagnose,
   7259                                        bool DiagnoseCFAudited,
   7260                                        bool ConvertRHS) {
   7261   // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
   7262   // we can't avoid *all* modifications at the moment, so we need some somewhere
   7263   // to put the updated value.
   7264   ExprResult LocalRHS = CallerRHS;
   7265   ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
   7266 
   7267   if (getLangOpts().CPlusPlus) {
   7268     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
   7269       // C++ 5.17p3: If the left operand is not of class type, the
   7270       // expression is implicitly converted (C++ 4) to the
   7271       // cv-unqualified type of the left operand.
   7272       ExprResult Res;
   7273       if (Diagnose) {
   7274         Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
   7275                                         AA_Assigning);
   7276       } else {
   7277         ImplicitConversionSequence ICS =
   7278             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
   7279                                   /*SuppressUserConversions=*/false,
   7280                                   /*AllowExplicit=*/false,
   7281                                   /*InOverloadResolution=*/false,
   7282                                   /*CStyle=*/false,
   7283                                   /*AllowObjCWritebackConversion=*/false);
   7284         if (ICS.isFailure())
   7285           return Incompatible;
   7286         Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
   7287                                         ICS, AA_Assigning);
   7288       }
   7289       if (Res.isInvalid())
   7290         return Incompatible;
   7291       Sema::AssignConvertType result = Compatible;
   7292       if (getLangOpts().ObjCAutoRefCount &&
   7293           !CheckObjCARCUnavailableWeakConversion(LHSType,
   7294                                                  RHS.get()->getType()))
   7295         result = IncompatibleObjCWeakRef;
   7296       RHS = Res;
   7297       return result;
   7298     }
   7299 
   7300     // FIXME: Currently, we fall through and treat C++ classes like C
   7301     // structures.
   7302     // FIXME: We also fall through for atomics; not sure what should
   7303     // happen there, though.
   7304   } else if (RHS.get()->getType() == Context.OverloadTy) {
   7305     // As a set of extensions to C, we support overloading on functions. These
   7306     // functions need to be resolved here.
   7307     DeclAccessPair DAP;
   7308     if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
   7309             RHS.get(), LHSType, /*Complain=*/false, DAP))
   7310       RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
   7311     else
   7312       return Incompatible;
   7313   }
   7314 
   7315   // C99 6.5.16.1p1: the left operand is a pointer and the right is
   7316   // a null pointer constant.
   7317   if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
   7318        LHSType->isBlockPointerType()) &&
   7319       RHS.get()->isNullPointerConstant(Context,
   7320                                        Expr::NPC_ValueDependentIsNull)) {
   7321     CastKind Kind;
   7322     CXXCastPath Path;
   7323     CheckPointerConversion(RHS.get(), LHSType, Kind, Path, false);
   7324     if (ConvertRHS)
   7325       RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
   7326     return Compatible;
   7327   }
   7328 
   7329   // This check seems unnatural, however it is necessary to ensure the proper
   7330   // conversion of functions/arrays. If the conversion were done for all
   7331   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
   7332   // expressions that suppress this implicit conversion (&, sizeof).
   7333   //
   7334   // Suppress this for references: C++ 8.5.3p5.
   7335   if (!LHSType->isReferenceType()) {
   7336     // FIXME: We potentially allocate here even if ConvertRHS is false.
   7337     RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
   7338     if (RHS.isInvalid())
   7339       return Incompatible;
   7340   }
   7341 
   7342   Expr *PRE = RHS.get()->IgnoreParenCasts();
   7343   if (ObjCProtocolExpr *OPE = dyn_cast<ObjCProtocolExpr>(PRE)) {
   7344     ObjCProtocolDecl *PDecl = OPE->getProtocol();
   7345     if (PDecl && !PDecl->hasDefinition()) {
   7346       Diag(PRE->getExprLoc(), diag::warn_atprotocol_protocol) << PDecl->getName();
   7347       Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl;
   7348     }
   7349   }
   7350 
   7351   CastKind Kind = CK_Invalid;
   7352   Sema::AssignConvertType result =
   7353     CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
   7354 
   7355   // C99 6.5.16.1p2: The value of the right operand is converted to the
   7356   // type of the assignment expression.
   7357   // CheckAssignmentConstraints allows the left-hand side to be a reference,
   7358   // so that we can use references in built-in functions even in C.
   7359   // The getNonReferenceType() call makes sure that the resulting expression
   7360   // does not have reference type.
   7361   if (result != Incompatible && RHS.get()->getType() != LHSType) {
   7362     QualType Ty = LHSType.getNonLValueExprType(Context);
   7363     Expr *E = RHS.get();
   7364     if (getLangOpts().ObjCAutoRefCount)
   7365       CheckObjCARCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
   7366                              DiagnoseCFAudited);
   7367     if (getLangOpts().ObjC1 &&
   7368         (CheckObjCBridgeRelatedConversions(E->getLocStart(),
   7369                                           LHSType, E->getType(), E) ||
   7370          ConversionToObjCStringLiteralCheck(LHSType, E))) {
   7371       RHS = E;
   7372       return Compatible;
   7373     }
   7374 
   7375     if (ConvertRHS)
   7376       RHS = ImpCastExprToType(E, Ty, Kind);
   7377   }
   7378   return result;
   7379 }
   7380 
   7381 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
   7382                                ExprResult &RHS) {
   7383   Diag(Loc, diag::err_typecheck_invalid_operands)
   7384     << LHS.get()->getType() << RHS.get()->getType()
   7385     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
   7386   return QualType();
   7387 }
   7388 
   7389 /// Try to convert a value of non-vector type to a vector type by converting
   7390 /// the type to the element type of the vector and then performing a splat.
   7391 /// If the language is OpenCL, we only use conversions that promote scalar
   7392 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
   7393 /// for float->int.
   7394 ///
   7395 /// \param scalar - if non-null, actually perform the conversions
   7396 /// \return true if the operation fails (but without diagnosing the failure)
   7397 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
   7398                                      QualType scalarTy,
   7399                                      QualType vectorEltTy,
   7400                                      QualType vectorTy) {
   7401   // The conversion to apply to the scalar before splatting it,
   7402   // if necessary.
   7403   CastKind scalarCast = CK_Invalid;
   7404 
   7405   if (vectorEltTy->isIntegralType(S.Context)) {
   7406     if (!scalarTy->isIntegralType(S.Context))
   7407       return true;
   7408     if (S.getLangOpts().OpenCL &&
   7409         S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0)
   7410       return true;
   7411     scalarCast = CK_IntegralCast;
   7412   } else if (vectorEltTy->isRealFloatingType()) {
   7413     if (scalarTy->isRealFloatingType()) {
   7414       if (S.getLangOpts().OpenCL &&
   7415           S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0)
   7416         return true;
   7417       scalarCast = CK_FloatingCast;
   7418     }
   7419     else if (scalarTy->isIntegralType(S.Context))
   7420       scalarCast = CK_IntegralToFloating;
   7421     else
   7422       return true;
   7423   } else {
   7424     return true;
   7425   }
   7426 
   7427   // Adjust scalar if desired.
   7428   if (scalar) {
   7429     if (scalarCast != CK_Invalid)
   7430       *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
   7431     *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
   7432   }
   7433   return false;
   7434 }
   7435 
   7436 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
   7437                                    SourceLocation Loc, bool IsCompAssign,
   7438                                    bool AllowBothBool,
   7439                                    bool AllowBoolConversions) {
   7440   if (!IsCompAssign) {
   7441     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
   7442     if (LHS.isInvalid())
   7443       return QualType();
   7444   }
   7445   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
   7446   if (RHS.isInvalid())
   7447     return QualType();
   7448 
   7449   // For conversion purposes, we ignore any qualifiers.
   7450   // For example, "const float" and "float" are equivalent.
   7451   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
   7452   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
   7453 
   7454   const VectorType *LHSVecType = LHSType->getAs<VectorType>();
   7455   const VectorType *RHSVecType = RHSType->getAs<VectorType>();
   7456   assert(LHSVecType || RHSVecType);
   7457 
   7458   // AltiVec-style "vector bool op vector bool" combinations are allowed
   7459   // for some operators but not others.
   7460   if (!AllowBothBool &&
   7461       LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
   7462       RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
   7463     return InvalidOperands(Loc, LHS, RHS);
   7464 
   7465   // If the vector types are identical, return.
   7466   if (Context.hasSameType(LHSType, RHSType))
   7467     return LHSType;
   7468 
   7469   // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
   7470   if (LHSVecType && RHSVecType &&
   7471       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
   7472     if (isa<ExtVectorType>(LHSVecType)) {
   7473       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
   7474       return LHSType;
   7475     }
   7476 
   7477     if (!IsCompAssign)
   7478       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
   7479     return RHSType;
   7480   }
   7481 
   7482   // AllowBoolConversions says that bool and non-bool AltiVec vectors
   7483   // can be mixed, with the result being the non-bool type.  The non-bool
   7484   // operand must have integer element type.
   7485   if (AllowBoolConversions && LHSVecType && RHSVecType &&
   7486       LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
   7487       (Context.getTypeSize(LHSVecType->getElementType()) ==
   7488        Context.getTypeSize(RHSVecType->getElementType()))) {
   7489     if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
   7490         LHSVecType->getElementType()->isIntegerType() &&
   7491         RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
   7492       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
   7493       return LHSType;
   7494     }
   7495     if (!IsCompAssign &&
   7496         LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
   7497         RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
   7498         RHSVecType->getElementType()->isIntegerType()) {
   7499       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
   7500       return RHSType;
   7501     }
   7502   }
   7503 
   7504   // If there's an ext-vector type and a scalar, try to convert the scalar to
   7505   // the vector element type and splat.
   7506   if (!RHSVecType && isa<ExtVectorType>(LHSVecType)) {
   7507     if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
   7508                                   LHSVecType->getElementType(), LHSType))
   7509       return LHSType;
   7510   }
   7511   if (!LHSVecType && isa<ExtVectorType>(RHSVecType)) {
   7512     if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
   7513                                   LHSType, RHSVecType->getElementType(),
   7514                                   RHSType))
   7515       return RHSType;
   7516   }
   7517 
   7518   // If we're allowing lax vector conversions, only the total (data) size
   7519   // needs to be the same.
   7520   // FIXME: Should we really be allowing this?
   7521   // FIXME: We really just pick the LHS type arbitrarily?
   7522   if (isLaxVectorConversion(RHSType, LHSType)) {
   7523     QualType resultType = LHSType;
   7524     RHS = ImpCastExprToType(RHS.get(), resultType, CK_BitCast);
   7525     return resultType;
   7526   }
   7527 
   7528   // Okay, the expression is invalid.
   7529 
   7530   // If there's a non-vector, non-real operand, diagnose that.
   7531   if ((!RHSVecType && !RHSType->isRealType()) ||
   7532       (!LHSVecType && !LHSType->isRealType())) {
   7533     Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
   7534       << LHSType << RHSType
   7535       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
   7536     return QualType();
   7537   }
   7538 
   7539   // OpenCL V1.1 6.2.6.p1:
   7540   // If the operands are of more than one vector type, then an error shall
   7541   // occur. Implicit conversions between vector types are not permitted, per
   7542   // section 6.2.1.
   7543   if (getLangOpts().OpenCL &&
   7544       RHSVecType && isa<ExtVectorType>(RHSVecType) &&
   7545       LHSVecType && isa<ExtVectorType>(LHSVecType)) {
   7546     Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
   7547                                                            << RHSType;
   7548     return QualType();
   7549   }
   7550 
   7551   // Otherwise, use the generic diagnostic.
   7552   Diag(Loc, diag::err_typecheck_vector_not_convertable)
   7553     << LHSType << RHSType
   7554     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
   7555   return QualType();
   7556 }
   7557 
   7558 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
   7559 // expression.  These are mainly cases where the null pointer is used as an
   7560 // integer instead of a pointer.
   7561 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
   7562                                 SourceLocation Loc, bool IsCompare) {
   7563   // The canonical way to check for a GNU null is with isNullPointerConstant,
   7564   // but we use a bit of a hack here for speed; this is a relatively
   7565   // hot path, and isNullPointerConstant is slow.
   7566   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
   7567   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
   7568 
   7569   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
   7570 
   7571   // Avoid analyzing cases where the result will either be invalid (and
   7572   // diagnosed as such) or entirely valid and not something to warn about.
   7573   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
   7574       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
   7575     return;
   7576 
   7577   // Comparison operations would not make sense with a null pointer no matter
   7578   // what the other expression is.
   7579   if (!IsCompare) {
   7580     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
   7581         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
   7582         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
   7583     return;
   7584   }
   7585 
   7586   // The rest of the operations only make sense with a null pointer
   7587   // if the other expression is a pointer.
   7588   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
   7589       NonNullType->canDecayToPointerType())
   7590     return;
   7591 
   7592   S.Diag(Loc, diag::warn_null_in_comparison_operation)
   7593       << LHSNull /* LHS is NULL */ << NonNullType
   7594       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
   7595 }
   7596 
   7597 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
   7598                                                ExprResult &RHS,
   7599                                                SourceLocation Loc, bool IsDiv) {
   7600   // Check for division/remainder by zero.
   7601   llvm::APSInt RHSValue;
   7602   if (!RHS.get()->isValueDependent() &&
   7603       RHS.get()->EvaluateAsInt(RHSValue, S.Context) && RHSValue == 0)
   7604     S.DiagRuntimeBehavior(Loc, RHS.get(),
   7605                           S.PDiag(diag::warn_remainder_division_by_zero)
   7606                             << IsDiv << RHS.get()->getSourceRange());
   7607 }
   7608 
   7609 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
   7610                                            SourceLocation Loc,
   7611                                            bool IsCompAssign, bool IsDiv) {
   7612   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
   7613 
   7614   if (LHS.get()->getType()->isVectorType() ||
   7615       RHS.get()->getType()->isVectorType())
   7616     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
   7617                                /*AllowBothBool*/getLangOpts().AltiVec,
   7618                                /*AllowBoolConversions*/false);
   7619 
   7620   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
   7621   if (LHS.isInvalid() || RHS.isInvalid())
   7622     return QualType();
   7623 
   7624 
   7625   if (compType.isNull() || !compType->isArithmeticType())
   7626     return InvalidOperands(Loc, LHS, RHS);
   7627   if (IsDiv)
   7628     DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
   7629   return compType;
   7630 }
   7631 
   7632 QualType Sema::CheckRemainderOperands(
   7633   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
   7634   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
   7635 
   7636   if (LHS.get()->getType()->isVectorType() ||
   7637       RHS.get()->getType()->isVectorType()) {
   7638     if (LHS.get()->getType()->hasIntegerRepresentation() &&
   7639         RHS.get()->getType()->hasIntegerRepresentation())
   7640       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
   7641                                  /*AllowBothBool*/getLangOpts().AltiVec,
   7642                                  /*AllowBoolConversions*/false);
   7643     return InvalidOperands(Loc, LHS, RHS);
   7644   }
   7645 
   7646   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
   7647   if (LHS.isInvalid() || RHS.isInvalid())
   7648     return QualType();
   7649 
   7650   if (compType.isNull() || !compType->isIntegerType())
   7651     return InvalidOperands(Loc, LHS, RHS);
   7652   DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
   7653   return compType;
   7654 }
   7655 
   7656 /// \brief Diagnose invalid arithmetic on two void pointers.
   7657 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
   7658                                                 Expr *LHSExpr, Expr *RHSExpr) {
   7659   S.Diag(Loc, S.getLangOpts().CPlusPlus
   7660                 ? diag::err_typecheck_pointer_arith_void_type
   7661                 : diag::ext_gnu_void_ptr)
   7662     << 1 /* two pointers */ << LHSExpr->getSourceRange()
   7663                             << RHSExpr->getSourceRange();
   7664 }
   7665 
   7666 /// \brief Diagnose invalid arithmetic on a void pointer.
   7667 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
   7668                                             Expr *Pointer) {
   7669   S.Diag(Loc, S.getLangOpts().CPlusPlus
   7670                 ? diag::err_typecheck_pointer_arith_void_type
   7671                 : diag::ext_gnu_void_ptr)
   7672     << 0 /* one pointer */ << Pointer->getSourceRange();
   7673 }
   7674 
   7675 /// \brief Diagnose invalid arithmetic on two function pointers.
   7676 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
   7677                                                     Expr *LHS, Expr *RHS) {
   7678   assert(LHS->getType()->isAnyPointerType());
   7679   assert(RHS->getType()->isAnyPointerType());
   7680   S.Diag(Loc, S.getLangOpts().CPlusPlus
   7681                 ? diag::err_typecheck_pointer_arith_function_type
   7682                 : diag::ext_gnu_ptr_func_arith)
   7683     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
   7684     // We only show the second type if it differs from the first.
   7685     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
   7686                                                    RHS->getType())
   7687     << RHS->getType()->getPointeeType()
   7688     << LHS->getSourceRange() << RHS->getSourceRange();
   7689 }
   7690 
   7691 /// \brief Diagnose invalid arithmetic on a function pointer.
   7692 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
   7693                                                 Expr *Pointer) {
   7694   assert(Pointer->getType()->isAnyPointerType());
   7695   S.Diag(Loc, S.getLangOpts().CPlusPlus
   7696                 ? diag::err_typecheck_pointer_arith_function_type
   7697                 : diag::ext_gnu_ptr_func_arith)
   7698     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
   7699     << 0 /* one pointer, so only one type */
   7700     << Pointer->getSourceRange();
   7701 }
   7702 
   7703 /// \brief Emit error if Operand is incomplete pointer type
   7704 ///
   7705 /// \returns True if pointer has incomplete type
   7706 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
   7707                                                  Expr *Operand) {
   7708   QualType ResType = Operand->getType();
   7709   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
   7710     ResType = ResAtomicType->getValueType();
   7711 
   7712   assert(ResType->isAnyPointerType() && !ResType->isDependentType());
   7713   QualType PointeeTy = ResType->getPointeeType();
   7714   return S.RequireCompleteType(Loc, PointeeTy,
   7715                                diag::err_typecheck_arithmetic_incomplete_type,
   7716                                PointeeTy, Operand->getSourceRange());
   7717 }
   7718 
   7719 /// \brief Check the validity of an arithmetic pointer operand.
   7720 ///
   7721 /// If the operand has pointer type, this code will check for pointer types
   7722 /// which are invalid in arithmetic operations. These will be diagnosed
   7723 /// appropriately, including whether or not the use is supported as an
   7724 /// extension.
   7725 ///
   7726 /// \returns True when the operand is valid to use (even if as an extension).
   7727 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
   7728                                             Expr *Operand) {
   7729   QualType ResType = Operand->getType();
   7730   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
   7731     ResType = ResAtomicType->getValueType();
   7732 
   7733   if (!ResType->isAnyPointerType()) return true;
   7734 
   7735   QualType PointeeTy = ResType->getPointeeType();
   7736   if (PointeeTy->isVoidType()) {
   7737     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
   7738     return !S.getLangOpts().CPlusPlus;
   7739   }
   7740   if (PointeeTy->isFunctionType()) {
   7741     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
   7742     return !S.getLangOpts().CPlusPlus;
   7743   }
   7744 
   7745   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
   7746 
   7747   return true;
   7748 }
   7749 
   7750 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
   7751 /// operands.
   7752 ///
   7753 /// This routine will diagnose any invalid arithmetic on pointer operands much
   7754 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
   7755 /// for emitting a single diagnostic even for operations where both LHS and RHS
   7756 /// are (potentially problematic) pointers.
   7757 ///
   7758 /// \returns True when the operand is valid to use (even if as an extension).
   7759 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
   7760                                                 Expr *LHSExpr, Expr *RHSExpr) {
   7761   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
   7762   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
   7763   if (!isLHSPointer && !isRHSPointer) return true;
   7764 
   7765   QualType LHSPointeeTy, RHSPointeeTy;
   7766   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
   7767   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
   7768 
   7769   // if both are pointers check if operation is valid wrt address spaces
   7770   if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) {
   7771     const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>();
   7772     const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>();
   7773     if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) {
   7774       S.Diag(Loc,
   7775              diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
   7776           << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
   7777           << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
   7778       return false;
   7779     }
   7780   }
   7781 
   7782   // Check for arithmetic on pointers to incomplete types.
   7783   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
   7784   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
   7785   if (isLHSVoidPtr || isRHSVoidPtr) {
   7786     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
   7787     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
   7788     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
   7789 
   7790     return !S.getLangOpts().CPlusPlus;
   7791   }
   7792 
   7793   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
   7794   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
   7795   if (isLHSFuncPtr || isRHSFuncPtr) {
   7796     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
   7797     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
   7798                                                                 RHSExpr);
   7799     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
   7800 
   7801     return !S.getLangOpts().CPlusPlus;
   7802   }
   7803 
   7804   if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
   7805     return false;
   7806   if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
   7807     return false;
   7808 
   7809   return true;
   7810 }
   7811 
   7812 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
   7813 /// literal.
   7814 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
   7815                                   Expr *LHSExpr, Expr *RHSExpr) {
   7816   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
   7817   Expr* IndexExpr = RHSExpr;
   7818   if (!StrExpr) {
   7819     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
   7820     IndexExpr = LHSExpr;
   7821   }
   7822 
   7823   bool IsStringPlusInt = StrExpr &&
   7824       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
   7825   if (!IsStringPlusInt || IndexExpr->isValueDependent())
   7826     return;
   7827 
   7828   llvm::APSInt index;
   7829   if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
   7830     unsigned StrLenWithNull = StrExpr->getLength() + 1;
   7831     if (index.isNonNegative() &&
   7832         index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
   7833                               index.isUnsigned()))
   7834       return;
   7835   }
   7836 
   7837   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
   7838   Self.Diag(OpLoc, diag::warn_string_plus_int)
   7839       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
   7840 
   7841   // Only print a fixit for "str" + int, not for int + "str".
   7842   if (IndexExpr == RHSExpr) {
   7843     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd());
   7844     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
   7845         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
   7846         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
   7847         << FixItHint::CreateInsertion(EndLoc, "]");
   7848   } else
   7849     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
   7850 }
   7851 
   7852 /// \brief Emit a warning when adding a char literal to a string.
   7853 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
   7854                                    Expr *LHSExpr, Expr *RHSExpr) {
   7855   const Expr *StringRefExpr = LHSExpr;
   7856   const CharacterLiteral *CharExpr =
   7857       dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
   7858 
   7859   if (!CharExpr) {
   7860     CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
   7861     StringRefExpr = RHSExpr;
   7862   }
   7863 
   7864   if (!CharExpr || !StringRefExpr)
   7865     return;
   7866 
   7867   const QualType StringType = StringRefExpr->getType();
   7868 
   7869   // Return if not a PointerType.
   7870   if (!StringType->isAnyPointerType())
   7871     return;
   7872 
   7873   // Return if not a CharacterType.
   7874   if (!StringType->getPointeeType()->isAnyCharacterType())
   7875     return;
   7876 
   7877   ASTContext &Ctx = Self.getASTContext();
   7878   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
   7879 
   7880   const QualType CharType = CharExpr->getType();
   7881   if (!CharType->isAnyCharacterType() &&
   7882       CharType->isIntegerType() &&
   7883       llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
   7884     Self.Diag(OpLoc, diag::warn_string_plus_char)
   7885         << DiagRange << Ctx.CharTy;
   7886   } else {
   7887     Self.Diag(OpLoc, diag::warn_string_plus_char)
   7888         << DiagRange << CharExpr->getType();
   7889   }
   7890 
   7891   // Only print a fixit for str + char, not for char + str.
   7892   if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
   7893     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd());
   7894     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
   7895         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
   7896         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
   7897         << FixItHint::CreateInsertion(EndLoc, "]");
   7898   } else {
   7899     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
   7900   }
   7901 }
   7902 
   7903 /// \brief Emit error when two pointers are incompatible.
   7904 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
   7905                                            Expr *LHSExpr, Expr *RHSExpr) {
   7906   assert(LHSExpr->getType()->isAnyPointerType());
   7907   assert(RHSExpr->getType()->isAnyPointerType());
   7908   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
   7909     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
   7910     << RHSExpr->getSourceRange();
   7911 }
   7912 
   7913 // C99 6.5.6
   7914 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
   7915                                      SourceLocation Loc, BinaryOperatorKind Opc,
   7916                                      QualType* CompLHSTy) {
   7917   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
   7918 
   7919   if (LHS.get()->getType()->isVectorType() ||
   7920       RHS.get()->getType()->isVectorType()) {
   7921     QualType compType = CheckVectorOperands(
   7922         LHS, RHS, Loc, CompLHSTy,
   7923         /*AllowBothBool*/getLangOpts().AltiVec,
   7924         /*AllowBoolConversions*/getLangOpts().ZVector);
   7925     if (CompLHSTy) *CompLHSTy = compType;
   7926     return compType;
   7927   }
   7928 
   7929   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
   7930   if (LHS.isInvalid() || RHS.isInvalid())
   7931     return QualType();
   7932 
   7933   // Diagnose "string literal" '+' int and string '+' "char literal".
   7934   if (Opc == BO_Add) {
   7935     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
   7936     diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
   7937   }
   7938 
   7939   // handle the common case first (both operands are arithmetic).
   7940   if (!compType.isNull() && compType->isArithmeticType()) {
   7941     if (CompLHSTy) *CompLHSTy = compType;
   7942     return compType;
   7943   }
   7944 
   7945   // Type-checking.  Ultimately the pointer's going to be in PExp;
   7946   // note that we bias towards the LHS being the pointer.
   7947   Expr *PExp = LHS.get(), *IExp = RHS.get();
   7948 
   7949   bool isObjCPointer;
   7950   if (PExp->getType()->isPointerType()) {
   7951     isObjCPointer = false;
   7952   } else if (PExp->getType()->isObjCObjectPointerType()) {
   7953     isObjCPointer = true;
   7954   } else {
   7955     std::swap(PExp, IExp);
   7956     if (PExp->getType()->isPointerType()) {
   7957       isObjCPointer = false;
   7958     } else if (PExp->getType()->isObjCObjectPointerType()) {
   7959       isObjCPointer = true;
   7960     } else {
   7961       return InvalidOperands(Loc, LHS, RHS);
   7962     }
   7963   }
   7964   assert(PExp->getType()->isAnyPointerType());
   7965 
   7966   if (!IExp->getType()->isIntegerType())
   7967     return InvalidOperands(Loc, LHS, RHS);
   7968 
   7969   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
   7970     return QualType();
   7971 
   7972   if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
   7973     return QualType();
   7974 
   7975   // Check array bounds for pointer arithemtic
   7976   CheckArrayAccess(PExp, IExp);
   7977 
   7978   if (CompLHSTy) {
   7979     QualType LHSTy = Context.isPromotableBitField(LHS.get());
   7980     if (LHSTy.isNull()) {
   7981       LHSTy = LHS.get()->getType();
   7982       if (LHSTy->isPromotableIntegerType())
   7983         LHSTy = Context.getPromotedIntegerType(LHSTy);
   7984     }
   7985     *CompLHSTy = LHSTy;
   7986   }
   7987 
   7988   return PExp->getType();
   7989 }
   7990 
   7991 // C99 6.5.6
   7992 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
   7993                                         SourceLocation Loc,
   7994                                         QualType* CompLHSTy) {
   7995   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
   7996 
   7997   if (LHS.get()->getType()->isVectorType() ||
   7998       RHS.get()->getType()->isVectorType()) {
   7999     QualType compType = CheckVectorOperands(
   8000         LHS, RHS, Loc, CompLHSTy,
   8001         /*AllowBothBool*/getLangOpts().AltiVec,
   8002         /*AllowBoolConversions*/getLangOpts().ZVector);
   8003     if (CompLHSTy) *CompLHSTy = compType;
   8004     return compType;
   8005   }
   8006 
   8007   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
   8008   if (LHS.isInvalid() || RHS.isInvalid())
   8009     return QualType();
   8010 
   8011   // Enforce type constraints: C99 6.5.6p3.
   8012 
   8013   // Handle the common case first (both operands are arithmetic).
   8014   if (!compType.isNull() && compType->isArithmeticType()) {
   8015     if (CompLHSTy) *CompLHSTy = compType;
   8016     return compType;
   8017   }
   8018 
   8019   // Either ptr - int   or   ptr - ptr.
   8020   if (LHS.get()->getType()->isAnyPointerType()) {
   8021     QualType lpointee = LHS.get()->getType()->getPointeeType();
   8022 
   8023     // Diagnose bad cases where we step over interface counts.
   8024     if (LHS.get()->getType()->isObjCObjectPointerType() &&
   8025         checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
   8026       return QualType();
   8027 
   8028     // The result type of a pointer-int computation is the pointer type.
   8029     if (RHS.get()->getType()->isIntegerType()) {
   8030       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
   8031         return QualType();
   8032 
   8033       // Check array bounds for pointer arithemtic
   8034       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
   8035                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
   8036 
   8037       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
   8038       return LHS.get()->getType();
   8039     }
   8040 
   8041     // Handle pointer-pointer subtractions.
   8042     if (const PointerType *RHSPTy
   8043           = RHS.get()->getType()->getAs<PointerType>()) {
   8044       QualType rpointee = RHSPTy->getPointeeType();
   8045 
   8046       if (getLangOpts().CPlusPlus) {
   8047         // Pointee types must be the same: C++ [expr.add]
   8048         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
   8049           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
   8050         }
   8051       } else {
   8052         // Pointee types must be compatible C99 6.5.6p3
   8053         if (!Context.typesAreCompatible(
   8054                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
   8055                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
   8056           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
   8057           return QualType();
   8058         }
   8059       }
   8060 
   8061       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
   8062                                                LHS.get(), RHS.get()))
   8063         return QualType();
   8064 
   8065       // The pointee type may have zero size.  As an extension, a structure or
   8066       // union may have zero size or an array may have zero length.  In this
   8067       // case subtraction does not make sense.
   8068       if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
   8069         CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
   8070         if (ElementSize.isZero()) {
   8071           Diag(Loc,diag::warn_sub_ptr_zero_size_types)
   8072             << rpointee.getUnqualifiedType()
   8073             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
   8074         }
   8075       }
   8076 
   8077       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
   8078       return Context.getPointerDiffType();
   8079     }
   8080   }
   8081 
   8082   return InvalidOperands(Loc, LHS, RHS);
   8083 }
   8084 
   8085 static bool isScopedEnumerationType(QualType T) {
   8086   if (const EnumType *ET = T->getAs<EnumType>())
   8087     return ET->getDecl()->isScoped();
   8088   return false;
   8089 }
   8090 
   8091 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
   8092                                    SourceLocation Loc, BinaryOperatorKind Opc,
   8093                                    QualType LHSType) {
   8094   // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
   8095   // so skip remaining warnings as we don't want to modify values within Sema.
   8096   if (S.getLangOpts().OpenCL)
   8097     return;
   8098 
   8099   llvm::APSInt Right;
   8100   // Check right/shifter operand
   8101   if (RHS.get()->isValueDependent() ||
   8102       !RHS.get()->EvaluateAsInt(Right, S.Context))
   8103     return;
   8104 
   8105   if (Right.isNegative()) {
   8106     S.DiagRuntimeBehavior(Loc, RHS.get(),
   8107                           S.PDiag(diag::warn_shift_negative)
   8108                             << RHS.get()->getSourceRange());
   8109     return;
   8110   }
   8111   llvm::APInt LeftBits(Right.getBitWidth(),
   8112                        S.Context.getTypeSize(LHS.get()->getType()));
   8113   if (Right.uge(LeftBits)) {
   8114     S.DiagRuntimeBehavior(Loc, RHS.get(),
   8115                           S.PDiag(diag::warn_shift_gt_typewidth)
   8116                             << RHS.get()->getSourceRange());
   8117     return;
   8118   }
   8119   if (Opc != BO_Shl)
   8120     return;
   8121 
   8122   // When left shifting an ICE which is signed, we can check for overflow which
   8123   // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
   8124   // integers have defined behavior modulo one more than the maximum value
   8125   // representable in the result type, so never warn for those.
   8126   llvm::APSInt Left;
   8127   if (LHS.get()->isValueDependent() ||
   8128       LHSType->hasUnsignedIntegerRepresentation() ||
   8129       !LHS.get()->EvaluateAsInt(Left, S.Context))
   8130     return;
   8131 
   8132   // If LHS does not have a signed type and non-negative value
   8133   // then, the behavior is undefined. Warn about it.
   8134   if (Left.isNegative()) {
   8135     S.DiagRuntimeBehavior(Loc, LHS.get(),
   8136                           S.PDiag(diag::warn_shift_lhs_negative)
   8137                             << LHS.get()->getSourceRange());
   8138     return;
   8139   }
   8140 
   8141   llvm::APInt ResultBits =
   8142       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
   8143   if (LeftBits.uge(ResultBits))
   8144     return;
   8145   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
   8146   Result = Result.shl(Right);
   8147 
   8148   // Print the bit representation of the signed integer as an unsigned
   8149   // hexadecimal number.
   8150   SmallString<40> HexResult;
   8151   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
   8152 
   8153   // If we are only missing a sign bit, this is less likely to result in actual
   8154   // bugs -- if the result is cast back to an unsigned type, it will have the
   8155   // expected value. Thus we place this behind a different warning that can be
   8156   // turned off separately if needed.
   8157   if (LeftBits == ResultBits - 1) {
   8158     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
   8159         << HexResult << LHSType
   8160         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
   8161     return;
   8162   }
   8163 
   8164   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
   8165     << HexResult.str() << Result.getMinSignedBits() << LHSType
   8166     << Left.getBitWidth() << LHS.get()->getSourceRange()
   8167     << RHS.get()->getSourceRange();
   8168 }
   8169 
   8170 /// \brief Return the resulting type when an OpenCL vector is shifted
   8171 ///        by a scalar or vector shift amount.
   8172 static QualType checkOpenCLVectorShift(Sema &S,
   8173                                        ExprResult &LHS, ExprResult &RHS,
   8174                                        SourceLocation Loc, bool IsCompAssign) {
   8175   // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
   8176   if (!LHS.get()->getType()->isVectorType()) {
   8177     S.Diag(Loc, diag::err_shift_rhs_only_vector)
   8178       << RHS.get()->getType() << LHS.get()->getType()
   8179       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
   8180     return QualType();
   8181   }
   8182 
   8183   if (!IsCompAssign) {
   8184     LHS = S.UsualUnaryConversions(LHS.get());
   8185     if (LHS.isInvalid()) return QualType();
   8186   }
   8187 
   8188   RHS = S.UsualUnaryConversions(RHS.get());
   8189   if (RHS.isInvalid()) return QualType();
   8190 
   8191   QualType LHSType = LHS.get()->getType();
   8192   const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
   8193   QualType LHSEleType = LHSVecTy->getElementType();
   8194 
   8195   // Note that RHS might not be a vector.
   8196   QualType RHSType = RHS.get()->getType();
   8197   const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
   8198   QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
   8199 
   8200   // OpenCL v1.1 s6.3.j says that the operands need to be integers.
   8201   if (!LHSEleType->isIntegerType()) {
   8202     S.Diag(Loc, diag::err_typecheck_expect_int)
   8203       << LHS.get()->getType() << LHS.get()->getSourceRange();
   8204     return QualType();
   8205   }
   8206 
   8207   if (!RHSEleType->isIntegerType()) {
   8208     S.Diag(Loc, diag::err_typecheck_expect_int)
   8209       << RHS.get()->getType() << RHS.get()->getSourceRange();
   8210     return QualType();
   8211   }
   8212 
   8213   if (RHSVecTy) {
   8214     // OpenCL v1.1 s6.3.j says that for vector types, the operators
   8215     // are applied component-wise. So if RHS is a vector, then ensure
   8216     // that the number of elements is the same as LHS...
   8217     if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
   8218       S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
   8219         << LHS.get()->getType() << RHS.get()->getType()
   8220         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
   8221       return QualType();
   8222     }
   8223   } else {
   8224     // ...else expand RHS to match the number of elements in LHS.
   8225     QualType VecTy =
   8226       S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
   8227     RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
   8228   }
   8229 
   8230   return LHSType;
   8231 }
   8232 
   8233 // C99 6.5.7
   8234 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
   8235                                   SourceLocation Loc, BinaryOperatorKind Opc,
   8236                                   bool IsCompAssign) {
   8237   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
   8238 
   8239   // Vector shifts promote their scalar inputs to vector type.
   8240   if (LHS.get()->getType()->isVectorType() ||
   8241       RHS.get()->getType()->isVectorType()) {
   8242     if (LangOpts.OpenCL)
   8243       return checkOpenCLVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
   8244     if (LangOpts.ZVector) {
   8245       // The shift operators for the z vector extensions work basically
   8246       // like OpenCL shifts, except that neither the LHS nor the RHS is
   8247       // allowed to be a "vector bool".
   8248       if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
   8249         if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
   8250           return InvalidOperands(Loc, LHS, RHS);
   8251       if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
   8252         if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
   8253           return InvalidOperands(Loc, LHS, RHS);
   8254       return checkOpenCLVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
   8255     }
   8256     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
   8257                                /*AllowBothBool*/true,
   8258                                /*AllowBoolConversions*/false);
   8259   }
   8260 
   8261   // Shifts don't perform usual arithmetic conversions, they just do integer
   8262   // promotions on each operand. C99 6.5.7p3
   8263 
   8264   // For the LHS, do usual unary conversions, but then reset them away
   8265   // if this is a compound assignment.
   8266   ExprResult OldLHS = LHS;
   8267   LHS = UsualUnaryConversions(LHS.get());
   8268   if (LHS.isInvalid())
   8269     return QualType();
   8270   QualType LHSType = LHS.get()->getType();
   8271   if (IsCompAssign) LHS = OldLHS;
   8272 
   8273   // The RHS is simpler.
   8274   RHS = UsualUnaryConversions(RHS.get());
   8275   if (RHS.isInvalid())
   8276     return QualType();
   8277   QualType RHSType = RHS.get()->getType();
   8278 
   8279   // C99 6.5.7p2: Each of the operands shall have integer type.
   8280   if (!LHSType->hasIntegerRepresentation() ||
   8281       !RHSType->hasIntegerRepresentation())
   8282     return InvalidOperands(Loc, LHS, RHS);
   8283 
   8284   // C++0x: Don't allow scoped enums. FIXME: Use something better than
   8285   // hasIntegerRepresentation() above instead of this.
   8286   if (isScopedEnumerationType(LHSType) ||
   8287       isScopedEnumerationType(RHSType)) {
   8288     return InvalidOperands(Loc, LHS, RHS);
   8289   }
   8290   // Sanity-check shift operands
   8291   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
   8292 
   8293   // "The type of the result is that of the promoted left operand."
   8294   return LHSType;
   8295 }
   8296 
   8297 static bool IsWithinTemplateSpecialization(Decl *D) {
   8298   if (DeclContext *DC = D->getDeclContext()) {
   8299     if (isa<ClassTemplateSpecializationDecl>(DC))
   8300       return true;
   8301     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
   8302       return FD->isFunctionTemplateSpecialization();
   8303   }
   8304   return false;
   8305 }
   8306 
   8307 /// If two different enums are compared, raise a warning.
   8308 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS,
   8309                                 Expr *RHS) {
   8310   QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
   8311   QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
   8312 
   8313   const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
   8314   if (!LHSEnumType)
   8315     return;
   8316   const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
   8317   if (!RHSEnumType)
   8318     return;
   8319 
   8320   // Ignore anonymous enums.
   8321   if (!LHSEnumType->getDecl()->getIdentifier())
   8322     return;
   8323   if (!RHSEnumType->getDecl()->getIdentifier())
   8324     return;
   8325 
   8326   if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
   8327     return;
   8328 
   8329   S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
   8330       << LHSStrippedType << RHSStrippedType
   8331       << LHS->getSourceRange() << RHS->getSourceRange();
   8332 }
   8333 
   8334 /// \brief Diagnose bad pointer comparisons.
   8335 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
   8336                                               ExprResult &LHS, ExprResult &RHS,
   8337                                               bool IsError) {
   8338   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
   8339                       : diag::ext_typecheck_comparison_of_distinct_pointers)
   8340     << LHS.get()->getType() << RHS.get()->getType()
   8341     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
   8342 }
   8343 
   8344 /// \brief Returns false if the pointers are converted to a composite type,
   8345 /// true otherwise.
   8346 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
   8347                                            ExprResult &LHS, ExprResult &RHS) {
   8348   // C++ [expr.rel]p2:
   8349   //   [...] Pointer conversions (4.10) and qualification
   8350   //   conversions (4.4) are performed on pointer operands (or on
   8351   //   a pointer operand and a null pointer constant) to bring
   8352   //   them to their composite pointer type. [...]
   8353   //
   8354   // C++ [expr.eq]p1 uses the same notion for (in)equality
   8355   // comparisons of pointers.
   8356 
   8357   // C++ [expr.eq]p2:
   8358   //   In addition, pointers to members can be compared, or a pointer to
   8359   //   member and a null pointer constant. Pointer to member conversions
   8360   //   (4.11) and qualification conversions (4.4) are performed to bring
   8361   //   them to a common type. If one operand is a null pointer constant,
   8362   //   the common type is the type of the other operand. Otherwise, the
   8363   //   common type is a pointer to member type similar (4.4) to the type
   8364   //   of one of the operands, with a cv-qualification signature (4.4)
   8365   //   that is the union of the cv-qualification signatures of the operand
   8366   //   types.
   8367 
   8368   QualType LHSType = LHS.get()->getType();
   8369   QualType RHSType = RHS.get()->getType();
   8370   assert((LHSType->isPointerType() && RHSType->isPointerType()) ||
   8371          (LHSType->isMemberPointerType() && RHSType->isMemberPointerType()));
   8372 
   8373   bool NonStandardCompositeType = false;
   8374   bool *BoolPtr = S.isSFINAEContext() ? nullptr : &NonStandardCompositeType;
   8375   QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr);
   8376   if (T.isNull()) {
   8377     diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
   8378     return true;
   8379   }
   8380 
   8381   if (NonStandardCompositeType)
   8382     S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
   8383       << LHSType << RHSType << T << LHS.get()->getSourceRange()
   8384       << RHS.get()->getSourceRange();
   8385 
   8386   LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast);
   8387   RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast);
   8388   return false;
   8389 }
   8390 
   8391 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
   8392                                                     ExprResult &LHS,
   8393                                                     ExprResult &RHS,
   8394                                                     bool IsError) {
   8395   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
   8396                       : diag::ext_typecheck_comparison_of_fptr_to_void)
   8397     << LHS.get()->getType() << RHS.get()->getType()
   8398     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
   8399 }
   8400 
   8401 static bool isObjCObjectLiteral(ExprResult &E) {
   8402   switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
   8403   case Stmt::ObjCArrayLiteralClass:
   8404   case Stmt::ObjCDictionaryLiteralClass:
   8405   case Stmt::ObjCStringLiteralClass:
   8406   case Stmt::ObjCBoxedExprClass:
   8407     return true;
   8408   default:
   8409     // Note that ObjCBoolLiteral is NOT an object literal!
   8410     return false;
   8411   }
   8412 }
   8413 
   8414 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
   8415   const ObjCObjectPointerType *Type =
   8416     LHS->getType()->getAs<ObjCObjectPointerType>();
   8417 
   8418   // If this is not actually an Objective-C object, bail out.
   8419   if (!Type)
   8420     return false;
   8421 
   8422   // Get the LHS object's interface type.
   8423   QualType InterfaceType = Type->getPointeeType();
   8424 
   8425   // If the RHS isn't an Objective-C object, bail out.
   8426   if (!RHS->getType()->isObjCObjectPointerType())
   8427     return false;
   8428 
   8429   // Try to find the -isEqual: method.
   8430   Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
   8431   ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
   8432                                                       InterfaceType,
   8433                                                       /*instance=*/true);
   8434   if (!Method) {
   8435     if (Type->isObjCIdType()) {
   8436       // For 'id', just check the global pool.
   8437       Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
   8438                                                   /*receiverId=*/true);
   8439     } else {
   8440       // Check protocols.
   8441       Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
   8442                                              /*instance=*/true);
   8443     }
   8444   }
   8445 
   8446   if (!Method)
   8447     return false;
   8448 
   8449   QualType T = Method->parameters()[0]->getType();
   8450   if (!T->isObjCObjectPointerType())
   8451     return false;
   8452 
   8453   QualType R = Method->getReturnType();
   8454   if (!R->isScalarType())
   8455     return false;
   8456 
   8457   return true;
   8458 }
   8459 
   8460 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
   8461   FromE = FromE->IgnoreParenImpCasts();
   8462   switch (FromE->getStmtClass()) {
   8463     default:
   8464       break;
   8465     case Stmt::ObjCStringLiteralClass:
   8466       // "string literal"
   8467       return LK_String;
   8468     case Stmt::ObjCArrayLiteralClass:
   8469       // "array literal"
   8470       return LK_Array;
   8471     case Stmt::ObjCDictionaryLiteralClass:
   8472       // "dictionary literal"
   8473       return LK_Dictionary;
   8474     case Stmt::BlockExprClass:
   8475       return LK_Block;
   8476     case Stmt::ObjCBoxedExprClass: {
   8477       Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
   8478       switch (Inner->getStmtClass()) {
   8479         case Stmt::IntegerLiteralClass:
   8480         case Stmt::FloatingLiteralClass:
   8481         case Stmt::CharacterLiteralClass:
   8482         case Stmt::ObjCBoolLiteralExprClass:
   8483         case Stmt::CXXBoolLiteralExprClass:
   8484           // "numeric literal"
   8485           return LK_Numeric;
   8486         case Stmt::ImplicitCastExprClass: {
   8487           CastKind CK = cast<CastExpr>(Inner)->getCastKind();
   8488           // Boolean literals can be represented by implicit casts.
   8489           if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
   8490             return LK_Numeric;
   8491           break;
   8492         }
   8493         default:
   8494           break;
   8495       }
   8496       return LK_Boxed;
   8497     }
   8498   }
   8499   return LK_None;
   8500 }
   8501 
   8502 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
   8503                                           ExprResult &LHS, ExprResult &RHS,
   8504                                           BinaryOperator::Opcode Opc){
   8505   Expr *Literal;
   8506   Expr *Other;
   8507   if (isObjCObjectLiteral(LHS)) {
   8508     Literal = LHS.get();
   8509     Other = RHS.get();
   8510   } else {
   8511     Literal = RHS.get();
   8512     Other = LHS.get();
   8513   }
   8514 
   8515   // Don't warn on comparisons against nil.
   8516   Other = Other->IgnoreParenCasts();
   8517   if (Other->isNullPointerConstant(S.getASTContext(),
   8518                                    Expr::NPC_ValueDependentIsNotNull))
   8519     return;
   8520 
   8521   // This should be kept in sync with warn_objc_literal_comparison.
   8522   // LK_String should always be after the other literals, since it has its own
   8523   // warning flag.
   8524   Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
   8525   assert(LiteralKind != Sema::LK_Block);
   8526   if (LiteralKind == Sema::LK_None) {
   8527     llvm_unreachable("Unknown Objective-C object literal kind");
   8528   }
   8529 
   8530   if (LiteralKind == Sema::LK_String)
   8531     S.Diag(Loc, diag::warn_objc_string_literal_comparison)
   8532       << Literal->getSourceRange();
   8533   else
   8534     S.Diag(Loc, diag::warn_objc_literal_comparison)
   8535       << LiteralKind << Literal->getSourceRange();
   8536 
   8537   if (BinaryOperator::isEqualityOp(Opc) &&
   8538       hasIsEqualMethod(S, LHS.get(), RHS.get())) {
   8539     SourceLocation Start = LHS.get()->getLocStart();
   8540     SourceLocation End = S.getLocForEndOfToken(RHS.get()->getLocEnd());
   8541     CharSourceRange OpRange =
   8542       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
   8543 
   8544     S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
   8545       << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
   8546       << FixItHint::CreateReplacement(OpRange, " isEqual:")
   8547       << FixItHint::CreateInsertion(End, "]");
   8548   }
   8549 }
   8550 
   8551 static void diagnoseLogicalNotOnLHSofComparison(Sema &S, ExprResult &LHS,
   8552                                                 ExprResult &RHS,
   8553                                                 SourceLocation Loc,
   8554                                                 BinaryOperatorKind Opc) {
   8555   // Check that left hand side is !something.
   8556   UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
   8557   if (!UO || UO->getOpcode() != UO_LNot) return;
   8558 
   8559   // Only check if the right hand side is non-bool arithmetic type.
   8560   if (RHS.get()->isKnownToHaveBooleanValue()) return;
   8561 
   8562   // Make sure that the something in !something is not bool.
   8563   Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
   8564   if (SubExpr->isKnownToHaveBooleanValue()) return;
   8565 
   8566   // Emit warning.
   8567   S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_comparison)
   8568       << Loc;
   8569 
   8570   // First note suggest !(x < y)
   8571   SourceLocation FirstOpen = SubExpr->getLocStart();
   8572   SourceLocation FirstClose = RHS.get()->getLocEnd();
   8573   FirstClose = S.getLocForEndOfToken(FirstClose);
   8574   if (FirstClose.isInvalid())
   8575     FirstOpen = SourceLocation();
   8576   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
   8577       << FixItHint::CreateInsertion(FirstOpen, "(")
   8578       << FixItHint::CreateInsertion(FirstClose, ")");
   8579 
   8580   // Second note suggests (!x) < y
   8581   SourceLocation SecondOpen = LHS.get()->getLocStart();
   8582   SourceLocation SecondClose = LHS.get()->getLocEnd();
   8583   SecondClose = S.getLocForEndOfToken(SecondClose);
   8584   if (SecondClose.isInvalid())
   8585     SecondOpen = SourceLocation();
   8586   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
   8587       << FixItHint::CreateInsertion(SecondOpen, "(")
   8588       << FixItHint::CreateInsertion(SecondClose, ")");
   8589 }
   8590 
   8591 // Get the decl for a simple expression: a reference to a variable,
   8592 // an implicit C++ field reference, or an implicit ObjC ivar reference.
   8593 static ValueDecl *getCompareDecl(Expr *E) {
   8594   if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E))
   8595     return DR->getDecl();
   8596   if (ObjCIvarRefExpr* Ivar = dyn_cast<ObjCIvarRefExpr>(E)) {
   8597     if (Ivar->isFreeIvar())
   8598       return Ivar->getDecl();
   8599   }
   8600   if (MemberExpr* Mem = dyn_cast<MemberExpr>(E)) {
   8601     if (Mem->isImplicitAccess())
   8602       return Mem->getMemberDecl();
   8603   }
   8604   return nullptr;
   8605 }
   8606 
   8607 // C99 6.5.8, C++ [expr.rel]
   8608 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
   8609                                     SourceLocation Loc, BinaryOperatorKind Opc,
   8610                                     bool IsRelational) {
   8611   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
   8612 
   8613   // Handle vector comparisons separately.
   8614   if (LHS.get()->getType()->isVectorType() ||
   8615       RHS.get()->getType()->isVectorType())
   8616     return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
   8617 
   8618   QualType LHSType = LHS.get()->getType();
   8619   QualType RHSType = RHS.get()->getType();
   8620 
   8621   Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
   8622   Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
   8623 
   8624   checkEnumComparison(*this, Loc, LHS.get(), RHS.get());
   8625   diagnoseLogicalNotOnLHSofComparison(*this, LHS, RHS, Loc, Opc);
   8626 
   8627   if (!LHSType->hasFloatingRepresentation() &&
   8628       !(LHSType->isBlockPointerType() && IsRelational) &&
   8629       !LHS.get()->getLocStart().isMacroID() &&
   8630       !RHS.get()->getLocStart().isMacroID() &&
   8631       ActiveTemplateInstantiations.empty()) {
   8632     // For non-floating point types, check for self-comparisons of the form
   8633     // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
   8634     // often indicate logic errors in the program.
   8635     //
   8636     // NOTE: Don't warn about comparison expressions resulting from macro
   8637     // expansion. Also don't warn about comparisons which are only self
   8638     // comparisons within a template specialization. The warnings should catch
   8639     // obvious cases in the definition of the template anyways. The idea is to
   8640     // warn when the typed comparison operator will always evaluate to the same
   8641     // result.
   8642     ValueDecl *DL = getCompareDecl(LHSStripped);
   8643     ValueDecl *DR = getCompareDecl(RHSStripped);
   8644     if (DL && DR && DL == DR && !IsWithinTemplateSpecialization(DL)) {
   8645       DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
   8646                           << 0 // self-
   8647                           << (Opc == BO_EQ
   8648                               || Opc == BO_LE
   8649                               || Opc == BO_GE));
   8650     } else if (DL && DR && LHSType->isArrayType() && RHSType->isArrayType() &&
   8651                !DL->getType()->isReferenceType() &&
   8652                !DR->getType()->isReferenceType()) {
   8653         // what is it always going to eval to?
   8654         char always_evals_to;
   8655         switch(Opc) {
   8656         case BO_EQ: // e.g. array1 == array2
   8657           always_evals_to = 0; // false
   8658           break;
   8659         case BO_NE: // e.g. array1 != array2
   8660           always_evals_to = 1; // true
   8661           break;
   8662         default:
   8663           // best we can say is 'a constant'
   8664           always_evals_to = 2; // e.g. array1 <= array2
   8665           break;
   8666         }
   8667         DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
   8668                             << 1 // array
   8669                             << always_evals_to);
   8670     }
   8671 
   8672     if (isa<CastExpr>(LHSStripped))
   8673       LHSStripped = LHSStripped->IgnoreParenCasts();
   8674     if (isa<CastExpr>(RHSStripped))
   8675       RHSStripped = RHSStripped->IgnoreParenCasts();
   8676 
   8677     // Warn about comparisons against a string constant (unless the other
   8678     // operand is null), the user probably wants strcmp.
   8679     Expr *literalString = nullptr;
   8680     Expr *literalStringStripped = nullptr;
   8681     if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
   8682         !RHSStripped->isNullPointerConstant(Context,
   8683                                             Expr::NPC_ValueDependentIsNull)) {
   8684       literalString = LHS.get();
   8685       literalStringStripped = LHSStripped;
   8686     } else if ((isa<StringLiteral>(RHSStripped) ||
   8687                 isa<ObjCEncodeExpr>(RHSStripped)) &&
   8688                !LHSStripped->isNullPointerConstant(Context,
   8689                                             Expr::NPC_ValueDependentIsNull)) {
   8690       literalString = RHS.get();
   8691       literalStringStripped = RHSStripped;
   8692     }
   8693 
   8694     if (literalString) {
   8695       DiagRuntimeBehavior(Loc, nullptr,
   8696         PDiag(diag::warn_stringcompare)
   8697           << isa<ObjCEncodeExpr>(literalStringStripped)
   8698           << literalString->getSourceRange());
   8699     }
   8700   }
   8701 
   8702   // C99 6.5.8p3 / C99 6.5.9p4
   8703   UsualArithmeticConversions(LHS, RHS);
   8704   if (LHS.isInvalid() || RHS.isInvalid())
   8705     return QualType();
   8706 
   8707   LHSType = LHS.get()->getType();
   8708   RHSType = RHS.get()->getType();
   8709 
   8710   // The result of comparisons is 'bool' in C++, 'int' in C.
   8711   QualType ResultTy = Context.getLogicalOperationType();
   8712 
   8713   if (IsRelational) {
   8714     if (LHSType->isRealType() && RHSType->isRealType())
   8715       return ResultTy;
   8716   } else {
   8717     // Check for comparisons of floating point operands using != and ==.
   8718     if (LHSType->hasFloatingRepresentation())
   8719       CheckFloatComparison(Loc, LHS.get(), RHS.get());
   8720 
   8721     if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
   8722       return ResultTy;
   8723   }
   8724 
   8725   const Expr::NullPointerConstantKind LHSNullKind =
   8726       LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
   8727   const Expr::NullPointerConstantKind RHSNullKind =
   8728       RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
   8729   bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
   8730   bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
   8731 
   8732   if (!IsRelational && LHSIsNull != RHSIsNull) {
   8733     bool IsEquality = Opc == BO_EQ;
   8734     if (RHSIsNull)
   8735       DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
   8736                                    RHS.get()->getSourceRange());
   8737     else
   8738       DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
   8739                                    LHS.get()->getSourceRange());
   8740   }
   8741 
   8742   // All of the following pointer-related warnings are GCC extensions, except
   8743   // when handling null pointer constants.
   8744   if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2
   8745     QualType LCanPointeeTy =
   8746       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
   8747     QualType RCanPointeeTy =
   8748       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
   8749 
   8750     if (getLangOpts().CPlusPlus) {
   8751       if (LCanPointeeTy == RCanPointeeTy)
   8752         return ResultTy;
   8753       if (!IsRelational &&
   8754           (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
   8755         // Valid unless comparison between non-null pointer and function pointer
   8756         // This is a gcc extension compatibility comparison.
   8757         // In a SFINAE context, we treat this as a hard error to maintain
   8758         // conformance with the C++ standard.
   8759         if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
   8760             && !LHSIsNull && !RHSIsNull) {
   8761           diagnoseFunctionPointerToVoidComparison(
   8762               *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
   8763 
   8764           if (isSFINAEContext())
   8765             return QualType();
   8766 
   8767           RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
   8768           return ResultTy;
   8769         }
   8770       }
   8771 
   8772       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
   8773         return QualType();
   8774       else
   8775         return ResultTy;
   8776     }
   8777     // C99 6.5.9p2 and C99 6.5.8p2
   8778     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
   8779                                    RCanPointeeTy.getUnqualifiedType())) {
   8780       // Valid unless a relational comparison of function pointers
   8781       if (IsRelational && LCanPointeeTy->isFunctionType()) {
   8782         Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
   8783           << LHSType << RHSType << LHS.get()->getSourceRange()
   8784           << RHS.get()->getSourceRange();
   8785       }
   8786     } else if (!IsRelational &&
   8787                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
   8788       // Valid unless comparison between non-null pointer and function pointer
   8789       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
   8790           && !LHSIsNull && !RHSIsNull)
   8791         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
   8792                                                 /*isError*/false);
   8793     } else {
   8794       // Invalid
   8795       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
   8796     }
   8797     if (LCanPointeeTy != RCanPointeeTy) {
   8798       // Treat NULL constant as a special case in OpenCL.
   8799       if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
   8800         const PointerType *LHSPtr = LHSType->getAs<PointerType>();
   8801         if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) {
   8802           Diag(Loc,
   8803                diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
   8804               << LHSType << RHSType << 0 /* comparison */
   8805               << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
   8806         }
   8807       }
   8808       unsigned AddrSpaceL = LCanPointeeTy.getAddressSpace();
   8809       unsigned AddrSpaceR = RCanPointeeTy.getAddressSpace();
   8810       CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
   8811                                                : CK_BitCast;
   8812       if (LHSIsNull && !RHSIsNull)
   8813         LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
   8814       else
   8815         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
   8816     }
   8817     return ResultTy;
   8818   }
   8819 
   8820   if (getLangOpts().CPlusPlus) {
   8821     // Comparison of nullptr_t with itself.
   8822     if (LHSType->isNullPtrType() && RHSType->isNullPtrType())
   8823       return ResultTy;
   8824 
   8825     // Comparison of pointers with null pointer constants and equality
   8826     // comparisons of member pointers to null pointer constants.
   8827     if (RHSIsNull &&
   8828         ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) ||
   8829          (!IsRelational &&
   8830           (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) {
   8831       RHS = ImpCastExprToType(RHS.get(), LHSType,
   8832                         LHSType->isMemberPointerType()
   8833                           ? CK_NullToMemberPointer
   8834                           : CK_NullToPointer);
   8835       return ResultTy;
   8836     }
   8837     if (LHSIsNull &&
   8838         ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) ||
   8839          (!IsRelational &&
   8840           (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) {
   8841       LHS = ImpCastExprToType(LHS.get(), RHSType,
   8842                         RHSType->isMemberPointerType()
   8843                           ? CK_NullToMemberPointer
   8844                           : CK_NullToPointer);
   8845       return ResultTy;
   8846     }
   8847 
   8848     // Comparison of member pointers.
   8849     if (!IsRelational &&
   8850         LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) {
   8851       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
   8852         return QualType();
   8853       else
   8854         return ResultTy;
   8855     }
   8856 
   8857     // Handle scoped enumeration types specifically, since they don't promote
   8858     // to integers.
   8859     if (LHS.get()->getType()->isEnumeralType() &&
   8860         Context.hasSameUnqualifiedType(LHS.get()->getType(),
   8861                                        RHS.get()->getType()))
   8862       return ResultTy;
   8863   }
   8864 
   8865   // Handle block pointer types.
   8866   if (!IsRelational && LHSType->isBlockPointerType() &&
   8867       RHSType->isBlockPointerType()) {
   8868     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
   8869     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
   8870 
   8871     if (!LHSIsNull && !RHSIsNull &&
   8872         !Context.typesAreCompatible(lpointee, rpointee)) {
   8873       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
   8874         << LHSType << RHSType << LHS.get()->getSourceRange()
   8875         << RHS.get()->getSourceRange();
   8876     }
   8877     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
   8878     return ResultTy;
   8879   }
   8880 
   8881   // Allow block pointers to be compared with null pointer constants.
   8882   if (!IsRelational
   8883       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
   8884           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
   8885     if (!LHSIsNull && !RHSIsNull) {
   8886       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
   8887              ->getPointeeType()->isVoidType())
   8888             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
   8889                 ->getPointeeType()->isVoidType())))
   8890         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
   8891           << LHSType << RHSType << LHS.get()->getSourceRange()
   8892           << RHS.get()->getSourceRange();
   8893     }
   8894     if (LHSIsNull && !RHSIsNull)
   8895       LHS = ImpCastExprToType(LHS.get(), RHSType,
   8896                               RHSType->isPointerType() ? CK_BitCast
   8897                                 : CK_AnyPointerToBlockPointerCast);
   8898     else
   8899       RHS = ImpCastExprToType(RHS.get(), LHSType,
   8900                               LHSType->isPointerType() ? CK_BitCast
   8901                                 : CK_AnyPointerToBlockPointerCast);
   8902     return ResultTy;
   8903   }
   8904 
   8905   if (LHSType->isObjCObjectPointerType() ||
   8906       RHSType->isObjCObjectPointerType()) {
   8907     const PointerType *LPT = LHSType->getAs<PointerType>();
   8908     const PointerType *RPT = RHSType->getAs<PointerType>();
   8909     if (LPT || RPT) {
   8910       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
   8911       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
   8912 
   8913       if (!LPtrToVoid && !RPtrToVoid &&
   8914           !Context.typesAreCompatible(LHSType, RHSType)) {
   8915         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
   8916                                           /*isError*/false);
   8917       }
   8918       if (LHSIsNull && !RHSIsNull) {
   8919         Expr *E = LHS.get();
   8920         if (getLangOpts().ObjCAutoRefCount)
   8921           CheckObjCARCConversion(SourceRange(), RHSType, E, CCK_ImplicitConversion);
   8922         LHS = ImpCastExprToType(E, RHSType,
   8923                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
   8924       }
   8925       else {
   8926         Expr *E = RHS.get();
   8927         if (getLangOpts().ObjCAutoRefCount)
   8928           CheckObjCARCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, false,
   8929                                  Opc);
   8930         RHS = ImpCastExprToType(E, LHSType,
   8931                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
   8932       }
   8933       return ResultTy;
   8934     }
   8935     if (LHSType->isObjCObjectPointerType() &&
   8936         RHSType->isObjCObjectPointerType()) {
   8937       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
   8938         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
   8939                                           /*isError*/false);
   8940       if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
   8941         diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
   8942 
   8943       if (LHSIsNull && !RHSIsNull)
   8944         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
   8945       else
   8946         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
   8947       return ResultTy;
   8948     }
   8949   }
   8950   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
   8951       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
   8952     unsigned DiagID = 0;
   8953     bool isError = false;
   8954     if (LangOpts.DebuggerSupport) {
   8955       // Under a debugger, allow the comparison of pointers to integers,
   8956       // since users tend to want to compare addresses.
   8957     } else if ((LHSIsNull && LHSType->isIntegerType()) ||
   8958         (RHSIsNull && RHSType->isIntegerType())) {
   8959       if (IsRelational && !getLangOpts().CPlusPlus)
   8960         DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
   8961     } else if (IsRelational && !getLangOpts().CPlusPlus)
   8962       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
   8963     else if (getLangOpts().CPlusPlus) {
   8964       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
   8965       isError = true;
   8966     } else
   8967       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
   8968 
   8969     if (DiagID) {
   8970       Diag(Loc, DiagID)
   8971         << LHSType << RHSType << LHS.get()->getSourceRange()
   8972         << RHS.get()->getSourceRange();
   8973       if (isError)
   8974         return QualType();
   8975     }
   8976 
   8977     if (LHSType->isIntegerType())
   8978       LHS = ImpCastExprToType(LHS.get(), RHSType,
   8979                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
   8980     else
   8981       RHS = ImpCastExprToType(RHS.get(), LHSType,
   8982                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
   8983     return ResultTy;
   8984   }
   8985 
   8986   // Handle block pointers.
   8987   if (!IsRelational && RHSIsNull
   8988       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
   8989     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
   8990     return ResultTy;
   8991   }
   8992   if (!IsRelational && LHSIsNull
   8993       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
   8994     LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
   8995     return ResultTy;
   8996   }
   8997 
   8998   return InvalidOperands(Loc, LHS, RHS);
   8999 }
   9000 
   9001 
   9002 // Return a signed type that is of identical size and number of elements.
   9003 // For floating point vectors, return an integer type of identical size
   9004 // and number of elements.
   9005 QualType Sema::GetSignedVectorType(QualType V) {
   9006   const VectorType *VTy = V->getAs<VectorType>();
   9007   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
   9008   if (TypeSize == Context.getTypeSize(Context.CharTy))
   9009     return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
   9010   else if (TypeSize == Context.getTypeSize(Context.ShortTy))
   9011     return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
   9012   else if (TypeSize == Context.getTypeSize(Context.IntTy))
   9013     return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
   9014   else if (TypeSize == Context.