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 "TypeLocBuilder.h"
     17 #include "clang/AST/ASTContext.h"
     18 #include "clang/AST/CXXInheritance.h"
     19 #include "clang/AST/CharUnits.h"
     20 #include "clang/AST/DeclObjC.h"
     21 #include "clang/AST/EvaluatedExprVisitor.h"
     22 #include "clang/AST/ExprCXX.h"
     23 #include "clang/AST/ExprObjC.h"
     24 #include "clang/AST/TypeLoc.h"
     25 #include "clang/Basic/PartialDiagnostic.h"
     26 #include "clang/Basic/TargetInfo.h"
     27 #include "clang/Lex/Preprocessor.h"
     28 #include "clang/Sema/DeclSpec.h"
     29 #include "clang/Sema/Initialization.h"
     30 #include "clang/Sema/Lookup.h"
     31 #include "clang/Sema/ParsedTemplate.h"
     32 #include "clang/Sema/Scope.h"
     33 #include "clang/Sema/ScopeInfo.h"
     34 #include "clang/Sema/TemplateDeduction.h"
     35 #include "llvm/ADT/APInt.h"
     36 #include "llvm/ADT/STLExtras.h"
     37 #include "llvm/Support/ErrorHandling.h"
     38 using namespace clang;
     39 using namespace sema;
     40 
     41 ParsedType Sema::getDestructorName(SourceLocation TildeLoc,
     42                                    IdentifierInfo &II,
     43                                    SourceLocation NameLoc,
     44                                    Scope *S, CXXScopeSpec &SS,
     45                                    ParsedType ObjectTypePtr,
     46                                    bool EnteringContext) {
     47   // Determine where to perform name lookup.
     48 
     49   // FIXME: This area of the standard is very messy, and the current
     50   // wording is rather unclear about which scopes we search for the
     51   // destructor name; see core issues 399 and 555. Issue 399 in
     52   // particular shows where the current description of destructor name
     53   // lookup is completely out of line with existing practice, e.g.,
     54   // this appears to be ill-formed:
     55   //
     56   //   namespace N {
     57   //     template <typename T> struct S {
     58   //       ~S();
     59   //     };
     60   //   }
     61   //
     62   //   void f(N::S<int>* s) {
     63   //     s->N::S<int>::~S();
     64   //   }
     65   //
     66   // See also PR6358 and PR6359.
     67   // For this reason, we're currently only doing the C++03 version of this
     68   // code; the C++0x version has to wait until we get a proper spec.
     69   QualType SearchType;
     70   DeclContext *LookupCtx = 0;
     71   bool isDependent = false;
     72   bool LookInScope = false;
     73 
     74   // If we have an object type, it's because we are in a
     75   // pseudo-destructor-expression or a member access expression, and
     76   // we know what type we're looking for.
     77   if (ObjectTypePtr)
     78     SearchType = GetTypeFromParser(ObjectTypePtr);
     79 
     80   if (SS.isSet()) {
     81     NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
     82 
     83     bool AlreadySearched = false;
     84     bool LookAtPrefix = true;
     85     // C++ [basic.lookup.qual]p6:
     86     //   If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier,
     87     //   the type-names are looked up as types in the scope designated by the
     88     //   nested-name-specifier. In a qualified-id of the form:
     89     //
     90     //     ::[opt] nested-name-specifier  ~ class-name
     91     //
     92     //   where the nested-name-specifier designates a namespace scope, and in
     93     //   a qualified-id of the form:
     94     //
     95     //     ::opt nested-name-specifier class-name ::  ~ class-name
     96     //
     97     //   the class-names are looked up as types in the scope designated by
     98     //   the nested-name-specifier.
     99     //
    100     // Here, we check the first case (completely) and determine whether the
    101     // code below is permitted to look at the prefix of the
    102     // nested-name-specifier.
    103     DeclContext *DC = computeDeclContext(SS, EnteringContext);
    104     if (DC && DC->isFileContext()) {
    105       AlreadySearched = true;
    106       LookupCtx = DC;
    107       isDependent = false;
    108     } else if (DC && isa<CXXRecordDecl>(DC))
    109       LookAtPrefix = false;
    110 
    111     // The second case from the C++03 rules quoted further above.
    112     NestedNameSpecifier *Prefix = 0;
    113     if (AlreadySearched) {
    114       // Nothing left to do.
    115     } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) {
    116       CXXScopeSpec PrefixSS;
    117       PrefixSS.Adopt(NestedNameSpecifierLoc(Prefix, SS.location_data()));
    118       LookupCtx = computeDeclContext(PrefixSS, EnteringContext);
    119       isDependent = isDependentScopeSpecifier(PrefixSS);
    120     } else if (ObjectTypePtr) {
    121       LookupCtx = computeDeclContext(SearchType);
    122       isDependent = SearchType->isDependentType();
    123     } else {
    124       LookupCtx = computeDeclContext(SS, EnteringContext);
    125       isDependent = LookupCtx && LookupCtx->isDependentContext();
    126     }
    127 
    128     LookInScope = false;
    129   } else if (ObjectTypePtr) {
    130     // C++ [basic.lookup.classref]p3:
    131     //   If the unqualified-id is ~type-name, the type-name is looked up
    132     //   in the context of the entire postfix-expression. If the type T
    133     //   of the object expression is of a class type C, the type-name is
    134     //   also looked up in the scope of class C. At least one of the
    135     //   lookups shall find a name that refers to (possibly
    136     //   cv-qualified) T.
    137     LookupCtx = computeDeclContext(SearchType);
    138     isDependent = SearchType->isDependentType();
    139     assert((isDependent || !SearchType->isIncompleteType()) &&
    140            "Caller should have completed object type");
    141 
    142     LookInScope = true;
    143   } else {
    144     // Perform lookup into the current scope (only).
    145     LookInScope = true;
    146   }
    147 
    148   TypeDecl *NonMatchingTypeDecl = 0;
    149   LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName);
    150   for (unsigned Step = 0; Step != 2; ++Step) {
    151     // Look for the name first in the computed lookup context (if we
    152     // have one) and, if that fails to find a match, in the scope (if
    153     // we're allowed to look there).
    154     Found.clear();
    155     if (Step == 0 && LookupCtx)
    156       LookupQualifiedName(Found, LookupCtx);
    157     else if (Step == 1 && LookInScope && S)
    158       LookupName(Found, S);
    159     else
    160       continue;
    161 
    162     // FIXME: Should we be suppressing ambiguities here?
    163     if (Found.isAmbiguous())
    164       return ParsedType();
    165 
    166     if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
    167       QualType T = Context.getTypeDeclType(Type);
    168 
    169       if (SearchType.isNull() || SearchType->isDependentType() ||
    170           Context.hasSameUnqualifiedType(T, SearchType)) {
    171         // We found our type!
    172 
    173         return ParsedType::make(T);
    174       }
    175 
    176       if (!SearchType.isNull())
    177         NonMatchingTypeDecl = Type;
    178     }
    179 
    180     // If the name that we found is a class template name, and it is
    181     // the same name as the template name in the last part of the
    182     // nested-name-specifier (if present) or the object type, then
    183     // this is the destructor for that class.
    184     // FIXME: This is a workaround until we get real drafting for core
    185     // issue 399, for which there isn't even an obvious direction.
    186     if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) {
    187       QualType MemberOfType;
    188       if (SS.isSet()) {
    189         if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) {
    190           // Figure out the type of the context, if it has one.
    191           if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx))
    192             MemberOfType = Context.getTypeDeclType(Record);
    193         }
    194       }
    195       if (MemberOfType.isNull())
    196         MemberOfType = SearchType;
    197 
    198       if (MemberOfType.isNull())
    199         continue;
    200 
    201       // We're referring into a class template specialization. If the
    202       // class template we found is the same as the template being
    203       // specialized, we found what we are looking for.
    204       if (const RecordType *Record = MemberOfType->getAs<RecordType>()) {
    205         if (ClassTemplateSpecializationDecl *Spec
    206               = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
    207           if (Spec->getSpecializedTemplate()->getCanonicalDecl() ==
    208                 Template->getCanonicalDecl())
    209             return ParsedType::make(MemberOfType);
    210         }
    211 
    212         continue;
    213       }
    214 
    215       // We're referring to an unresolved class template
    216       // specialization. Determine whether we class template we found
    217       // is the same as the template being specialized or, if we don't
    218       // know which template is being specialized, that it at least
    219       // has the same name.
    220       if (const TemplateSpecializationType *SpecType
    221             = MemberOfType->getAs<TemplateSpecializationType>()) {
    222         TemplateName SpecName = SpecType->getTemplateName();
    223 
    224         // The class template we found is the same template being
    225         // specialized.
    226         if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) {
    227           if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl())
    228             return ParsedType::make(MemberOfType);
    229 
    230           continue;
    231         }
    232 
    233         // The class template we found has the same name as the
    234         // (dependent) template name being specialized.
    235         if (DependentTemplateName *DepTemplate
    236                                     = SpecName.getAsDependentTemplateName()) {
    237           if (DepTemplate->isIdentifier() &&
    238               DepTemplate->getIdentifier() == Template->getIdentifier())
    239             return ParsedType::make(MemberOfType);
    240 
    241           continue;
    242         }
    243       }
    244     }
    245   }
    246 
    247   if (isDependent) {
    248     // We didn't find our type, but that's okay: it's dependent
    249     // anyway.
    250 
    251     // FIXME: What if we have no nested-name-specifier?
    252     QualType T = CheckTypenameType(ETK_None, SourceLocation(),
    253                                    SS.getWithLocInContext(Context),
    254                                    II, NameLoc);
    255     return ParsedType::make(T);
    256   }
    257 
    258   if (NonMatchingTypeDecl) {
    259     QualType T = Context.getTypeDeclType(NonMatchingTypeDecl);
    260     Diag(NameLoc, diag::err_destructor_expr_type_mismatch)
    261       << T << SearchType;
    262     Diag(NonMatchingTypeDecl->getLocation(), diag::note_destructor_type_here)
    263       << T;
    264   } else if (ObjectTypePtr)
    265     Diag(NameLoc, diag::err_ident_in_dtor_not_a_type)
    266       << &II;
    267   else
    268     Diag(NameLoc, diag::err_destructor_class_name);
    269 
    270   return ParsedType();
    271 }
    272 
    273 ParsedType Sema::getDestructorType(const DeclSpec& DS, ParsedType ObjectType) {
    274     if (DS.getTypeSpecType() == DeclSpec::TST_error || !ObjectType)
    275       return ParsedType();
    276     assert(DS.getTypeSpecType() == DeclSpec::TST_decltype
    277            && "only get destructor types from declspecs");
    278     QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
    279     QualType SearchType = GetTypeFromParser(ObjectType);
    280     if (SearchType->isDependentType() || Context.hasSameUnqualifiedType(SearchType, T)) {
    281       return ParsedType::make(T);
    282     }
    283 
    284     Diag(DS.getTypeSpecTypeLoc(), diag::err_destructor_expr_type_mismatch)
    285       << T << SearchType;
    286     return ParsedType();
    287 }
    288 
    289 /// \brief Build a C++ typeid expression with a type operand.
    290 ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
    291                                 SourceLocation TypeidLoc,
    292                                 TypeSourceInfo *Operand,
    293                                 SourceLocation RParenLoc) {
    294   // C++ [expr.typeid]p4:
    295   //   The top-level cv-qualifiers of the lvalue expression or the type-id
    296   //   that is the operand of typeid are always ignored.
    297   //   If the type of the type-id is a class type or a reference to a class
    298   //   type, the class shall be completely-defined.
    299   Qualifiers Quals;
    300   QualType T
    301     = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
    302                                       Quals);
    303   if (T->getAs<RecordType>() &&
    304       RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
    305     return ExprError();
    306 
    307   return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
    308                                            Operand,
    309                                            SourceRange(TypeidLoc, RParenLoc)));
    310 }
    311 
    312 /// \brief Build a C++ typeid expression with an expression operand.
    313 ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
    314                                 SourceLocation TypeidLoc,
    315                                 Expr *E,
    316                                 SourceLocation RParenLoc) {
    317   if (E && !E->isTypeDependent()) {
    318     if (E->getType()->isPlaceholderType()) {
    319       ExprResult result = CheckPlaceholderExpr(E);
    320       if (result.isInvalid()) return ExprError();
    321       E = result.take();
    322     }
    323 
    324     QualType T = E->getType();
    325     if (const RecordType *RecordT = T->getAs<RecordType>()) {
    326       CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
    327       // C++ [expr.typeid]p3:
    328       //   [...] If the type of the expression is a class type, the class
    329       //   shall be completely-defined.
    330       if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
    331         return ExprError();
    332 
    333       // C++ [expr.typeid]p3:
    334       //   When typeid is applied to an expression other than an glvalue of a
    335       //   polymorphic class type [...] [the] expression is an unevaluated
    336       //   operand. [...]
    337       if (RecordD->isPolymorphic() && E->isGLValue()) {
    338         // The subexpression is potentially evaluated; switch the context
    339         // and recheck the subexpression.
    340         ExprResult Result = TransformToPotentiallyEvaluated(E);
    341         if (Result.isInvalid()) return ExprError();
    342         E = Result.take();
    343 
    344         // We require a vtable to query the type at run time.
    345         MarkVTableUsed(TypeidLoc, RecordD);
    346       }
    347     }
    348 
    349     // C++ [expr.typeid]p4:
    350     //   [...] If the type of the type-id is a reference to a possibly
    351     //   cv-qualified type, the result of the typeid expression refers to a
    352     //   std::type_info object representing the cv-unqualified referenced
    353     //   type.
    354     Qualifiers Quals;
    355     QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
    356     if (!Context.hasSameType(T, UnqualT)) {
    357       T = UnqualT;
    358       E = ImpCastExprToType(E, UnqualT, CK_NoOp, E->getValueKind()).take();
    359     }
    360   }
    361 
    362   return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
    363                                            E,
    364                                            SourceRange(TypeidLoc, RParenLoc)));
    365 }
    366 
    367 /// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
    368 ExprResult
    369 Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
    370                      bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
    371   // Find the std::type_info type.
    372   if (!getStdNamespace())
    373     return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
    374 
    375   if (!CXXTypeInfoDecl) {
    376     IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
    377     LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
    378     LookupQualifiedName(R, getStdNamespace());
    379     CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
    380     // Microsoft's typeinfo doesn't have type_info in std but in the global
    381     // namespace if _HAS_EXCEPTIONS is defined to 0. See PR13153.
    382     if (!CXXTypeInfoDecl && LangOpts.MicrosoftMode) {
    383       LookupQualifiedName(R, Context.getTranslationUnitDecl());
    384       CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
    385     }
    386     if (!CXXTypeInfoDecl)
    387       return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
    388   }
    389 
    390   if (!getLangOpts().RTTI) {
    391     return ExprError(Diag(OpLoc, diag::err_no_typeid_with_fno_rtti));
    392   }
    393 
    394   QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl);
    395 
    396   if (isType) {
    397     // The operand is a type; handle it as such.
    398     TypeSourceInfo *TInfo = 0;
    399     QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
    400                                    &TInfo);
    401     if (T.isNull())
    402       return ExprError();
    403 
    404     if (!TInfo)
    405       TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
    406 
    407     return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
    408   }
    409 
    410   // The operand is an expression.
    411   return BuildCXXTypeId(TypeInfoType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
    412 }
    413 
    414 /// \brief Build a Microsoft __uuidof expression with a type operand.
    415 ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
    416                                 SourceLocation TypeidLoc,
    417                                 TypeSourceInfo *Operand,
    418                                 SourceLocation RParenLoc) {
    419   if (!Operand->getType()->isDependentType()) {
    420     if (!CXXUuidofExpr::GetUuidAttrOfType(Operand->getType()))
    421       return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
    422   }
    423 
    424   // FIXME: add __uuidof semantic analysis for type operand.
    425   return Owned(new (Context) CXXUuidofExpr(TypeInfoType.withConst(),
    426                                            Operand,
    427                                            SourceRange(TypeidLoc, RParenLoc)));
    428 }
    429 
    430 /// \brief Build a Microsoft __uuidof expression with an expression operand.
    431 ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
    432                                 SourceLocation TypeidLoc,
    433                                 Expr *E,
    434                                 SourceLocation RParenLoc) {
    435   if (!E->getType()->isDependentType()) {
    436     if (!CXXUuidofExpr::GetUuidAttrOfType(E->getType()) &&
    437         !E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
    438       return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
    439   }
    440   // FIXME: add __uuidof semantic analysis for type operand.
    441   return Owned(new (Context) CXXUuidofExpr(TypeInfoType.withConst(),
    442                                            E,
    443                                            SourceRange(TypeidLoc, RParenLoc)));
    444 }
    445 
    446 /// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression);
    447 ExprResult
    448 Sema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc,
    449                      bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
    450   // If MSVCGuidDecl has not been cached, do the lookup.
    451   if (!MSVCGuidDecl) {
    452     IdentifierInfo *GuidII = &PP.getIdentifierTable().get("_GUID");
    453     LookupResult R(*this, GuidII, SourceLocation(), LookupTagName);
    454     LookupQualifiedName(R, Context.getTranslationUnitDecl());
    455     MSVCGuidDecl = R.getAsSingle<RecordDecl>();
    456     if (!MSVCGuidDecl)
    457       return ExprError(Diag(OpLoc, diag::err_need_header_before_ms_uuidof));
    458   }
    459 
    460   QualType GuidType = Context.getTypeDeclType(MSVCGuidDecl);
    461 
    462   if (isType) {
    463     // The operand is a type; handle it as such.
    464     TypeSourceInfo *TInfo = 0;
    465     QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
    466                                    &TInfo);
    467     if (T.isNull())
    468       return ExprError();
    469 
    470     if (!TInfo)
    471       TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
    472 
    473     return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc);
    474   }
    475 
    476   // The operand is an expression.
    477   return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
    478 }
    479 
    480 /// ActOnCXXBoolLiteral - Parse {true,false} literals.
    481 ExprResult
    482 Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
    483   assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
    484          "Unknown C++ Boolean value!");
    485   return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
    486                                                 Context.BoolTy, OpLoc));
    487 }
    488 
    489 /// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
    490 ExprResult
    491 Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
    492   return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
    493 }
    494 
    495 /// ActOnCXXThrow - Parse throw expressions.
    496 ExprResult
    497 Sema::ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *Ex) {
    498   bool IsThrownVarInScope = false;
    499   if (Ex) {
    500     // C++0x [class.copymove]p31:
    501     //   When certain criteria are met, an implementation is allowed to omit the
    502     //   copy/move construction of a class object [...]
    503     //
    504     //     - in a throw-expression, when the operand is the name of a
    505     //       non-volatile automatic object (other than a function or catch-
    506     //       clause parameter) whose scope does not extend beyond the end of the
    507     //       innermost enclosing try-block (if there is one), the copy/move
    508     //       operation from the operand to the exception object (15.1) can be
    509     //       omitted by constructing the automatic object directly into the
    510     //       exception object
    511     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Ex->IgnoreParens()))
    512       if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
    513         if (Var->hasLocalStorage() && !Var->getType().isVolatileQualified()) {
    514           for( ; S; S = S->getParent()) {
    515             if (S->isDeclScope(Var)) {
    516               IsThrownVarInScope = true;
    517               break;
    518             }
    519 
    520             if (S->getFlags() &
    521                 (Scope::FnScope | Scope::ClassScope | Scope::BlockScope |
    522                  Scope::FunctionPrototypeScope | Scope::ObjCMethodScope |
    523                  Scope::TryScope))
    524               break;
    525           }
    526         }
    527       }
    528   }
    529 
    530   return BuildCXXThrow(OpLoc, Ex, IsThrownVarInScope);
    531 }
    532 
    533 ExprResult Sema::BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
    534                                bool IsThrownVarInScope) {
    535   // Don't report an error if 'throw' is used in system headers.
    536   if (!getLangOpts().CXXExceptions &&
    537       !getSourceManager().isInSystemHeader(OpLoc))
    538     Diag(OpLoc, diag::err_exceptions_disabled) << "throw";
    539 
    540   if (Ex && !Ex->isTypeDependent()) {
    541     ExprResult ExRes = CheckCXXThrowOperand(OpLoc, Ex, IsThrownVarInScope);
    542     if (ExRes.isInvalid())
    543       return ExprError();
    544     Ex = ExRes.take();
    545   }
    546 
    547   return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc,
    548                                           IsThrownVarInScope));
    549 }
    550 
    551 /// CheckCXXThrowOperand - Validate the operand of a throw.
    552 ExprResult Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *E,
    553                                       bool IsThrownVarInScope) {
    554   // C++ [except.throw]p3:
    555   //   A throw-expression initializes a temporary object, called the exception
    556   //   object, the type of which is determined by removing any top-level
    557   //   cv-qualifiers from the static type of the operand of throw and adjusting
    558   //   the type from "array of T" or "function returning T" to "pointer to T"
    559   //   or "pointer to function returning T", [...]
    560   if (E->getType().hasQualifiers())
    561     E = ImpCastExprToType(E, E->getType().getUnqualifiedType(), CK_NoOp,
    562                           E->getValueKind()).take();
    563 
    564   ExprResult Res = DefaultFunctionArrayConversion(E);
    565   if (Res.isInvalid())
    566     return ExprError();
    567   E = Res.take();
    568 
    569   //   If the type of the exception would be an incomplete type or a pointer
    570   //   to an incomplete type other than (cv) void the program is ill-formed.
    571   QualType Ty = E->getType();
    572   bool isPointer = false;
    573   if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
    574     Ty = Ptr->getPointeeType();
    575     isPointer = true;
    576   }
    577   if (!isPointer || !Ty->isVoidType()) {
    578     if (RequireCompleteType(ThrowLoc, Ty,
    579                             isPointer? diag::err_throw_incomplete_ptr
    580                                      : diag::err_throw_incomplete,
    581                             E->getSourceRange()))
    582       return ExprError();
    583 
    584     if (RequireNonAbstractType(ThrowLoc, E->getType(),
    585                                diag::err_throw_abstract_type, E))
    586       return ExprError();
    587   }
    588 
    589   // Initialize the exception result.  This implicitly weeds out
    590   // abstract types or types with inaccessible copy constructors.
    591 
    592   // C++0x [class.copymove]p31:
    593   //   When certain criteria are met, an implementation is allowed to omit the
    594   //   copy/move construction of a class object [...]
    595   //
    596   //     - in a throw-expression, when the operand is the name of a
    597   //       non-volatile automatic object (other than a function or catch-clause
    598   //       parameter) whose scope does not extend beyond the end of the
    599   //       innermost enclosing try-block (if there is one), the copy/move
    600   //       operation from the operand to the exception object (15.1) can be
    601   //       omitted by constructing the automatic object directly into the
    602   //       exception object
    603   const VarDecl *NRVOVariable = 0;
    604   if (IsThrownVarInScope)
    605     NRVOVariable = getCopyElisionCandidate(QualType(), E, false);
    606 
    607   InitializedEntity Entity =
    608       InitializedEntity::InitializeException(ThrowLoc, E->getType(),
    609                                              /*NRVO=*/NRVOVariable != 0);
    610   Res = PerformMoveOrCopyInitialization(Entity, NRVOVariable,
    611                                         QualType(), E,
    612                                         IsThrownVarInScope);
    613   if (Res.isInvalid())
    614     return ExprError();
    615   E = Res.take();
    616 
    617   // If the exception has class type, we need additional handling.
    618   const RecordType *RecordTy = Ty->getAs<RecordType>();
    619   if (!RecordTy)
    620     return Owned(E);
    621   CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
    622 
    623   // If we are throwing a polymorphic class type or pointer thereof,
    624   // exception handling will make use of the vtable.
    625   MarkVTableUsed(ThrowLoc, RD);
    626 
    627   // If a pointer is thrown, the referenced object will not be destroyed.
    628   if (isPointer)
    629     return Owned(E);
    630 
    631   // If the class has a destructor, we must be able to call it.
    632   if (RD->hasIrrelevantDestructor())
    633     return Owned(E);
    634 
    635   CXXDestructorDecl *Destructor = LookupDestructor(RD);
    636   if (!Destructor)
    637     return Owned(E);
    638 
    639   MarkFunctionReferenced(E->getExprLoc(), Destructor);
    640   CheckDestructorAccess(E->getExprLoc(), Destructor,
    641                         PDiag(diag::err_access_dtor_exception) << Ty);
    642   DiagnoseUseOfDecl(Destructor, E->getExprLoc());
    643   return Owned(E);
    644 }
    645 
    646 QualType Sema::getCurrentThisType() {
    647   DeclContext *DC = getFunctionLevelDeclContext();
    648   QualType ThisTy = CXXThisTypeOverride;
    649   if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC)) {
    650     if (method && method->isInstance())
    651       ThisTy = method->getThisType(Context);
    652   }
    653 
    654   return ThisTy;
    655 }
    656 
    657 Sema::CXXThisScopeRAII::CXXThisScopeRAII(Sema &S,
    658                                          Decl *ContextDecl,
    659                                          unsigned CXXThisTypeQuals,
    660                                          bool Enabled)
    661   : S(S), OldCXXThisTypeOverride(S.CXXThisTypeOverride), Enabled(false)
    662 {
    663   if (!Enabled || !ContextDecl)
    664     return;
    665 
    666   CXXRecordDecl *Record = 0;
    667   if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(ContextDecl))
    668     Record = Template->getTemplatedDecl();
    669   else
    670     Record = cast<CXXRecordDecl>(ContextDecl);
    671 
    672   S.CXXThisTypeOverride
    673     = S.Context.getPointerType(
    674         S.Context.getRecordType(Record).withCVRQualifiers(CXXThisTypeQuals));
    675 
    676   this->Enabled = true;
    677 }
    678 
    679 
    680 Sema::CXXThisScopeRAII::~CXXThisScopeRAII() {
    681   if (Enabled) {
    682     S.CXXThisTypeOverride = OldCXXThisTypeOverride;
    683   }
    684 }
    685 
    686 void Sema::CheckCXXThisCapture(SourceLocation Loc, bool Explicit) {
    687   // We don't need to capture this in an unevaluated context.
    688   if (ExprEvalContexts.back().Context == Unevaluated && !Explicit)
    689     return;
    690 
    691   // Otherwise, check that we can capture 'this'.
    692   unsigned NumClosures = 0;
    693   for (unsigned idx = FunctionScopes.size() - 1; idx != 0; idx--) {
    694     if (CapturingScopeInfo *CSI =
    695             dyn_cast<CapturingScopeInfo>(FunctionScopes[idx])) {
    696       if (CSI->CXXThisCaptureIndex != 0) {
    697         // 'this' is already being captured; there isn't anything more to do.
    698         break;
    699       }
    700 
    701       if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByref ||
    702           CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval ||
    703           CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_Block ||
    704           Explicit) {
    705         // This closure can capture 'this'; continue looking upwards.
    706         NumClosures++;
    707         Explicit = false;
    708         continue;
    709       }
    710       // This context can't implicitly capture 'this'; fail out.
    711       Diag(Loc, diag::err_this_capture) << Explicit;
    712       return;
    713     }
    714     break;
    715   }
    716 
    717   // Mark that we're implicitly capturing 'this' in all the scopes we skipped.
    718   // FIXME: We need to delay this marking in PotentiallyPotentiallyEvaluated
    719   // contexts.
    720   for (unsigned idx = FunctionScopes.size() - 1;
    721        NumClosures; --idx, --NumClosures) {
    722     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[idx]);
    723     Expr *ThisExpr = 0;
    724     QualType ThisTy = getCurrentThisType();
    725     if (LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
    726       // For lambda expressions, build a field and an initializing expression.
    727       CXXRecordDecl *Lambda = LSI->Lambda;
    728       FieldDecl *Field
    729         = FieldDecl::Create(Context, Lambda, Loc, Loc, 0, ThisTy,
    730                             Context.getTrivialTypeSourceInfo(ThisTy, Loc),
    731                             0, false, ICIS_NoInit);
    732       Field->setImplicit(true);
    733       Field->setAccess(AS_private);
    734       Lambda->addDecl(Field);
    735       ThisExpr = new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit=*/true);
    736     }
    737     bool isNested = NumClosures > 1;
    738     CSI->addThisCapture(isNested, Loc, ThisTy, ThisExpr);
    739   }
    740 }
    741 
    742 ExprResult Sema::ActOnCXXThis(SourceLocation Loc) {
    743   /// C++ 9.3.2: In the body of a non-static member function, the keyword this
    744   /// is a non-lvalue expression whose value is the address of the object for
    745   /// which the function is called.
    746 
    747   QualType ThisTy = getCurrentThisType();
    748   if (ThisTy.isNull()) return Diag(Loc, diag::err_invalid_this_use);
    749 
    750   CheckCXXThisCapture(Loc);
    751   return Owned(new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit=*/false));
    752 }
    753 
    754 bool Sema::isThisOutsideMemberFunctionBody(QualType BaseType) {
    755   // If we're outside the body of a member function, then we'll have a specified
    756   // type for 'this'.
    757   if (CXXThisTypeOverride.isNull())
    758     return false;
    759 
    760   // Determine whether we're looking into a class that's currently being
    761   // defined.
    762   CXXRecordDecl *Class = BaseType->getAsCXXRecordDecl();
    763   return Class && Class->isBeingDefined();
    764 }
    765 
    766 ExprResult
    767 Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep,
    768                                 SourceLocation LParenLoc,
    769                                 MultiExprArg exprs,
    770                                 SourceLocation RParenLoc) {
    771   if (!TypeRep)
    772     return ExprError();
    773 
    774   TypeSourceInfo *TInfo;
    775   QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
    776   if (!TInfo)
    777     TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
    778 
    779   return BuildCXXTypeConstructExpr(TInfo, LParenLoc, exprs, RParenLoc);
    780 }
    781 
    782 /// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
    783 /// Can be interpreted either as function-style casting ("int(x)")
    784 /// or class type construction ("ClassType(x,y,z)")
    785 /// or creation of a value-initialized type ("int()").
    786 ExprResult
    787 Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo,
    788                                 SourceLocation LParenLoc,
    789                                 MultiExprArg exprs,
    790                                 SourceLocation RParenLoc) {
    791   QualType Ty = TInfo->getType();
    792   SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
    793 
    794   if (Ty->isDependentType() || CallExpr::hasAnyTypeDependentArguments(exprs)) {
    795     return Owned(CXXUnresolvedConstructExpr::Create(Context, TInfo,
    796                                                     LParenLoc,
    797                                                     exprs,
    798                                                     RParenLoc));
    799   }
    800 
    801   unsigned NumExprs = exprs.size();
    802   Expr **Exprs = exprs.data();
    803 
    804   bool ListInitialization = LParenLoc.isInvalid();
    805   assert((!ListInitialization || (NumExprs == 1 && isa<InitListExpr>(Exprs[0])))
    806          && "List initialization must have initializer list as expression.");
    807   SourceRange FullRange = SourceRange(TyBeginLoc,
    808       ListInitialization ? Exprs[0]->getSourceRange().getEnd() : RParenLoc);
    809 
    810   // C++ [expr.type.conv]p1:
    811   // If the expression list is a single expression, the type conversion
    812   // expression is equivalent (in definedness, and if defined in meaning) to the
    813   // corresponding cast expression.
    814   if (NumExprs == 1 && !ListInitialization) {
    815     Expr *Arg = Exprs[0];
    816     return BuildCXXFunctionalCastExpr(TInfo, LParenLoc, Arg, RParenLoc);
    817   }
    818 
    819   QualType ElemTy = Ty;
    820   if (Ty->isArrayType()) {
    821     if (!ListInitialization)
    822       return ExprError(Diag(TyBeginLoc,
    823                             diag::err_value_init_for_array_type) << FullRange);
    824     ElemTy = Context.getBaseElementType(Ty);
    825   }
    826 
    827   if (!Ty->isVoidType() &&
    828       RequireCompleteType(TyBeginLoc, ElemTy,
    829                           diag::err_invalid_incomplete_type_use, FullRange))
    830     return ExprError();
    831 
    832   if (RequireNonAbstractType(TyBeginLoc, Ty,
    833                              diag::err_allocation_of_abstract_type))
    834     return ExprError();
    835 
    836   InitializedEntity Entity = InitializedEntity::InitializeTemporary(TInfo);
    837   InitializationKind Kind
    838     = NumExprs ? ListInitialization
    839                     ? InitializationKind::CreateDirectList(TyBeginLoc)
    840                     : InitializationKind::CreateDirect(TyBeginLoc,
    841                                                        LParenLoc, RParenLoc)
    842                : InitializationKind::CreateValue(TyBeginLoc,
    843                                                  LParenLoc, RParenLoc);
    844   InitializationSequence InitSeq(*this, Entity, Kind, Exprs, NumExprs);
    845   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, exprs);
    846 
    847   if (!Result.isInvalid() && ListInitialization &&
    848       isa<InitListExpr>(Result.get())) {
    849     // If the list-initialization doesn't involve a constructor call, we'll get
    850     // the initializer-list (with corrected type) back, but that's not what we
    851     // want, since it will be treated as an initializer list in further
    852     // processing. Explicitly insert a cast here.
    853     InitListExpr *List = cast<InitListExpr>(Result.take());
    854     Result = Owned(CXXFunctionalCastExpr::Create(Context, List->getType(),
    855                                     Expr::getValueKindForType(TInfo->getType()),
    856                                                  TInfo, TyBeginLoc, CK_NoOp,
    857                                                  List, /*Path=*/0, RParenLoc));
    858   }
    859 
    860   // FIXME: Improve AST representation?
    861   return Result;
    862 }
    863 
    864 /// doesUsualArrayDeleteWantSize - Answers whether the usual
    865 /// operator delete[] for the given type has a size_t parameter.
    866 static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc,
    867                                          QualType allocType) {
    868   const RecordType *record =
    869     allocType->getBaseElementTypeUnsafe()->getAs<RecordType>();
    870   if (!record) return false;
    871 
    872   // Try to find an operator delete[] in class scope.
    873 
    874   DeclarationName deleteName =
    875     S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
    876   LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
    877   S.LookupQualifiedName(ops, record->getDecl());
    878 
    879   // We're just doing this for information.
    880   ops.suppressDiagnostics();
    881 
    882   // Very likely: there's no operator delete[].
    883   if (ops.empty()) return false;
    884 
    885   // If it's ambiguous, it should be illegal to call operator delete[]
    886   // on this thing, so it doesn't matter if we allocate extra space or not.
    887   if (ops.isAmbiguous()) return false;
    888 
    889   LookupResult::Filter filter = ops.makeFilter();
    890   while (filter.hasNext()) {
    891     NamedDecl *del = filter.next()->getUnderlyingDecl();
    892 
    893     // C++0x [basic.stc.dynamic.deallocation]p2:
    894     //   A template instance is never a usual deallocation function,
    895     //   regardless of its signature.
    896     if (isa<FunctionTemplateDecl>(del)) {
    897       filter.erase();
    898       continue;
    899     }
    900 
    901     // C++0x [basic.stc.dynamic.deallocation]p2:
    902     //   If class T does not declare [an operator delete[] with one
    903     //   parameter] but does declare a member deallocation function
    904     //   named operator delete[] with exactly two parameters, the
    905     //   second of which has type std::size_t, then this function
    906     //   is a usual deallocation function.
    907     if (!cast<CXXMethodDecl>(del)->isUsualDeallocationFunction()) {
    908       filter.erase();
    909       continue;
    910     }
    911   }
    912   filter.done();
    913 
    914   if (!ops.isSingleResult()) return false;
    915 
    916   const FunctionDecl *del = cast<FunctionDecl>(ops.getFoundDecl());
    917   return (del->getNumParams() == 2);
    918 }
    919 
    920 /// \brief Parsed a C++ 'new' expression (C++ 5.3.4).
    921 ///
    922 /// E.g.:
    923 /// @code new (memory) int[size][4] @endcode
    924 /// or
    925 /// @code ::new Foo(23, "hello") @endcode
    926 ///
    927 /// \param StartLoc The first location of the expression.
    928 /// \param UseGlobal True if 'new' was prefixed with '::'.
    929 /// \param PlacementLParen Opening paren of the placement arguments.
    930 /// \param PlacementArgs Placement new arguments.
    931 /// \param PlacementRParen Closing paren of the placement arguments.
    932 /// \param TypeIdParens If the type is in parens, the source range.
    933 /// \param D The type to be allocated, as well as array dimensions.
    934 /// \param Initializer The initializing expression or initializer-list, or null
    935 ///   if there is none.
    936 ExprResult
    937 Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
    938                   SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
    939                   SourceLocation PlacementRParen, SourceRange TypeIdParens,
    940                   Declarator &D, Expr *Initializer) {
    941   bool TypeContainsAuto = D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto;
    942 
    943   Expr *ArraySize = 0;
    944   // If the specified type is an array, unwrap it and save the expression.
    945   if (D.getNumTypeObjects() > 0 &&
    946       D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
    947      DeclaratorChunk &Chunk = D.getTypeObject(0);
    948     if (TypeContainsAuto)
    949       return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto)
    950         << D.getSourceRange());
    951     if (Chunk.Arr.hasStatic)
    952       return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
    953         << D.getSourceRange());
    954     if (!Chunk.Arr.NumElts)
    955       return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
    956         << D.getSourceRange());
    957 
    958     ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
    959     D.DropFirstTypeObject();
    960   }
    961 
    962   // Every dimension shall be of constant size.
    963   if (ArraySize) {
    964     for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
    965       if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
    966         break;
    967 
    968       DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
    969       if (Expr *NumElts = (Expr *)Array.NumElts) {
    970         if (!NumElts->isTypeDependent() && !NumElts->isValueDependent()) {
    971           Array.NumElts
    972             = VerifyIntegerConstantExpression(NumElts, 0,
    973                                               diag::err_new_array_nonconst)
    974                 .take();
    975           if (!Array.NumElts)
    976             return ExprError();
    977         }
    978       }
    979     }
    980   }
    981 
    982   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/0);
    983   QualType AllocType = TInfo->getType();
    984   if (D.isInvalidType())
    985     return ExprError();
    986 
    987   SourceRange DirectInitRange;
    988   if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer))
    989     DirectInitRange = List->getSourceRange();
    990 
    991   return BuildCXXNew(SourceRange(StartLoc, D.getLocEnd()), UseGlobal,
    992                      PlacementLParen,
    993                      PlacementArgs,
    994                      PlacementRParen,
    995                      TypeIdParens,
    996                      AllocType,
    997                      TInfo,
    998                      ArraySize,
    999                      DirectInitRange,
   1000                      Initializer,
   1001                      TypeContainsAuto);
   1002 }
   1003 
   1004 static bool isLegalArrayNewInitializer(CXXNewExpr::InitializationStyle Style,
   1005                                        Expr *Init) {
   1006   if (!Init)
   1007     return true;
   1008   if (ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init))
   1009     return PLE->getNumExprs() == 0;
   1010   if (isa<ImplicitValueInitExpr>(Init))
   1011     return true;
   1012   else if (CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init))
   1013     return !CCE->isListInitialization() &&
   1014            CCE->getConstructor()->isDefaultConstructor();
   1015   else if (Style == CXXNewExpr::ListInit) {
   1016     assert(isa<InitListExpr>(Init) &&
   1017            "Shouldn't create list CXXConstructExprs for arrays.");
   1018     return true;
   1019   }
   1020   return false;
   1021 }
   1022 
   1023 ExprResult
   1024 Sema::BuildCXXNew(SourceRange Range, bool UseGlobal,
   1025                   SourceLocation PlacementLParen,
   1026                   MultiExprArg PlacementArgs,
   1027                   SourceLocation PlacementRParen,
   1028                   SourceRange TypeIdParens,
   1029                   QualType AllocType,
   1030                   TypeSourceInfo *AllocTypeInfo,
   1031                   Expr *ArraySize,
   1032                   SourceRange DirectInitRange,
   1033                   Expr *Initializer,
   1034                   bool TypeMayContainAuto) {
   1035   SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
   1036   SourceLocation StartLoc = Range.getBegin();
   1037 
   1038   CXXNewExpr::InitializationStyle initStyle;
   1039   if (DirectInitRange.isValid()) {
   1040     assert(Initializer && "Have parens but no initializer.");
   1041     initStyle = CXXNewExpr::CallInit;
   1042   } else if (Initializer && isa<InitListExpr>(Initializer))
   1043     initStyle = CXXNewExpr::ListInit;
   1044   else {
   1045     assert((!Initializer || isa<ImplicitValueInitExpr>(Initializer) ||
   1046             isa<CXXConstructExpr>(Initializer)) &&
   1047            "Initializer expression that cannot have been implicitly created.");
   1048     initStyle = CXXNewExpr::NoInit;
   1049   }
   1050 
   1051   Expr **Inits = &Initializer;
   1052   unsigned NumInits = Initializer ? 1 : 0;
   1053   if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer)) {
   1054     assert(initStyle == CXXNewExpr::CallInit && "paren init for non-call init");
   1055     Inits = List->getExprs();
   1056     NumInits = List->getNumExprs();
   1057   }
   1058 
   1059   // Determine whether we've already built the initializer.
   1060   bool HaveCompleteInit = false;
   1061   if (Initializer && isa<CXXConstructExpr>(Initializer) &&
   1062       !isa<CXXTemporaryObjectExpr>(Initializer))
   1063     HaveCompleteInit = true;
   1064   else if (Initializer && isa<ImplicitValueInitExpr>(Initializer))
   1065     HaveCompleteInit = true;
   1066 
   1067   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
   1068   AutoType *AT = 0;
   1069   if (TypeMayContainAuto &&
   1070       (AT = AllocType->getContainedAutoType()) && !AT->isDeduced()) {
   1071     if (initStyle == CXXNewExpr::NoInit || NumInits == 0)
   1072       return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg)
   1073                        << AllocType << TypeRange);
   1074     if (initStyle == CXXNewExpr::ListInit)
   1075       return ExprError(Diag(Inits[0]->getLocStart(),
   1076                             diag::err_auto_new_requires_parens)
   1077                        << AllocType << TypeRange);
   1078     if (NumInits > 1) {
   1079       Expr *FirstBad = Inits[1];
   1080       return ExprError(Diag(FirstBad->getLocStart(),
   1081                             diag::err_auto_new_ctor_multiple_expressions)
   1082                        << AllocType << TypeRange);
   1083     }
   1084     Expr *Deduce = Inits[0];
   1085     TypeSourceInfo *DeducedType = 0;
   1086     if (DeduceAutoType(AllocTypeInfo, Deduce, DeducedType) == DAR_Failed)
   1087       return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure)
   1088                        << AllocType << Deduce->getType()
   1089                        << TypeRange << Deduce->getSourceRange());
   1090     if (!DeducedType)
   1091       return ExprError();
   1092 
   1093     AllocTypeInfo = DeducedType;
   1094     AllocType = AllocTypeInfo->getType();
   1095   }
   1096 
   1097   // Per C++0x [expr.new]p5, the type being constructed may be a
   1098   // typedef of an array type.
   1099   if (!ArraySize) {
   1100     if (const ConstantArrayType *Array
   1101                               = Context.getAsConstantArrayType(AllocType)) {
   1102       ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
   1103                                          Context.getSizeType(),
   1104                                          TypeRange.getEnd());
   1105       AllocType = Array->getElementType();
   1106     }
   1107   }
   1108 
   1109   if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
   1110     return ExprError();
   1111 
   1112   if (initStyle == CXXNewExpr::ListInit && isStdInitializerList(AllocType, 0)) {
   1113     Diag(AllocTypeInfo->getTypeLoc().getBeginLoc(),
   1114          diag::warn_dangling_std_initializer_list)
   1115         << /*at end of FE*/0 << Inits[0]->getSourceRange();
   1116   }
   1117 
   1118   // In ARC, infer 'retaining' for the allocated
   1119   if (getLangOpts().ObjCAutoRefCount &&
   1120       AllocType.getObjCLifetime() == Qualifiers::OCL_None &&
   1121       AllocType->isObjCLifetimeType()) {
   1122     AllocType = Context.getLifetimeQualifiedType(AllocType,
   1123                                     AllocType->getObjCARCImplicitLifetime());
   1124   }
   1125 
   1126   QualType ResultType = Context.getPointerType(AllocType);
   1127 
   1128   // C++98 5.3.4p6: "The expression in a direct-new-declarator shall have
   1129   //   integral or enumeration type with a non-negative value."
   1130   // C++11 [expr.new]p6: The expression [...] shall be of integral or unscoped
   1131   //   enumeration type, or a class type for which a single non-explicit
   1132   //   conversion function to integral or unscoped enumeration type exists.
   1133   if (ArraySize && !ArraySize->isTypeDependent()) {
   1134     class SizeConvertDiagnoser : public ICEConvertDiagnoser {
   1135       Expr *ArraySize;
   1136 
   1137     public:
   1138       SizeConvertDiagnoser(Expr *ArraySize)
   1139         : ICEConvertDiagnoser(false, false), ArraySize(ArraySize) { }
   1140 
   1141       virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
   1142                                                QualType T) {
   1143         return S.Diag(Loc, diag::err_array_size_not_integral)
   1144                  << S.getLangOpts().CPlusPlus11 << T;
   1145       }
   1146 
   1147       virtual DiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
   1148                                                    QualType T) {
   1149         return S.Diag(Loc, diag::err_array_size_incomplete_type)
   1150                  << T << ArraySize->getSourceRange();
   1151       }
   1152 
   1153       virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S,
   1154                                                      SourceLocation Loc,
   1155                                                      QualType T,
   1156                                                      QualType ConvTy) {
   1157         return S.Diag(Loc, diag::err_array_size_explicit_conversion) << T << ConvTy;
   1158       }
   1159 
   1160       virtual DiagnosticBuilder noteExplicitConv(Sema &S,
   1161                                                  CXXConversionDecl *Conv,
   1162                                                  QualType ConvTy) {
   1163         return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
   1164                  << ConvTy->isEnumeralType() << ConvTy;
   1165       }
   1166 
   1167       virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
   1168                                                   QualType T) {
   1169         return S.Diag(Loc, diag::err_array_size_ambiguous_conversion) << T;
   1170       }
   1171 
   1172       virtual DiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
   1173                                               QualType ConvTy) {
   1174         return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
   1175                  << ConvTy->isEnumeralType() << ConvTy;
   1176       }
   1177 
   1178       virtual DiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
   1179                                                    QualType T,
   1180                                                    QualType ConvTy) {
   1181         return S.Diag(Loc,
   1182                       S.getLangOpts().CPlusPlus11
   1183                         ? diag::warn_cxx98_compat_array_size_conversion
   1184                         : diag::ext_array_size_conversion)
   1185                  << T << ConvTy->isEnumeralType() << ConvTy;
   1186       }
   1187     } SizeDiagnoser(ArraySize);
   1188 
   1189     ExprResult ConvertedSize
   1190       = ConvertToIntegralOrEnumerationType(StartLoc, ArraySize, SizeDiagnoser,
   1191                                            /*AllowScopedEnumerations*/ false);
   1192     if (ConvertedSize.isInvalid())
   1193       return ExprError();
   1194 
   1195     ArraySize = ConvertedSize.take();
   1196     QualType SizeType = ArraySize->getType();
   1197     if (!SizeType->isIntegralOrUnscopedEnumerationType())
   1198       return ExprError();
   1199 
   1200     // C++98 [expr.new]p7:
   1201     //   The expression in a direct-new-declarator shall have integral type
   1202     //   with a non-negative value.
   1203     //
   1204     // Let's see if this is a constant < 0. If so, we reject it out of
   1205     // hand. Otherwise, if it's not a constant, we must have an unparenthesized
   1206     // array type.
   1207     //
   1208     // Note: such a construct has well-defined semantics in C++11: it throws
   1209     // std::bad_array_new_length.
   1210     if (!ArraySize->isValueDependent()) {
   1211       llvm::APSInt Value;
   1212       // We've already performed any required implicit conversion to integer or
   1213       // unscoped enumeration type.
   1214       if (ArraySize->isIntegerConstantExpr(Value, Context)) {
   1215         if (Value < llvm::APSInt(
   1216                         llvm::APInt::getNullValue(Value.getBitWidth()),
   1217                                  Value.isUnsigned())) {
   1218           if (getLangOpts().CPlusPlus11)
   1219             Diag(ArraySize->getLocStart(),
   1220                  diag::warn_typecheck_negative_array_new_size)
   1221               << ArraySize->getSourceRange();
   1222           else
   1223             return ExprError(Diag(ArraySize->getLocStart(),
   1224                                   diag::err_typecheck_negative_array_size)
   1225                              << ArraySize->getSourceRange());
   1226         } else if (!AllocType->isDependentType()) {
   1227           unsigned ActiveSizeBits =
   1228             ConstantArrayType::getNumAddressingBits(Context, AllocType, Value);
   1229           if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
   1230             if (getLangOpts().CPlusPlus11)
   1231               Diag(ArraySize->getLocStart(),
   1232                    diag::warn_array_new_too_large)
   1233                 << Value.toString(10)
   1234                 << ArraySize->getSourceRange();
   1235             else
   1236               return ExprError(Diag(ArraySize->getLocStart(),
   1237                                     diag::err_array_too_large)
   1238                                << Value.toString(10)
   1239                                << ArraySize->getSourceRange());
   1240           }
   1241         }
   1242       } else if (TypeIdParens.isValid()) {
   1243         // Can't have dynamic array size when the type-id is in parentheses.
   1244         Diag(ArraySize->getLocStart(), diag::ext_new_paren_array_nonconst)
   1245           << ArraySize->getSourceRange()
   1246           << FixItHint::CreateRemoval(TypeIdParens.getBegin())
   1247           << FixItHint::CreateRemoval(TypeIdParens.getEnd());
   1248 
   1249         TypeIdParens = SourceRange();
   1250       }
   1251     }
   1252 
   1253     // Note that we do *not* convert the argument in any way.  It can
   1254     // be signed, larger than size_t, whatever.
   1255   }
   1256 
   1257   FunctionDecl *OperatorNew = 0;
   1258   FunctionDecl *OperatorDelete = 0;
   1259   Expr **PlaceArgs = PlacementArgs.data();
   1260   unsigned NumPlaceArgs = PlacementArgs.size();
   1261 
   1262   if (!AllocType->isDependentType() &&
   1263       !Expr::hasAnyTypeDependentArguments(
   1264         llvm::makeArrayRef(PlaceArgs, NumPlaceArgs)) &&
   1265       FindAllocationFunctions(StartLoc,
   1266                               SourceRange(PlacementLParen, PlacementRParen),
   1267                               UseGlobal, AllocType, ArraySize, PlaceArgs,
   1268                               NumPlaceArgs, OperatorNew, OperatorDelete))
   1269     return ExprError();
   1270 
   1271   // If this is an array allocation, compute whether the usual array
   1272   // deallocation function for the type has a size_t parameter.
   1273   bool UsualArrayDeleteWantsSize = false;
   1274   if (ArraySize && !AllocType->isDependentType())
   1275     UsualArrayDeleteWantsSize
   1276       = doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);
   1277 
   1278   SmallVector<Expr *, 8> AllPlaceArgs;
   1279   if (OperatorNew) {
   1280     // Add default arguments, if any.
   1281     const FunctionProtoType *Proto =
   1282       OperatorNew->getType()->getAs<FunctionProtoType>();
   1283     VariadicCallType CallType =
   1284       Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
   1285 
   1286     if (GatherArgumentsForCall(PlacementLParen, OperatorNew,
   1287                                Proto, 1, PlaceArgs, NumPlaceArgs,
   1288                                AllPlaceArgs, CallType))
   1289       return ExprError();
   1290 
   1291     NumPlaceArgs = AllPlaceArgs.size();
   1292     if (NumPlaceArgs > 0)
   1293       PlaceArgs = &AllPlaceArgs[0];
   1294 
   1295     DiagnoseSentinelCalls(OperatorNew, PlacementLParen,
   1296                           PlaceArgs, NumPlaceArgs);
   1297 
   1298     // FIXME: Missing call to CheckFunctionCall or equivalent
   1299   }
   1300 
   1301   // Warn if the type is over-aligned and is being allocated by global operator
   1302   // new.
   1303   if (NumPlaceArgs == 0 && OperatorNew &&
   1304       (OperatorNew->isImplicit() ||
   1305        getSourceManager().isInSystemHeader(OperatorNew->getLocStart()))) {
   1306     if (unsigned Align = Context.getPreferredTypeAlign(AllocType.getTypePtr())){
   1307       unsigned SuitableAlign = Context.getTargetInfo().getSuitableAlign();
   1308       if (Align > SuitableAlign)
   1309         Diag(StartLoc, diag::warn_overaligned_type)
   1310             << AllocType
   1311             << unsigned(Align / Context.getCharWidth())
   1312             << unsigned(SuitableAlign / Context.getCharWidth());
   1313     }
   1314   }
   1315 
   1316   QualType InitType = AllocType;
   1317   // Array 'new' can't have any initializers except empty parentheses.
   1318   // Initializer lists are also allowed, in C++11. Rely on the parser for the
   1319   // dialect distinction.
   1320   if (ResultType->isArrayType() || ArraySize) {
   1321     if (!isLegalArrayNewInitializer(initStyle, Initializer)) {
   1322       SourceRange InitRange(Inits[0]->getLocStart(),
   1323                             Inits[NumInits - 1]->getLocEnd());
   1324       Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
   1325       return ExprError();
   1326     }
   1327     if (InitListExpr *ILE = dyn_cast_or_null<InitListExpr>(Initializer)) {
   1328       // We do the initialization typechecking against the array type
   1329       // corresponding to the number of initializers + 1 (to also check
   1330       // default-initialization).
   1331       unsigned NumElements = ILE->getNumInits() + 1;
   1332       InitType = Context.getConstantArrayType(AllocType,
   1333           llvm::APInt(Context.getTypeSize(Context.getSizeType()), NumElements),
   1334                                               ArrayType::Normal, 0);
   1335     }
   1336   }
   1337 
   1338   // If we can perform the initialization, and we've not already done so,
   1339   // do it now.
   1340   if (!AllocType->isDependentType() &&
   1341       !Expr::hasAnyTypeDependentArguments(
   1342         llvm::makeArrayRef(Inits, NumInits)) &&
   1343       !HaveCompleteInit) {
   1344     // C++11 [expr.new]p15:
   1345     //   A new-expression that creates an object of type T initializes that
   1346     //   object as follows:
   1347     InitializationKind Kind
   1348     //     - If the new-initializer is omitted, the object is default-
   1349     //       initialized (8.5); if no initialization is performed,
   1350     //       the object has indeterminate value
   1351       = initStyle == CXXNewExpr::NoInit
   1352           ? InitializationKind::CreateDefault(TypeRange.getBegin())
   1353     //     - Otherwise, the new-initializer is interpreted according to the
   1354     //       initialization rules of 8.5 for direct-initialization.
   1355           : initStyle == CXXNewExpr::ListInit
   1356               ? InitializationKind::CreateDirectList(TypeRange.getBegin())
   1357               : InitializationKind::CreateDirect(TypeRange.getBegin(),
   1358                                                  DirectInitRange.getBegin(),
   1359                                                  DirectInitRange.getEnd());
   1360 
   1361     InitializedEntity Entity
   1362       = InitializedEntity::InitializeNew(StartLoc, InitType);
   1363     InitializationSequence InitSeq(*this, Entity, Kind, Inits, NumInits);
   1364     ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
   1365                                           MultiExprArg(Inits, NumInits));
   1366     if (FullInit.isInvalid())
   1367       return ExprError();
   1368 
   1369     // FullInit is our initializer; strip off CXXBindTemporaryExprs, because
   1370     // we don't want the initialized object to be destructed.
   1371     if (CXXBindTemporaryExpr *Binder =
   1372             dyn_cast_or_null<CXXBindTemporaryExpr>(FullInit.get()))
   1373       FullInit = Owned(Binder->getSubExpr());
   1374 
   1375     Initializer = FullInit.take();
   1376   }
   1377 
   1378   // Mark the new and delete operators as referenced.
   1379   if (OperatorNew) {
   1380     DiagnoseUseOfDecl(OperatorNew, StartLoc);
   1381     MarkFunctionReferenced(StartLoc, OperatorNew);
   1382   }
   1383   if (OperatorDelete) {
   1384     DiagnoseUseOfDecl(OperatorDelete, StartLoc);
   1385     MarkFunctionReferenced(StartLoc, OperatorDelete);
   1386   }
   1387 
   1388   // C++0x [expr.new]p17:
   1389   //   If the new expression creates an array of objects of class type,
   1390   //   access and ambiguity control are done for the destructor.
   1391   QualType BaseAllocType = Context.getBaseElementType(AllocType);
   1392   if (ArraySize && !BaseAllocType->isDependentType()) {
   1393     if (const RecordType *BaseRecordType = BaseAllocType->getAs<RecordType>()) {
   1394       if (CXXDestructorDecl *dtor = LookupDestructor(
   1395               cast<CXXRecordDecl>(BaseRecordType->getDecl()))) {
   1396         MarkFunctionReferenced(StartLoc, dtor);
   1397         CheckDestructorAccess(StartLoc, dtor,
   1398                               PDiag(diag::err_access_dtor)
   1399                                 << BaseAllocType);
   1400         DiagnoseUseOfDecl(dtor, StartLoc);
   1401       }
   1402     }
   1403   }
   1404 
   1405   return Owned(new (Context) CXXNewExpr(Context, UseGlobal, OperatorNew,
   1406                                         OperatorDelete,
   1407                                         UsualArrayDeleteWantsSize,
   1408                                    llvm::makeArrayRef(PlaceArgs, NumPlaceArgs),
   1409                                         TypeIdParens,
   1410                                         ArraySize, initStyle, Initializer,
   1411                                         ResultType, AllocTypeInfo,
   1412                                         Range, DirectInitRange));
   1413 }
   1414 
   1415 /// \brief Checks that a type is suitable as the allocated type
   1416 /// in a new-expression.
   1417 bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
   1418                               SourceRange R) {
   1419   // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
   1420   //   abstract class type or array thereof.
   1421   if (AllocType->isFunctionType())
   1422     return Diag(Loc, diag::err_bad_new_type)
   1423       << AllocType << 0 << R;
   1424   else if (AllocType->isReferenceType())
   1425     return Diag(Loc, diag::err_bad_new_type)
   1426       << AllocType << 1 << R;
   1427   else if (!AllocType->isDependentType() &&
   1428            RequireCompleteType(Loc, AllocType, diag::err_new_incomplete_type,R))
   1429     return true;
   1430   else if (RequireNonAbstractType(Loc, AllocType,
   1431                                   diag::err_allocation_of_abstract_type))
   1432     return true;
   1433   else if (AllocType->isVariablyModifiedType())
   1434     return Diag(Loc, diag::err_variably_modified_new_type)
   1435              << AllocType;
   1436   else if (unsigned AddressSpace = AllocType.getAddressSpace())
   1437     return Diag(Loc, diag::err_address_space_qualified_new)
   1438       << AllocType.getUnqualifiedType() << AddressSpace;
   1439   else if (getLangOpts().ObjCAutoRefCount) {
   1440     if (const ArrayType *AT = Context.getAsArrayType(AllocType)) {
   1441       QualType BaseAllocType = Context.getBaseElementType(AT);
   1442       if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None &&
   1443           BaseAllocType->isObjCLifetimeType())
   1444         return Diag(Loc, diag::err_arc_new_array_without_ownership)
   1445           << BaseAllocType;
   1446     }
   1447   }
   1448 
   1449   return false;
   1450 }
   1451 
   1452 /// \brief Determine whether the given function is a non-placement
   1453 /// deallocation function.
   1454 static bool isNonPlacementDeallocationFunction(FunctionDecl *FD) {
   1455   if (FD->isInvalidDecl())
   1456     return false;
   1457 
   1458   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
   1459     return Method->isUsualDeallocationFunction();
   1460 
   1461   return ((FD->getOverloadedOperator() == OO_Delete ||
   1462            FD->getOverloadedOperator() == OO_Array_Delete) &&
   1463           FD->getNumParams() == 1);
   1464 }
   1465 
   1466 /// FindAllocationFunctions - Finds the overloads of operator new and delete
   1467 /// that are appropriate for the allocation.
   1468 bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
   1469                                    bool UseGlobal, QualType AllocType,
   1470                                    bool IsArray, Expr **PlaceArgs,
   1471                                    unsigned NumPlaceArgs,
   1472                                    FunctionDecl *&OperatorNew,
   1473                                    FunctionDecl *&OperatorDelete) {
   1474   // --- Choosing an allocation function ---
   1475   // C++ 5.3.4p8 - 14 & 18
   1476   // 1) If UseGlobal is true, only look in the global scope. Else, also look
   1477   //   in the scope of the allocated class.
   1478   // 2) If an array size is given, look for operator new[], else look for
   1479   //   operator new.
   1480   // 3) The first argument is always size_t. Append the arguments from the
   1481   //   placement form.
   1482 
   1483   SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
   1484   // We don't care about the actual value of this argument.
   1485   // FIXME: Should the Sema create the expression and embed it in the syntax
   1486   // tree? Or should the consumer just recalculate the value?
   1487   IntegerLiteral Size(Context, llvm::APInt::getNullValue(
   1488                       Context.getTargetInfo().getPointerWidth(0)),
   1489                       Context.getSizeType(),
   1490                       SourceLocation());
   1491   AllocArgs[0] = &Size;
   1492   std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
   1493 
   1494   // C++ [expr.new]p8:
   1495   //   If the allocated type is a non-array type, the allocation
   1496   //   function's name is operator new and the deallocation function's
   1497   //   name is operator delete. If the allocated type is an array
   1498   //   type, the allocation function's name is operator new[] and the
   1499   //   deallocation function's name is operator delete[].
   1500   DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
   1501                                         IsArray ? OO_Array_New : OO_New);
   1502   DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
   1503                                         IsArray ? OO_Array_Delete : OO_Delete);
   1504 
   1505   QualType AllocElemType = Context.getBaseElementType(AllocType);
   1506 
   1507   if (AllocElemType->isRecordType() && !UseGlobal) {
   1508     CXXRecordDecl *Record
   1509       = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
   1510     if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
   1511                           AllocArgs.size(), Record, /*AllowMissing=*/true,
   1512                           OperatorNew))
   1513       return true;
   1514   }
   1515   if (!OperatorNew) {
   1516     // Didn't find a member overload. Look for a global one.
   1517     DeclareGlobalNewDelete();
   1518     DeclContext *TUDecl = Context.getTranslationUnitDecl();
   1519     if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
   1520                           AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
   1521                           OperatorNew))
   1522       return true;
   1523   }
   1524 
   1525   // We don't need an operator delete if we're running under
   1526   // -fno-exceptions.
   1527   if (!getLangOpts().Exceptions) {
   1528     OperatorDelete = 0;
   1529     return false;
   1530   }
   1531 
   1532   // FindAllocationOverload can change the passed in arguments, so we need to
   1533   // copy them back.
   1534   if (NumPlaceArgs > 0)
   1535     std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
   1536 
   1537   // C++ [expr.new]p19:
   1538   //
   1539   //   If the new-expression begins with a unary :: operator, the
   1540   //   deallocation function's name is looked up in the global
   1541   //   scope. Otherwise, if the allocated type is a class type T or an
   1542   //   array thereof, the deallocation function's name is looked up in
   1543   //   the scope of T. If this lookup fails to find the name, or if
   1544   //   the allocated type is not a class type or array thereof, the
   1545   //   deallocation function's name is looked up in the global scope.
   1546   LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
   1547   if (AllocElemType->isRecordType() && !UseGlobal) {
   1548     CXXRecordDecl *RD
   1549       = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
   1550     LookupQualifiedName(FoundDelete, RD);
   1551   }
   1552   if (FoundDelete.isAmbiguous())
   1553     return true; // FIXME: clean up expressions?
   1554 
   1555   if (FoundDelete.empty()) {
   1556     DeclareGlobalNewDelete();
   1557     LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
   1558   }
   1559 
   1560   FoundDelete.suppressDiagnostics();
   1561 
   1562   SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
   1563 
   1564   // Whether we're looking for a placement operator delete is dictated
   1565   // by whether we selected a placement operator new, not by whether
   1566   // we had explicit placement arguments.  This matters for things like
   1567   //   struct A { void *operator new(size_t, int = 0); ... };
   1568   //   A *a = new A()
   1569   bool isPlacementNew = (NumPlaceArgs > 0 || OperatorNew->param_size() != 1);
   1570 
   1571   if (isPlacementNew) {
   1572     // C++ [expr.new]p20:
   1573     //   A declaration of a placement deallocation function matches the
   1574     //   declaration of a placement allocation function if it has the
   1575     //   same number of parameters and, after parameter transformations
   1576     //   (8.3.5), all parameter types except the first are
   1577     //   identical. [...]
   1578     //
   1579     // To perform this comparison, we compute the function type that
   1580     // the deallocation function should have, and use that type both
   1581     // for template argument deduction and for comparison purposes.
   1582     //
   1583     // FIXME: this comparison should ignore CC and the like.
   1584     QualType ExpectedFunctionType;
   1585     {
   1586       const FunctionProtoType *Proto
   1587         = OperatorNew->getType()->getAs<FunctionProtoType>();
   1588 
   1589       SmallVector<QualType, 4> ArgTypes;
   1590       ArgTypes.push_back(Context.VoidPtrTy);
   1591       for (unsigned I = 1, N = Proto->getNumArgs(); I < N; ++I)
   1592         ArgTypes.push_back(Proto->getArgType(I));
   1593 
   1594       FunctionProtoType::ExtProtoInfo EPI;
   1595       EPI.Variadic = Proto->isVariadic();
   1596 
   1597       ExpectedFunctionType
   1598         = Context.getFunctionType(Context.VoidTy, ArgTypes, EPI);
   1599     }
   1600 
   1601     for (LookupResult::iterator D = FoundDelete.begin(),
   1602                              DEnd = FoundDelete.end();
   1603          D != DEnd; ++D) {
   1604       FunctionDecl *Fn = 0;
   1605       if (FunctionTemplateDecl *FnTmpl
   1606             = dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
   1607         // Perform template argument deduction to try to match the
   1608         // expected function type.
   1609         TemplateDeductionInfo Info(StartLoc);
   1610         if (DeduceTemplateArguments(FnTmpl, 0, ExpectedFunctionType, Fn, Info))
   1611           continue;
   1612       } else
   1613         Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
   1614 
   1615       if (Context.hasSameType(Fn->getType(), ExpectedFunctionType))
   1616         Matches.push_back(std::make_pair(D.getPair(), Fn));
   1617     }
   1618   } else {
   1619     // C++ [expr.new]p20:
   1620     //   [...] Any non-placement deallocation function matches a
   1621     //   non-placement allocation function. [...]
   1622     for (LookupResult::iterator D = FoundDelete.begin(),
   1623                              DEnd = FoundDelete.end();
   1624          D != DEnd; ++D) {
   1625       if (FunctionDecl *Fn = dyn_cast<FunctionDecl>((*D)->getUnderlyingDecl()))
   1626         if (isNonPlacementDeallocationFunction(Fn))
   1627           Matches.push_back(std::make_pair(D.getPair(), Fn));
   1628     }
   1629   }
   1630 
   1631   // C++ [expr.new]p20:
   1632   //   [...] If the lookup finds a single matching deallocation
   1633   //   function, that function will be called; otherwise, no
   1634   //   deallocation function will be called.
   1635   if (Matches.size() == 1) {
   1636     OperatorDelete = Matches[0].second;
   1637 
   1638     // C++0x [expr.new]p20:
   1639     //   If the lookup finds the two-parameter form of a usual
   1640     //   deallocation function (3.7.4.2) and that function, considered
   1641     //   as a placement deallocation function, would have been
   1642     //   selected as a match for the allocation function, the program
   1643     //   is ill-formed.
   1644     if (NumPlaceArgs && getLangOpts().CPlusPlus11 &&
   1645         isNonPlacementDeallocationFunction(OperatorDelete)) {
   1646       Diag(StartLoc, diag::err_placement_new_non_placement_delete)
   1647         << SourceRange(PlaceArgs[0]->getLocStart(),
   1648                        PlaceArgs[NumPlaceArgs - 1]->getLocEnd());
   1649       Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
   1650         << DeleteName;
   1651     } else {
   1652       CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
   1653                             Matches[0].first);
   1654     }
   1655   }
   1656 
   1657   return false;
   1658 }
   1659 
   1660 /// FindAllocationOverload - Find an fitting overload for the allocation
   1661 /// function in the specified scope.
   1662 bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
   1663                                   DeclarationName Name, Expr** Args,
   1664                                   unsigned NumArgs, DeclContext *Ctx,
   1665                                   bool AllowMissing, FunctionDecl *&Operator,
   1666                                   bool Diagnose) {
   1667   LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
   1668   LookupQualifiedName(R, Ctx);
   1669   if (R.empty()) {
   1670     if (AllowMissing || !Diagnose)
   1671       return false;
   1672     return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
   1673       << Name << Range;
   1674   }
   1675 
   1676   if (R.isAmbiguous())
   1677     return true;
   1678 
   1679   R.suppressDiagnostics();
   1680 
   1681   OverloadCandidateSet Candidates(StartLoc);
   1682   for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
   1683        Alloc != AllocEnd; ++Alloc) {
   1684     // Even member operator new/delete are implicitly treated as
   1685     // static, so don't use AddMemberCandidate.
   1686     NamedDecl *D = (*Alloc)->getUnderlyingDecl();
   1687 
   1688     if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
   1689       AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
   1690                                    /*ExplicitTemplateArgs=*/0,
   1691                                    llvm::makeArrayRef(Args, NumArgs),
   1692                                    Candidates,
   1693                                    /*SuppressUserConversions=*/false);
   1694       continue;
   1695     }
   1696 
   1697     FunctionDecl *Fn = cast<FunctionDecl>(D);
   1698     AddOverloadCandidate(Fn, Alloc.getPair(),
   1699                          llvm::makeArrayRef(Args, NumArgs), Candidates,
   1700                          /*SuppressUserConversions=*/false);
   1701   }
   1702 
   1703   // Do the resolution.
   1704   OverloadCandidateSet::iterator Best;
   1705   switch (Candidates.BestViableFunction(*this, StartLoc, Best)) {
   1706   case OR_Success: {
   1707     // Got one!
   1708     FunctionDecl *FnDecl = Best->Function;
   1709     MarkFunctionReferenced(StartLoc, FnDecl);
   1710     // The first argument is size_t, and the first parameter must be size_t,
   1711     // too. This is checked on declaration and can be assumed. (It can't be
   1712     // asserted on, though, since invalid decls are left in there.)
   1713     // Watch out for variadic allocator function.
   1714     unsigned NumArgsInFnDecl = FnDecl->getNumParams();
   1715     for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) {
   1716       InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
   1717                                                        FnDecl->getParamDecl(i));
   1718 
   1719       if (!Diagnose && !CanPerformCopyInitialization(Entity, Owned(Args[i])))
   1720         return true;
   1721 
   1722       ExprResult Result
   1723         = PerformCopyInitialization(Entity, SourceLocation(), Owned(Args[i]));
   1724       if (Result.isInvalid())
   1725         return true;
   1726 
   1727       Args[i] = Result.takeAs<Expr>();
   1728     }
   1729 
   1730     Operator = FnDecl;
   1731 
   1732     if (CheckAllocationAccess(StartLoc, Range, R.getNamingClass(),
   1733                               Best->FoundDecl, Diagnose) == AR_inaccessible)
   1734       return true;
   1735 
   1736     return false;
   1737   }
   1738 
   1739   case OR_No_Viable_Function:
   1740     if (Diagnose) {
   1741       Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
   1742         << Name << Range;
   1743       Candidates.NoteCandidates(*this, OCD_AllCandidates,
   1744                                 llvm::makeArrayRef(Args, NumArgs));
   1745     }
   1746     return true;
   1747 
   1748   case OR_Ambiguous:
   1749     if (Diagnose) {
   1750       Diag(StartLoc, diag::err_ovl_ambiguous_call)
   1751         << Name << Range;
   1752       Candidates.NoteCandidates(*this, OCD_ViableCandidates,
   1753                                 llvm::makeArrayRef(Args, NumArgs));
   1754     }
   1755     return true;
   1756 
   1757   case OR_Deleted: {
   1758     if (Diagnose) {
   1759       Diag(StartLoc, diag::err_ovl_deleted_call)
   1760         << Best->Function->isDeleted()
   1761         << Name
   1762         << getDeletedOrUnavailableSuffix(Best->Function)
   1763         << Range;
   1764       Candidates.NoteCandidates(*this, OCD_AllCandidates,
   1765                                 llvm::makeArrayRef(Args, NumArgs));
   1766     }
   1767     return true;
   1768   }
   1769   }
   1770   llvm_unreachable("Unreachable, bad result from BestViableFunction");
   1771 }
   1772 
   1773 
   1774 /// DeclareGlobalNewDelete - Declare the global forms of operator new and
   1775 /// delete. These are:
   1776 /// @code
   1777 ///   // C++03:
   1778 ///   void* operator new(std::size_t) throw(std::bad_alloc);
   1779 ///   void* operator new[](std::size_t) throw(std::bad_alloc);
   1780 ///   void operator delete(void *) throw();
   1781 ///   void operator delete[](void *) throw();
   1782 ///   // C++0x:
   1783 ///   void* operator new(std::size_t);
   1784 ///   void* operator new[](std::size_t);
   1785 ///   void operator delete(void *);
   1786 ///   void operator delete[](void *);
   1787 /// @endcode
   1788 /// C++0x operator delete is implicitly noexcept.
   1789 /// Note that the placement and nothrow forms of new are *not* implicitly
   1790 /// declared. Their use requires including \<new\>.
   1791 void Sema::DeclareGlobalNewDelete() {
   1792   if (GlobalNewDeleteDeclared)
   1793     return;
   1794 
   1795   // C++ [basic.std.dynamic]p2:
   1796   //   [...] The following allocation and deallocation functions (18.4) are
   1797   //   implicitly declared in global scope in each translation unit of a
   1798   //   program
   1799   //
   1800   //     C++03:
   1801   //     void* operator new(std::size_t) throw(std::bad_alloc);
   1802   //     void* operator new[](std::size_t) throw(std::bad_alloc);
   1803   //     void  operator delete(void*) throw();
   1804   //     void  operator delete[](void*) throw();
   1805   //     C++0x:
   1806   //     void* operator new(std::size_t);
   1807   //     void* operator new[](std::size_t);
   1808   //     void  operator delete(void*);
   1809   //     void  operator delete[](void*);
   1810   //
   1811   //   These implicit declarations introduce only the function names operator
   1812   //   new, operator new[], operator delete, operator delete[].
   1813   //
   1814   // Here, we need to refer to std::bad_alloc, so we will implicitly declare
   1815   // "std" or "bad_alloc" as necessary to form the exception specification.
   1816   // However, we do not make these implicit declarations visible to name
   1817   // lookup.
   1818   // Note that the C++0x versions of operator delete are deallocation functions,
   1819   // and thus are implicitly noexcept.
   1820   if (!StdBadAlloc && !getLangOpts().CPlusPlus11) {
   1821     // The "std::bad_alloc" class has not yet been declared, so build it
   1822     // implicitly.
   1823     StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
   1824                                         getOrCreateStdNamespace(),
   1825                                         SourceLocation(), SourceLocation(),
   1826                                       &PP.getIdentifierTable().get("bad_alloc"),
   1827                                         0);
   1828     getStdBadAlloc()->setImplicit(true);
   1829   }
   1830 
   1831   GlobalNewDeleteDeclared = true;
   1832 
   1833   QualType VoidPtr = Context.getPointerType(Context.VoidTy);
   1834   QualType SizeT = Context.getSizeType();
   1835   bool AssumeSaneOperatorNew = getLangOpts().AssumeSaneOperatorNew;
   1836 
   1837   DeclareGlobalAllocationFunction(
   1838       Context.DeclarationNames.getCXXOperatorName(OO_New),
   1839       VoidPtr, SizeT, AssumeSaneOperatorNew);
   1840   DeclareGlobalAllocationFunction(
   1841       Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
   1842       VoidPtr, SizeT, AssumeSaneOperatorNew);
   1843   DeclareGlobalAllocationFunction(
   1844       Context.DeclarationNames.getCXXOperatorName(OO_Delete),
   1845       Context.VoidTy, VoidPtr);
   1846   DeclareGlobalAllocationFunction(
   1847       Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
   1848       Context.VoidTy, VoidPtr);
   1849 }
   1850 
   1851 /// DeclareGlobalAllocationFunction - Declares a single implicit global
   1852 /// allocation function if it doesn't already exist.
   1853 void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
   1854                                            QualType Return, QualType Argument,
   1855                                            bool AddMallocAttr) {
   1856   DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
   1857 
   1858   // Check if this function is already declared.
   1859   {
   1860     DeclContext::lookup_result R = GlobalCtx->lookup(Name);
   1861     for (DeclContext::lookup_iterator Alloc = R.begin(), AllocEnd = R.end();
   1862          Alloc != AllocEnd; ++Alloc) {
   1863       // Only look at non-template functions, as it is the predefined,
   1864       // non-templated allocation function we are trying to declare here.
   1865       if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
   1866         QualType InitialParamType =
   1867           Context.getCanonicalType(
   1868             Func->getParamDecl(0)->getType().getUnqualifiedType());
   1869         // FIXME: Do we need to check for default arguments here?
   1870         if (Func->getNumParams() == 1 && InitialParamType == Argument) {
   1871           if(AddMallocAttr && !Func->hasAttr<MallocAttr>())
   1872             Func->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
   1873           return;
   1874         }
   1875       }
   1876     }
   1877   }
   1878 
   1879   QualType BadAllocType;
   1880   bool HasBadAllocExceptionSpec
   1881     = (Name.getCXXOverloadedOperator() == OO_New ||
   1882        Name.getCXXOverloadedOperator() == OO_Array_New);
   1883   if (HasBadAllocExceptionSpec && !getLangOpts().CPlusPlus11) {
   1884     assert(StdBadAlloc && "Must have std::bad_alloc declared");
   1885     BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
   1886   }
   1887 
   1888   FunctionProtoType::ExtProtoInfo EPI;
   1889   if (HasBadAllocExceptionSpec) {
   1890     if (!getLangOpts().CPlusPlus11) {
   1891       EPI.ExceptionSpecType = EST_Dynamic;
   1892       EPI.NumExceptions = 1;
   1893       EPI.Exceptions = &BadAllocType;
   1894     }
   1895   } else {
   1896     EPI.ExceptionSpecType = getLangOpts().CPlusPlus11 ?
   1897                                 EST_BasicNoexcept : EST_DynamicNone;
   1898   }
   1899 
   1900   QualType FnType = Context.getFunctionType(Return, Argument, EPI);
   1901   FunctionDecl *Alloc =
   1902     FunctionDecl::Create(Context, GlobalCtx, SourceLocation(),
   1903                          SourceLocation(), Name,
   1904                          FnType, /*TInfo=*/0, SC_None,
   1905                          SC_None, false, true);
   1906   Alloc->setImplicit();
   1907 
   1908   if (AddMallocAttr)
   1909     Alloc->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
   1910 
   1911   ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
   1912                                            SourceLocation(), 0,
   1913                                            Argument, /*TInfo=*/0,
   1914                                            SC_None, SC_None, 0);
   1915   Alloc->setParams(Param);
   1916 
   1917   // FIXME: Also add this declaration to the IdentifierResolver, but
   1918   // make sure it is at the end of the chain to coincide with the
   1919   // global scope.
   1920   Context.getTranslationUnitDecl()->addDecl(Alloc);
   1921 }
   1922 
   1923 bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
   1924                                     DeclarationName Name,
   1925                                     FunctionDecl* &Operator, bool Diagnose) {
   1926   LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
   1927   // Try to find operator delete/operator delete[] in class scope.
   1928   LookupQualifiedName(Found, RD);
   1929 
   1930   if (Found.isAmbiguous())
   1931     return true;
   1932 
   1933   Found.suppressDiagnostics();
   1934 
   1935   SmallVector<DeclAccessPair,4> Matches;
   1936   for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
   1937        F != FEnd; ++F) {
   1938     NamedDecl *ND = (*F)->getUnderlyingDecl();
   1939 
   1940     // Ignore template operator delete members from the check for a usual
   1941     // deallocation function.
   1942     if (isa<FunctionTemplateDecl>(ND))
   1943       continue;
   1944 
   1945     if (cast<CXXMethodDecl>(ND)->isUsualDeallocationFunction())
   1946       Matches.push_back(F.getPair());
   1947   }
   1948 
   1949   // There's exactly one suitable operator;  pick it.
   1950   if (Matches.size() == 1) {
   1951     Operator = cast<CXXMethodDecl>(Matches[0]->getUnderlyingDecl());
   1952 
   1953     if (Operator->isDeleted()) {
   1954       if (Diagnose) {
   1955         Diag(StartLoc, diag::err_deleted_function_use);
   1956         NoteDeletedFunction(Operator);
   1957       }
   1958       return true;
   1959     }
   1960 
   1961     if (CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
   1962                               Matches[0], Diagnose) == AR_inaccessible)
   1963       return true;
   1964 
   1965     return false;
   1966 
   1967   // We found multiple suitable operators;  complain about the ambiguity.
   1968   } else if (!Matches.empty()) {
   1969     if (Diagnose) {
   1970       Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
   1971         << Name << RD;
   1972 
   1973       for (SmallVectorImpl<DeclAccessPair>::iterator
   1974              F = Matches.begin(), FEnd = Matches.end(); F != FEnd; ++F)
   1975         Diag((*F)->getUnderlyingDecl()->getLocation(),
   1976              diag::note_member_declared_here) << Name;
   1977     }
   1978     return true;
   1979   }
   1980 
   1981   // We did find operator delete/operator delete[] declarations, but
   1982   // none of them were suitable.
   1983   if (!Found.empty()) {
   1984     if (Diagnose) {
   1985       Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
   1986         << Name << RD;
   1987 
   1988       for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
   1989            F != FEnd; ++F)
   1990         Diag((*F)->getUnderlyingDecl()->getLocation(),
   1991              diag::note_member_declared_here) << Name;
   1992     }
   1993     return true;
   1994   }
   1995 
   1996   // Look for a global declaration.
   1997   DeclareGlobalNewDelete();
   1998   DeclContext *TUDecl = Context.getTranslationUnitDecl();
   1999 
   2000   CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation());
   2001   Expr* DeallocArgs[1];
   2002   DeallocArgs[0] = &Null;
   2003   if (FindAllocationOverload(StartLoc, SourceRange(), Name,
   2004                              DeallocArgs, 1, TUDecl, !Diagnose,
   2005                              Operator, Diagnose))
   2006     return true;
   2007 
   2008   assert(Operator && "Did not find a deallocation function!");
   2009   return false;
   2010 }
   2011 
   2012 /// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
   2013 /// @code ::delete ptr; @endcode
   2014 /// or
   2015 /// @code delete [] ptr; @endcode
   2016 ExprResult
   2017 Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
   2018                      bool ArrayForm, Expr *ExE) {
   2019   // C++ [expr.delete]p1:
   2020   //   The operand shall have a pointer type, or a class type having a single
   2021   //   conversion function to a pointer type. The result has type void.
   2022   //
   2023   // DR599 amends "pointer type" to "pointer to object type" in both cases.
   2024 
   2025   ExprResult Ex = Owned(ExE);
   2026   FunctionDecl *OperatorDelete = 0;
   2027   bool ArrayFormAsWritten = ArrayForm;
   2028   bool UsualArrayDeleteWantsSize = false;
   2029 
   2030   if (!Ex.get()->isTypeDependent()) {
   2031     // Perform lvalue-to-rvalue cast, if needed.
   2032     Ex = DefaultLvalueConversion(Ex.take());
   2033     if (Ex.isInvalid())
   2034       return ExprError();
   2035 
   2036     QualType Type = Ex.get()->getType();
   2037 
   2038     if (const RecordType *Record = Type->getAs<RecordType>()) {
   2039       if (RequireCompleteType(StartLoc, Type,
   2040                               diag::err_delete_incomplete_class_type))
   2041         return ExprError();
   2042 
   2043       SmallVector<CXXConversionDecl*, 4> ObjectPtrConversions;
   2044 
   2045       CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
   2046       std::pair<CXXRecordDecl::conversion_iterator,
   2047                 CXXRecordDecl::conversion_iterator>
   2048         Conversions = RD->getVisibleConversionFunctions();
   2049       for (CXXRecordDecl::conversion_iterator
   2050              I = Conversions.first, E = Conversions.second; I != E; ++I) {
   2051         NamedDecl *D = I.getDecl();
   2052         if (isa<UsingShadowDecl>(D))
   2053           D = cast<UsingShadowDecl>(D)->getTargetDecl();
   2054 
   2055         // Skip over templated conversion functions; they aren't considered.
   2056         if (isa<FunctionTemplateDecl>(D))
   2057           continue;
   2058 
   2059         CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
   2060 
   2061         QualType ConvType = Conv->getConversionType().getNonReferenceType();
   2062         if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
   2063           if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
   2064             ObjectPtrConversions.push_back(Conv);
   2065       }
   2066       if (ObjectPtrConversions.size() == 1) {
   2067         // We have a single conversion to a pointer-to-object type. Perform
   2068         // that conversion.
   2069         // TODO: don't redo the conversion calculation.
   2070         ExprResult Res =
   2071           PerformImplicitConversion(Ex.get(),
   2072                             ObjectPtrConversions.front()->getConversionType(),
   2073                                     AA_Converting);
   2074         if (Res.isUsable()) {
   2075           Ex = Res;
   2076           Type = Ex.get()->getType();
   2077         }
   2078       }
   2079       else if (ObjectPtrConversions.size() > 1) {
   2080         Diag(StartLoc, diag::err_ambiguous_delete_operand)
   2081               << Type << Ex.get()->getSourceRange();
   2082         for (unsigned i= 0; i < ObjectPtrConversions.size(); i++)
   2083           NoteOverloadCandidate(ObjectPtrConversions[i]);
   2084         return ExprError();
   2085       }
   2086     }
   2087 
   2088     if (!Type->isPointerType())
   2089       return ExprError(Diag(StartLoc, diag::err_delete_operand)
   2090         << Type << Ex.get()->getSourceRange());
   2091 
   2092     QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
   2093     QualType PointeeElem = Context.getBaseElementType(Pointee);
   2094 
   2095     if (unsigned AddressSpace = Pointee.getAddressSpace())
   2096       return Diag(Ex.get()->getLocStart(),
   2097                   diag::err_address_space_qualified_delete)
   2098                << Pointee.getUnqualifiedType() << AddressSpace;
   2099 
   2100     CXXRecordDecl *PointeeRD = 0;
   2101     if (Pointee->isVoidType() && !isSFINAEContext()) {
   2102       // The C++ standard bans deleting a pointer to a non-object type, which
   2103       // effectively bans deletion of "void*". However, most compilers support
   2104       // this, so we treat it as a warning unless we're in a SFINAE context.
   2105       Diag(StartLoc, diag::ext_delete_void_ptr_operand)
   2106         << Type << Ex.get()->getSourceRange();
   2107     } else if (Pointee->isFunctionType() || Pointee->isVoidType()) {
   2108       return ExprError(Diag(StartLoc, diag::err_delete_operand)
   2109         << Type << Ex.get()->getSourceRange());
   2110     } else if (!Pointee->isDependentType()) {
   2111       if (!RequireCompleteType(StartLoc, Pointee,
   2112                                diag::warn_delete_incomplete, Ex.get())) {
   2113         if (const RecordType *RT = PointeeElem->getAs<RecordType>())
   2114           PointeeRD = cast<CXXRecordDecl>(RT->getDecl());
   2115       }
   2116     }
   2117 
   2118     // C++ [expr.delete]p2:
   2119     //   [Note: a pointer to a const type can be the operand of a
   2120     //   delete-expression; it is not necessary to cast away the constness
   2121     //   (5.2.11) of the pointer expression before it is used as the operand
   2122     //   of the delete-expression. ]
   2123 
   2124     if (Pointee->isArrayType() && !ArrayForm) {
   2125       Diag(StartLoc, diag::warn_delete_array_type)
   2126           << Type << Ex.get()->getSourceRange()
   2127           << FixItHint::CreateInsertion(PP.getLocForEndOfToken(StartLoc), "[]");
   2128       ArrayForm = true;
   2129     }
   2130 
   2131     DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
   2132                                       ArrayForm ? OO_Array_Delete : OO_Delete);
   2133 
   2134     if (PointeeRD) {
   2135       if (!UseGlobal &&
   2136           FindDeallocationFunction(StartLoc, PointeeRD, DeleteName,
   2137                                    OperatorDelete))
   2138         return ExprError();
   2139 
   2140       // If we're allocating an array of records, check whether the
   2141       // usual operator delete[] has a size_t parameter.
   2142       if (ArrayForm) {
   2143         // If the user specifically asked to use the global allocator,
   2144         // we'll need to do the lookup into the class.
   2145         if (UseGlobal)
   2146           UsualArrayDeleteWantsSize =
   2147             doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);
   2148 
   2149         // Otherwise, the usual operator delete[] should be the
   2150         // function we just found.
   2151         else if (isa<CXXMethodDecl>(OperatorDelete))
   2152           UsualArrayDeleteWantsSize = (OperatorDelete->getNumParams() == 2);
   2153       }
   2154 
   2155       if (!PointeeRD->hasIrrelevantDestructor())
   2156         if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
   2157           MarkFunctionReferenced(StartLoc,
   2158                                     const_cast<CXXDestructorDecl*>(Dtor));
   2159           DiagnoseUseOfDecl(Dtor, StartLoc);
   2160         }
   2161 
   2162       // C++ [expr.delete]p3:
   2163       //   In the first alternative (delete object), if the static type of the
   2164       //   object to be deleted is different from its dynamic type, the static
   2165       //   type shall be a base class of the dynamic type of the object to be
   2166       //   deleted and the static type shall have a virtual destructor or the
   2167       //   behavior is undefined.
   2168       //
   2169       // Note: a final class cannot be derived from, no issue there
   2170       if (PointeeRD->isPolymorphic() && !PointeeRD->hasAttr<FinalAttr>()) {
   2171         CXXDestructorDecl *dtor = PointeeRD->getDestructor();
   2172         if (dtor && !dtor->isVirtual()) {
   2173           if (PointeeRD->isAbstract()) {
   2174             // If the class is abstract, we warn by default, because we're
   2175             // sure the code has undefined behavior.
   2176             Diag(StartLoc, diag::warn_delete_abstract_non_virtual_dtor)
   2177                 << PointeeElem;
   2178           } else if (!ArrayForm) {
   2179             // Otherwise, if this is not an array delete, it's a bit suspect,
   2180             // but not necessarily wrong.
   2181             Diag(StartLoc, diag::warn_delete_non_virtual_dtor) << PointeeElem;
   2182           }
   2183         }
   2184       }
   2185 
   2186     }
   2187 
   2188     if (!OperatorDelete) {
   2189       // Look for a global declaration.
   2190       DeclareGlobalNewDelete();
   2191       DeclContext *TUDecl = Context.getTranslationUnitDecl();
   2192       Expr *Arg = Ex.get();
   2193       if (!Context.hasSameType(Arg->getType(), Context.VoidPtrTy))
   2194         Arg = ImplicitCastExpr::Create(Context, Context.VoidPtrTy,
   2195                                        CK_BitCast, Arg, 0, VK_RValue);
   2196       if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
   2197                                  &Arg, 1, TUDecl, /*AllowMissing=*/false,
   2198                                  OperatorDelete))
   2199         return ExprError();
   2200     }
   2201 
   2202     MarkFunctionReferenced(StartLoc, OperatorDelete);
   2203 
   2204     // Check access and ambiguity of operator delete and destructor.
   2205     if (PointeeRD) {
   2206       if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
   2207           CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor,
   2208                       PDiag(diag::err_access_dtor) << PointeeElem);
   2209       }
   2210     }
   2211 
   2212   }
   2213 
   2214   return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
   2215                                            ArrayFormAsWritten,
   2216                                            UsualArrayDeleteWantsSize,
   2217                                            OperatorDelete, Ex.take(), StartLoc));
   2218 }
   2219 
   2220 /// \brief Check the use of the given variable as a C++ condition in an if,
   2221 /// while, do-while, or switch statement.
   2222 ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
   2223                                         SourceLocation StmtLoc,
   2224                                         bool ConvertToBoolean) {
   2225   QualType T = ConditionVar->getType();
   2226 
   2227   // C++ [stmt.select]p2:
   2228   //   The declarator shall not specify a function or an array.
   2229   if (T->isFunctionType())
   2230     return ExprError(Diag(ConditionVar->getLocation(),
   2231                           diag::err_invalid_use_of_function_type)
   2232                        << ConditionVar->getSourceRange());
   2233   else if (T->isArrayType())
   2234     return ExprError(Diag(ConditionVar->getLocation(),
   2235                           diag::err_invalid_use_of_array_type)
   2236                      << ConditionVar->getSourceRange());
   2237 
   2238   ExprResult Condition =
   2239     Owned(DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
   2240                               SourceLocation(),
   2241                               ConditionVar,
   2242                               /*enclosing*/ false,
   2243                               ConditionVar->getLocation(),
   2244                               ConditionVar->getType().getNonReferenceType(),
   2245                               VK_LValue));
   2246 
   2247   MarkDeclRefReferenced(cast<DeclRefExpr>(Condition.get()));
   2248 
   2249   if (ConvertToBoolean) {
   2250     Condition = CheckBooleanCondition(Condition.take(), StmtLoc);
   2251     if (Condition.isInvalid())
   2252       return ExprError();
   2253   }
   2254 
   2255   return Condition;
   2256 }
   2257 
   2258 /// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
   2259 ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr) {
   2260   // C++ 6.4p4:
   2261   // The value of a condition that is an initialized declaration in a statement
   2262   // other than a switch statement is the value of the declared variable
   2263   // implicitly converted to type bool. If that conversion is ill-formed, the
   2264   // program is ill-formed.
   2265   // The value of a condition that is an expression is the value of the
   2266   // expression, implicitly converted to bool.
   2267   //
   2268   return PerformContextuallyConvertToBool(CondExpr);
   2269 }
   2270 
   2271 /// Helper function to determine whether this is the (deprecated) C++
   2272 /// conversion from a string literal to a pointer to non-const char or
   2273 /// non-const wchar_t (for narrow and wide string literals,
   2274 /// respectively).
   2275 bool
   2276 Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
   2277   // Look inside the implicit cast, if it exists.
   2278   if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
   2279     From = Cast->getSubExpr();
   2280 
   2281   // A string literal (2.13.4) that is not a wide string literal can
   2282   // be converted to an rvalue of type "pointer to char"; a wide
   2283   // string literal can be converted to an rvalue of type "pointer
   2284   // to wchar_t" (C++ 4.2p2).
   2285   if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
   2286     if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
   2287       if (const BuiltinType *ToPointeeType
   2288           = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
   2289         // This conversion is considered only when there is an
   2290         // explicit appropriate pointer target type (C++ 4.2p2).
   2291         if (!ToPtrType->getPointeeType().hasQualifiers()) {
   2292           switch (StrLit->getKind()) {
   2293             case StringLiteral::UTF8:
   2294             case StringLiteral::UTF16:
   2295             case StringLiteral::UTF32:
   2296               // We don't allow UTF literals to be implicitly converted
   2297               break;
   2298             case StringLiteral::Ascii:
   2299               return (ToPointeeType->getKind() == BuiltinType::Char_U ||
   2300                       ToPointeeType->getKind() == BuiltinType::Char_S);
   2301             case StringLiteral::Wide:
   2302               return ToPointeeType->isWideCharType();
   2303           }
   2304         }
   2305       }
   2306 
   2307   return false;
   2308 }
   2309 
   2310 static ExprResult BuildCXXCastArgument(Sema &S,
   2311                                        SourceLocation CastLoc,
   2312                                        QualType Ty,
   2313                                        CastKind Kind,
   2314                                        CXXMethodDecl *Method,
   2315                                        DeclAccessPair FoundDecl,
   2316                                        bool HadMultipleCandidates,
   2317                                        Expr *From) {
   2318   switch (Kind) {
   2319   default: llvm_unreachable("Unhandled cast kind!");
   2320   case CK_ConstructorConversion: {
   2321     CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Method);
   2322     SmallVector<Expr*, 8> ConstructorArgs;
   2323 
   2324     if (S.CompleteConstructorCall(Constructor, From, CastLoc, ConstructorArgs))
   2325       return ExprError();
   2326 
   2327     S.CheckConstructorAccess(CastLoc, Constructor,
   2328                              InitializedEntity::InitializeTemporary(Ty),
   2329                              Constructor->getAccess());
   2330 
   2331     ExprResult Result
   2332       = S.BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
   2333                                 ConstructorArgs, HadMultipleCandidates,
   2334                                 /*ListInit*/ false, /*ZeroInit*/ false,
   2335                                 CXXConstructExpr::CK_Complete, SourceRange());
   2336     if (Result.isInvalid())
   2337       return ExprError();
   2338 
   2339     return S.MaybeBindToTemporary(Result.takeAs<Expr>());
   2340   }
   2341 
   2342   case CK_UserDefinedConversion: {
   2343     assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
   2344 
   2345     // Create an implicit call expr that calls it.
   2346     CXXConversionDecl *Conv = cast<CXXConversionDecl>(Method);
   2347     ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Conv,
   2348                                                  HadMultipleCandidates);
   2349     if (Result.isInvalid())
   2350       return ExprError();
   2351     // Record usage of conversion in an implicit cast.
   2352     Result = S.Owned(ImplicitCastExpr::Create(S.Context,
   2353                                               Result.get()->getType(),
   2354                                               CK_UserDefinedConversion,
   2355                                               Result.get(), 0,
   2356                                               Result.get()->getValueKind()));
   2357 
   2358     S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ 0, FoundDecl);
   2359 
   2360     return S.MaybeBindToTemporary(Result.get());
   2361   }
   2362   }
   2363 }
   2364 
   2365 /// PerformImplicitConversion - Perform an implicit conversion of the
   2366 /// expression From to the type ToType using the pre-computed implicit
   2367 /// conversion sequence ICS. Returns the converted
   2368 /// expression. Action is the kind of conversion we're performing,
   2369 /// used in the error message.
   2370 ExprResult
   2371 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
   2372                                 const ImplicitConversionSequence &ICS,
   2373                                 AssignmentAction Action,
   2374                                 CheckedConversionKind CCK) {
   2375   switch (ICS.getKind()) {
   2376   case ImplicitConversionSequence::StandardConversion: {
   2377     ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard,
   2378                                                Action, CCK);
   2379     if (Res.isInvalid())
   2380       return ExprError();
   2381     From = Res.take();
   2382     break;
   2383   }
   2384 
   2385   case ImplicitConversionSequence::UserDefinedConversion: {
   2386 
   2387       FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
   2388       CastKind CastKind;
   2389       QualType BeforeToType;
   2390       assert(FD && "FIXME: aggregate initialization from init list");
   2391       if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
   2392         CastKind = CK_UserDefinedConversion;
   2393 
   2394         // If the user-defined conversion is specified by a conversion function,
   2395         // the initial standard conversion sequence converts the source type to
   2396         // the implicit object parameter of the conversion function.
   2397         BeforeToType = Context.getTagDeclType(Conv->getParent());
   2398       } else {
   2399         const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
   2400         CastKind = CK_ConstructorConversion;
   2401         // Do no conversion if dealing with ... for the first conversion.
   2402         if (!ICS.UserDefined.EllipsisConversion) {
   2403           // If the user-defined conversion is specified by a constructor, the
   2404           // initial standard conversion sequence converts the source type to the
   2405           // type required by the argument of the constructor
   2406           BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
   2407         }
   2408       }
   2409       // Watch out for elipsis conversion.
   2410       if (!ICS.UserDefined.EllipsisConversion) {
   2411         ExprResult Res =
   2412           PerformImplicitConversion(From, BeforeToType,
   2413                                     ICS.UserDefined.Before, AA_Converting,
   2414                                     CCK);
   2415         if (Res.isInvalid())
   2416           return ExprError();
   2417         From = Res.take();
   2418       }
   2419 
   2420       ExprResult CastArg
   2421         = BuildCXXCastArgument(*this,
   2422                                From->getLocStart(),
   2423                                ToType.getNonReferenceType(),
   2424                                CastKind, cast<CXXMethodDecl>(FD),
   2425                                ICS.UserDefined.FoundConversionFunction,
   2426                                ICS.UserDefined.HadMultipleCandidates,
   2427                                From);
   2428 
   2429       if (CastArg.isInvalid())
   2430         return ExprError();
   2431 
   2432       From = CastArg.take();
   2433 
   2434       return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
   2435                                        AA_Converting, CCK);
   2436   }
   2437 
   2438   case ImplicitConversionSequence::AmbiguousConversion:
   2439     ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
   2440                           PDiag(diag::err_typecheck_ambiguous_condition)
   2441                             << From->getSourceRange());
   2442      return ExprError();
   2443 
   2444   case ImplicitConversionSequence::EllipsisConversion:
   2445     llvm_unreachable("Cannot perform an ellipsis conversion");
   2446 
   2447   case ImplicitConversionSequence::BadConversion:
   2448     return ExprError();
   2449   }
   2450 
   2451   // Everything went well.
   2452   return Owned(From);
   2453 }
   2454 
   2455 /// PerformImplicitConversion - Perform an implicit conversion of the
   2456 /// expression From to the type ToType by following the standard
   2457 /// conversion sequence SCS. Returns the converted
   2458 /// expression. Flavor is the context in which we're performing this
   2459 /// conversion, for use in error messages.
   2460 ExprResult
   2461 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
   2462                                 const StandardConversionSequence& SCS,
   2463                                 AssignmentAction Action,
   2464                                 CheckedConversionKind CCK) {
   2465   bool CStyle = (CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast);
   2466 
   2467   // Overall FIXME: we are recomputing too many types here and doing far too
   2468   // much extra work. What this means is that we need to keep track of more
   2469   // information that is computed when we try the implicit conversion initially,
   2470   // so that we don't need to recompute anything here.
   2471   QualType FromType = From->getType();
   2472 
   2473   if (SCS.CopyConstructor) {
   2474     // FIXME: When can ToType be a reference type?
   2475     assert(!ToType->isReferenceType());
   2476     if (SCS.Second == ICK_Derived_To_Base) {
   2477       SmallVector<Expr*, 8> ConstructorArgs;
   2478       if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
   2479                                   From, /*FIXME:ConstructLoc*/SourceLocation(),
   2480                                   ConstructorArgs))
   2481         return ExprError();
   2482       return BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
   2483                                    ToType, SCS.CopyConstructor,
   2484                                    ConstructorArgs,
   2485                                    /*HadMultipleCandidates*/ false,
   2486                                    /*ListInit*/ false, /*ZeroInit*/ false,
   2487                                    CXXConstructExpr::CK_Complete,
   2488                                    SourceRange());
   2489     }
   2490     return BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
   2491                                  ToType, SCS.CopyConstructor,
   2492                                  From, /*HadMultipleCandidates*/ false,
   2493                                  /*ListInit*/ false, /*ZeroInit*/ false,
   2494                                  CXXConstructExpr::CK_Complete,
   2495                                  SourceRange());
   2496   }
   2497 
   2498   // Resolve overloaded function references.
   2499   if (Context.hasSameType(FromType, Context.OverloadTy)) {
   2500     DeclAccessPair Found;
   2501     FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
   2502                                                           true, Found);
   2503     if (!Fn)
   2504       return ExprError();
   2505 
   2506     if (DiagnoseUseOfDecl(Fn, From->getLocStart()))
   2507       return ExprError();
   2508 
   2509     From = FixOverloadedFunctionReference(From, Found, Fn);
   2510     FromType = From->getType();
   2511   }
   2512 
   2513   // Perform the first implicit conversion.
   2514   switch (SCS.First) {
   2515   case ICK_Identity:
   2516     // Nothing to do.
   2517     break;
   2518 
   2519   case ICK_Lvalue_To_Rvalue: {
   2520     assert(From->getObjectKind() != OK_ObjCProperty);
   2521     FromType = FromType.getUnqualifiedType();
   2522     ExprResult FromRes = DefaultLvalueConversion(From);
   2523     assert(!FromRes.isInvalid() && "Can't perform deduced conversion?!");
   2524     From = FromRes.take();
   2525     break;
   2526   }
   2527 
   2528   case ICK_Array_To_Pointer:
   2529     FromType = Context.getArrayDecayedType(FromType);
   2530     From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay,
   2531                              VK_RValue, /*BasePath=*/0, CCK).take();
   2532     break;
   2533 
   2534   case ICK_Function_To_Pointer:
   2535     FromType = Context.getPointerType(FromType);
   2536     From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay,
   2537                              VK_RValue, /*BasePath=*/0, CCK).take();
   2538     break;
   2539 
   2540   default:
   2541     llvm_unreachable("Improper first standard conversion");
   2542   }
   2543 
   2544   // Perform the second implicit conversion
   2545   switch (SCS.Second) {
   2546   case ICK_Identity:
   2547     // If both sides are functions (or pointers/references to them), there could
   2548     // be incompatible exception declarations.
   2549     if (CheckExceptionSpecCompatibility(From, ToType))
   2550       return ExprError();
   2551     // Nothing else to do.
   2552     break;
   2553 
   2554   case ICK_NoReturn_Adjustment:
   2555     // If both sides are functions (or pointers/references to them), there could
   2556     // be incompatible exception declarations.
   2557     if (CheckExceptionSpecCompatibility(From, ToType))
   2558       return ExprError();
   2559 
   2560     From = ImpCastExprToType(From, ToType, CK_NoOp,
   2561                              VK_RValue, /*BasePath=*/0, CCK).take();
   2562     break;
   2563 
   2564   case ICK_Integral_Promotion:
   2565   case ICK_Integral_Conversion:
   2566     if (ToType->isBooleanType()) {
   2567       assert(FromType->castAs<EnumType>()->getDecl()->isFixed() &&
   2568              SCS.Second == ICK_Integral_Promotion &&
   2569              "only enums with fixed underlying type can promote to bool");
   2570       From = ImpCastExprToType(From, ToType, CK_IntegralToBoolean,
   2571                                VK_RValue, /*BasePath=*/0, CCK).take();
   2572     } else {
   2573       From = ImpCastExprToType(From, ToType, CK_IntegralCast,
   2574                                VK_RValue, /*BasePath=*/0, CCK).take();
   2575     }
   2576     break;
   2577 
   2578   case ICK_Floating_Promotion:
   2579   case ICK_Floating_Conversion:
   2580     From = ImpCastExprToType(From, ToType, CK_FloatingCast,
   2581                              VK_RValue, /*BasePath=*/0, CCK).take();
   2582     break;
   2583 
   2584   case ICK_Complex_Promotion:
   2585   case ICK_Complex_Conversion: {
   2586     QualType FromEl = From->getType()->getAs<ComplexType>()->getElementType();
   2587     QualType ToEl = ToType->getAs<ComplexType>()->getElementType();
   2588     CastKind CK;
   2589     if (FromEl->isRealFloatingType()) {
   2590       if (ToEl->isRealFloatingType())
   2591         CK = CK_FloatingComplexCast;
   2592       else
   2593         CK = CK_FloatingComplexToIntegralComplex;
   2594     } else if (ToEl->isRealFloatingType()) {
   2595       CK = CK_IntegralComplexToFloatingComplex;
   2596     } else {
   2597       CK = CK_IntegralComplexCast;
   2598     }
   2599     From = ImpCastExprToType(From, ToType, CK,
   2600                              VK_RValue, /*BasePath=*/0, CCK).take();
   2601     break;
   2602   }
   2603 
   2604   case ICK_Floating_Integral:
   2605     if (ToType->isRealFloatingType())
   2606       From = ImpCastExprToType(From, ToType, CK_IntegralToFloating,
   2607                                VK_RValue, /*BasePath=*/0, CCK).take();
   2608     else
   2609       From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral,
   2610                                VK_RValue, /*BasePath=*/0, CCK).take();
   2611     break;
   2612 
   2613   case ICK_Compatible_Conversion:
   2614       From = ImpCastExprToType(From, ToType, CK_NoOp,
   2615                                VK_RValue, /*BasePath=*/0, CCK).take();
   2616     break;
   2617 
   2618   case ICK_Writeback_Conversion:
   2619   case ICK_Pointer_Conversion: {
   2620     if (SCS.IncompatibleObjC && Action != AA_Casting) {
   2621       // Diagnose incompatible Objective-C conversions
   2622       if (Action == AA_Initializing || Action == AA_Assigning)
   2623         Diag(From->getLocStart(),
   2624              diag::ext_typecheck_convert_incompatible_pointer)
   2625           << ToType << From->getType() << Action
   2626           << From->getSourceRange() << 0;
   2627       else
   2628         Diag(From->getLocStart(),
   2629              diag::ext_typecheck_convert_incompatible_pointer)
   2630           << From->getType() << ToType << Action
   2631           << From->getSourceRange() << 0;
   2632 
   2633       if (From->getType()->isObjCObjectPointerType() &&
   2634           ToType->isObjCObjectPointerType())
   2635         EmitRelatedResultTypeNote(From);
   2636     }
   2637     else if (getLangOpts().ObjCAutoRefCount &&
   2638              !CheckObjCARCUnavailableWeakConversion(ToType,
   2639                                                     From->getType())) {
   2640       if (Action == AA_Initializing)
   2641         Diag(From->getLocStart(),
   2642              diag::err_arc_weak_unavailable_assign);
   2643       else
   2644         Diag(From->getLocStart(),
   2645              diag::err_arc_convesion_of_weak_unavailable)
   2646           << (Action == AA_Casting) << From->getType() << ToType
   2647           << From->getSourceRange();
   2648     }
   2649 
   2650     CastKind Kind = CK_Invalid;
   2651     CXXCastPath BasePath;
   2652     if (CheckPointerConversion(From, ToType, Kind, BasePath, CStyle))
   2653       return ExprError();
   2654 
   2655     // Make sure we extend blocks if necessary.
   2656     // FIXME: doing this here is really ugly.
   2657     if (Kind == CK_BlockPointerToObjCPointerCast) {
   2658       ExprResult E = From;
   2659       (void) PrepareCastToObjCObjectPointer(E);
   2660       From = E.take();
   2661     }
   2662 
   2663     From = ImpCastExprToType(From, ToType, Kind,