Home | History | Annotate | Download | only in Sema
      1 //===--- SemaExprCXX.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 /// \file
     11 /// \brief Implements semantic analysis for C++ expressions.
     12 ///
     13 //===----------------------------------------------------------------------===//
     14 
     15 #include "clang/Sema/SemaInternal.h"
     16 #include "TreeTransform.h"
     17 #include "TypeLocBuilder.h"
     18 #include "clang/AST/ASTContext.h"
     19 #include "clang/AST/ASTLambda.h"
     20 #include "clang/AST/CXXInheritance.h"
     21 #include "clang/AST/CharUnits.h"
     22 #include "clang/AST/DeclObjC.h"
     23 #include "clang/AST/ExprCXX.h"
     24 #include "clang/AST/ExprObjC.h"
     25 #include "clang/AST/RecursiveASTVisitor.h"
     26 #include "clang/AST/TypeLoc.h"
     27 #include "clang/Basic/PartialDiagnostic.h"
     28 #include "clang/Basic/TargetInfo.h"
     29 #include "clang/Lex/Preprocessor.h"
     30 #include "clang/Sema/DeclSpec.h"
     31 #include "clang/Sema/Initialization.h"
     32 #include "clang/Sema/Lookup.h"
     33 #include "clang/Sema/ParsedTemplate.h"
     34 #include "clang/Sema/Scope.h"
     35 #include "clang/Sema/ScopeInfo.h"
     36 #include "clang/Sema/SemaLambda.h"
     37 #include "clang/Sema/TemplateDeduction.h"
     38 #include "llvm/ADT/APInt.h"
     39 #include "llvm/ADT/STLExtras.h"
     40 #include "llvm/Support/ErrorHandling.h"
     41 using namespace clang;
     42 using namespace sema;
     43 
     44 /// \brief Handle the result of the special case name lookup for inheriting
     45 /// constructor declarations. 'NS::X::X' and 'NS::X<...>::X' are treated as
     46 /// constructor names in member using declarations, even if 'X' is not the
     47 /// name of the corresponding type.
     48 ParsedType Sema::getInheritingConstructorName(CXXScopeSpec &SS,
     49                                               SourceLocation NameLoc,
     50                                               IdentifierInfo &Name) {
     51   NestedNameSpecifier *NNS = SS.getScopeRep();
     52 
     53   // Convert the nested-name-specifier into a type.
     54   QualType Type;
     55   switch (NNS->getKind()) {
     56   case NestedNameSpecifier::TypeSpec:
     57   case NestedNameSpecifier::TypeSpecWithTemplate:
     58     Type = QualType(NNS->getAsType(), 0);
     59     break;
     60 
     61   case NestedNameSpecifier::Identifier:
     62     // Strip off the last layer of the nested-name-specifier and build a
     63     // typename type for it.
     64     assert(NNS->getAsIdentifier() == &Name && "not a constructor name");
     65     Type = Context.getDependentNameType(ETK_None, NNS->getPrefix(),
     66                                         NNS->getAsIdentifier());
     67     break;
     68 
     69   case NestedNameSpecifier::Global:
     70   case NestedNameSpecifier::Super:
     71   case NestedNameSpecifier::Namespace:
     72   case NestedNameSpecifier::NamespaceAlias:
     73     llvm_unreachable("Nested name specifier is not a type for inheriting ctor");
     74   }
     75 
     76   // This reference to the type is located entirely at the location of the
     77   // final identifier in the qualified-id.
     78   return CreateParsedType(Type,
     79                           Context.getTrivialTypeSourceInfo(Type, NameLoc));
     80 }
     81 
     82 ParsedType Sema::getDestructorName(SourceLocation TildeLoc,
     83                                    IdentifierInfo &II,
     84                                    SourceLocation NameLoc,
     85                                    Scope *S, CXXScopeSpec &SS,
     86                                    ParsedType ObjectTypePtr,
     87                                    bool EnteringContext) {
     88   // Determine where to perform name lookup.
     89 
     90   // FIXME: This area of the standard is very messy, and the current
     91   // wording is rather unclear about which scopes we search for the
     92   // destructor name; see core issues 399 and 555. Issue 399 in
     93   // particular shows where the current description of destructor name
     94   // lookup is completely out of line with existing practice, e.g.,
     95   // this appears to be ill-formed:
     96   //
     97   //   namespace N {
     98   //     template <typename T> struct S {
     99   //       ~S();
    100   //     };
    101   //   }
    102   //
    103   //   void f(N::S<int>* s) {
    104   //     s->N::S<int>::~S();
    105   //   }
    106   //
    107   // See also PR6358 and PR6359.
    108   // For this reason, we're currently only doing the C++03 version of this
    109   // code; the C++0x version has to wait until we get a proper spec.
    110   QualType SearchType;
    111   DeclContext *LookupCtx = nullptr;
    112   bool isDependent = false;
    113   bool LookInScope = false;
    114 
    115   if (SS.isInvalid())
    116     return nullptr;
    117 
    118   // If we have an object type, it's because we are in a
    119   // pseudo-destructor-expression or a member access expression, and
    120   // we know what type we're looking for.
    121   if (ObjectTypePtr)
    122     SearchType = GetTypeFromParser(ObjectTypePtr);
    123 
    124   if (SS.isSet()) {
    125     NestedNameSpecifier *NNS = SS.getScopeRep();
    126 
    127     bool AlreadySearched = false;
    128     bool LookAtPrefix = true;
    129     // C++11 [basic.lookup.qual]p6:
    130     //   If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier,
    131     //   the type-names are looked up as types in the scope designated by the
    132     //   nested-name-specifier. Similarly, in a qualified-id of the form:
    133     //
    134     //     nested-name-specifier[opt] class-name :: ~ class-name
    135     //
    136     //   the second class-name is looked up in the same scope as the first.
    137     //
    138     // Here, we determine whether the code below is permitted to look at the
    139     // prefix of the nested-name-specifier.
    140     DeclContext *DC = computeDeclContext(SS, EnteringContext);
    141     if (DC && DC->isFileContext()) {
    142       AlreadySearched = true;
    143       LookupCtx = DC;
    144       isDependent = false;
    145     } else if (DC && isa<CXXRecordDecl>(DC)) {
    146       LookAtPrefix = false;
    147       LookInScope = true;
    148     }
    149 
    150     // The second case from the C++03 rules quoted further above.
    151     NestedNameSpecifier *Prefix = nullptr;
    152     if (AlreadySearched) {
    153       // Nothing left to do.
    154     } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) {
    155       CXXScopeSpec PrefixSS;
    156       PrefixSS.Adopt(NestedNameSpecifierLoc(Prefix, SS.location_data()));
    157       LookupCtx = computeDeclContext(PrefixSS, EnteringContext);
    158       isDependent = isDependentScopeSpecifier(PrefixSS);
    159     } else if (ObjectTypePtr) {
    160       LookupCtx = computeDeclContext(SearchType);
    161       isDependent = SearchType->isDependentType();
    162     } else {
    163       LookupCtx = computeDeclContext(SS, EnteringContext);
    164       isDependent = LookupCtx && LookupCtx->isDependentContext();
    165     }
    166   } else if (ObjectTypePtr) {
    167     // C++ [basic.lookup.classref]p3:
    168     //   If the unqualified-id is ~type-name, the type-name is looked up
    169     //   in the context of the entire postfix-expression. If the type T
    170     //   of the object expression is of a class type C, the type-name is
    171     //   also looked up in the scope of class C. At least one of the
    172     //   lookups shall find a name that refers to (possibly
    173     //   cv-qualified) T.
    174     LookupCtx = computeDeclContext(SearchType);
    175     isDependent = SearchType->isDependentType();
    176     assert((isDependent || !SearchType->isIncompleteType()) &&
    177            "Caller should have completed object type");
    178 
    179     LookInScope = true;
    180   } else {
    181     // Perform lookup into the current scope (only).
    182     LookInScope = true;
    183   }
    184 
    185   TypeDecl *NonMatchingTypeDecl = nullptr;
    186   LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName);
    187   for (unsigned Step = 0; Step != 2; ++Step) {
    188     // Look for the name first in the computed lookup context (if we
    189     // have one) and, if that fails to find a match, in the scope (if
    190     // we're allowed to look there).
    191     Found.clear();
    192     if (Step == 0 && LookupCtx)
    193       LookupQualifiedName(Found, LookupCtx);
    194     else if (Step == 1 && LookInScope && S)
    195       LookupName(Found, S);
    196     else
    197       continue;
    198 
    199     // FIXME: Should we be suppressing ambiguities here?
    200     if (Found.isAmbiguous())
    201       return nullptr;
    202 
    203     if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
    204       QualType T = Context.getTypeDeclType(Type);
    205       MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
    206 
    207       if (SearchType.isNull() || SearchType->isDependentType() ||
    208           Context.hasSameUnqualifiedType(T, SearchType)) {
    209         // We found our type!
    210 
    211         return CreateParsedType(T,
    212                                 Context.getTrivialTypeSourceInfo(T, NameLoc));
    213       }
    214 
    215       if (!SearchType.isNull())
    216         NonMatchingTypeDecl = Type;
    217     }
    218 
    219     // If the name that we found is a class template name, and it is
    220     // the same name as the template name in the last part of the
    221     // nested-name-specifier (if present) or the object type, then
    222     // this is the destructor for that class.
    223     // FIXME: This is a workaround until we get real drafting for core
    224     // issue 399, for which there isn't even an obvious direction.
    225     if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) {
    226       QualType MemberOfType;
    227       if (SS.isSet()) {
    228         if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) {
    229           // Figure out the type of the context, if it has one.
    230           if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx))
    231             MemberOfType = Context.getTypeDeclType(Record);
    232         }
    233       }
    234       if (MemberOfType.isNull())
    235         MemberOfType = SearchType;
    236 
    237       if (MemberOfType.isNull())
    238         continue;
    239 
    240       // We're referring into a class template specialization. If the
    241       // class template we found is the same as the template being
    242       // specialized, we found what we are looking for.
    243       if (const RecordType *Record = MemberOfType->getAs<RecordType>()) {
    244         if (ClassTemplateSpecializationDecl *Spec
    245               = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
    246           if (Spec->getSpecializedTemplate()->getCanonicalDecl() ==
    247                 Template->getCanonicalDecl())
    248             return CreateParsedType(
    249                 MemberOfType,
    250                 Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc));
    251         }
    252 
    253         continue;
    254       }
    255 
    256       // We're referring to an unresolved class template
    257       // specialization. Determine whether we class template we found
    258       // is the same as the template being specialized or, if we don't
    259       // know which template is being specialized, that it at least
    260       // has the same name.
    261       if (const TemplateSpecializationType *SpecType
    262             = MemberOfType->getAs<TemplateSpecializationType>()) {
    263         TemplateName SpecName = SpecType->getTemplateName();
    264 
    265         // The class template we found is the same template being
    266         // specialized.
    267         if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) {
    268           if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl())
    269             return CreateParsedType(
    270                 MemberOfType,
    271                 Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc));
    272 
    273           continue;
    274         }
    275 
    276         // The class template we found has the same name as the
    277         // (dependent) template name being specialized.
    278         if (DependentTemplateName *DepTemplate
    279                                     = SpecName.getAsDependentTemplateName()) {
    280           if (DepTemplate->isIdentifier() &&
    281               DepTemplate->getIdentifier() == Template->getIdentifier())
    282             return CreateParsedType(
    283                 MemberOfType,
    284                 Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc));
    285 
    286           continue;
    287         }
    288       }
    289     }
    290   }
    291 
    292   if (isDependent) {
    293     // We didn't find our type, but that's okay: it's dependent
    294     // anyway.
    295 
    296     // FIXME: What if we have no nested-name-specifier?
    297     QualType T = CheckTypenameType(ETK_None, SourceLocation(),
    298                                    SS.getWithLocInContext(Context),
    299                                    II, NameLoc);
    300     return ParsedType::make(T);
    301   }
    302 
    303   if (NonMatchingTypeDecl) {
    304     QualType T = Context.getTypeDeclType(NonMatchingTypeDecl);
    305     Diag(NameLoc, diag::err_destructor_expr_type_mismatch)
    306       << T << SearchType;
    307     Diag(NonMatchingTypeDecl->getLocation(), diag::note_destructor_type_here)
    308       << T;
    309   } else if (ObjectTypePtr)
    310     Diag(NameLoc, diag::err_ident_in_dtor_not_a_type)
    311       << &II;
    312   else {
    313     SemaDiagnosticBuilder DtorDiag = Diag(NameLoc,
    314                                           diag::err_destructor_class_name);
    315     if (S) {
    316       const DeclContext *Ctx = S->getEntity();
    317       if (const CXXRecordDecl *Class = dyn_cast_or_null<CXXRecordDecl>(Ctx))
    318         DtorDiag << FixItHint::CreateReplacement(SourceRange(NameLoc),
    319                                                  Class->getNameAsString());
    320     }
    321   }
    322 
    323   return nullptr;
    324 }
    325 
    326 ParsedType Sema::getDestructorType(const DeclSpec& DS, ParsedType ObjectType) {
    327     if (DS.getTypeSpecType() == DeclSpec::TST_error || !ObjectType)
    328       return nullptr;
    329     assert(DS.getTypeSpecType() == DeclSpec::TST_decltype
    330            && "only get destructor types from declspecs");
    331     QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
    332     QualType SearchType = GetTypeFromParser(ObjectType);
    333     if (SearchType->isDependentType() || Context.hasSameUnqualifiedType(SearchType, T)) {
    334       return ParsedType::make(T);
    335     }
    336 
    337     Diag(DS.getTypeSpecTypeLoc(), diag::err_destructor_expr_type_mismatch)
    338       << T << SearchType;
    339     return nullptr;
    340 }
    341 
    342 bool Sema::checkLiteralOperatorId(const CXXScopeSpec &SS,
    343                                   const UnqualifiedId &Name) {
    344   assert(Name.getKind() == UnqualifiedId::IK_LiteralOperatorId);
    345 
    346   if (!SS.isValid())
    347     return false;
    348 
    349   switch (SS.getScopeRep()->getKind()) {
    350   case NestedNameSpecifier::Identifier:
    351   case NestedNameSpecifier::TypeSpec:
    352   case NestedNameSpecifier::TypeSpecWithTemplate:
    353     // Per C++11 [over.literal]p2, literal operators can only be declared at
    354     // namespace scope. Therefore, this unqualified-id cannot name anything.
    355     // Reject it early, because we have no AST representation for this in the
    356     // case where the scope is dependent.
    357     Diag(Name.getLocStart(), diag::err_literal_operator_id_outside_namespace)
    358       << SS.getScopeRep();
    359     return true;
    360 
    361   case NestedNameSpecifier::Global:
    362   case NestedNameSpecifier::Super:
    363   case NestedNameSpecifier::Namespace:
    364   case NestedNameSpecifier::NamespaceAlias:
    365     return false;
    366   }
    367 
    368   llvm_unreachable("unknown nested name specifier kind");
    369 }
    370 
    371 /// \brief Build a C++ typeid expression with a type operand.
    372 ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
    373                                 SourceLocation TypeidLoc,
    374                                 TypeSourceInfo *Operand,
    375                                 SourceLocation RParenLoc) {
    376   // C++ [expr.typeid]p4:
    377   //   The top-level cv-qualifiers of the lvalue expression or the type-id
    378   //   that is the operand of typeid are always ignored.
    379   //   If the type of the type-id is a class type or a reference to a class
    380   //   type, the class shall be completely-defined.
    381   Qualifiers Quals;
    382   QualType T
    383     = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
    384                                       Quals);
    385   if (T->getAs<RecordType>() &&
    386       RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
    387     return ExprError();
    388 
    389   if (T->isVariablyModifiedType())
    390     return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid) << T);
    391 
    392   return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), Operand,
    393                                      SourceRange(TypeidLoc, RParenLoc));
    394 }
    395 
    396 /// \brief Build a C++ typeid expression with an expression operand.
    397 ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
    398                                 SourceLocation TypeidLoc,
    399                                 Expr *E,
    400                                 SourceLocation RParenLoc) {
    401   bool WasEvaluated = false;
    402   if (E && !E->isTypeDependent()) {
    403     if (E->getType()->isPlaceholderType()) {
    404       ExprResult result = CheckPlaceholderExpr(E);
    405       if (result.isInvalid()) return ExprError();
    406       E = result.get();
    407     }
    408 
    409     QualType T = E->getType();
    410     if (const RecordType *RecordT = T->getAs<RecordType>()) {
    411       CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
    412       // C++ [expr.typeid]p3:
    413       //   [...] If the type of the expression is a class type, the class
    414       //   shall be completely-defined.
    415       if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
    416         return ExprError();
    417 
    418       // C++ [expr.typeid]p3:
    419       //   When typeid is applied to an expression other than an glvalue of a
    420       //   polymorphic class type [...] [the] expression is an unevaluated
    421       //   operand. [...]
    422       if (RecordD->isPolymorphic() && E->isGLValue()) {
    423         // The subexpression is potentially evaluated; switch the context
    424         // and recheck the subexpression.
    425         ExprResult Result = TransformToPotentiallyEvaluated(E);
    426         if (Result.isInvalid()) return ExprError();
    427         E = Result.get();
    428 
    429         // We require a vtable to query the type at run time.
    430         MarkVTableUsed(TypeidLoc, RecordD);
    431         WasEvaluated = true;
    432       }
    433     }
    434 
    435     // C++ [expr.typeid]p4:
    436     //   [...] If the type of the type-id is a reference to a possibly
    437     //   cv-qualified type, the result of the typeid expression refers to a
    438     //   std::type_info object representing the cv-unqualified referenced
    439     //   type.
    440     Qualifiers Quals;
    441     QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
    442     if (!Context.hasSameType(T, UnqualT)) {
    443       T = UnqualT;
    444       E = ImpCastExprToType(E, UnqualT, CK_NoOp, E->getValueKind()).get();
    445     }
    446   }
    447 
    448   if (E->getType()->isVariablyModifiedType())
    449     return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid)
    450                      << E->getType());
    451   else if (ActiveTemplateInstantiations.empty() &&
    452            E->HasSideEffects(Context, WasEvaluated)) {
    453     // The expression operand for typeid is in an unevaluated expression
    454     // context, so side effects could result in unintended consequences.
    455     Diag(E->getExprLoc(), WasEvaluated
    456                               ? diag::warn_side_effects_typeid
    457                               : diag::warn_side_effects_unevaluated_context);
    458   }
    459 
    460   return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), E,
    461                                      SourceRange(TypeidLoc, RParenLoc));
    462 }
    463 
    464 /// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
    465 ExprResult
    466 Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
    467                      bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
    468   // Find the std::type_info type.
    469   if (!getStdNamespace())
    470     return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
    471 
    472   if (!CXXTypeInfoDecl) {
    473     IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
    474     LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
    475     LookupQualifiedName(R, getStdNamespace());
    476     CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
    477     // Microsoft's typeinfo doesn't have type_info in std but in the global
    478     // namespace if _HAS_EXCEPTIONS is defined to 0. See PR13153.
    479     if (!CXXTypeInfoDecl && LangOpts.MSVCCompat) {
    480       LookupQualifiedName(R, Context.getTranslationUnitDecl());
    481       CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
    482     }
    483     if (!CXXTypeInfoDecl)
    484       return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
    485   }
    486 
    487   if (!getLangOpts().RTTI) {
    488     return ExprError(Diag(OpLoc, diag::err_no_typeid_with_fno_rtti));
    489   }
    490 
    491   QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl);
    492 
    493   if (isType) {
    494     // The operand is a type; handle it as such.
    495     TypeSourceInfo *TInfo = nullptr;
    496     QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
    497                                    &TInfo);
    498     if (T.isNull())
    499       return ExprError();
    500 
    501     if (!TInfo)
    502       TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
    503 
    504     return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
    505   }
    506 
    507   // The operand is an expression.
    508   return BuildCXXTypeId(TypeInfoType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
    509 }
    510 
    511 /// Grabs __declspec(uuid()) off a type, or returns 0 if we cannot resolve to
    512 /// a single GUID.
    513 static void
    514 getUuidAttrOfType(Sema &SemaRef, QualType QT,
    515                   llvm::SmallSetVector<const UuidAttr *, 1> &UuidAttrs) {
    516   // Optionally remove one level of pointer, reference or array indirection.
    517   const Type *Ty = QT.getTypePtr();
    518   if (QT->isPointerType() || QT->isReferenceType())
    519     Ty = QT->getPointeeType().getTypePtr();
    520   else if (QT->isArrayType())
    521     Ty = Ty->getBaseElementTypeUnsafe();
    522 
    523   const auto *RD = Ty->getAsCXXRecordDecl();
    524   if (!RD)
    525     return;
    526 
    527   if (const auto *Uuid = RD->getMostRecentDecl()->getAttr<UuidAttr>()) {
    528     UuidAttrs.insert(Uuid);
    529     return;
    530   }
    531 
    532   // __uuidof can grab UUIDs from template arguments.
    533   if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
    534     const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
    535     for (const TemplateArgument &TA : TAL.asArray()) {
    536       const UuidAttr *UuidForTA = nullptr;
    537       if (TA.getKind() == TemplateArgument::Type)
    538         getUuidAttrOfType(SemaRef, TA.getAsType(), UuidAttrs);
    539       else if (TA.getKind() == TemplateArgument::Declaration)
    540         getUuidAttrOfType(SemaRef, TA.getAsDecl()->getType(), UuidAttrs);
    541 
    542       if (UuidForTA)
    543         UuidAttrs.insert(UuidForTA);
    544     }
    545   }
    546 }
    547 
    548 /// \brief Build a Microsoft __uuidof expression with a type operand.
    549 ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
    550                                 SourceLocation TypeidLoc,
    551                                 TypeSourceInfo *Operand,
    552                                 SourceLocation RParenLoc) {
    553   StringRef UuidStr;
    554   if (!Operand->getType()->isDependentType()) {
    555     llvm::SmallSetVector<const UuidAttr *, 1> UuidAttrs;
    556     getUuidAttrOfType(*this, Operand->getType(), UuidAttrs);
    557     if (UuidAttrs.empty())
    558       return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
    559     if (UuidAttrs.size() > 1)
    560       return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
    561     UuidStr = UuidAttrs.back()->getGuid();
    562   }
    563 
    564   return new (Context) CXXUuidofExpr(TypeInfoType.withConst(), Operand, UuidStr,
    565                                      SourceRange(TypeidLoc, RParenLoc));
    566 }
    567 
    568 /// \brief Build a Microsoft __uuidof expression with an expression operand.
    569 ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
    570                                 SourceLocation TypeidLoc,
    571                                 Expr *E,
    572                                 SourceLocation RParenLoc) {
    573   StringRef UuidStr;
    574   if (!E->getType()->isDependentType()) {
    575     if (E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
    576       UuidStr = "00000000-0000-0000-0000-000000000000";
    577     } else {
    578       llvm::SmallSetVector<const UuidAttr *, 1> UuidAttrs;
    579       getUuidAttrOfType(*this, E->getType(), UuidAttrs);
    580       if (UuidAttrs.empty())
    581         return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
    582       if (UuidAttrs.size() > 1)
    583         return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
    584       UuidStr = UuidAttrs.back()->getGuid();
    585     }
    586   }
    587 
    588   return new (Context) CXXUuidofExpr(TypeInfoType.withConst(), E, UuidStr,
    589                                      SourceRange(TypeidLoc, RParenLoc));
    590 }
    591 
    592 /// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression);
    593 ExprResult
    594 Sema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc,
    595                      bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
    596   // If MSVCGuidDecl has not been cached, do the lookup.
    597   if (!MSVCGuidDecl) {
    598     IdentifierInfo *GuidII = &PP.getIdentifierTable().get("_GUID");
    599     LookupResult R(*this, GuidII, SourceLocation(), LookupTagName);
    600     LookupQualifiedName(R, Context.getTranslationUnitDecl());
    601     MSVCGuidDecl = R.getAsSingle<RecordDecl>();
    602     if (!MSVCGuidDecl)
    603       return ExprError(Diag(OpLoc, diag::err_need_header_before_ms_uuidof));
    604   }
    605 
    606   QualType GuidType = Context.getTypeDeclType(MSVCGuidDecl);
    607 
    608   if (isType) {
    609     // The operand is a type; handle it as such.
    610     TypeSourceInfo *TInfo = nullptr;
    611     QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
    612                                    &TInfo);
    613     if (T.isNull())
    614       return ExprError();
    615 
    616     if (!TInfo)
    617       TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
    618 
    619     return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc);
    620   }
    621 
    622   // The operand is an expression.
    623   return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
    624 }
    625 
    626 /// ActOnCXXBoolLiteral - Parse {true,false} literals.
    627 ExprResult
    628 Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
    629   assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
    630          "Unknown C++ Boolean value!");
    631   return new (Context)
    632       CXXBoolLiteralExpr(Kind == tok::kw_true, Context.BoolTy, OpLoc);
    633 }
    634 
    635 /// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
    636 ExprResult
    637 Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
    638   return new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
    639 }
    640 
    641 /// ActOnCXXThrow - Parse throw expressions.
    642 ExprResult
    643 Sema::ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *Ex) {
    644   bool IsThrownVarInScope = false;
    645   if (Ex) {
    646     // C++0x [class.copymove]p31:
    647     //   When certain criteria are met, an implementation is allowed to omit the
    648     //   copy/move construction of a class object [...]
    649     //
    650     //     - in a throw-expression, when the operand is the name of a
    651     //       non-volatile automatic object (other than a function or catch-
    652     //       clause parameter) whose scope does not extend beyond the end of the
    653     //       innermost enclosing try-block (if there is one), the copy/move
    654     //       operation from the operand to the exception object (15.1) can be
    655     //       omitted by constructing the automatic object directly into the
    656     //       exception object
    657     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Ex->IgnoreParens()))
    658       if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
    659         if (Var->hasLocalStorage() && !Var->getType().isVolatileQualified()) {
    660           for( ; S; S = S->getParent()) {
    661             if (S->isDeclScope(Var)) {
    662               IsThrownVarInScope = true;
    663               break;
    664             }
    665 
    666             if (S->getFlags() &
    667                 (Scope::FnScope | Scope::ClassScope | Scope::BlockScope |
    668                  Scope::FunctionPrototypeScope | Scope::ObjCMethodScope |
    669                  Scope::TryScope))
    670               break;
    671           }
    672         }
    673       }
    674   }
    675 
    676   return BuildCXXThrow(OpLoc, Ex, IsThrownVarInScope);
    677 }
    678 
    679 ExprResult Sema::BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
    680                                bool IsThrownVarInScope) {
    681   // Don't report an error if 'throw' is used in system headers.
    682   if (!getLangOpts().CXXExceptions &&
    683       !getSourceManager().isInSystemHeader(OpLoc))
    684     Diag(OpLoc, diag::err_exceptions_disabled) << "throw";
    685 
    686   if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
    687     Diag(OpLoc, diag::err_omp_simd_region_cannot_use_stmt) << "throw";
    688 
    689   if (Ex && !Ex->isTypeDependent()) {
    690     QualType ExceptionObjectTy = Context.getExceptionObjectType(Ex->getType());
    691     if (CheckCXXThrowOperand(OpLoc, ExceptionObjectTy, Ex))
    692       return ExprError();
    693 
    694     // Initialize the exception result.  This implicitly weeds out
    695     // abstract types or types with inaccessible copy constructors.
    696 
    697     // C++0x [class.copymove]p31:
    698     //   When certain criteria are met, an implementation is allowed to omit the
    699     //   copy/move construction of a class object [...]
    700     //
    701     //     - in a throw-expression, when the operand is the name of a
    702     //       non-volatile automatic object (other than a function or
    703     //       catch-clause
    704     //       parameter) whose scope does not extend beyond the end of the
    705     //       innermost enclosing try-block (if there is one), the copy/move
    706     //       operation from the operand to the exception object (15.1) can be
    707     //       omitted by constructing the automatic object directly into the
    708     //       exception object
    709     const VarDecl *NRVOVariable = nullptr;
    710     if (IsThrownVarInScope)
    711       NRVOVariable = getCopyElisionCandidate(QualType(), Ex, false);
    712 
    713     InitializedEntity Entity = InitializedEntity::InitializeException(
    714         OpLoc, ExceptionObjectTy,
    715         /*NRVO=*/NRVOVariable != nullptr);
    716     ExprResult Res = PerformMoveOrCopyInitialization(
    717         Entity, NRVOVariable, QualType(), Ex, IsThrownVarInScope);
    718     if (Res.isInvalid())
    719       return ExprError();
    720     Ex = Res.get();
    721   }
    722 
    723   return new (Context)
    724       CXXThrowExpr(Ex, Context.VoidTy, OpLoc, IsThrownVarInScope);
    725 }
    726 
    727 static void
    728 collectPublicBases(CXXRecordDecl *RD,
    729                    llvm::DenseMap<CXXRecordDecl *, unsigned> &SubobjectsSeen,
    730                    llvm::SmallPtrSetImpl<CXXRecordDecl *> &VBases,
    731                    llvm::SetVector<CXXRecordDecl *> &PublicSubobjectsSeen,
    732                    bool ParentIsPublic) {
    733   for (const CXXBaseSpecifier &BS : RD->bases()) {
    734     CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
    735     bool NewSubobject;
    736     // Virtual bases constitute the same subobject.  Non-virtual bases are
    737     // always distinct subobjects.
    738     if (BS.isVirtual())
    739       NewSubobject = VBases.insert(BaseDecl).second;
    740     else
    741       NewSubobject = true;
    742 
    743     if (NewSubobject)
    744       ++SubobjectsSeen[BaseDecl];
    745 
    746     // Only add subobjects which have public access throughout the entire chain.
    747     bool PublicPath = ParentIsPublic && BS.getAccessSpecifier() == AS_public;
    748     if (PublicPath)
    749       PublicSubobjectsSeen.insert(BaseDecl);
    750 
    751     // Recurse on to each base subobject.
    752     collectPublicBases(BaseDecl, SubobjectsSeen, VBases, PublicSubobjectsSeen,
    753                        PublicPath);
    754   }
    755 }
    756 
    757 static void getUnambiguousPublicSubobjects(
    758     CXXRecordDecl *RD, llvm::SmallVectorImpl<CXXRecordDecl *> &Objects) {
    759   llvm::DenseMap<CXXRecordDecl *, unsigned> SubobjectsSeen;
    760   llvm::SmallSet<CXXRecordDecl *, 2> VBases;
    761   llvm::SetVector<CXXRecordDecl *> PublicSubobjectsSeen;
    762   SubobjectsSeen[RD] = 1;
    763   PublicSubobjectsSeen.insert(RD);
    764   collectPublicBases(RD, SubobjectsSeen, VBases, PublicSubobjectsSeen,
    765                      /*ParentIsPublic=*/true);
    766 
    767   for (CXXRecordDecl *PublicSubobject : PublicSubobjectsSeen) {
    768     // Skip ambiguous objects.
    769     if (SubobjectsSeen[PublicSubobject] > 1)
    770       continue;
    771 
    772     Objects.push_back(PublicSubobject);
    773   }
    774 }
    775 
    776 /// CheckCXXThrowOperand - Validate the operand of a throw.
    777 bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc,
    778                                 QualType ExceptionObjectTy, Expr *E) {
    779   //   If the type of the exception would be an incomplete type or a pointer
    780   //   to an incomplete type other than (cv) void the program is ill-formed.
    781   QualType Ty = ExceptionObjectTy;
    782   bool isPointer = false;
    783   if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
    784     Ty = Ptr->getPointeeType();
    785     isPointer = true;
    786   }
    787   if (!isPointer || !Ty->isVoidType()) {
    788     if (RequireCompleteType(ThrowLoc, Ty,
    789                             isPointer ? diag::err_throw_incomplete_ptr
    790                                       : diag::err_throw_incomplete,
    791                             E->getSourceRange()))
    792       return true;
    793 
    794     if (RequireNonAbstractType(ThrowLoc, ExceptionObjectTy,
    795                                diag::err_throw_abstract_type, E))
    796       return true;
    797   }
    798 
    799   // If the exception has class type, we need additional handling.
    800   CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
    801   if (!RD)
    802     return false;
    803 
    804   // If we are throwing a polymorphic class type or pointer thereof,
    805   // exception handling will make use of the vtable.
    806   MarkVTableUsed(ThrowLoc, RD);
    807 
    808   // If a pointer is thrown, the referenced object will not be destroyed.
    809   if (isPointer)
    810     return false;
    811 
    812   // If the class has a destructor, we must be able to call it.
    813   if (!RD->hasIrrelevantDestructor()) {
    814     if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
    815       MarkFunctionReferenced(E->getExprLoc(), Destructor);
    816       CheckDestructorAccess(E->getExprLoc(), Destructor,
    817                             PDiag(diag::err_access_dtor_exception) << Ty);
    818       if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
    819         return true;
    820     }
    821   }
    822 
    823   // The MSVC ABI creates a list of all types which can catch the exception
    824   // object.  This list also references the appropriate copy constructor to call
    825   // if the object is caught by value and has a non-trivial copy constructor.
    826   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
    827     // We are only interested in the public, unambiguous bases contained within
    828     // the exception object.  Bases which are ambiguous or otherwise
    829     // inaccessible are not catchable types.
    830     llvm::SmallVector<CXXRecordDecl *, 2> UnambiguousPublicSubobjects;
    831     getUnambiguousPublicSubobjects(RD, UnambiguousPublicSubobjects);
    832 
    833     for (CXXRecordDecl *Subobject : UnambiguousPublicSubobjects) {
    834       // Attempt to lookup the copy constructor.  Various pieces of machinery
    835       // will spring into action, like template instantiation, which means this
    836       // cannot be a simple walk of the class's decls.  Instead, we must perform
    837       // lookup and overload resolution.
    838       CXXConstructorDecl *CD = LookupCopyingConstructor(Subobject, 0);
    839       if (!CD)
    840         continue;
    841 
    842       // Mark the constructor referenced as it is used by this throw expression.
    843       MarkFunctionReferenced(E->getExprLoc(), CD);
    844 
    845       // Skip this copy constructor if it is trivial, we don't need to record it
    846       // in the catchable type data.
    847       if (CD->isTrivial())
    848         continue;
    849 
    850       // The copy constructor is non-trivial, create a mapping from this class
    851       // type to this constructor.
    852       // N.B.  The selection of copy constructor is not sensitive to this
    853       // particular throw-site.  Lookup will be performed at the catch-site to
    854       // ensure that the copy constructor is, in fact, accessible (via
    855       // friendship or any other means).
    856       Context.addCopyConstructorForExceptionObject(Subobject, CD);
    857 
    858       // We don't keep the instantiated default argument expressions around so
    859       // we must rebuild them here.
    860       for (unsigned I = 1, E = CD->getNumParams(); I != E; ++I) {
    861         // Skip any default arguments that we've already instantiated.
    862         if (Context.getDefaultArgExprForConstructor(CD, I))
    863           continue;
    864 
    865         Expr *DefaultArg =
    866             BuildCXXDefaultArgExpr(ThrowLoc, CD, CD->getParamDecl(I)).get();
    867         Context.addDefaultArgExprForConstructor(CD, I, DefaultArg);
    868       }
    869     }
    870   }
    871 
    872   return false;
    873 }
    874 
    875 static QualType adjustCVQualifiersForCXXThisWithinLambda(
    876     ArrayRef<FunctionScopeInfo *> FunctionScopes, QualType ThisTy,
    877     DeclContext *CurSemaContext, ASTContext &ASTCtx) {
    878 
    879   QualType ClassType = ThisTy->getPointeeType();
    880   LambdaScopeInfo *CurLSI = nullptr;
    881   DeclContext *CurDC = CurSemaContext;
    882 
    883   // Iterate through the stack of lambdas starting from the innermost lambda to
    884   // the outermost lambda, checking if '*this' is ever captured by copy - since
    885   // that could change the cv-qualifiers of the '*this' object.
    886   // The object referred to by '*this' starts out with the cv-qualifiers of its
    887   // member function.  We then start with the innermost lambda and iterate
    888   // outward checking to see if any lambda performs a by-copy capture of '*this'
    889   // - and if so, any nested lambda must respect the 'constness' of that
    890   // capturing lamdbda's call operator.
    891   //
    892 
    893   // The issue is that we cannot rely entirely on the FunctionScopeInfo stack
    894   // since ScopeInfos are pushed on during parsing and treetransforming. But
    895   // since a generic lambda's call operator can be instantiated anywhere (even
    896   // end of the TU) we need to be able to examine its enclosing lambdas and so
    897   // we use the DeclContext to get a hold of the closure-class and query it for
    898   // capture information.  The reason we don't just resort to always using the
    899   // DeclContext chain is that it is only mature for lambda expressions
    900   // enclosing generic lambda's call operators that are being instantiated.
    901 
    902   for (int I = FunctionScopes.size();
    903        I-- && isa<LambdaScopeInfo>(FunctionScopes[I]);
    904        CurDC = getLambdaAwareParentOfDeclContext(CurDC)) {
    905     CurLSI = cast<LambdaScopeInfo>(FunctionScopes[I]);
    906 
    907     if (!CurLSI->isCXXThisCaptured())
    908         continue;
    909 
    910     auto C = CurLSI->getCXXThisCapture();
    911 
    912     if (C.isCopyCapture()) {
    913       ClassType.removeLocalCVRQualifiers(Qualifiers::CVRMask);
    914       if (CurLSI->CallOperator->isConst())
    915         ClassType.addConst();
    916       return ASTCtx.getPointerType(ClassType);
    917     }
    918   }
    919   // We've run out of ScopeInfos but check if CurDC is a lambda (which can
    920   // happen during instantiation of generic lambdas)
    921   if (isLambdaCallOperator(CurDC)) {
    922     assert(CurLSI);
    923     assert(isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator));
    924     assert(CurDC == getLambdaAwareParentOfDeclContext(CurLSI->CallOperator));
    925 
    926     auto IsThisCaptured =
    927         [](CXXRecordDecl *Closure, bool &IsByCopy, bool &IsConst) {
    928       IsConst = false;
    929       IsByCopy = false;
    930       for (auto &&C : Closure->captures()) {
    931         if (C.capturesThis()) {
    932           if (C.getCaptureKind() == LCK_StarThis)
    933             IsByCopy = true;
    934           if (Closure->getLambdaCallOperator()->isConst())
    935             IsConst = true;
    936           return true;
    937         }
    938       }
    939       return false;
    940     };
    941 
    942     bool IsByCopyCapture = false;
    943     bool IsConstCapture = false;
    944     CXXRecordDecl *Closure = cast<CXXRecordDecl>(CurDC->getParent());
    945     while (Closure &&
    946            IsThisCaptured(Closure, IsByCopyCapture, IsConstCapture)) {
    947       if (IsByCopyCapture) {
    948         ClassType.removeLocalCVRQualifiers(Qualifiers::CVRMask);
    949         if (IsConstCapture)
    950           ClassType.addConst();
    951         return ASTCtx.getPointerType(ClassType);
    952       }
    953       Closure = isLambdaCallOperator(Closure->getParent())
    954                     ? cast<CXXRecordDecl>(Closure->getParent()->getParent())
    955                     : nullptr;
    956     }
    957   }
    958   return ASTCtx.getPointerType(ClassType);
    959 }
    960 
    961 QualType Sema::getCurrentThisType() {
    962   DeclContext *DC = getFunctionLevelDeclContext();
    963   QualType ThisTy = CXXThisTypeOverride;
    964   if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC)) {
    965     if (method && method->isInstance())
    966       ThisTy = method->getThisType(Context);
    967   }
    968   if (ThisTy.isNull()) {
    969     if (isGenericLambdaCallOperatorSpecialization(CurContext) &&
    970         CurContext->getParent()->getParent()->isRecord()) {
    971       // This is a generic lambda call operator that is being instantiated
    972       // within a default initializer - so use the enclosing class as 'this'.
    973       // There is no enclosing member function to retrieve the 'this' pointer
    974       // from.
    975 
    976       // FIXME: This looks wrong. If we're in a lambda within a lambda within a
    977       // default member initializer, we need to recurse up more parents to find
    978       // the right context. Looks like we should be walking up to the parent of
    979       // the closure type, checking whether that is itself a lambda, and if so,
    980       // recursing, until we reach a class or a function that isn't a lambda
    981       // call operator. And we should accumulate the constness of *this on the
    982       // way.
    983 
    984       QualType ClassTy = Context.getTypeDeclType(
    985           cast<CXXRecordDecl>(CurContext->getParent()->getParent()));
    986       // There are no cv-qualifiers for 'this' within default initializers,
    987       // per [expr.prim.general]p4.
    988       ThisTy = Context.getPointerType(ClassTy);
    989     }
    990   }
    991 
    992   // If we are within a lambda's call operator, the cv-qualifiers of 'this'
    993   // might need to be adjusted if the lambda or any of its enclosing lambda's
    994   // captures '*this' by copy.
    995   if (!ThisTy.isNull() && isLambdaCallOperator(CurContext))
    996     return adjustCVQualifiersForCXXThisWithinLambda(FunctionScopes, ThisTy,
    997                                                     CurContext, Context);
    998   return ThisTy;
    999 }
   1000 
   1001 Sema::CXXThisScopeRAII::CXXThisScopeRAII(Sema &S,
   1002                                          Decl *ContextDecl,
   1003                                          unsigned CXXThisTypeQuals,
   1004                                          bool Enabled)
   1005   : S(S), OldCXXThisTypeOverride(S.CXXThisTypeOverride), Enabled(false)
   1006 {
   1007   if (!Enabled || !ContextDecl)
   1008     return;
   1009 
   1010   CXXRecordDecl *Record = nullptr;
   1011   if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(ContextDecl))
   1012     Record = Template->getTemplatedDecl();
   1013   else
   1014     Record = cast<CXXRecordDecl>(ContextDecl);
   1015 
   1016   // We care only for CVR qualifiers here, so cut everything else.
   1017   CXXThisTypeQuals &= Qualifiers::FastMask;
   1018   S.CXXThisTypeOverride
   1019     = S.Context.getPointerType(
   1020         S.Context.getRecordType(Record).withCVRQualifiers(CXXThisTypeQuals));
   1021 
   1022   this->Enabled = true;
   1023 }
   1024 
   1025 
   1026 Sema::CXXThisScopeRAII::~CXXThisScopeRAII() {
   1027   if (Enabled) {
   1028     S.CXXThisTypeOverride = OldCXXThisTypeOverride;
   1029   }
   1030 }
   1031 
   1032 static Expr *captureThis(Sema &S, ASTContext &Context, RecordDecl *RD,
   1033                          QualType ThisTy, SourceLocation Loc,
   1034                          const bool ByCopy) {
   1035 
   1036   QualType AdjustedThisTy = ThisTy;
   1037   // The type of the corresponding data member (not a 'this' pointer if 'by
   1038   // copy').
   1039   QualType CaptureThisFieldTy = ThisTy;
   1040   if (ByCopy) {
   1041     // If we are capturing the object referred to by '*this' by copy, ignore any
   1042     // cv qualifiers inherited from the type of the member function for the type
   1043     // of the closure-type's corresponding data member and any use of 'this'.
   1044     CaptureThisFieldTy = ThisTy->getPointeeType();
   1045     CaptureThisFieldTy.removeLocalCVRQualifiers(Qualifiers::CVRMask);
   1046     AdjustedThisTy = Context.getPointerType(CaptureThisFieldTy);
   1047   }
   1048 
   1049   FieldDecl *Field = FieldDecl::Create(
   1050       Context, RD, Loc, Loc, nullptr, CaptureThisFieldTy,
   1051       Context.getTrivialTypeSourceInfo(CaptureThisFieldTy, Loc), nullptr, false,
   1052       ICIS_NoInit);
   1053 
   1054   Field->setImplicit(true);
   1055   Field->setAccess(AS_private);
   1056   RD->addDecl(Field);
   1057   Expr *This =
   1058       new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit*/ true);
   1059   if (ByCopy) {
   1060     Expr *StarThis =  S.CreateBuiltinUnaryOp(Loc,
   1061                                       UO_Deref,
   1062                                       This).get();
   1063     InitializedEntity Entity = InitializedEntity::InitializeLambdaCapture(
   1064       nullptr, CaptureThisFieldTy, Loc);
   1065     InitializationKind InitKind = InitializationKind::CreateDirect(Loc, Loc, Loc);
   1066     InitializationSequence Init(S, Entity, InitKind, StarThis);
   1067     ExprResult ER = Init.Perform(S, Entity, InitKind, StarThis);
   1068     if (ER.isInvalid()) return nullptr;
   1069     return ER.get();
   1070   }
   1071   return This;
   1072 }
   1073 
   1074 bool Sema::CheckCXXThisCapture(SourceLocation Loc, const bool Explicit,
   1075     bool BuildAndDiagnose, const unsigned *const FunctionScopeIndexToStopAt,
   1076     const bool ByCopy) {
   1077   // We don't need to capture this in an unevaluated context.
   1078   if (isUnevaluatedContext() && !Explicit)
   1079     return true;
   1080 
   1081   assert((!ByCopy || Explicit) && "cannot implicitly capture *this by value");
   1082 
   1083   const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt ?
   1084     *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
   1085 
   1086   // Check that we can capture the *enclosing object* (referred to by '*this')
   1087   // by the capturing-entity/closure (lambda/block/etc) at
   1088   // MaxFunctionScopesIndex-deep on the FunctionScopes stack.
   1089 
   1090   // Note: The *enclosing object* can only be captured by-value by a
   1091   // closure that is a lambda, using the explicit notation:
   1092   //    [*this] { ... }.
   1093   // Every other capture of the *enclosing object* results in its by-reference
   1094   // capture.
   1095 
   1096   // For a closure 'L' (at MaxFunctionScopesIndex in the FunctionScopes
   1097   // stack), we can capture the *enclosing object* only if:
   1098   // - 'L' has an explicit byref or byval capture of the *enclosing object*
   1099   // -  or, 'L' has an implicit capture.
   1100   // AND
   1101   //   -- there is no enclosing closure
   1102   //   -- or, there is some enclosing closure 'E' that has already captured the
   1103   //      *enclosing object*, and every intervening closure (if any) between 'E'
   1104   //      and 'L' can implicitly capture the *enclosing object*.
   1105   //   -- or, every enclosing closure can implicitly capture the
   1106   //      *enclosing object*
   1107 
   1108 
   1109   unsigned NumCapturingClosures = 0;
   1110   for (unsigned idx = MaxFunctionScopesIndex; idx != 0; idx--) {
   1111     if (CapturingScopeInfo *CSI =
   1112             dyn_cast<CapturingScopeInfo>(FunctionScopes[idx])) {
   1113       if (CSI->CXXThisCaptureIndex != 0) {
   1114         // 'this' is already being captured; there isn't anything more to do.
   1115         break;
   1116       }
   1117       LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI);
   1118       if (LSI && isGenericLambdaCallOperatorSpecialization(LSI->CallOperator)) {
   1119         // This context can't implicitly capture 'this'; fail out.
   1120         if (BuildAndDiagnose)
   1121           Diag(Loc, diag::err_this_capture)
   1122               << (Explicit && idx == MaxFunctionScopesIndex);
   1123         return true;
   1124       }
   1125       if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByref ||
   1126           CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval ||
   1127           CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_Block ||
   1128           CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_CapturedRegion ||
   1129           (Explicit && idx == MaxFunctionScopesIndex)) {
   1130         // Regarding (Explicit && idx == MaxFunctionScopesIndex): only the first
   1131         // iteration through can be an explicit capture, all enclosing closures,
   1132         // if any, must perform implicit captures.
   1133 
   1134         // This closure can capture 'this'; continue looking upwards.
   1135         NumCapturingClosures++;
   1136         continue;
   1137       }
   1138       // This context can't implicitly capture 'this'; fail out.
   1139       if (BuildAndDiagnose)
   1140         Diag(Loc, diag::err_this_capture)
   1141             << (Explicit && idx == MaxFunctionScopesIndex);
   1142       return true;
   1143     }
   1144     break;
   1145   }
   1146   if (!BuildAndDiagnose) return false;
   1147 
   1148   // If we got here, then the closure at MaxFunctionScopesIndex on the
   1149   // FunctionScopes stack, can capture the *enclosing object*, so capture it
   1150   // (including implicit by-reference captures in any enclosing closures).
   1151 
   1152   // In the loop below, respect the ByCopy flag only for the closure requesting
   1153   // the capture (i.e. first iteration through the loop below).  Ignore it for
   1154   // all enclosing closure's upto NumCapturingClosures (since they must be
   1155   // implicitly capturing the *enclosing  object* by reference (see loop
   1156   // above)).
   1157   assert((!ByCopy ||
   1158           dyn_cast<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) &&
   1159          "Only a lambda can capture the enclosing object (referred to by "
   1160          "*this) by copy");
   1161   // FIXME: We need to delay this marking in PotentiallyPotentiallyEvaluated
   1162   // contexts.
   1163   QualType ThisTy = getCurrentThisType();
   1164   for (unsigned idx = MaxFunctionScopesIndex; NumCapturingClosures;
   1165       --idx, --NumCapturingClosures) {
   1166     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[idx]);
   1167     Expr *ThisExpr = nullptr;
   1168 
   1169     if (LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
   1170       // For lambda expressions, build a field and an initializing expression,
   1171       // and capture the *enclosing object* by copy only if this is the first
   1172       // iteration.
   1173       ThisExpr = captureThis(*this, Context, LSI->Lambda, ThisTy, Loc,
   1174                              ByCopy && idx == MaxFunctionScopesIndex);
   1175 
   1176     } else if (CapturedRegionScopeInfo *RSI
   1177         = dyn_cast<CapturedRegionScopeInfo>(FunctionScopes[idx]))
   1178       ThisExpr =
   1179           captureThis(*this, Context, RSI->TheRecordDecl, ThisTy, Loc,
   1180                       false/*ByCopy*/);
   1181 
   1182     bool isNested = NumCapturingClosures > 1;
   1183     CSI->addThisCapture(isNested, Loc, ThisExpr, ByCopy);
   1184   }
   1185   return false;
   1186 }
   1187 
   1188 ExprResult Sema::ActOnCXXThis(SourceLocation Loc) {
   1189   /// C++ 9.3.2: In the body of a non-static member function, the keyword this
   1190   /// is a non-lvalue expression whose value is the address of the object for
   1191   /// which the function is called.
   1192 
   1193   QualType ThisTy = getCurrentThisType();
   1194   if (ThisTy.isNull()) return Diag(Loc, diag::err_invalid_this_use);
   1195 
   1196   CheckCXXThisCapture(Loc);
   1197   return new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit=*/false);
   1198 }
   1199 
   1200 bool Sema::isThisOutsideMemberFunctionBody(QualType BaseType) {
   1201   // If we're outside the body of a member function, then we'll have a specified
   1202   // type for 'this'.
   1203   if (CXXThisTypeOverride.isNull())
   1204     return false;
   1205 
   1206   // Determine whether we're looking into a class that's currently being
   1207   // defined.
   1208   CXXRecordDecl *Class = BaseType->getAsCXXRecordDecl();
   1209   return Class && Class->isBeingDefined();
   1210 }
   1211 
   1212 ExprResult
   1213 Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep,
   1214                                 SourceLocation LParenLoc,
   1215                                 MultiExprArg exprs,
   1216                                 SourceLocation RParenLoc) {
   1217   if (!TypeRep)
   1218     return ExprError();
   1219 
   1220   TypeSourceInfo *TInfo;
   1221   QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
   1222   if (!TInfo)
   1223     TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
   1224 
   1225   auto Result = BuildCXXTypeConstructExpr(TInfo, LParenLoc, exprs, RParenLoc);
   1226   // Avoid creating a non-type-dependent expression that contains typos.
   1227   // Non-type-dependent expressions are liable to be discarded without
   1228   // checking for embedded typos.
   1229   if (!Result.isInvalid() && Result.get()->isInstantiationDependent() &&
   1230       !Result.get()->isTypeDependent())
   1231     Result = CorrectDelayedTyposInExpr(Result.get());
   1232   return Result;
   1233 }
   1234 
   1235 /// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
   1236 /// Can be interpreted either as function-style casting ("int(x)")
   1237 /// or class type construction ("ClassType(x,y,z)")
   1238 /// or creation of a value-initialized type ("int()").
   1239 ExprResult
   1240 Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo,
   1241                                 SourceLocation LParenLoc,
   1242                                 MultiExprArg Exprs,
   1243                                 SourceLocation RParenLoc) {
   1244   QualType Ty = TInfo->getType();
   1245   SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
   1246 
   1247   if (Ty->isDependentType() || CallExpr::hasAnyTypeDependentArguments(Exprs)) {
   1248     return CXXUnresolvedConstructExpr::Create(Context, TInfo, LParenLoc, Exprs,
   1249                                               RParenLoc);
   1250   }
   1251 
   1252   bool ListInitialization = LParenLoc.isInvalid();
   1253   assert((!ListInitialization || (Exprs.size() == 1 && isa<InitListExpr>(Exprs[0])))
   1254          && "List initialization must have initializer list as expression.");
   1255   SourceRange FullRange = SourceRange(TyBeginLoc,
   1256       ListInitialization ? Exprs[0]->getSourceRange().getEnd() : RParenLoc);
   1257 
   1258   // C++ [expr.type.conv]p1:
   1259   // If the expression list is a single expression, the type conversion
   1260   // expression is equivalent (in definedness, and if defined in meaning) to the
   1261   // corresponding cast expression.
   1262   if (Exprs.size() == 1 && !ListInitialization) {
   1263     Expr *Arg = Exprs[0];
   1264     return BuildCXXFunctionalCastExpr(TInfo, LParenLoc, Arg, RParenLoc);
   1265   }
   1266 
   1267   // C++14 [expr.type.conv]p2: The expression T(), where T is a
   1268   //   simple-type-specifier or typename-specifier for a non-array complete
   1269   //   object type or the (possibly cv-qualified) void type, creates a prvalue
   1270   //   of the specified type, whose value is that produced by value-initializing
   1271   //   an object of type T.
   1272   QualType ElemTy = Ty;
   1273   if (Ty->isArrayType()) {
   1274     if (!ListInitialization)
   1275       return ExprError(Diag(TyBeginLoc,
   1276                             diag::err_value_init_for_array_type) << FullRange);
   1277     ElemTy = Context.getBaseElementType(Ty);
   1278   }
   1279 
   1280   if (!ListInitialization && Ty->isFunctionType())
   1281     return ExprError(Diag(TyBeginLoc, diag::err_value_init_for_function_type)
   1282                      << FullRange);
   1283 
   1284   if (!Ty->isVoidType() &&
   1285       RequireCompleteType(TyBeginLoc, ElemTy,
   1286                           diag::err_invalid_incomplete_type_use, FullRange))
   1287     return ExprError();
   1288 
   1289   if (RequireNonAbstractType(TyBeginLoc, Ty,
   1290                              diag::err_allocation_of_abstract_type))
   1291     return ExprError();
   1292 
   1293   InitializedEntity Entity = InitializedEntity::InitializeTemporary(TInfo);
   1294   InitializationKind Kind =
   1295       Exprs.size() ? ListInitialization
   1296       ? InitializationKind::CreateDirectList(TyBeginLoc)
   1297       : InitializationKind::CreateDirect(TyBeginLoc, LParenLoc, RParenLoc)
   1298       : InitializationKind::CreateValue(TyBeginLoc, LParenLoc, RParenLoc);
   1299   InitializationSequence InitSeq(*this, Entity, Kind, Exprs);
   1300   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Exprs);
   1301 
   1302   if (Result.isInvalid() || !ListInitialization)
   1303     return Result;
   1304 
   1305   Expr *Inner = Result.get();
   1306   if (CXXBindTemporaryExpr *BTE = dyn_cast_or_null<CXXBindTemporaryExpr>(Inner))
   1307     Inner = BTE->getSubExpr();
   1308   if (!isa<CXXTemporaryObjectExpr>(Inner)) {
   1309     // If we created a CXXTemporaryObjectExpr, that node also represents the
   1310     // functional cast. Otherwise, create an explicit cast to represent
   1311     // the syntactic form of a functional-style cast that was used here.
   1312     //
   1313     // FIXME: Creating a CXXFunctionalCastExpr around a CXXConstructExpr
   1314     // would give a more consistent AST representation than using a
   1315     // CXXTemporaryObjectExpr. It's also weird that the functional cast
   1316     // is sometimes handled by initialization and sometimes not.
   1317     QualType ResultType = Result.get()->getType();
   1318     Result = CXXFunctionalCastExpr::Create(
   1319         Context, ResultType, Expr::getValueKindForType(TInfo->getType()), TInfo,
   1320         CK_NoOp, Result.get(), /*Path=*/nullptr, LParenLoc, RParenLoc);
   1321   }
   1322 
   1323   return Result;
   1324 }
   1325 
   1326 /// doesUsualArrayDeleteWantSize - Answers whether the usual
   1327 /// operator delete[] for the given type has a size_t parameter.
   1328 static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc,
   1329                                          QualType allocType) {
   1330   const RecordType *record =
   1331     allocType->getBaseElementTypeUnsafe()->getAs<RecordType>();
   1332   if (!record) return false;
   1333 
   1334   // Try to find an operator delete[] in class scope.
   1335 
   1336   DeclarationName deleteName =
   1337     S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
   1338   LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
   1339   S.LookupQualifiedName(ops, record->getDecl());
   1340 
   1341   // We're just doing this for information.
   1342   ops.suppressDiagnostics();
   1343 
   1344   // Very likely: there's no operator delete[].
   1345   if (ops.empty()) return false;
   1346 
   1347   // If it's ambiguous, it should be illegal to call operator delete[]
   1348   // on this thing, so it doesn't matter if we allocate extra space or not.
   1349   if (ops.isAmbiguous()) return false;
   1350 
   1351   LookupResult::Filter filter = ops.makeFilter();
   1352   while (filter.hasNext()) {
   1353     NamedDecl *del = filter.next()->getUnderlyingDecl();
   1354 
   1355     // C++0x [basic.stc.dynamic.deallocation]p2:
   1356     //   A template instance is never a usual deallocation function,
   1357     //   regardless of its signature.
   1358     if (isa<FunctionTemplateDecl>(del)) {
   1359       filter.erase();
   1360       continue;
   1361     }
   1362 
   1363     // C++0x [basic.stc.dynamic.deallocation]p2:
   1364     //   If class T does not declare [an operator delete[] with one
   1365     //   parameter] but does declare a member deallocation function
   1366     //   named operator delete[] with exactly two parameters, the
   1367     //   second of which has type std::size_t, then this function
   1368     //   is a usual deallocation function.
   1369     if (!cast<CXXMethodDecl>(del)->isUsualDeallocationFunction()) {
   1370       filter.erase();
   1371       continue;
   1372     }
   1373   }
   1374   filter.done();
   1375 
   1376   if (!ops.isSingleResult()) return false;
   1377 
   1378   const FunctionDecl *del = cast<FunctionDecl>(ops.getFoundDecl());
   1379   return (del->getNumParams() == 2);
   1380 }
   1381 
   1382 /// \brief Parsed a C++ 'new' expression (C++ 5.3.4).
   1383 ///
   1384 /// E.g.:
   1385 /// @code new (memory) int[size][4] @endcode
   1386 /// or
   1387 /// @code ::new Foo(23, "hello") @endcode
   1388 ///
   1389 /// \param StartLoc The first location of the expression.
   1390 /// \param UseGlobal True if 'new' was prefixed with '::'.
   1391 /// \param PlacementLParen Opening paren of the placement arguments.
   1392 /// \param PlacementArgs Placement new arguments.
   1393 /// \param PlacementRParen Closing paren of the placement arguments.
   1394 /// \param TypeIdParens If the type is in parens, the source range.
   1395 /// \param D The type to be allocated, as well as array dimensions.
   1396 /// \param Initializer The initializing expression or initializer-list, or null
   1397 ///   if there is none.
   1398 ExprResult
   1399 Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
   1400                   SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
   1401                   SourceLocation PlacementRParen, SourceRange TypeIdParens,
   1402                   Declarator &D, Expr *Initializer) {
   1403   bool TypeContainsAuto = D.getDeclSpec().containsPlaceholderType();
   1404 
   1405   Expr *ArraySize = nullptr;
   1406   // If the specified type is an array, unwrap it and save the expression.
   1407   if (D.getNumTypeObjects() > 0 &&
   1408       D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
   1409      DeclaratorChunk &Chunk = D.getTypeObject(0);
   1410     if (TypeContainsAuto)
   1411       return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto)
   1412         << D.getSourceRange());
   1413     if (Chunk.Arr.hasStatic)
   1414       return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
   1415         << D.getSourceRange());
   1416     if (!Chunk.Arr.NumElts)
   1417       return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
   1418         << D.getSourceRange());
   1419 
   1420     ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
   1421     D.DropFirstTypeObject();
   1422   }
   1423 
   1424   // Every dimension shall be of constant size.
   1425   if (ArraySize) {
   1426     for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
   1427       if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
   1428         break;
   1429 
   1430       DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
   1431       if (Expr *NumElts = (Expr *)Array.NumElts) {
   1432         if (!NumElts->isTypeDependent() && !NumElts->isValueDependent()) {
   1433           if (getLangOpts().CPlusPlus14) {
   1434 	    // C++1y [expr.new]p6: Every constant-expression in a noptr-new-declarator
   1435 	    //   shall be a converted constant expression (5.19) of type std::size_t
   1436 	    //   and shall evaluate to a strictly positive value.
   1437             unsigned IntWidth = Context.getTargetInfo().getIntWidth();
   1438             assert(IntWidth && "Builtin type of size 0?");
   1439             llvm::APSInt Value(IntWidth);
   1440             Array.NumElts
   1441              = CheckConvertedConstantExpression(NumElts, Context.getSizeType(), Value,
   1442                                                 CCEK_NewExpr)
   1443                  .get();
   1444           } else {
   1445             Array.NumElts
   1446               = VerifyIntegerConstantExpression(NumElts, nullptr,
   1447                                                 diag::err_new_array_nonconst)
   1448                   .get();
   1449           }
   1450           if (!Array.NumElts)
   1451             return ExprError();
   1452         }
   1453       }
   1454     }
   1455   }
   1456 
   1457   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/nullptr);
   1458   QualType AllocType = TInfo->getType();
   1459   if (D.isInvalidType())
   1460     return ExprError();
   1461 
   1462   SourceRange DirectInitRange;
   1463   if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer))
   1464     DirectInitRange = List->getSourceRange();
   1465 
   1466   return BuildCXXNew(SourceRange(StartLoc, D.getLocEnd()), UseGlobal,
   1467                      PlacementLParen,
   1468                      PlacementArgs,
   1469                      PlacementRParen,
   1470                      TypeIdParens,
   1471                      AllocType,
   1472                      TInfo,
   1473                      ArraySize,
   1474                      DirectInitRange,
   1475                      Initializer,
   1476                      TypeContainsAuto);
   1477 }
   1478 
   1479 static bool isLegalArrayNewInitializer(CXXNewExpr::InitializationStyle Style,
   1480                                        Expr *Init) {
   1481   if (!Init)
   1482     return true;
   1483   if (ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init))
   1484     return PLE->getNumExprs() == 0;
   1485   if (isa<ImplicitValueInitExpr>(Init))
   1486     return true;
   1487   else if (CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init))
   1488     return !CCE->isListInitialization() &&
   1489            CCE->getConstructor()->isDefaultConstructor();
   1490   else if (Style == CXXNewExpr::ListInit) {
   1491     assert(isa<InitListExpr>(Init) &&
   1492            "Shouldn't create list CXXConstructExprs for arrays.");
   1493     return true;
   1494   }
   1495   return false;
   1496 }
   1497 
   1498 ExprResult
   1499 Sema::BuildCXXNew(SourceRange Range, bool UseGlobal,
   1500                   SourceLocation PlacementLParen,
   1501                   MultiExprArg PlacementArgs,
   1502                   SourceLocation PlacementRParen,
   1503                   SourceRange TypeIdParens,
   1504                   QualType AllocType,
   1505                   TypeSourceInfo *AllocTypeInfo,
   1506                   Expr *ArraySize,
   1507                   SourceRange DirectInitRange,
   1508                   Expr *Initializer,
   1509                   bool TypeMayContainAuto) {
   1510   SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
   1511   SourceLocation StartLoc = Range.getBegin();
   1512 
   1513   CXXNewExpr::InitializationStyle initStyle;
   1514   if (DirectInitRange.isValid()) {
   1515     assert(Initializer && "Have parens but no initializer.");
   1516     initStyle = CXXNewExpr::CallInit;
   1517   } else if (Initializer && isa<InitListExpr>(Initializer))
   1518     initStyle = CXXNewExpr::ListInit;
   1519   else {
   1520     assert((!Initializer || isa<ImplicitValueInitExpr>(Initializer) ||
   1521             isa<CXXConstructExpr>(Initializer)) &&
   1522            "Initializer expression that cannot have been implicitly created.");
   1523     initStyle = CXXNewExpr::NoInit;
   1524   }
   1525 
   1526   Expr **Inits = &Initializer;
   1527   unsigned NumInits = Initializer ? 1 : 0;
   1528   if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer)) {
   1529     assert(initStyle == CXXNewExpr::CallInit && "paren init for non-call init");
   1530     Inits = List->getExprs();
   1531     NumInits = List->getNumExprs();
   1532   }
   1533 
   1534   // C++11 [dcl.spec.auto]p6. Deduce the type which 'auto' stands in for.
   1535   if (TypeMayContainAuto && AllocType->isUndeducedType()) {
   1536     if (initStyle == CXXNewExpr::NoInit || NumInits == 0)
   1537       return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg)
   1538                        << AllocType << TypeRange);
   1539     if (initStyle == CXXNewExpr::ListInit ||
   1540         (NumInits == 1 && isa<InitListExpr>(Inits[0])))
   1541       return ExprError(Diag(Inits[0]->getLocStart(),
   1542                             diag::err_auto_new_list_init)
   1543                        << AllocType << TypeRange);
   1544     if (NumInits > 1) {
   1545       Expr *FirstBad = Inits[1];
   1546       return ExprError(Diag(FirstBad->getLocStart(),
   1547                             diag::err_auto_new_ctor_multiple_expressions)
   1548                        << AllocType << TypeRange);
   1549     }
   1550     Expr *Deduce = Inits[0];
   1551     QualType DeducedType;
   1552     if (DeduceAutoType(AllocTypeInfo, Deduce, DeducedType) == DAR_Failed)
   1553       return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure)
   1554                        << AllocType << Deduce->getType()
   1555                        << TypeRange << Deduce->getSourceRange());
   1556     if (DeducedType.isNull())
   1557       return ExprError();
   1558     AllocType = DeducedType;
   1559   }
   1560 
   1561   // Per C++0x [expr.new]p5, the type being constructed may be a
   1562   // typedef of an array type.
   1563   if (!ArraySize) {
   1564     if (const ConstantArrayType *Array
   1565                               = Context.getAsConstantArrayType(AllocType)) {
   1566       ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
   1567                                          Context.getSizeType(),
   1568                                          TypeRange.getEnd());
   1569       AllocType = Array->getElementType();
   1570     }
   1571   }
   1572 
   1573   if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
   1574     return ExprError();
   1575 
   1576   if (initStyle == CXXNewExpr::ListInit &&
   1577       isStdInitializerList(AllocType, nullptr)) {
   1578     Diag(AllocTypeInfo->getTypeLoc().getBeginLoc(),
   1579          diag::warn_dangling_std_initializer_list)
   1580         << /*at end of FE*/0 << Inits[0]->getSourceRange();
   1581   }
   1582 
   1583   // In ARC, infer 'retaining' for the allocated
   1584   if (getLangOpts().ObjCAutoRefCount &&
   1585       AllocType.getObjCLifetime() == Qualifiers::OCL_None &&
   1586       AllocType->isObjCLifetimeType()) {
   1587     AllocType = Context.getLifetimeQualifiedType(AllocType,
   1588                                     AllocType->getObjCARCImplicitLifetime());
   1589   }
   1590 
   1591   QualType ResultType = Context.getPointerType(AllocType);
   1592 
   1593   if (ArraySize && ArraySize->getType()->isNonOverloadPlaceholderType()) {
   1594     ExprResult result = CheckPlaceholderExpr(ArraySize);
   1595     if (result.isInvalid()) return ExprError();
   1596     ArraySize = result.get();
   1597   }
   1598   // C++98 5.3.4p6: "The expression in a direct-new-declarator shall have
   1599   //   integral or enumeration type with a non-negative value."
   1600   // C++11 [expr.new]p6: The expression [...] shall be of integral or unscoped
   1601   //   enumeration type, or a class type for which a single non-explicit
   1602   //   conversion function to integral or unscoped enumeration type exists.
   1603   // C++1y [expr.new]p6: The expression [...] is implicitly converted to
   1604   //   std::size_t.
   1605   if (ArraySize && !ArraySize->isTypeDependent()) {
   1606     ExprResult ConvertedSize;
   1607     if (getLangOpts().CPlusPlus14) {
   1608       assert(Context.getTargetInfo().getIntWidth() && "Builtin type of size 0?");
   1609 
   1610       ConvertedSize = PerformImplicitConversion(ArraySize, Context.getSizeType(),
   1611 						AA_Converting);
   1612 
   1613       if (!ConvertedSize.isInvalid() &&
   1614           ArraySize->getType()->getAs<RecordType>())
   1615         // Diagnose the compatibility of this conversion.
   1616         Diag(StartLoc, diag::warn_cxx98_compat_array_size_conversion)
   1617           << ArraySize->getType() << 0 << "'size_t'";
   1618     } else {
   1619       class SizeConvertDiagnoser : public ICEConvertDiagnoser {
   1620       protected:
   1621         Expr *ArraySize;
   1622 
   1623       public:
   1624         SizeConvertDiagnoser(Expr *ArraySize)
   1625             : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, false, false),
   1626               ArraySize(ArraySize) {}
   1627 
   1628         SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
   1629                                              QualType T) override {
   1630           return S.Diag(Loc, diag::err_array_size_not_integral)
   1631                    << S.getLangOpts().CPlusPlus11 << T;
   1632         }
   1633 
   1634         SemaDiagnosticBuilder diagnoseIncomplete(
   1635             Sema &S, SourceLocation Loc, QualType T) override {
   1636           return S.Diag(Loc, diag::err_array_size_incomplete_type)
   1637                    << T << ArraySize->getSourceRange();
   1638         }
   1639 
   1640         SemaDiagnosticBuilder diagnoseExplicitConv(
   1641             Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
   1642           return S.Diag(Loc, diag::err_array_size_explicit_conversion) << T << ConvTy;
   1643         }
   1644 
   1645         SemaDiagnosticBuilder noteExplicitConv(
   1646             Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
   1647           return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
   1648                    << ConvTy->isEnumeralType() << ConvTy;
   1649         }
   1650 
   1651         SemaDiagnosticBuilder diagnoseAmbiguous(
   1652             Sema &S, SourceLocation Loc, QualType T) override {
   1653           return S.Diag(Loc, diag::err_array_size_ambiguous_conversion) << T;
   1654         }
   1655 
   1656         SemaDiagnosticBuilder noteAmbiguous(
   1657             Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
   1658           return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
   1659                    << ConvTy->isEnumeralType() << ConvTy;
   1660         }
   1661 
   1662         SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
   1663                                                  QualType T,
   1664                                                  QualType ConvTy) override {
   1665           return S.Diag(Loc,
   1666                         S.getLangOpts().CPlusPlus11
   1667                           ? diag::warn_cxx98_compat_array_size_conversion
   1668                           : diag::ext_array_size_conversion)
   1669                    << T << ConvTy->isEnumeralType() << ConvTy;
   1670         }
   1671       } SizeDiagnoser(ArraySize);
   1672 
   1673       ConvertedSize = PerformContextualImplicitConversion(StartLoc, ArraySize,
   1674                                                           SizeDiagnoser);
   1675     }
   1676     if (ConvertedSize.isInvalid())
   1677       return ExprError();
   1678 
   1679     ArraySize = ConvertedSize.get();
   1680     QualType SizeType = ArraySize->getType();
   1681 
   1682     if (!SizeType->isIntegralOrUnscopedEnumerationType())
   1683       return ExprError();
   1684 
   1685     // C++98 [expr.new]p7:
   1686     //   The expression in a direct-new-declarator shall have integral type
   1687     //   with a non-negative value.
   1688     //
   1689     // Let's see if this is a constant < 0. If so, we reject it out of
   1690     // hand. Otherwise, if it's not a constant, we must have an unparenthesized
   1691     // array type.
   1692     //
   1693     // Note: such a construct has well-defined semantics in C++11: it throws
   1694     // std::bad_array_new_length.
   1695     if (!ArraySize->isValueDependent()) {
   1696       llvm::APSInt Value;
   1697       // We've already performed any required implicit conversion to integer or
   1698       // unscoped enumeration type.
   1699       if (ArraySize->isIntegerConstantExpr(Value, Context)) {
   1700         if (Value < llvm::APSInt(
   1701                         llvm::APInt::getNullValue(Value.getBitWidth()),
   1702                                  Value.isUnsigned())) {
   1703           if (getLangOpts().CPlusPlus11)
   1704             Diag(ArraySize->getLocStart(),
   1705                  diag::warn_typecheck_negative_array_new_size)
   1706               << ArraySize->getSourceRange();
   1707           else
   1708             return ExprError(Diag(ArraySize->getLocStart(),
   1709                                   diag::err_typecheck_negative_array_size)
   1710                              << ArraySize->getSourceRange());
   1711         } else if (!AllocType->isDependentType()) {
   1712           unsigned ActiveSizeBits =
   1713             ConstantArrayType::getNumAddressingBits(Context, AllocType, Value);
   1714           if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
   1715             if (getLangOpts().CPlusPlus11)
   1716               Diag(ArraySize->getLocStart(),
   1717                    diag::warn_array_new_too_large)
   1718                 << Value.toString(10)
   1719                 << ArraySize->getSourceRange();
   1720             else
   1721               return ExprError(Diag(ArraySize->getLocStart(),
   1722                                     diag::err_array_too_large)
   1723                                << Value.toString(10)
   1724                                << ArraySize->getSourceRange());
   1725           }
   1726         }
   1727       } else if (TypeIdParens.isValid()) {
   1728         // Can't have dynamic array size when the type-id is in parentheses.
   1729         Diag(ArraySize->getLocStart(), diag::ext_new_paren_array_nonconst)
   1730           << ArraySize->getSourceRange()
   1731           << FixItHint::CreateRemoval(TypeIdParens.getBegin())
   1732           << FixItHint::CreateRemoval(TypeIdParens.getEnd());
   1733 
   1734         TypeIdParens = SourceRange();
   1735       }
   1736     }
   1737 
   1738     // Note that we do *not* convert the argument in any way.  It can
   1739     // be signed, larger than size_t, whatever.
   1740   }
   1741 
   1742   FunctionDecl *OperatorNew = nullptr;
   1743   FunctionDecl *OperatorDelete = nullptr;
   1744 
   1745   if (!AllocType->isDependentType() &&
   1746       !Expr::hasAnyTypeDependentArguments(PlacementArgs) &&
   1747       FindAllocationFunctions(StartLoc,
   1748                               SourceRange(PlacementLParen, PlacementRParen),
   1749                               UseGlobal, AllocType, ArraySize, PlacementArgs,
   1750                               OperatorNew, OperatorDelete))
   1751     return ExprError();
   1752 
   1753   // If this is an array allocation, compute whether the usual array
   1754   // deallocation function for the type has a size_t parameter.
   1755   bool UsualArrayDeleteWantsSize = false;
   1756   if (ArraySize && !AllocType->isDependentType())
   1757     UsualArrayDeleteWantsSize
   1758       = doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);
   1759 
   1760   SmallVector<Expr *, 8> AllPlaceArgs;
   1761   if (OperatorNew) {
   1762     const FunctionProtoType *Proto =
   1763         OperatorNew->getType()->getAs<FunctionProtoType>();
   1764     VariadicCallType CallType = Proto->isVariadic() ? VariadicFunction
   1765                                                     : VariadicDoesNotApply;
   1766 
   1767     // We've already converted the placement args, just fill in any default
   1768     // arguments. Skip the first parameter because we don't have a corresponding
   1769     // argument.
   1770     if (GatherArgumentsForCall(PlacementLParen, OperatorNew, Proto, 1,
   1771                                PlacementArgs, AllPlaceArgs, CallType))
   1772       return ExprError();
   1773 
   1774     if (!AllPlaceArgs.empty())
   1775       PlacementArgs = AllPlaceArgs;
   1776 
   1777     // FIXME: This is wrong: PlacementArgs misses out the first (size) argument.
   1778     DiagnoseSentinelCalls(OperatorNew, PlacementLParen, PlacementArgs);
   1779 
   1780     // FIXME: Missing call to CheckFunctionCall or equivalent
   1781   }
   1782 
   1783   // Warn if the type is over-aligned and is being allocated by global operator
   1784   // new.
   1785   if (PlacementArgs.empty() && OperatorNew &&
   1786       (OperatorNew->isImplicit() ||
   1787        (OperatorNew->getLocStart().isValid() &&
   1788         getSourceManager().isInSystemHeader(OperatorNew->getLocStart())))) {
   1789     if (unsigned Align = Context.getPreferredTypeAlign(AllocType.getTypePtr())){
   1790       unsigned SuitableAlign = Context.getTargetInfo().getSuitableAlign();
   1791       if (Align > SuitableAlign)
   1792         Diag(StartLoc, diag::warn_overaligned_type)
   1793             << AllocType
   1794             << unsigned(Align / Context.getCharWidth())
   1795             << unsigned(SuitableAlign / Context.getCharWidth());
   1796     }
   1797   }
   1798 
   1799   QualType InitType = AllocType;
   1800   // Array 'new' can't have any initializers except empty parentheses.
   1801   // Initializer lists are also allowed, in C++11. Rely on the parser for the
   1802   // dialect distinction.
   1803   if (ResultType->isArrayType() || ArraySize) {
   1804     if (!isLegalArrayNewInitializer(initStyle, Initializer)) {
   1805       SourceRange InitRange(Inits[0]->getLocStart(),
   1806                             Inits[NumInits - 1]->getLocEnd());
   1807       Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
   1808       return ExprError();
   1809     }
   1810     if (InitListExpr *ILE = dyn_cast_or_null<InitListExpr>(Initializer)) {
   1811       // We do the initialization typechecking against the array type
   1812       // corresponding to the number of initializers + 1 (to also check
   1813       // default-initialization).
   1814       unsigned NumElements = ILE->getNumInits() + 1;
   1815       InitType = Context.getConstantArrayType(AllocType,
   1816           llvm::APInt(Context.getTypeSize(Context.getSizeType()), NumElements),
   1817                                               ArrayType::Normal, 0);
   1818     }
   1819   }
   1820 
   1821   // If we can perform the initialization, and we've not already done so,
   1822   // do it now.
   1823   if (!AllocType->isDependentType() &&
   1824       !Expr::hasAnyTypeDependentArguments(
   1825           llvm::makeArrayRef(Inits, NumInits))) {
   1826     // C++11 [expr.new]p15:
   1827     //   A new-expression that creates an object of type T initializes that
   1828     //   object as follows:
   1829     InitializationKind Kind
   1830     //     - If the new-initializer is omitted, the object is default-
   1831     //       initialized (8.5); if no initialization is performed,
   1832     //       the object has indeterminate value
   1833       = initStyle == CXXNewExpr::NoInit
   1834           ? InitializationKind::CreateDefault(TypeRange.getBegin())
   1835     //     - Otherwise, the new-initializer is interpreted according to the
   1836     //       initialization rules of 8.5 for direct-initialization.
   1837           : initStyle == CXXNewExpr::ListInit
   1838               ? InitializationKind::CreateDirectList(TypeRange.getBegin())
   1839               : InitializationKind::CreateDirect(TypeRange.getBegin(),
   1840                                                  DirectInitRange.getBegin(),
   1841                                                  DirectInitRange.getEnd());
   1842 
   1843     InitializedEntity Entity
   1844       = InitializedEntity::InitializeNew(StartLoc, InitType);
   1845     InitializationSequence InitSeq(*this, Entity, Kind, MultiExprArg(Inits, NumInits));
   1846     ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
   1847                                           MultiExprArg(Inits, NumInits));
   1848     if (FullInit.isInvalid())
   1849       return ExprError();
   1850 
   1851     // FullInit is our initializer; strip off CXXBindTemporaryExprs, because
   1852     // we don't want the initialized object to be destructed.
   1853     if (CXXBindTemporaryExpr *Binder =
   1854             dyn_cast_or_null<CXXBindTemporaryExpr>(FullInit.get()))
   1855       FullInit = Binder->getSubExpr();
   1856 
   1857     Initializer = FullInit.get();
   1858   }
   1859 
   1860   // Mark the new and delete operators as referenced.
   1861   if (OperatorNew) {
   1862     if (DiagnoseUseOfDecl(OperatorNew, StartLoc))
   1863       return ExprError();
   1864     MarkFunctionReferenced(StartLoc, OperatorNew);
   1865   }
   1866   if (OperatorDelete) {
   1867     if (DiagnoseUseOfDecl(OperatorDelete, StartLoc))
   1868       return ExprError();
   1869     MarkFunctionReferenced(StartLoc, OperatorDelete);
   1870   }
   1871 
   1872   // C++0x [expr.new]p17:
   1873   //   If the new expression creates an array of objects of class type,
   1874   //   access and ambiguity control are done for the destructor.
   1875   QualType BaseAllocType = Context.getBaseElementType(AllocType);
   1876   if (ArraySize && !BaseAllocType->isDependentType()) {
   1877     if (const RecordType *BaseRecordType = BaseAllocType->getAs<RecordType>()) {
   1878       if (CXXDestructorDecl *dtor = LookupDestructor(
   1879               cast<CXXRecordDecl>(BaseRecordType->getDecl()))) {
   1880         MarkFunctionReferenced(StartLoc, dtor);
   1881         CheckDestructorAccess(StartLoc, dtor,
   1882                               PDiag(diag::err_access_dtor)
   1883                                 << BaseAllocType);
   1884         if (DiagnoseUseOfDecl(dtor, StartLoc))
   1885           return ExprError();
   1886       }
   1887     }
   1888   }
   1889 
   1890   return new (Context)
   1891       CXXNewExpr(Context, UseGlobal, OperatorNew, OperatorDelete,
   1892                  UsualArrayDeleteWantsSize, PlacementArgs, TypeIdParens,
   1893                  ArraySize, initStyle, Initializer, ResultType, AllocTypeInfo,
   1894                  Range, DirectInitRange);
   1895 }
   1896 
   1897 /// \brief Checks that a type is suitable as the allocated type
   1898 /// in a new-expression.
   1899 bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
   1900                               SourceRange R) {
   1901   // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
   1902   //   abstract class type or array thereof.
   1903   if (AllocType->isFunctionType())
   1904     return Diag(Loc, diag::err_bad_new_type)
   1905       << AllocType << 0 << R;
   1906   else if (AllocType->isReferenceType())
   1907     return Diag(Loc, diag::err_bad_new_type)
   1908       << AllocType << 1 << R;
   1909   else if (!AllocType->isDependentType() &&
   1910            RequireCompleteType(Loc, AllocType, diag::err_new_incomplete_type,R))
   1911     return true;
   1912   else if (RequireNonAbstractType(Loc, AllocType,
   1913                                   diag::err_allocation_of_abstract_type))
   1914     return true;
   1915   else if (AllocType->isVariablyModifiedType())
   1916     return Diag(Loc, diag::err_variably_modified_new_type)
   1917              << AllocType;
   1918   else if (unsigned AddressSpace = AllocType.getAddressSpace())
   1919     return Diag(Loc, diag::err_address_space_qualified_new)
   1920       << AllocType.getUnqualifiedType() << AddressSpace;
   1921   else if (getLangOpts().ObjCAutoRefCount) {
   1922     if (const ArrayType *AT = Context.getAsArrayType(AllocType)) {
   1923       QualType BaseAllocType = Context.getBaseElementType(AT);
   1924       if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None &&
   1925           BaseAllocType->isObjCLifetimeType())
   1926         return Diag(Loc, diag::err_arc_new_array_without_ownership)
   1927           << BaseAllocType;
   1928     }
   1929   }
   1930 
   1931   return false;
   1932 }
   1933 
   1934 /// \brief Determine whether the given function is a non-placement
   1935 /// deallocation function.
   1936 static bool isNonPlacementDeallocationFunction(Sema &S, FunctionDecl *FD) {
   1937   if (FD->isInvalidDecl())
   1938     return false;
   1939 
   1940   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
   1941     return Method->isUsualDeallocationFunction();
   1942 
   1943   if (FD->getOverloadedOperator() != OO_Delete &&
   1944       FD->getOverloadedOperator() != OO_Array_Delete)
   1945     return false;
   1946 
   1947   if (FD->getNumParams() == 1)
   1948     return true;
   1949 
   1950   return S.getLangOpts().SizedDeallocation && FD->getNumParams() == 2 &&
   1951          S.Context.hasSameUnqualifiedType(FD->getParamDecl(1)->getType(),
   1952                                           S.Context.getSizeType());
   1953 }
   1954 
   1955 /// FindAllocationFunctions - Finds the overloads of operator new and delete
   1956 /// that are appropriate for the allocation.
   1957 bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
   1958                                    bool UseGlobal, QualType AllocType,
   1959                                    bool IsArray, MultiExprArg PlaceArgs,
   1960                                    FunctionDecl *&OperatorNew,
   1961                                    FunctionDecl *&OperatorDelete) {
   1962   // --- Choosing an allocation function ---
   1963   // C++ 5.3.4p8 - 14 & 18
   1964   // 1) If UseGlobal is true, only look in the global scope. Else, also look
   1965   //   in the scope of the allocated class.
   1966   // 2) If an array size is given, look for operator new[], else look for
   1967   //   operator new.
   1968   // 3) The first argument is always size_t. Append the arguments from the
   1969   //   placement form.
   1970 
   1971   SmallVector<Expr*, 8> AllocArgs(1 + PlaceArgs.size());
   1972   // We don't care about the actual value of this argument.
   1973   // FIXME: Should the Sema create the expression and embed it in the syntax
   1974   // tree? Or should the consumer just recalculate the value?
   1975   IntegerLiteral Size(Context, llvm::APInt::getNullValue(
   1976                       Context.getTargetInfo().getPointerWidth(0)),
   1977                       Context.getSizeType(),
   1978                       SourceLocation());
   1979   AllocArgs[0] = &Size;
   1980   std::copy(PlaceArgs.begin(), PlaceArgs.end(), AllocArgs.begin() + 1);
   1981 
   1982   // C++ [expr.new]p8:
   1983   //   If the allocated type is a non-array type, the allocation
   1984   //   function's name is operator new and the deallocation function's
   1985   //   name is operator delete. If the allocated type is an array
   1986   //   type, the allocation function's name is operator new[] and the
   1987   //   deallocation function's name is operator delete[].
   1988   DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
   1989                                         IsArray ? OO_Array_New : OO_New);
   1990   DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
   1991                                         IsArray ? OO_Array_Delete : OO_Delete);
   1992 
   1993   QualType AllocElemType = Context.getBaseElementType(AllocType);
   1994 
   1995   if (AllocElemType->isRecordType() && !UseGlobal) {
   1996     CXXRecordDecl *Record
   1997       = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
   1998     if (FindAllocationOverload(StartLoc, Range, NewName, AllocArgs, Record,
   1999                                /*AllowMissing=*/true, OperatorNew))
   2000       return true;
   2001   }
   2002 
   2003   if (!OperatorNew) {
   2004     // Didn't find a member overload. Look for a global one.
   2005     DeclareGlobalNewDelete();
   2006     DeclContext *TUDecl = Context.getTranslationUnitDecl();
   2007     bool FallbackEnabled = IsArray && Context.getLangOpts().MSVCCompat;
   2008     if (FindAllocationOverload(StartLoc, Range, NewName, AllocArgs, TUDecl,
   2009                                /*AllowMissing=*/FallbackEnabled, OperatorNew,
   2010                                /*Diagnose=*/!FallbackEnabled)) {
   2011       if (!FallbackEnabled)
   2012         return true;
   2013 
   2014       // MSVC will fall back on trying to find a matching global operator new
   2015       // if operator new[] cannot be found.  Also, MSVC will leak by not
   2016       // generating a call to operator delete or operator delete[], but we
   2017       // will not replicate that bug.
   2018       NewName = Context.DeclarationNames.getCXXOperatorName(OO_New);
   2019       DeleteName = Context.DeclarationNames.getCXXOperatorName(OO_Delete);
   2020       if (FindAllocationOverload(StartLoc, Range, NewName, AllocArgs, TUDecl,
   2021                                /*AllowMissing=*/false, OperatorNew))
   2022       return true;
   2023     }
   2024   }
   2025 
   2026   // We don't need an operator delete if we're running under
   2027   // -fno-exceptions.
   2028   if (!getLangOpts().Exceptions) {
   2029     OperatorDelete = nullptr;
   2030     return false;
   2031   }
   2032 
   2033   // C++ [expr.new]p19:
   2034   //
   2035   //   If the new-expression begins with a unary :: operator, the
   2036   //   deallocation function's name is looked up in the global
   2037   //   scope. Otherwise, if the allocated type is a class type T or an
   2038   //   array thereof, the deallocation function's name is looked up in
   2039   //   the scope of T. If this lookup fails to find the name, or if
   2040   //   the allocated type is not a class type or array thereof, the
   2041   //   deallocation function's name is looked up in the global scope.
   2042   LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
   2043   if (AllocElemType->isRecordType() && !UseGlobal) {
   2044     CXXRecordDecl *RD
   2045       = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
   2046     LookupQualifiedName(FoundDelete, RD);
   2047   }
   2048   if (FoundDelete.isAmbiguous())
   2049     return true; // FIXME: clean up expressions?
   2050 
   2051   if (FoundDelete.empty()) {
   2052     DeclareGlobalNewDelete();
   2053     LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
   2054   }
   2055 
   2056   FoundDelete.suppressDiagnostics();
   2057 
   2058   SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
   2059 
   2060   // Whether we're looking for a placement operator delete is dictated
   2061   // by whether we selected a placement operator new, not by whether
   2062   // we had explicit placement arguments.  This matters for things like
   2063   //   struct A { void *operator new(size_t, int = 0); ... };
   2064   //   A *a = new A()
   2065   bool isPlacementNew = (!PlaceArgs.empty() || OperatorNew->param_size() != 1);
   2066 
   2067   if (isPlacementNew) {
   2068     // C++ [expr.new]p20:
   2069     //   A declaration of a placement deallocation function matches the
   2070     //   declaration of a placement allocation function if it has the
   2071     //   same number of parameters and, after parameter transformations
   2072     //   (8.3.5), all parameter types except the first are
   2073     //   identical. [...]
   2074     //
   2075     // To perform this comparison, we compute the function type that
   2076     // the deallocation function should have, and use that type both
   2077     // for template argument deduction and for comparison purposes.
   2078     //
   2079     // FIXME: this comparison should ignore CC and the like.
   2080     QualType ExpectedFunctionType;
   2081     {
   2082       const FunctionProtoType *Proto
   2083         = OperatorNew->getType()->getAs<FunctionProtoType>();
   2084 
   2085       SmallVector<QualType, 4> ArgTypes;
   2086       ArgTypes.push_back(Context.VoidPtrTy);
   2087       for (unsigned I = 1, N = Proto->getNumParams(); I < N; ++I)
   2088         ArgTypes.push_back(Proto->getParamType(I));
   2089 
   2090       FunctionProtoType::ExtProtoInfo EPI;
   2091       EPI.Variadic = Proto->isVariadic();
   2092 
   2093       ExpectedFunctionType
   2094         = Context.getFunctionType(Context.VoidTy, ArgTypes, EPI);
   2095     }
   2096 
   2097     for (LookupResult::iterator D = FoundDelete.begin(),
   2098                              DEnd = FoundDelete.end();
   2099          D != DEnd; ++D) {
   2100       FunctionDecl *Fn = nullptr;
   2101       if (FunctionTemplateDecl *FnTmpl
   2102             = dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
   2103         // Perform template argument deduction to try to match the
   2104         // expected function type.
   2105         TemplateDeductionInfo Info(StartLoc);
   2106         if (DeduceTemplateArguments(FnTmpl, nullptr, ExpectedFunctionType, Fn,
   2107                                     Info))
   2108           continue;
   2109       } else
   2110         Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
   2111 
   2112       if (Context.hasSameType(Fn->getType(), ExpectedFunctionType))
   2113         Matches.push_back(std::make_pair(D.getPair(), Fn));
   2114     }
   2115   } else {
   2116     // C++ [expr.new]p20:
   2117     //   [...] Any non-placement deallocation function matches a
   2118     //   non-placement allocation function. [...]
   2119     for (LookupResult::iterator D = FoundDelete.begin(),
   2120                              DEnd = FoundDelete.end();
   2121          D != DEnd; ++D) {
   2122       if (FunctionDecl *Fn = dyn_cast<FunctionDecl>((*D)->getUnderlyingDecl()))
   2123         if (isNonPlacementDeallocationFunction(*this, Fn))
   2124           Matches.push_back(std::make_pair(D.getPair(), Fn));
   2125     }
   2126 
   2127     // C++1y [expr.new]p22:
   2128     //   For a non-placement allocation function, the normal deallocation
   2129     //   function lookup is used
   2130     // C++1y [expr.delete]p?:
   2131     //   If [...] deallocation function lookup finds both a usual deallocation
   2132     //   function with only a pointer parameter and a usual deallocation
   2133     //   function with both a pointer parameter and a size parameter, then the
   2134     //   selected deallocation function shall be the one with two parameters.
   2135     //   Otherwise, the selected deallocation function shall be the function
   2136     //   with one parameter.
   2137     if (getLangOpts().SizedDeallocation && Matches.size() == 2) {
   2138       if (Matches[0].second->getNumParams() == 1)
   2139         Matches.erase(Matches.begin());
   2140       else
   2141         Matches.erase(Matches.begin() + 1);
   2142       assert(Matches[0].second->getNumParams() == 2 &&
   2143              "found an unexpected usual deallocation function");
   2144     }
   2145   }
   2146 
   2147   // C++ [expr.new]p20:
   2148   //   [...] If the lookup finds a single matching deallocation
   2149   //   function, that function will be called; otherwise, no
   2150   //   deallocation function will be called.
   2151   if (Matches.size() == 1) {
   2152     OperatorDelete = Matches[0].second;
   2153 
   2154     // C++0x [expr.new]p20:
   2155     //   If the lookup finds the two-parameter form of a usual
   2156     //   deallocation function (3.7.4.2) and that function, considered
   2157     //   as a placement deallocation function, would have been
   2158     //   selected as a match for the allocation function, the program
   2159     //   is ill-formed.
   2160     if (!PlaceArgs.empty() && getLangOpts().CPlusPlus11 &&
   2161         isNonPlacementDeallocationFunction(*this, OperatorDelete)) {
   2162       Diag(StartLoc, diag::err_placement_new_non_placement_delete)
   2163         << SourceRange(PlaceArgs.front()->getLocStart(),
   2164                        PlaceArgs.back()->getLocEnd());
   2165       if (!OperatorDelete->isImplicit())
   2166         Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
   2167           << DeleteName;
   2168     } else {
   2169       CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
   2170                             Matches[0].first);
   2171     }
   2172   }
   2173 
   2174   return false;
   2175 }
   2176 
   2177 /// \brief Find an fitting overload for the allocation function
   2178 /// in the specified scope.
   2179 ///
   2180 /// \param StartLoc The location of the 'new' token.
   2181 /// \param Range The range of the placement arguments.
   2182 /// \param Name The name of the function ('operator new' or 'operator new[]').
   2183 /// \param Args The placement arguments specified.
   2184 /// \param Ctx The scope in which we should search; either a class scope or the
   2185 ///        translation unit.
   2186 /// \param AllowMissing If \c true, report an error if we can't find any
   2187 ///        allocation functions. Otherwise, succeed but don't fill in \p
   2188 ///        Operator.
   2189 /// \param Operator Filled in with the found allocation function. Unchanged if
   2190 ///        no allocation function was found.
   2191 /// \param Diagnose If \c true, issue errors if the allocation function is not
   2192 ///        usable.
   2193 bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
   2194                                   DeclarationName Name, MultiExprArg Args,
   2195                                   DeclContext *Ctx,
   2196                                   bool AllowMissing, FunctionDecl *&Operator,
   2197                                   bool Diagnose) {
   2198   LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
   2199   LookupQualifiedName(R, Ctx);
   2200   if (R.empty()) {
   2201     if (AllowMissing || !Diagnose)
   2202       return false;
   2203     return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
   2204       << Name << Range;
   2205   }
   2206 
   2207   if (R.isAmbiguous())
   2208     return true;
   2209 
   2210   R.suppressDiagnostics();
   2211 
   2212   OverloadCandidateSet Candidates(StartLoc, OverloadCandidateSet::CSK_Normal);
   2213   for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
   2214        Alloc != AllocEnd; ++Alloc) {
   2215     // Even member operator new/delete are implicitly treated as
   2216     // static, so don't use AddMemberCandidate.
   2217     NamedDecl *D = (*Alloc)->getUnderlyingDecl();
   2218 
   2219     if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
   2220       AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
   2221                                    /*ExplicitTemplateArgs=*/nullptr,
   2222                                    Args, Candidates,
   2223                                    /*SuppressUserConversions=*/false);
   2224       continue;
   2225     }
   2226 
   2227     FunctionDecl *Fn = cast<FunctionDecl>(D);
   2228     AddOverloadCandidate(Fn, Alloc.getPair(), Args, Candidates,
   2229                          /*SuppressUserConversions=*/false);
   2230   }
   2231 
   2232   // Do the resolution.
   2233   OverloadCandidateSet::iterator Best;
   2234   switch (Candidates.BestViableFunction(*this, StartLoc, Best)) {
   2235   case OR_Success: {
   2236     // Got one!
   2237     FunctionDecl *FnDecl = Best->Function;
   2238     if (CheckAllocationAccess(StartLoc, Range, R.getNamingClass(),
   2239                               Best->FoundDecl, Diagnose) == AR_inaccessible)
   2240       return true;
   2241 
   2242     Operator = FnDecl;
   2243     return false;
   2244   }
   2245 
   2246   case OR_No_Viable_Function:
   2247     if (Diagnose) {
   2248       Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
   2249         << Name << Range;
   2250       Candidates.NoteCandidates(*this, OCD_AllCandidates, Args);
   2251     }
   2252     return true;
   2253 
   2254   case OR_Ambiguous:
   2255     if (Diagnose) {
   2256       Diag(StartLoc, diag::err_ovl_ambiguous_call)
   2257         << Name << Range;
   2258       Candidates.NoteCandidates(*this, OCD_ViableCandidates, Args);
   2259     }
   2260     return true;
   2261 
   2262   case OR_Deleted: {
   2263     if (Diagnose) {
   2264       Diag(StartLoc, diag::err_ovl_deleted_call)
   2265         << Best->Function->isDeleted()
   2266         << Name
   2267         << getDeletedOrUnavailableSuffix(Best->Function)
   2268         << Range;
   2269       Candidates.NoteCandidates(*this, OCD_AllCandidates, Args);
   2270     }
   2271     return true;
   2272   }
   2273   }
   2274   llvm_unreachable("Unreachable, bad result from BestViableFunction");
   2275 }
   2276 
   2277 
   2278 /// DeclareGlobalNewDelete - Declare the global forms of operator new and
   2279 /// delete. These are:
   2280 /// @code
   2281 ///   // C++03:
   2282 ///   void* operator new(std::size_t) throw(std::bad_alloc);
   2283 ///   void* operator new[](std::size_t) throw(std::bad_alloc);
   2284 ///   void operator delete(void *) throw();
   2285 ///   void operator delete[](void *) throw();
   2286 ///   // C++11:
   2287 ///   void* operator new(std::size_t);
   2288 ///   void* operator new[](std::size_t);
   2289 ///   void operator delete(void *) noexcept;
   2290 ///   void operator delete[](void *) noexcept;
   2291 ///   // C++1y:
   2292 ///   void* operator new(std::size_t);
   2293 ///   void* operator new[](std::size_t);
   2294 ///   void operator delete(void *) noexcept;
   2295 ///   void operator delete[](void *) noexcept;
   2296 ///   void operator delete(void *, std::size_t) noexcept;
   2297 ///   void operator delete[](void *, std::size_t) noexcept;
   2298 /// @endcode
   2299 /// Note that the placement and nothrow forms of new are *not* implicitly
   2300 /// declared. Their use requires including \<new\>.
   2301 void Sema::DeclareGlobalNewDelete() {
   2302   if (GlobalNewDeleteDeclared)
   2303     return;
   2304 
   2305   // C++ [basic.std.dynamic]p2:
   2306   //   [...] The following allocation and deallocation functions (18.4) are
   2307   //   implicitly declared in global scope in each translation unit of a
   2308   //   program
   2309   //
   2310   //     C++03:
   2311   //     void* operator new(std::size_t) throw(std::bad_alloc);
   2312   //     void* operator new[](std::size_t) throw(std::bad_alloc);
   2313   //     void  operator delete(void*) throw();
   2314   //     void  operator delete[](void*) throw();
   2315   //     C++11:
   2316   //     void* operator new(std::size_t);
   2317   //     void* operator new[](std::size_t);
   2318   //     void  operator delete(void*) noexcept;
   2319   //     void  operator delete[](void*) noexcept;
   2320   //     C++1y:
   2321   //     void* operator new(std::size_t);
   2322   //     void* operator new[](std::size_t);
   2323   //     void  operator delete(void*) noexcept;
   2324   //     void  operator delete[](void*) noexcept;
   2325   //     void  operator delete(void*, std::size_t) noexcept;
   2326   //     void  operator delete[](void*, std::size_t) noexcept;
   2327   //
   2328   //   These implicit declarations introduce only the function names operator
   2329   //   new, operator new[], operator delete, operator delete[].
   2330   //
   2331   // Here, we need to refer to std::bad_alloc, so we will implicitly declare
   2332   // "std" or "bad_alloc" as necessary to form the exception specification.
   2333   // However, we do not make these implicit declarations visible to name
   2334   // lookup.
   2335   if (!StdBadAlloc && !getLangOpts().CPlusPlus11) {
   2336     // The "std::bad_alloc" class has not yet been declared, so build it
   2337     // implicitly.
   2338     StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
   2339                                         getOrCreateStdNamespace(),
   2340                                         SourceLocation(), SourceLocation(),
   2341                                       &PP.getIdentifierTable().get("bad_alloc"),
   2342                                         nullptr);
   2343     getStdBadAlloc()->setImplicit(true);
   2344   }
   2345 
   2346   GlobalNewDeleteDeclared = true;
   2347 
   2348   QualType VoidPtr = Context.getPointerType(Context.VoidTy);
   2349   QualType SizeT = Context.getSizeType();
   2350 
   2351   DeclareGlobalAllocationFunction(
   2352       Context.DeclarationNames.getCXXOperatorName(OO_New),
   2353       VoidPtr, SizeT, QualType());
   2354   DeclareGlobalAllocationFunction(
   2355       Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
   2356       VoidPtr, SizeT, QualType());
   2357   DeclareGlobalAllocationFunction(
   2358       Context.DeclarationNames.getCXXOperatorName(OO_Delete),
   2359       Context.VoidTy, VoidPtr);
   2360   DeclareGlobalAllocationFunction(
   2361       Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
   2362       Context.VoidTy, VoidPtr);
   2363   if (getLangOpts().SizedDeallocation) {
   2364     DeclareGlobalAllocationFunction(
   2365         Context.DeclarationNames.getCXXOperatorName(OO_Delete),
   2366         Context.VoidTy, VoidPtr, Context.getSizeType());
   2367     DeclareGlobalAllocationFunction(
   2368         Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
   2369         Context.VoidTy, VoidPtr, Context.getSizeType());
   2370   }
   2371 }
   2372 
   2373 /// DeclareGlobalAllocationFunction - Declares a single implicit global
   2374 /// allocation function if it doesn't already exist.
   2375 void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
   2376                                            QualType Return,
   2377                                            QualType Param1, QualType Param2) {
   2378   DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
   2379   unsigned NumParams = Param2.isNull() ? 1 : 2;
   2380 
   2381   // Check if this function is already declared.
   2382   DeclContext::lookup_result R = GlobalCtx->lookup(Name);
   2383   for (DeclContext::lookup_iterator Alloc = R.begin(), AllocEnd = R.end();
   2384        Alloc != AllocEnd; ++Alloc) {
   2385     // Only look at non-template functions, as it is the predefined,
   2386     // non-templated allocation function we are trying to declare here.
   2387     if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
   2388       if (Func->getNumParams() == NumParams) {
   2389         QualType InitialParam1Type =
   2390             Context.getCanonicalType(Func->getParamDecl(0)
   2391                                          ->getType().getUnqualifiedType());
   2392         QualType InitialParam2Type =
   2393             NumParams == 2
   2394                 ? Context.getCanonicalType(Func->getParamDecl(1)
   2395                                                ->getType().getUnqualifiedType())
   2396                 : QualType();
   2397         // FIXME: Do we need to check for default arguments here?
   2398         if (InitialParam1Type == Param1 &&
   2399             (NumParams == 1 || InitialParam2Type == Param2)) {
   2400           // Make the function visible to name lookup, even if we found it in
   2401           // an unimported module. It either is an implicitly-declared global
   2402           // allocation function, or is suppressing that function.
   2403           Func->setHidden(false);
   2404           return;
   2405         }
   2406       }
   2407     }
   2408   }
   2409 
   2410   FunctionProtoType::ExtProtoInfo EPI;
   2411 
   2412   QualType BadAllocType;
   2413   bool HasBadAllocExceptionSpec
   2414     = (Name.getCXXOverloadedOperator() == OO_New ||
   2415        Name.getCXXOverloadedOperator() == OO_Array_New);
   2416   if (HasBadAllocExceptionSpec) {
   2417     if (!getLangOpts().CPlusPlus11) {
   2418       BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
   2419       assert(StdBadAlloc && "Must have std::bad_alloc declared");
   2420       EPI.ExceptionSpec.Type = EST_Dynamic;
   2421       EPI.ExceptionSpec.Exceptions = llvm::makeArrayRef(BadAllocType);
   2422     }
   2423   } else {
   2424     EPI.ExceptionSpec =
   2425         getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
   2426   }
   2427 
   2428   QualType Params[] = { Param1, Param2 };
   2429 
   2430   QualType FnType = Context.getFunctionType(
   2431       Return, llvm::makeArrayRef(Params, NumParams), EPI);
   2432   FunctionDecl *Alloc =
   2433     FunctionDecl::Create(Context, GlobalCtx, SourceLocation(),
   2434                          SourceLocation(), Name,
   2435                          FnType, /*TInfo=*/nullptr, SC_None, false, true);
   2436   Alloc->setImplicit();
   2437 
   2438   // Implicit sized deallocation functions always have default visibility.
   2439   Alloc->addAttr(VisibilityAttr::CreateImplicit(Context,
   2440                                                 VisibilityAttr::Default));
   2441 
   2442   ParmVarDecl *ParamDecls[2];
   2443   for (unsigned I = 0; I != NumParams; ++I) {
   2444     ParamDecls[I] = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
   2445                                         SourceLocation(), nullptr,
   2446                                         Params[I], /*TInfo=*/nullptr,
   2447                                         SC_None, nullptr);
   2448     ParamDecls[I]->setImplicit();
   2449   }
   2450   Alloc->setParams(llvm::makeArrayRef(ParamDecls, NumParams));
   2451 
   2452   Context.getTranslationUnitDecl()->addDecl(Alloc);
   2453   IdResolver.tryAddTopLevelDecl(Alloc, Name);
   2454 }
   2455 
   2456 FunctionDecl *Sema::FindUsualDeallocationFunction(SourceLocation StartLoc,
   2457                                                   bool CanProvideSize,
   2458                                                   DeclarationName Name) {
   2459   DeclareGlobalNewDelete();
   2460 
   2461   LookupResult FoundDelete(*this, Name, StartLoc, LookupOrdinaryName);
   2462   LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
   2463 
   2464   // C++ [expr.new]p20:
   2465   //   [...] Any non-placement deallocation function matches a
   2466   //   non-placement allocation function. [...]
   2467   llvm::SmallVector<FunctionDecl*, 2> Matches;
   2468   for (LookupResult::iterator D = FoundDelete.begin(),
   2469                            DEnd = FoundDelete.end();
   2470        D != DEnd; ++D) {
   2471     if (FunctionDecl *Fn = dyn_cast<FunctionDecl>(*D))
   2472       if (isNonPlacementDeallocationFunction(*this, Fn))
   2473         Matches.push_back(Fn);
   2474   }
   2475 
   2476   // C++1y [expr.delete]p?:
   2477   //   If the type is complete and deallocation function lookup finds both a
   2478   //   usual deallocation function with only a pointer parameter and a usual
   2479   //   deallocation function with both a pointer parameter and a size
   2480   //   parameter, then the selected deallocation function shall be the one
   2481   //   with two parameters.  Otherwise, the selected deallocation function
   2482   //   shall be the function with one parameter.
   2483   if (getLangOpts().SizedDeallocation && Matches.size() == 2) {
   2484     unsigned NumArgs = CanProvideSize ? 2 : 1;
   2485     if (Matches[0]->getNumParams() != NumArgs)
   2486       Matches.erase(Matches.begin());
   2487     else
   2488       Matches.erase(Matches.begin() + 1);
   2489     assert(Matches[0]->getNumParams() == NumArgs &&
   2490            "found an unexpected usual deallocation function");
   2491   }
   2492 
   2493   if (getLangOpts().CUDA)
   2494     EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(CurContext), Matches);
   2495 
   2496   assert(Matches.size() == 1 &&
   2497          "unexpectedly have multiple usual deallocation functions");
   2498   return Matches.front();
   2499 }
   2500 
   2501 bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
   2502                                     DeclarationName Name,
   2503                                     FunctionDecl* &Operator, bool Diagnose) {
   2504   LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
   2505   // Try to find operator delete/operator delete[] in class scope.
   2506   LookupQualifiedName(Found, RD);
   2507 
   2508   if (Found.isAmbiguous())
   2509     return true;
   2510 
   2511   Found.suppressDiagnostics();
   2512 
   2513   SmallVector<DeclAccessPair,4> Matches;
   2514   for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
   2515        F != FEnd; ++F) {
   2516     NamedDecl *ND = (*F)->getUnderlyingDecl();
   2517 
   2518     // Ignore template operator delete members from the check for a usual
   2519     // deallocation function.
   2520     if (isa<FunctionTemplateDecl>(ND))
   2521       continue;
   2522 
   2523     if (cast<CXXMethodDecl>(ND)->isUsualDeallocationFunction())
   2524       Matches.push_back(F.getPair());
   2525   }
   2526 
   2527   if (getLangOpts().CUDA)
   2528     EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(CurContext), Matches);
   2529 
   2530   // There's exactly one suitable operator;  pick it.
   2531   if (Matches.size() == 1) {
   2532     Operator = cast<CXXMethodDecl>(Matches[0]->getUnderlyingDecl());
   2533 
   2534     if (Operator->isDeleted()) {
   2535       if (Diagnose) {
   2536         Diag(StartLoc, diag::err_deleted_function_use);
   2537         NoteDeletedFunction(Operator);
   2538       }
   2539       return true;
   2540     }
   2541 
   2542     if (CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
   2543                               Matches[0], Diagnose) == AR_inaccessible)
   2544       return true;
   2545 
   2546     return false;
   2547 
   2548   // We found multiple suitable operators;  complain about the ambiguity.
   2549   } else if (!Matches.empty()) {
   2550     if (Diagnose) {
   2551       Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
   2552         << Name << RD;
   2553 
   2554       for (SmallVectorImpl<DeclAccessPair>::iterator
   2555              F = Matches.begin(), FEnd = Matches.end(); F != FEnd; ++F)
   2556         Diag((*F)->getUnderlyingDecl()->getLocation(),
   2557              diag::note_member_declared_here) << Name;
   2558     }
   2559     return true;
   2560   }
   2561 
   2562   // We did find operator delete/operator delete[] declarations, but
   2563   // none of them were suitable.
   2564   if (!Found.empty()) {
   2565     if (Diagnose) {
   2566       Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
   2567         << Name << RD;
   2568 
   2569       for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
   2570            F != FEnd; ++F)
   2571         Diag((*F)->getUnderlyingDecl()->getLocation(),
   2572              diag::note_member_declared_here) << Name;
   2573     }
   2574     return true;
   2575   }
   2576 
   2577   Operator = nullptr;
   2578   return false;
   2579 }
   2580 
   2581 namespace {
   2582 /// \brief Checks whether delete-expression, and new-expression used for
   2583 ///  initializing deletee have the same array form.
   2584 class MismatchingNewDeleteDetector {
   2585 public:
   2586   enum MismatchResult {
   2587     /// Indicates that there is no mismatch or a mismatch cannot be proven.
   2588     NoMismatch,
   2589     /// Indicates that variable is initialized with mismatching form of \a new.
   2590     VarInitMismatches,
   2591     /// Indicates that member is initialized with mismatching form of \a new.
   2592     MemberInitMismatches,
   2593     /// Indicates that 1 or more constructors' definitions could not been
   2594     /// analyzed, and they will be checked again at the end of translation unit.
   2595     AnalyzeLater
   2596   };
   2597 
   2598   /// \param EndOfTU True, if this is the final analysis at the end of
   2599   /// translation unit. False, if this is the initial analysis at the point
   2600   /// delete-expression was encountered.
   2601   explicit MismatchingNewDeleteDetector(bool EndOfTU)
   2602       : IsArrayForm(false), Field(nullptr), EndOfTU(EndOfTU),
   2603         HasUndefinedConstructors(false) {}
   2604 
   2605   /// \brief Checks whether pointee of a delete-expression is initialized with
   2606   /// matching form of new-expression.
   2607   ///
   2608   /// If return value is \c VarInitMismatches or \c MemberInitMismatches at the
   2609   /// point where delete-expression is encountered, then a warning will be
   2610   /// issued immediately. If return value is \c AnalyzeLater at the point where
   2611   /// delete-expression is seen, then member will be analyzed at the end of
   2612   /// translation unit. \c AnalyzeLater is returned iff at least one constructor
   2613   /// couldn't be analyzed. If at least one constructor initializes the member
   2614   /// with matching type of new, the return value is \c NoMismatch.
   2615   MismatchResult analyzeDeleteExpr(const CXXDeleteExpr *DE);
   2616   /// \brief Analyzes a class member.
   2617   /// \param Field Class member to analyze.
   2618   /// \param DeleteWasArrayForm Array form-ness of the delete-expression used
   2619   /// for deleting the \p Field.
   2620   MismatchResult analyzeField(FieldDecl *Field, bool DeleteWasArrayForm);
   2621   /// List of mismatching new-expressions used for initialization of the pointee
   2622   llvm::SmallVector<const CXXNewExpr *, 4> NewExprs;
   2623   /// Indicates whether delete-expression was in array form.
   2624   bool IsArrayForm;
   2625   FieldDecl *Field;
   2626 
   2627 private:
   2628   const bool EndOfTU;
   2629   /// \brief Indicates that there is at least one constructor without body.
   2630   bool HasUndefinedConstructors;
   2631   /// \brief Returns \c CXXNewExpr from given initialization expression.
   2632   /// \param E Expression used for initializing pointee in delete-expression.
   2633   /// E can be a single-element \c InitListExpr consisting of new-expression.
   2634   const CXXNewExpr *getNewExprFromInitListOrExpr(const Expr *E);
   2635   /// \brief Returns whether member is initialized with mismatching form of
   2636   /// \c new either by the member initializer or in-class initialization.
   2637   ///
   2638   /// If bodies of all constructors are not visible at the end of translation
   2639   /// unit or at least one constructor initializes member with the matching
   2640   /// form of \c new, mismatch cannot be proven, and this function will return
   2641   /// \c NoMismatch.
   2642   MismatchResult analyzeMemberExpr(const MemberExpr *ME);
   2643   /// \brief Returns whether variable is initialized with mismatching form of
   2644   /// \c new.
   2645   ///
   2646   /// If variable is initialized with matching form of \c new or variable is not
   2647   /// initialized with a \c new expression, this function will return true.
   2648   /// If variable is initialized with mismatching form of \c new, returns false.
   2649   /// \param D Variable to analyze.
   2650   bool hasMatchingVarInit(const DeclRefExpr *D);
   2651   /// \brief Checks whether the constructor initializes pointee with mismatching
   2652   /// form of \c new.
   2653   ///
   2654   /// Returns true, if member is initialized with matching form of \c new in
   2655   /// member initializer list. Returns false, if member is initialized with the
   2656   /// matching form of \c new in this constructor's initializer or given
   2657   /// constructor isn't defined at the point where delete-expression is seen, or
   2658   /// member isn't initialized by the constructor.
   2659   bool hasMatchingNewInCtor(const CXXConstructorDecl *CD);
   2660   /// \brief Checks whether member is initialized with matching form of
   2661   /// \c new in member initializer list.
   2662   bool hasMatchingNewInCtorInit(const CXXCtorInitializer *CI);
   2663   /// Checks whether member is initialized with mismatching form of \c new by
   2664   /// in-class initializer.
   2665   MismatchResult analyzeInClassInitializer();
   2666 };
   2667 }
   2668 
   2669 MismatchingNewDeleteDetector::MismatchResult
   2670 MismatchingNewDeleteDetector::analyzeDeleteExpr(const CXXDeleteExpr *DE) {
   2671   NewExprs.clear();
   2672   assert(DE && "Expected delete-expression");
   2673   IsArrayForm = DE->isArrayForm();
   2674   const Expr *E = DE->getArgument()->IgnoreParenImpCasts();
   2675   if (const MemberExpr *ME = dyn_cast<const MemberExpr>(E)) {
   2676     return analyzeMemberExpr(ME);
   2677   } else if (const DeclRefExpr *D = dyn_cast<const DeclRefExpr>(E)) {
   2678     if (!hasMatchingVarInit(D))
   2679       return VarInitMismatches;
   2680   }
   2681   return NoMismatch;
   2682 }
   2683 
   2684 const CXXNewExpr *
   2685 MismatchingNewDeleteDetector::getNewExprFromInitListOrExpr(const Expr *E) {
   2686   assert(E != nullptr && "Expected a valid initializer expression");
   2687   E = E->IgnoreParenImpCasts();
   2688   if (const InitListExpr *ILE = dyn_cast<const InitListExpr>(E)) {
   2689     if (ILE->getNumInits() == 1)
   2690       E = dyn_cast<const CXXNewExpr>(ILE->getInit(0)->IgnoreParenImpCasts());
   2691   }
   2692 
   2693   return dyn_cast_or_null<const CXXNewExpr>(E);
   2694 }
   2695 
   2696 bool MismatchingNewDeleteDetector::hasMatchingNewInCtorInit(
   2697     const CXXCtorInitializer *CI) {
   2698   const CXXNewExpr *NE = nullptr;
   2699   if (Field == CI->getMember() &&
   2700       (NE = getNewExprFromInitListOrExpr(CI->getInit()))) {
   2701     if (NE->isArray() == IsArrayForm)
   2702       return true;
   2703     else
   2704       NewExprs.push_back(NE);
   2705   }
   2706   return false;
   2707 }
   2708 
   2709 bool MismatchingNewDeleteDetector::hasMatchingNewInCtor(
   2710     const CXXConstructorDecl *CD) {
   2711   if (CD->isImplicit())
   2712     return false;
   2713   const FunctionDecl *Definition = CD;
   2714   if (!CD->isThisDeclarationADefinition() && !CD->isDefined(Definition)) {
   2715     HasUndefinedConstructors = true;
   2716     return EndOfTU;
   2717   }
   2718   for (const auto *CI : cast<const CXXConstructorDecl>(Definition)->inits()) {
   2719     if (hasMatchingNewInCtorInit(CI))
   2720       return true;
   2721   }
   2722   return false;
   2723 }
   2724 
   2725 MismatchingNewDeleteDetector::MismatchResult
   2726 MismatchingNewDeleteDetector::analyzeInClassInitializer() {
   2727   assert(Field != nullptr && "This should be called only for members");
   2728   const Expr *InitExpr = Field->getInClassInitializer();
   2729   if (!InitExpr)
   2730     return EndOfTU ? NoMismatch : AnalyzeLater;
   2731   if (const CXXNewExpr *NE = getNewExprFromInitListOrExpr(InitExpr)) {
   2732     if (NE->isArray() != IsArrayForm) {
   2733       NewExprs.push_back(NE);
   2734       return MemberInitMismatches;
   2735     }
   2736   }
   2737   return NoMismatch;
   2738 }
   2739 
   2740 MismatchingNewDeleteDetector::MismatchResult
   2741 MismatchingNewDeleteDetector::analyzeField(FieldDecl *Field,
   2742                                            bool DeleteWasArrayForm) {
   2743   assert(Field != nullptr && "Analysis requires a valid class member.");
   2744   this->Field = Field;
   2745   IsArrayForm = DeleteWasArrayForm;
   2746   const CXXRecordDecl *RD = cast<const CXXRecordDecl>(Field->getParent());
   2747   for (const auto *CD : RD->ctors()) {
   2748     if (hasMatchingNewInCtor(CD))
   2749       return NoMismatch;
   2750   }
   2751   if (HasUndefinedConstructors)
   2752     return EndOfTU ? NoMismatch : AnalyzeLater;
   2753   if (!NewExprs.empty())
   2754     return MemberInitMismatches;
   2755   return Field->hasInClassInitializer() ? analyzeInClassInitializer()
   2756                                         : NoMismatch;
   2757 }
   2758 
   2759 MismatchingNewDeleteDetector::MismatchResult
   2760 MismatchingNewDeleteDetector::analyzeMemberExpr(const MemberExpr *ME) {
   2761   assert(ME != nullptr && "Expected a member expression");
   2762   if (FieldDecl *F = dyn_cast<FieldDecl>(ME->getMemberDecl()))
   2763     return analyzeField(F, IsArrayForm);
   2764   return NoMismatch;
   2765 }
   2766 
   2767 bool MismatchingNewDeleteDetector::hasMatchingVarInit(const DeclRefExpr *D) {
   2768   const CXXNewExpr *NE = nullptr;
   2769   if (const VarDecl *VD = dyn_cast<const VarDecl>(D->getDecl())) {
   2770     if (VD->hasInit() && (NE = getNewExprFromInitListOrExpr(VD->getInit())) &&
   2771         NE->isArray() != IsArrayForm) {
   2772       NewExprs.push_back(NE);
   2773     }
   2774   }
   2775   return NewExprs.empty();
   2776 }
   2777 
   2778 static void
   2779 DiagnoseMismatchedNewDelete(Sema &SemaRef, SourceLocation DeleteLoc,
   2780                             const MismatchingNewDeleteDetector &Detector) {
   2781   SourceLocation EndOfDelete = SemaRef.getLocForEndOfToken(DeleteLoc);
   2782   FixItHint H;
   2783   if (!Detector.IsArrayForm)
   2784     H = FixItHint::CreateInsertion(EndOfDelete, "[]");
   2785   else {
   2786     SourceLocation RSquare = Lexer::findLocationAfterToken(
   2787         DeleteLoc, tok::l_square, SemaRef.getSourceManager(),
   2788         SemaRef.getLangOpts(), true);
   2789     if (RSquare.isValid())
   2790       H = FixItHint::CreateRemoval(SourceRange(EndOfDelete, RSquare));
   2791   }
   2792   SemaRef.Diag(DeleteLoc, diag::warn_mismatched_delete_new)
   2793       << Detector.IsArrayForm << H;
   2794 
   2795   for (const auto *NE : Detector.NewExprs)
   2796     SemaRef.Diag(NE->getExprLoc(), diag::note_allocated_here)
   2797         << Detector.IsArrayForm;
   2798 }
   2799 
   2800 void Sema::AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE) {
   2801   if (Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation()))
   2802     return;
   2803   MismatchingNewDeleteDetector Detector(/*EndOfTU=*/false);
   2804   switch (Detector.analyzeDeleteExpr(DE)) {
   2805   case MismatchingNewDeleteDetector::VarInitMismatches:
   2806   case MismatchingNewDeleteDetector::MemberInitMismatches: {
   2807     DiagnoseMismatchedNewDelete(*this, DE->getLocStart(), Detector);
   2808     break;
   2809   }
   2810   case MismatchingNewDeleteDetector::AnalyzeLater: {
   2811     DeleteExprs[Detector.Field].push_back(
   2812         std::make_pair(DE->getLocStart(), DE->isArrayForm()));
   2813     break;
   2814   }
   2815   case MismatchingNewDeleteDetector::NoMismatch:
   2816     break;
   2817   }
   2818 }
   2819 
   2820 void Sema::AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
   2821                                      bool DeleteWasArrayForm) {
   2822   MismatchingNewDeleteDetector Detector(/*EndOfTU=*/true);
   2823   switch (Detector.analyzeField(Field, DeleteWasArrayForm)) {
   2824   case MismatchingNewDeleteDetector::VarInitMismatches:
   2825     llvm_unreachable("This analysis should have been done for class members.");
   2826   case MismatchingNewDeleteDetector::AnalyzeLater:
   2827     llvm_unreachable("Analysis cannot be postponed any point beyond end of "
   2828                      "translation unit.");
   2829   case MismatchingNewDeleteDetector::MemberInitMismatches:
   2830     DiagnoseMismatchedNewDelete(*this, DeleteLoc, Detector);
   2831     break;
   2832   case MismatchingNewDeleteDetector::NoMismatch:
   2833     break;
   2834   }
   2835 }
   2836 
   2837 /// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
   2838 /// @code ::delete ptr; @endcode
   2839 /// or
   2840 /// @code delete [] ptr; @endcode
   2841 ExprResult
   2842 Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
   2843                      bool ArrayForm, Expr *ExE) {
   2844   // C++ [expr.delete]p1:
   2845   //   The operand shall have a pointer type, or a class type having a single
   2846   //   non-explicit conversion function to a pointer type. The result has type
   2847   //   void.
   2848   //
   2849   // DR599 amends "pointer type" to "pointer to object type" in both cases.
   2850 
   2851   ExprResult Ex = ExE;
   2852   FunctionDecl *OperatorDelete = nullptr;
   2853   bool ArrayFormAsWritten = ArrayForm;
   2854   bool UsualArrayDeleteWantsSize = false;
   2855 
   2856   if (!Ex.get()->isTypeDependent()) {
   2857     // Perform lvalue-to-rvalue cast, if needed.
   2858     Ex = DefaultLvalueConversion(Ex.get());
   2859     if (Ex.isInvalid())
   2860       return ExprError();
   2861 
   2862     QualType Type = Ex.get()->getType();
   2863 
   2864     class DeleteConverter : public ContextualImplicitConverter {
   2865     public:
   2866       DeleteConverter() : ContextualImplicitConverter(false, true) {}
   2867 
   2868       bool match(QualType ConvType) override {
   2869         // FIXME: If we have an operator T* and an operator void*, we must pick
   2870         // the operator T*.
   2871         if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
   2872           if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
   2873             return true;
   2874         return false;
   2875       }
   2876 
   2877       SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc,
   2878                                             QualType T) override {
   2879         return S.Diag(Loc, diag::err_delete_operand) << T;
   2880       }
   2881 
   2882       SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
   2883                                                QualType T) override {
   2884         return S.Diag(Loc, diag::err_delete_incomplete_class_type) << T;
   2885       }
   2886 
   2887       SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
   2888                                                  QualType T,
   2889                                                  QualType ConvTy) override {
   2890         return S.Diag(Loc, diag::err_delete_explicit_conversion) << T << ConvTy;
   2891       }
   2892 
   2893       SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
   2894                                              QualType ConvTy) override {
   2895         return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
   2896           << ConvTy;
   2897       }
   2898 
   2899       SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
   2900                                               QualType T) override {
   2901         return S.Diag(Loc, diag::err_ambiguous_delete_operand) << T;
   2902       }
   2903 
   2904       SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
   2905                                           QualType ConvTy) override {
   2906         return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
   2907           << ConvTy;
   2908       }
   2909 
   2910       SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
   2911                                                QualType T,
   2912                                                QualType ConvTy) override {
   2913         llvm_unreachable("conversion functions are permitted");
   2914       }
   2915     } Converter;
   2916 
   2917     Ex = PerformContextualImplicitConversion(StartLoc, Ex.get(), Converter);
   2918     if (Ex.isInvalid())
   2919       return ExprError();
   2920     Type = Ex.get()->getType();
   2921     if (!Converter.match(Type))
   2922       // FIXME: PerformContextualImplicitConversion should return ExprError
   2923       //        itself in this case.
   2924       return ExprError();
   2925 
   2926     QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
   2927     QualType PointeeElem = Context.getBaseElementType(Pointee);
   2928 
   2929     if (unsigned AddressSpace = Pointee.getAddressSpace())
   2930       return Diag(Ex.get()->getLocStart(),
   2931                   diag::err_address_space_qualified_delete)
   2932                << Pointee.getUnqualifiedType() << AddressSpace;
   2933 
   2934     CXXRecordDecl *PointeeRD = nullptr;
   2935     if (Pointee->isVoidType() && !isSFINAEContext()) {
   2936       // The C++ standard bans deleting a pointer to a non-object type, which
   2937       // effectively bans deletion of "void*". However, most compilers support
   2938       // this, so we treat it as a warning unless we're in a SFINAE context.
   2939       Diag(StartLoc, diag::ext_delete_void_ptr_operand)
   2940         << Type << Ex.get()->getSourceRange();
   2941     } else if (Pointee->isFunctionType() || Pointee->isVoidType()) {
   2942       return ExprError(Diag(StartLoc, diag::err_delete_operand)
   2943         << Type << Ex.get()->getSourceRange());
   2944     } else if (!Pointee->isDependentType()) {
   2945       // FIXME: This can result in errors if the definition was imported from a
   2946       // module but is hidden.
   2947       if (!RequireCompleteType(StartLoc, Pointee,
   2948                                diag::warn_delete_incomplete, Ex.get())) {
   2949         if (const RecordType *RT = PointeeElem->getAs<RecordType>())
   2950           PointeeRD = cast<CXXRecordDecl>(RT->getDecl());
   2951       }
   2952     }
   2953 
   2954     if (Pointee->isArrayType() && !ArrayForm) {
   2955       Diag(StartLoc, diag::warn_delete_array_type)
   2956           << Type << Ex.get()->getSourceRange()
   2957           << FixItHint::CreateInsertion(getLocForEndOfToken(StartLoc), "[]");
   2958       ArrayForm = true;
   2959     }
   2960 
   2961     DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
   2962                                       ArrayForm ? OO_Array_Delete : OO_Delete);
   2963 
   2964     if (PointeeRD) {
   2965       if (!UseGlobal &&
   2966           FindDeallocationFunction(StartLoc, PointeeRD, DeleteName,
   2967                                    OperatorDelete))
   2968         return ExprError();
   2969 
   2970       // If we're allocating an array of records, check whether the
   2971       // usual operator delete[] has a size_t parameter.
   2972       if (ArrayForm) {
   2973         // If the user specifically asked to use the global allocator,
   2974         // we'll need to do the lookup into the class.
   2975         if (UseGlobal)
   2976           UsualArrayDeleteWantsSize =
   2977             doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);
   2978 
   2979         // Otherwise, the usual operator delete[] should be the
   2980         // function we just found.
   2981         else if (OperatorDelete && isa<CXXMethodDecl>(OperatorDelete))
   2982           UsualArrayDeleteWantsSize = (OperatorDelete->getNumParams() == 2);
   2983       }
   2984 
   2985       if (!PointeeRD->hasIrrelevantDestructor())
   2986         if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
   2987           MarkFunctionReferenced(StartLoc,
   2988                                     const_cast<CXXDestructorDecl*>(Dtor));
   2989           if (DiagnoseUseOfDecl(Dtor, StartLoc))
   2990             return ExprError();
   2991         }
   2992 
   2993       CheckVirtualDtorCall(PointeeRD->getDestructor(), StartLoc,
   2994                            /*IsDelete=*/true, /*CallCanBeVirtual=*/true,
   2995                            /*WarnOnNonAbstractTypes=*/!ArrayForm,
   2996                            SourceLocation());
   2997     }
   2998 
   2999     if (!OperatorDelete)
   3000       // Look for a global declaration.
   3001       OperatorDelete = FindUsualDeallocationFunction(
   3002           StartLoc, isCompleteType(StartLoc, Pointee) &&
   3003                     (!ArrayForm || UsualArrayDeleteWantsSize ||
   3004                      Pointee.isDestructedType()),
   3005           DeleteName);
   3006 
   3007     MarkFunctionReferenced(StartLoc, OperatorDelete);
   3008 
   3009     // Check access and ambiguity of operator delete and destructor.
   3010     if (PointeeRD) {
   3011       if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
   3012           CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor,
   3013                       PDiag(diag::err_access_dtor) << PointeeElem);
   3014       }
   3015     }
   3016   }
   3017 
   3018   CXXDeleteExpr *Result = new (Context) CXXDeleteExpr(
   3019       Context.VoidTy, UseGlobal, ArrayForm, ArrayFormAsWritten,
   3020       UsualArrayDeleteWantsSize, OperatorDelete, Ex.get(), StartLoc);
   3021   AnalyzeDeleteExprMismatch(Result);
   3022   return Result;
   3023 }
   3024 
   3025 void Sema::CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc,
   3026                                 bool IsDelete, bool CallCanBeVirtual,
   3027                                 bool WarnOnNonAbstractTypes,
   3028                                 SourceLocation DtorLoc) {
   3029   if (!dtor || dtor->isVirtual() || !CallCanBeVirtual)
   3030     return;
   3031 
   3032   // C++ [expr.delete]p3:
   3033   //   In the first alternative (delete object), if the static type of the
   3034   //   object to be deleted is different from its dynamic type, the static
   3035   //   type shall be a base class of the dynamic type of the object to be
   3036   //   deleted and the static type shall have a virtual destructor or the
   3037   //   behavior is undefined.
   3038   //
   3039   const CXXRecordDecl *PointeeRD = dtor->getParent();
   3040   // Note: a final class cannot be derived from, no issue there
   3041   if (!PointeeRD->isPolymorphic() || PointeeRD->hasAttr<FinalAttr>())
   3042     return;
   3043 
   3044   QualType ClassType = dtor->getThisType(Context)->getPointeeType();
   3045   if (PointeeRD->isAbstract()) {
   3046     // If the class is abstract, we warn by default, because we're
   3047     // sure the code has undefined behavior.
   3048     Diag(Loc, diag::warn_delete_abstract_non_virtual_dtor) << (IsDelete ? 0 : 1)
   3049                                                            << ClassType;
   3050   } else if (WarnOnNonAbstractTypes) {
   3051     // Otherwise, if this is not an array delete, it's a bit suspect,
   3052     // but not necessarily wrong.
   3053     Diag(Loc, diag::warn_delete_non_virtual_dtor) << (IsDelete ? 0 : 1)
   3054                                                   << ClassType;
   3055   }
   3056   if (!IsDelete) {
   3057     std::string TypeStr;
   3058     ClassType.getAsStringInternal(TypeStr, getPrintingPolicy());
   3059     Diag(DtorLoc, diag::note_delete_non_virtual)
   3060         << FixItHint::CreateInsertion(DtorLoc, TypeStr + "::");
   3061   }
   3062 }
   3063 
   3064 Sema::ConditionResult Sema::ActOnConditionVariable(Decl *ConditionVar,
   3065                                                    SourceLocation StmtLoc,
   3066                                                    ConditionKind CK) {
   3067   ExprResult E =
   3068       CheckConditionVariable(cast<VarDecl>(ConditionVar), StmtLoc, CK);
   3069   if (E.isInvalid())
   3070     return ConditionError();
   3071   return ConditionResult(*this, ConditionVar, MakeFullExpr(E.get(), StmtLoc),
   3072                          CK == ConditionKind::ConstexprIf);
   3073 }
   3074 
   3075 /// \brief Check the use of the given variable as a C++ condition in an if,
   3076 /// while, do-while, or switch statement.
   3077 ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
   3078                                         SourceLocation StmtLoc,
   3079                                         ConditionKind CK) {
   3080   if (ConditionVar->isInvalidDecl())
   3081     return ExprError();
   3082 
   3083   QualType T = ConditionVar->getType();
   3084 
   3085   // C++ [stmt.select]p2:
   3086   //   The declarator shall not specify a function or an array.
   3087   if (T->isFunctionType())
   3088     return ExprError(Diag(ConditionVar->getLocation(),
   3089                           diag::err_invalid_use_of_function_type)
   3090                        << ConditionVar->getSourceRange());
   3091   else if (T->isArrayType())
   3092     return ExprError(Diag(ConditionVar->getLocation(),
   3093                           diag::err_invalid_use_of_array_type)
   3094                      << ConditionVar->getSourceRange());
   3095 
   3096   ExprResult Condition = DeclRefExpr::Create(
   3097       Context, NestedNameSpecifierLoc(), SourceLocation(), ConditionVar,
   3098       /*enclosing*/ false, ConditionVar->getLocation(),
   3099       ConditionVar->getType().getNonReferenceType(), VK_LValue);
   3100 
   3101   MarkDeclRefReferenced(cast<DeclRefExpr>(Condition.get()));
   3102 
   3103   switch (CK) {
   3104   case ConditionKind::Boolean:
   3105     return CheckBooleanCondition(StmtLoc, Condition.get());
   3106 
   3107   case ConditionKind::ConstexprIf:
   3108     return CheckBooleanCondition(StmtLoc, Condition.get(), true);
   3109 
   3110   case ConditionKind::Switch:
   3111     return CheckSwitchCondition(StmtLoc, Condition.get());
   3112   }
   3113 
   3114   llvm_unreachable("unexpected condition kind");
   3115 }
   3116 
   3117 /// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
   3118 ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr) {
   3119   // C++ 6.4p4:
   3120   // The value of a condition that is an initialized declaration in a statement
   3121   // other than a switch statement is the value of the declared variable
   3122   // implicitly converted to type bool. If that conversion is ill-formed, the
   3123   // program is ill-formed.
   3124   // The value of a condition that is an expression is the value of the
   3125   // expression, implicitly converted to bool.
   3126   //
   3127   // FIXME: Return this value to the caller so they don't need to recompute it.
   3128   llvm::APSInt Value(/*BitWidth*/1);
   3129   return (IsConstexpr && !CondExpr->isValueDependent())
   3130              ? CheckConvertedConstantExpression(CondExpr, Context.BoolTy, Value,
   3131                                                 CCEK_ConstexprIf)
   3132              : PerformContextuallyConvertToBool(CondExpr);
   3133 }
   3134 
   3135 /// Helper function to determine whether this is the (deprecated) C++
   3136 /// conversion from a string literal to a pointer to non-const char or
   3137 /// non-const wchar_t (for narrow and wide string literals,
   3138 /// respectively).
   3139 bool
   3140 Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
   3141   // Look inside the implicit cast, if it exists.
   3142   if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
   3143     From = Cast->getSubExpr();
   3144 
   3145   // A string literal (2.13.4) that is not a wide string literal can
   3146   // be converted to an rvalue of type "pointer to char"; a wide
   3147   // string literal can be converted to an rvalue of type "pointer
   3148   // to wchar_t" (C++ 4.2p2).
   3149   if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
   3150     if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
   3151       if (const BuiltinType *ToPointeeType
   3152           = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
   3153         // This conversion is considered only when there is an
   3154         // explicit appropriate pointer target type (C++ 4.2p2).
   3155         if (!ToPtrType->getPointeeType().hasQualifiers()) {
   3156           switch (StrLit->getKind()) {
   3157             case StringLiteral::UTF8:
   3158             case StringLiteral::UTF16:
   3159             case StringLiteral::UTF32:
   3160               // We don't allow UTF literals to be implicitly converted
   3161               break;
   3162             case StringLiteral::Ascii:
   3163               return (ToPointeeType->getKind() == BuiltinType::Char_U ||
   3164                       ToPointeeType->getKind() == BuiltinType::Char_S);
   3165             case StringLiteral::Wide:
   3166               return Context.typesAreCompatible(Context.getWideCharType(),
   3167                                                 QualType(ToPointeeType, 0));
   3168           }
   3169         }
   3170       }
   3171 
   3172   return false;
   3173 }
   3174 
   3175 static ExprResult BuildCXXCastArgument(Sema &S,
   3176                                        SourceLocation CastLoc,
   3177                                        QualType Ty,
   3178                                        CastKind Kind,
   3179                                        CXXMethodDecl *Method,
   3180                                        DeclAccessPair FoundDecl,
   3181                                        bool HadMultipleCandidates,
   3182                                        Expr *From) {
   3183   switch (Kind) {
   3184   default: llvm_unreachable("Unhandled cast kind!");
   3185   case CK_ConstructorConversion: {
   3186     CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Method);
   3187     SmallVector<Expr*, 8> ConstructorArgs;
   3188 
   3189     if (S.RequireNonAbstractType(CastLoc, Ty,
   3190                                  diag::err_allocation_of_abstract_type))
   3191       return ExprError();
   3192 
   3193     if (S.CompleteConstructorCall(Constructor, From, CastLoc, ConstructorArgs))
   3194       return ExprError();
   3195 
   3196     S.CheckConstructorAccess(CastLoc, Constructor, FoundDecl,
   3197                              InitializedEntity::InitializeTemporary(Ty));
   3198     if (S.DiagnoseUseOfDecl(Method, CastLoc))
   3199       return ExprError();
   3200 
   3201     ExprResult Result = S.BuildCXXConstructExpr(
   3202         CastLoc, Ty, FoundDecl, cast<CXXConstructorDecl>(Method),
   3203         ConstructorArgs, HadMultipleCandidates,
   3204         /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
   3205         CXXConstructExpr::CK_Complete, SourceRange());
   3206     if (Result.isInvalid())
   3207       return ExprError();
   3208 
   3209     return S.MaybeBindToTemporary(Result.getAs<Expr>());
   3210   }
   3211 
   3212   case CK_UserDefinedConversion: {
   3213     assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
   3214 
   3215     S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ nullptr, FoundDecl);
   3216     if (S.DiagnoseUseOfDecl(Method, CastLoc))
   3217       return ExprError();
   3218 
   3219     // Create an implicit call expr that calls it.
   3220     CXXConversionDecl *Conv = cast<CXXConversionDecl>(Method);
   3221     ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Conv,
   3222                                                  HadMultipleCandidates);
   3223     if (Result.isInvalid())
   3224       return ExprError();
   3225     // Record usage of conversion in an implicit cast.
   3226     Result = ImplicitCastExpr::Create(S.Context, Result.get()->getType(),
   3227                                       CK_UserDefinedConversion, Result.get(),
   3228                                       nullptr, Result.get()->getValueKind());
   3229 
   3230     return S.MaybeBindToTemporary(Result.get());
   3231   }
   3232   }
   3233 }
   3234 
   3235 /// PerformImplicitConversion - Perform an implicit conversion of the
   3236 /// expression From to the type ToType using the pre-computed implicit
   3237 /// conversion sequence ICS. Returns the converted
   3238 /// expression. Action is the kind of conversion we're performing,
   3239 /// used in the error message.
   3240 ExprResult
   3241 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
   3242                                 const ImplicitConversionSequence &ICS,
   3243                                 AssignmentAction Action,
   3244                                 CheckedConversionKind CCK) {
   3245   switch (ICS.getKind()) {
   3246   case ImplicitConversionSequence::StandardConversion: {
   3247     ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard,
   3248                                                Action, CCK);
   3249     if (Res.isInvalid())
   3250       return ExprError();
   3251     From = Res.get();
   3252     break;
   3253   }
   3254 
   3255   case ImplicitConversionSequence::UserDefinedConversion: {
   3256 
   3257       FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
   3258       CastKind CastKind;
   3259       QualType BeforeToType;
   3260       assert(FD && "no conversion function for user-defined conversion seq");
   3261       if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
   3262         CastKind = CK_UserDefinedConversion;
   3263 
   3264         // If the user-defined conversion is specified by a conversion function,
   3265         // the initial standard conversion sequence converts the source type to
   3266         // the implicit object parameter of the conversion function.
   3267         BeforeToType = Context.getTagDeclType(Conv->getParent());
   3268       } else {
   3269         const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
   3270         CastKind = CK_ConstructorConversion;
   3271         // Do no conversion if dealing with ... for the first conversion.
   3272         if (!ICS.UserDefined.EllipsisConversion) {
   3273           // If the user-defined conversion is specified by a constructor, the
   3274           // initial standard conversion sequence converts the source type to
   3275           // the type required by the argument of the constructor
   3276           BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
   3277         }
   3278       }
   3279       // Watch out for ellipsis conversion.
   3280       if (!ICS.UserDefined.EllipsisConversion) {
   3281         ExprResult Res =
   3282           PerformImplicitConversion(From, BeforeToType,
   3283                                     ICS.UserDefined.Before, AA_Converting,
   3284                                     CCK);
   3285         if (Res.isInvalid())
   3286           return ExprError();
   3287         From = Res.get();
   3288       }
   3289 
   3290       ExprResult CastArg
   3291         = BuildCXXCastArgument(*this,
   3292                                From->getLocStart(),
   3293                                ToType.getNonReferenceType(),
   3294                                CastKind, cast<CXXMethodDecl>(FD),
   3295                                ICS.UserDefined.FoundConversionFunction,
   3296                                ICS.UserDefined.HadMultipleCandidates,
   3297                                From);
   3298 
   3299       if (CastArg.isInvalid())
   3300         return ExprError();
   3301 
   3302       From = CastArg.get();
   3303 
   3304       return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
   3305                                        AA_Converting, CCK);
   3306   }
   3307 
   3308   case ImplicitConversionSequence::AmbiguousConversion:
   3309     ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
   3310                           PDiag(diag::err_typecheck_ambiguous_condition)
   3311                             << From->getSourceRange());
   3312      return ExprError();
   3313 
   3314   case ImplicitConversionSequence::EllipsisConversion:
   3315     llvm_unreachable("Cannot perform an ellipsis conversion");
   3316 
   3317   case ImplicitConversionSequence::BadConversion:
   3318     return ExprError();
   3319   }
   3320 
   3321   // Everything went well.
   3322   return From;
   3323 }
   3324 
   3325 /// PerformImplicitConversion - Perform an implicit conversion of the
   3326 /// expression From to the type ToType by following the standard
   3327 /// conversion sequence SCS. Returns the converted
   3328 /// expression. Flavor is the context in which we're performing this
   3329 /// conversion, for use in error messages.
   3330 ExprResult
   3331 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
   3332                                 const StandardConversionSequence& SCS,
   3333                                 AssignmentAction Action,
   3334                                 CheckedConversionKind CCK) {
   3335   bool CStyle = (CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast);
   3336 
   3337   // Overall FIXME: we are recomputing too many types here and doing far too
   3338   // much extra work. What this means is that we need to keep track of more
   3339   // information that is computed when we try the implicit conversion initially,
   3340   // so that we don't need to recompute anything here.
   3341   QualType FromType = From->getType();
   3342 
   3343   if (SCS.CopyConstructor) {
   3344     // FIXME: When can ToType be a reference type?
   3345     assert(!ToType->isReferenceType());
   3346     if (SCS.Second == ICK_Derived_To_Base) {
   3347       SmallVector<Expr*, 8> ConstructorArgs;
   3348       if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
   3349                                   From, /*FIXME:ConstructLoc*/SourceLocation(),
   3350                                   ConstructorArgs))
   3351         return ExprError();
   3352       return BuildCXXConstructExpr(
   3353           /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
   3354           SCS.FoundCopyConstructor, SCS.CopyConstructor,
   3355           ConstructorArgs, /*HadMultipleCandidates*/ false,
   3356           /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
   3357           CXXConstructExpr::CK_Complete, SourceRange());
   3358     }
   3359     return BuildCXXConstructExpr(
   3360         /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
   3361         SCS.FoundCopyConstructor, SCS.CopyConstructor,
   3362         From, /*HadMultipleCandidates*/ false,
   3363         /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
   3364         CXXConstructExpr::CK_Complete, SourceRange());
   3365   }
   3366 
   3367   // Resolve overloaded function references.
   3368   if (Context.hasSameType(FromType, Context.OverloadTy)) {
   3369     DeclAccessPair Found;
   3370     FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
   3371                                                           true, Found);
   3372     if (!Fn)
   3373       return ExprError();
   3374 
   3375     if (DiagnoseUseOfDecl(Fn, From->getLocStart()))
   3376       return ExprError();
   3377 
   3378     From = FixOverloadedFunctionReference(From, Found, Fn);
   3379     FromType = From->getType();
   3380   }
   3381 
   3382   // If we're converting to an atomic type, first convert to the corresponding
   3383   // non-atomic type.
   3384   QualType ToAtomicType;
   3385   if (const AtomicType *ToAtomic = ToType->getAs<AtomicType>()) {
   3386     ToAtomicType = ToType;
   3387     ToType = ToAtomic->getValueType();
   3388   }
   3389 
   3390   QualType InitialFromType = FromType;
   3391   // Perform the first implicit conversion.
   3392   switch (SCS.First) {
   3393   case ICK_Identity:
   3394     if (const AtomicType *FromAtomic = FromType->getAs<AtomicType>()) {
   3395       FromType = FromAtomic->getValueType().getUnqualifiedType();
   3396       From = ImplicitCastExpr::Create(Context, FromType, CK_AtomicToNonAtomic,
   3397                                       From, /*BasePath=*/nullptr, VK_RValue);
   3398     }
   3399     break;
   3400 
   3401   case ICK_Lvalue_To_Rvalue: {
   3402     assert(From->getObjectKind() != OK_ObjCProperty);
   3403     ExprResult FromRes = DefaultLvalueConversion(From);
   3404     assert(!FromRes.isInvalid() && "Can't perform deduced conversion?!");
   3405     From = FromRes.get();
   3406     FromType = From->getType();
   3407     break;
   3408   }
   3409 
   3410   case ICK_Array_To_Pointer:
   3411     FromType = Context.getArrayDecayedType(FromType);
   3412     From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay,
   3413                              VK_RValue, /*BasePath=*/nullptr, CCK).get();
   3414     break;
   3415 
   3416   case ICK_Function_To_Pointer:
   3417     FromType = Context.getPointerType(FromType);
   3418     From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay,
   3419                              VK_RValue, /*BasePath=*/nullptr, CCK).get();
   3420     break;
   3421 
   3422   default:
   3423     llvm_unreachable("Improper first standard conversion");
   3424   }
   3425 
   3426   // Perform the second implicit conversion
   3427   switch (SCS.Second) {
   3428   case ICK_Identity:
   3429     // C++ [except.spec]p5:
   3430     //   [For] assignment to and initialization of pointers to functions,
   3431     //   pointers to member functions, and references to functions: the
   3432     //   target entity shall allow at least the exceptions allowed by the
   3433     //   source value in the assignment or initialization.
   3434     switch (Action) {
   3435     case AA_Assigning:
   3436     case AA_Initializing:
   3437       // Note, function argument passing and returning are initialization.
   3438     case AA_Passing:
   3439     case AA_Returning:
   3440     case AA_Sending:
   3441     case AA_Passing_CFAudited:
   3442       if (CheckExceptionSpecCompatibility(From, ToType))
   3443         return ExprError();
   3444       break;
   3445 
   3446     case AA_Casting:
   3447     case AA_Converting:
   3448       // Casts and implicit conversions are not initialization, so are not
   3449       // checked for exception specification mismatches.
   3450       break;
   3451     }
   3452     // Nothing else to do.
   3453     break;
   3454 
   3455   case ICK_NoReturn_Adjustment:
   3456     // If both sides are functions (or pointers/references to them), there could
   3457     // be incompatible exception declarations.
   3458     if (CheckExceptionSpecCompatibility(From, ToType))
   3459       return ExprError();
   3460 
   3461     From = ImpCastExprToType(From, ToType, CK_NoOp,
   3462                              VK_RValue, /*BasePath=*/nullptr, CCK).get();
   3463     break;
   3464 
   3465   case ICK_Integral_Promotion:
   3466   case ICK_Integral_Conversion:
   3467     if (ToType->isBooleanType()) {
   3468       assert(FromType->castAs<EnumType>()->getDecl()->isFixed() &&
   3469              SCS.Second == ICK_Integral_Promotion &&
   3470              "only enums with fixed underlying type can promote to bool");
   3471       From = ImpCastExprToType(From, ToType, CK_IntegralToBoolean,
   3472                                VK_RValue, /*BasePath=*/nullptr, CCK).get();
   3473     } else {
   3474       From = ImpCastExprToType(From, ToType, CK_IntegralCast,
   3475                                VK_RValue, /*BasePath=*/nullptr, CCK).get();
   3476     }
   3477     break;
   3478 
   3479   case ICK_Floating_Promotion:
   3480   case ICK_Floating_Conversion:
   3481     From = ImpCastExprToType(From, ToType, CK_FloatingCast,
   3482                              VK_RValue, /*BasePath=*/nullptr, CCK).get();
   3483     break;
   3484 
   3485   case ICK_Complex_Promotion:
   3486   case ICK_Complex_Conversion: {
   3487     QualType FromEl = From->getType()->getAs<ComplexType>()->getElementType();
   3488     QualType ToEl = ToType->getAs<ComplexType>()->getElementType();
   3489     CastKind CK;
   3490     if (FromEl->isRealFloatingType()) {
   3491       if (ToEl->isRealFloatingType())
   3492         CK = CK_FloatingComplexCast;
   3493       else
   3494         CK = CK_FloatingComplexToIntegralComplex;
   3495     } else if (ToEl->isRealFloatingType()) {
   3496       CK = CK_IntegralComplexToFloatingComplex;
   3497     } else {
   3498       CK = CK_IntegralComplexCast;
   3499     }
   3500     From = ImpCastExprToType(From, ToType, CK,
   3501                              VK_RValue, /*BasePath=*/nullptr, CCK).get();
   3502     break;
   3503   }
   3504 
   3505   case ICK_Floating_Integral:
   3506     if (ToType->isRealFloatingType())
   3507       From = ImpCastExprToType(From, ToType, CK_IntegralToFloating,
   3508                                VK_RValue, /*BasePath=*/nullptr, CCK).get();
   3509     else
   3510       From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral,
   3511                                VK_RValue, /*BasePath=*/nullptr, CCK).get();
   3512     break;
   3513 
   3514   case ICK_Compatible_Conversion:
   3515       From = ImpCastExprToType(From, ToType, CK_NoOp,
   3516                                VK_RValue, /*BasePath=*/nullptr, CCK).get();
   3517     break;
   3518 
   3519   case ICK_Writeback_Conversion:
   3520   case ICK_Pointer_Conversion: {
   3521     if (SCS.IncompatibleObjC && Action != AA_Casting) {
   3522       // Diagnose incompatible Objective-C conversions
   3523       if (Action == AA_Initializing || Action == AA_Assigning)
   3524         Diag(From->getLocStart(),
   3525              diag::ext_typecheck_convert_incompatible_pointer)
   3526           << ToType << From->getType() << Action
   3527           << From->getSourceRange() << 0;
   3528       else
   3529         Diag(From->getLocStart(),
   3530              diag::ext_typecheck_convert_incompatible_pointer)
   3531           << From->getType() << ToType << Action
   3532           << From->getSourceRange() << 0;
   3533 
   3534       if (From->getType()->isObjCObjectPointerType() &&
   3535           ToType->isObjCObjectPointerType())
   3536         EmitRelatedResultTypeNote(From);
   3537     }
   3538     else if (getLangOpts().ObjCAutoRefCount &&
   3539              !CheckObjCARCUnavailableWeakConversion(ToType,
   3540                                                     From->getType())) {
   3541       if (Action == AA_Initializing)
   3542         Diag(From->getLocStart(),
   3543              diag::err_arc_weak_unavailable_assign);
   3544       else
   3545         Diag(From->getLocStart(),
   3546              diag::err_arc_convesion_of_weak_unavailable)
   3547           << (Action == AA_Casting) << From->getType() << ToType
   3548           << From->getSourceRange();
   3549     }
   3550 
   3551     CastKind Kind = CK_Invalid;
   3552     CXXCastPath BasePath;
   3553     if (CheckPointerConversion(From, ToType, Kind, BasePath, CStyle))
   3554       return ExprError();
   3555 
   3556     // Make sure we extend blocks if necessary.
   3557     // FIXME: doing this here is really ugly.
   3558     if (Kind == CK_BlockPointerToObjCPointerCast) {
   3559       ExprResult E = From;
   3560       (void) PrepareCastToObjCObjectPointer(E);
   3561       From = E.get();
   3562     }
   3563     if (getLangOpts().ObjCAutoRefCount)
   3564       CheckObjCARCConversion(SourceRange(), ToType, From, CCK);
   3565     From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
   3566              .get();
   3567     break;
   3568   }
   3569 
   3570   case ICK_Pointer_Member: {
   3571     CastKind Kind = CK_Invalid;
   3572     CXXCastPath BasePath;
   3573     if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
   3574       return ExprError();
   3575     if (CheckExceptionSpecCompatibility(From, ToType))
   3576       return ExprError();
   3577 
   3578     // We may not have been able to figure out what this member pointer resolved
   3579     // to up until this exact point.  Attempt to lock-in it's inheritance model.
   3580     if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
   3581       (void)isCompleteType(From->getExprLoc(), From->getType());
   3582       (void)isCompleteType(From->getExprLoc(), ToType);
   3583     }
   3584 
   3585     From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
   3586              .get();
   3587     break;
   3588   }
   3589 
   3590   case ICK_Boolean_Conversion:
   3591     // Perform half-to-boolean conversion via float.
   3592     if (From->getType()->isHalfType()) {
   3593       From = ImpCastExprToType(From, Context.FloatTy, CK_FloatingCast).get();
   3594       FromType = Context.FloatTy;
   3595     }
   3596 
   3597     From = ImpCastExprToType(From, Context.BoolTy,
   3598                              ScalarTypeToBooleanCastKind(FromType),
   3599                              VK_RValue, /*BasePath=*/nullptr, CCK).get();
   3600     break;
   3601 
   3602   case ICK_Derived_To_Base: {
   3603     CXXCastPath BasePath;
   3604     if (CheckDerivedToBaseConversion(From->getType(),
   3605                                      ToType.getNonReferenceType(),
   3606                                      From->getLocStart(),
   3607                                      From->getSourceRange(),
   3608                                      &BasePath,
   3609                                      CStyle))
   3610       return ExprError();
   3611 
   3612     From = ImpCastExprToType(From, ToType.getNonReferenceType(),
   3613                       CK_DerivedToBase, From->getValueKind(),
   3614                       &BasePath, CCK).get();
   3615     break;
   3616   }
   3617 
   3618   case ICK_Vector_Conversion:
   3619     From = ImpCastExprToType(From, ToType, CK_BitCast,
   3620                              VK_RValue, /*BasePath=*/nullptr, CCK).get();
   3621     break;
   3622 
   3623   case ICK_Vector_Splat: {
   3624     // Vector splat from any arithmetic type to a vector.
   3625     Expr *Elem = prepareVectorSplat(ToType, From).get();
   3626     From = ImpCastExprToType(Elem, ToType, CK_VectorSplat, VK_RValue,
   3627                              /*BasePath=*/nullptr, CCK).get();
   3628     break;
   3629   }
   3630 
   3631   case ICK_Complex_Real:
   3632     // Case 1.  x -> _Complex y
   3633     if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
   3634       QualType ElType = ToComplex->getElementType();
   3635       bool isFloatingComplex = ElType->isRealFloatingType();
   3636 
   3637       // x -> y
   3638       if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
   3639         // do nothing
   3640       } else if (From->getType()->isRealFloatingType()) {
   3641         From = ImpCastExprToType(From, ElType,
   3642                 isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).get();
   3643       } else {
   3644         assert(From->getType()->isIntegerType());
   3645         From = ImpCastExprToType(From, ElType,
   3646                 isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).get();
   3647       }
   3648       // y -> _Complex y
   3649       From = ImpCastExprToType(From, ToType,
   3650                    isFloatingComplex ? CK_FloatingRealToComplex
   3651                                      : CK_IntegralRealToComplex).get();
   3652 
   3653     // Case 2.  _Complex x -> y
   3654     } else {
   3655       const ComplexType *FromComplex = From->getType()->getAs<ComplexType>();
   3656       assert(FromComplex);
   3657 
   3658