Home | History | Annotate | Download | only in AST
      1 //===--- ExprCXX.cpp - (C++) Expression AST Node Implementation -----------===//
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is distributed under the University of Illinois Open Source
      6 // License. See LICENSE.TXT for details.
      7 //
      8 //===----------------------------------------------------------------------===//
      9 //
     10 // This file implements the subclesses of Expr class declared in ExprCXX.h
     11 //
     12 //===----------------------------------------------------------------------===//
     13 
     14 #include "clang/AST/ASTContext.h"
     15 #include "clang/AST/Attr.h"
     16 #include "clang/AST/DeclCXX.h"
     17 #include "clang/AST/DeclTemplate.h"
     18 #include "clang/AST/ExprCXX.h"
     19 #include "clang/AST/TypeLoc.h"
     20 #include "clang/Basic/IdentifierTable.h"
     21 using namespace clang;
     22 
     23 
     24 //===----------------------------------------------------------------------===//
     25 //  Child Iterators for iterating over subexpressions/substatements
     26 //===----------------------------------------------------------------------===//
     27 
     28 bool CXXTypeidExpr::isPotentiallyEvaluated() const {
     29   if (isTypeOperand())
     30     return false;
     31 
     32   // C++11 [expr.typeid]p3:
     33   //   When typeid is applied to an expression other than a glvalue of
     34   //   polymorphic class type, [...] the expression is an unevaluated operand.
     35   const Expr *E = getExprOperand();
     36   if (const CXXRecordDecl *RD = E->getType()->getAsCXXRecordDecl())
     37     if (RD->isPolymorphic() && E->isGLValue())
     38       return true;
     39 
     40   return false;
     41 }
     42 
     43 QualType CXXTypeidExpr::getTypeOperand() const {
     44   assert(isTypeOperand() && "Cannot call getTypeOperand for typeid(expr)");
     45   return Operand.get<TypeSourceInfo *>()->getType().getNonReferenceType()
     46                                                         .getUnqualifiedType();
     47 }
     48 
     49 QualType CXXUuidofExpr::getTypeOperand() const {
     50   assert(isTypeOperand() && "Cannot call getTypeOperand for __uuidof(expr)");
     51   return Operand.get<TypeSourceInfo *>()->getType().getNonReferenceType()
     52                                                         .getUnqualifiedType();
     53 }
     54 
     55 // static
     56 UuidAttr *CXXUuidofExpr::GetUuidAttrOfType(QualType QT) {
     57   // Optionally remove one level of pointer, reference or array indirection.
     58   const Type *Ty = QT.getTypePtr();
     59   if (QT->isPointerType() || QT->isReferenceType())
     60     Ty = QT->getPointeeType().getTypePtr();
     61   else if (QT->isArrayType())
     62     Ty = cast<ArrayType>(QT)->getElementType().getTypePtr();
     63 
     64   // Loop all record redeclaration looking for an uuid attribute.
     65   CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
     66   for (CXXRecordDecl::redecl_iterator I = RD->redecls_begin(),
     67        E = RD->redecls_end(); I != E; ++I) {
     68     if (UuidAttr *Uuid = I->getAttr<UuidAttr>())
     69       return Uuid;
     70   }
     71 
     72   return 0;
     73 }
     74 
     75 // CXXScalarValueInitExpr
     76 SourceLocation CXXScalarValueInitExpr::getLocStart() const {
     77   return TypeInfo ? TypeInfo->getTypeLoc().getBeginLoc() : RParenLoc;
     78 }
     79 
     80 // CXXNewExpr
     81 CXXNewExpr::CXXNewExpr(ASTContext &C, bool globalNew, FunctionDecl *operatorNew,
     82                        FunctionDecl *operatorDelete,
     83                        bool usualArrayDeleteWantsSize,
     84                        ArrayRef<Expr*> placementArgs,
     85                        SourceRange typeIdParens, Expr *arraySize,
     86                        InitializationStyle initializationStyle,
     87                        Expr *initializer, QualType ty,
     88                        TypeSourceInfo *allocatedTypeInfo,
     89                        SourceRange Range, SourceRange directInitRange)
     90   : Expr(CXXNewExprClass, ty, VK_RValue, OK_Ordinary,
     91          ty->isDependentType(), ty->isDependentType(),
     92          ty->isInstantiationDependentType(),
     93          ty->containsUnexpandedParameterPack()),
     94     SubExprs(0), OperatorNew(operatorNew), OperatorDelete(operatorDelete),
     95     AllocatedTypeInfo(allocatedTypeInfo), TypeIdParens(typeIdParens),
     96     Range(Range), DirectInitRange(directInitRange),
     97     GlobalNew(globalNew), UsualArrayDeleteWantsSize(usualArrayDeleteWantsSize) {
     98   assert((initializer != 0 || initializationStyle == NoInit) &&
     99          "Only NoInit can have no initializer.");
    100   StoredInitializationStyle = initializer ? initializationStyle + 1 : 0;
    101   AllocateArgsArray(C, arraySize != 0, placementArgs.size(), initializer != 0);
    102   unsigned i = 0;
    103   if (Array) {
    104     if (arraySize->isInstantiationDependent())
    105       ExprBits.InstantiationDependent = true;
    106 
    107     if (arraySize->containsUnexpandedParameterPack())
    108       ExprBits.ContainsUnexpandedParameterPack = true;
    109 
    110     SubExprs[i++] = arraySize;
    111   }
    112 
    113   if (initializer) {
    114     if (initializer->isInstantiationDependent())
    115       ExprBits.InstantiationDependent = true;
    116 
    117     if (initializer->containsUnexpandedParameterPack())
    118       ExprBits.ContainsUnexpandedParameterPack = true;
    119 
    120     SubExprs[i++] = initializer;
    121   }
    122 
    123   for (unsigned j = 0; j != placementArgs.size(); ++j) {
    124     if (placementArgs[j]->isInstantiationDependent())
    125       ExprBits.InstantiationDependent = true;
    126     if (placementArgs[j]->containsUnexpandedParameterPack())
    127       ExprBits.ContainsUnexpandedParameterPack = true;
    128 
    129     SubExprs[i++] = placementArgs[j];
    130   }
    131 
    132   switch (getInitializationStyle()) {
    133   case CallInit:
    134     this->Range.setEnd(DirectInitRange.getEnd()); break;
    135   case ListInit:
    136     this->Range.setEnd(getInitializer()->getSourceRange().getEnd()); break;
    137   default:
    138     if (TypeIdParens.isValid())
    139       this->Range.setEnd(TypeIdParens.getEnd());
    140     break;
    141   }
    142 }
    143 
    144 void CXXNewExpr::AllocateArgsArray(ASTContext &C, bool isArray,
    145                                    unsigned numPlaceArgs, bool hasInitializer){
    146   assert(SubExprs == 0 && "SubExprs already allocated");
    147   Array = isArray;
    148   NumPlacementArgs = numPlaceArgs;
    149 
    150   unsigned TotalSize = Array + hasInitializer + NumPlacementArgs;
    151   SubExprs = new (C) Stmt*[TotalSize];
    152 }
    153 
    154 bool CXXNewExpr::shouldNullCheckAllocation(ASTContext &Ctx) const {
    155   return getOperatorNew()->getType()->
    156     castAs<FunctionProtoType>()->isNothrow(Ctx);
    157 }
    158 
    159 // CXXDeleteExpr
    160 QualType CXXDeleteExpr::getDestroyedType() const {
    161   const Expr *Arg = getArgument();
    162   // The type-to-delete may not be a pointer if it's a dependent type.
    163   const QualType ArgType = Arg->getType();
    164 
    165   if (ArgType->isDependentType() && !ArgType->isPointerType())
    166     return QualType();
    167 
    168   return ArgType->getAs<PointerType>()->getPointeeType();
    169 }
    170 
    171 // CXXPseudoDestructorExpr
    172 PseudoDestructorTypeStorage::PseudoDestructorTypeStorage(TypeSourceInfo *Info)
    173  : Type(Info)
    174 {
    175   Location = Info->getTypeLoc().getLocalSourceRange().getBegin();
    176 }
    177 
    178 CXXPseudoDestructorExpr::CXXPseudoDestructorExpr(ASTContext &Context,
    179                 Expr *Base, bool isArrow, SourceLocation OperatorLoc,
    180                 NestedNameSpecifierLoc QualifierLoc, TypeSourceInfo *ScopeType,
    181                 SourceLocation ColonColonLoc, SourceLocation TildeLoc,
    182                 PseudoDestructorTypeStorage DestroyedType)
    183   : Expr(CXXPseudoDestructorExprClass,
    184          Context.getPointerType(Context.getFunctionType(Context.VoidTy, None,
    185                                          FunctionProtoType::ExtProtoInfo())),
    186          VK_RValue, OK_Ordinary,
    187          /*isTypeDependent=*/(Base->isTypeDependent() ||
    188            (DestroyedType.getTypeSourceInfo() &&
    189             DestroyedType.getTypeSourceInfo()->getType()->isDependentType())),
    190          /*isValueDependent=*/Base->isValueDependent(),
    191          (Base->isInstantiationDependent() ||
    192           (QualifierLoc &&
    193            QualifierLoc.getNestedNameSpecifier()->isInstantiationDependent()) ||
    194           (ScopeType &&
    195            ScopeType->getType()->isInstantiationDependentType()) ||
    196           (DestroyedType.getTypeSourceInfo() &&
    197            DestroyedType.getTypeSourceInfo()->getType()
    198                                              ->isInstantiationDependentType())),
    199          // ContainsUnexpandedParameterPack
    200          (Base->containsUnexpandedParameterPack() ||
    201           (QualifierLoc &&
    202            QualifierLoc.getNestedNameSpecifier()
    203                                         ->containsUnexpandedParameterPack()) ||
    204           (ScopeType &&
    205            ScopeType->getType()->containsUnexpandedParameterPack()) ||
    206           (DestroyedType.getTypeSourceInfo() &&
    207            DestroyedType.getTypeSourceInfo()->getType()
    208                                    ->containsUnexpandedParameterPack()))),
    209     Base(static_cast<Stmt *>(Base)), IsArrow(isArrow),
    210     OperatorLoc(OperatorLoc), QualifierLoc(QualifierLoc),
    211     ScopeType(ScopeType), ColonColonLoc(ColonColonLoc), TildeLoc(TildeLoc),
    212     DestroyedType(DestroyedType) { }
    213 
    214 QualType CXXPseudoDestructorExpr::getDestroyedType() const {
    215   if (TypeSourceInfo *TInfo = DestroyedType.getTypeSourceInfo())
    216     return TInfo->getType();
    217 
    218   return QualType();
    219 }
    220 
    221 SourceLocation CXXPseudoDestructorExpr::getLocEnd() const {
    222   SourceLocation End = DestroyedType.getLocation();
    223   if (TypeSourceInfo *TInfo = DestroyedType.getTypeSourceInfo())
    224     End = TInfo->getTypeLoc().getLocalSourceRange().getEnd();
    225   return End;
    226 }
    227 
    228 // UnresolvedLookupExpr
    229 UnresolvedLookupExpr *
    230 UnresolvedLookupExpr::Create(ASTContext &C,
    231                              CXXRecordDecl *NamingClass,
    232                              NestedNameSpecifierLoc QualifierLoc,
    233                              SourceLocation TemplateKWLoc,
    234                              const DeclarationNameInfo &NameInfo,
    235                              bool ADL,
    236                              const TemplateArgumentListInfo *Args,
    237                              UnresolvedSetIterator Begin,
    238                              UnresolvedSetIterator End)
    239 {
    240   assert(Args || TemplateKWLoc.isValid());
    241   unsigned num_args = Args ? Args->size() : 0;
    242   void *Mem = C.Allocate(sizeof(UnresolvedLookupExpr) +
    243                          ASTTemplateKWAndArgsInfo::sizeFor(num_args));
    244   return new (Mem) UnresolvedLookupExpr(C, NamingClass, QualifierLoc,
    245                                         TemplateKWLoc, NameInfo,
    246                                         ADL, /*Overload*/ true, Args,
    247                                         Begin, End);
    248 }
    249 
    250 UnresolvedLookupExpr *
    251 UnresolvedLookupExpr::CreateEmpty(ASTContext &C,
    252                                   bool HasTemplateKWAndArgsInfo,
    253                                   unsigned NumTemplateArgs) {
    254   std::size_t size = sizeof(UnresolvedLookupExpr);
    255   if (HasTemplateKWAndArgsInfo)
    256     size += ASTTemplateKWAndArgsInfo::sizeFor(NumTemplateArgs);
    257 
    258   void *Mem = C.Allocate(size, llvm::alignOf<UnresolvedLookupExpr>());
    259   UnresolvedLookupExpr *E = new (Mem) UnresolvedLookupExpr(EmptyShell());
    260   E->HasTemplateKWAndArgsInfo = HasTemplateKWAndArgsInfo;
    261   return E;
    262 }
    263 
    264 OverloadExpr::OverloadExpr(StmtClass K, ASTContext &C,
    265                            NestedNameSpecifierLoc QualifierLoc,
    266                            SourceLocation TemplateKWLoc,
    267                            const DeclarationNameInfo &NameInfo,
    268                            const TemplateArgumentListInfo *TemplateArgs,
    269                            UnresolvedSetIterator Begin,
    270                            UnresolvedSetIterator End,
    271                            bool KnownDependent,
    272                            bool KnownInstantiationDependent,
    273                            bool KnownContainsUnexpandedParameterPack)
    274   : Expr(K, C.OverloadTy, VK_LValue, OK_Ordinary, KnownDependent,
    275          KnownDependent,
    276          (KnownInstantiationDependent ||
    277           NameInfo.isInstantiationDependent() ||
    278           (QualifierLoc &&
    279            QualifierLoc.getNestedNameSpecifier()->isInstantiationDependent())),
    280          (KnownContainsUnexpandedParameterPack ||
    281           NameInfo.containsUnexpandedParameterPack() ||
    282           (QualifierLoc &&
    283            QualifierLoc.getNestedNameSpecifier()
    284                                       ->containsUnexpandedParameterPack()))),
    285     NameInfo(NameInfo), QualifierLoc(QualifierLoc),
    286     Results(0), NumResults(End - Begin),
    287     HasTemplateKWAndArgsInfo(TemplateArgs != 0 || TemplateKWLoc.isValid())
    288 {
    289   NumResults = End - Begin;
    290   if (NumResults) {
    291     // Determine whether this expression is type-dependent.
    292     for (UnresolvedSetImpl::const_iterator I = Begin; I != End; ++I) {
    293       if ((*I)->getDeclContext()->isDependentContext() ||
    294           isa<UnresolvedUsingValueDecl>(*I)) {
    295         ExprBits.TypeDependent = true;
    296         ExprBits.ValueDependent = true;
    297         ExprBits.InstantiationDependent = true;
    298       }
    299     }
    300 
    301     Results = static_cast<DeclAccessPair *>(
    302                                 C.Allocate(sizeof(DeclAccessPair) * NumResults,
    303                                            llvm::alignOf<DeclAccessPair>()));
    304     memcpy(Results, &*Begin.getIterator(),
    305            NumResults * sizeof(DeclAccessPair));
    306   }
    307 
    308   // If we have explicit template arguments, check for dependent
    309   // template arguments and whether they contain any unexpanded pack
    310   // expansions.
    311   if (TemplateArgs) {
    312     bool Dependent = false;
    313     bool InstantiationDependent = false;
    314     bool ContainsUnexpandedParameterPack = false;
    315     getTemplateKWAndArgsInfo()->initializeFrom(TemplateKWLoc, *TemplateArgs,
    316                                                Dependent,
    317                                                InstantiationDependent,
    318                                                ContainsUnexpandedParameterPack);
    319 
    320     if (Dependent) {
    321       ExprBits.TypeDependent = true;
    322       ExprBits.ValueDependent = true;
    323     }
    324     if (InstantiationDependent)
    325       ExprBits.InstantiationDependent = true;
    326     if (ContainsUnexpandedParameterPack)
    327       ExprBits.ContainsUnexpandedParameterPack = true;
    328   } else if (TemplateKWLoc.isValid()) {
    329     getTemplateKWAndArgsInfo()->initializeFrom(TemplateKWLoc);
    330   }
    331 
    332   if (isTypeDependent())
    333     setType(C.DependentTy);
    334 }
    335 
    336 void OverloadExpr::initializeResults(ASTContext &C,
    337                                      UnresolvedSetIterator Begin,
    338                                      UnresolvedSetIterator End) {
    339   assert(Results == 0 && "Results already initialized!");
    340   NumResults = End - Begin;
    341   if (NumResults) {
    342      Results = static_cast<DeclAccessPair *>(
    343                                C.Allocate(sizeof(DeclAccessPair) * NumResults,
    344 
    345                                           llvm::alignOf<DeclAccessPair>()));
    346      memcpy(Results, &*Begin.getIterator(),
    347             NumResults * sizeof(DeclAccessPair));
    348   }
    349 }
    350 
    351 CXXRecordDecl *OverloadExpr::getNamingClass() const {
    352   if (isa<UnresolvedLookupExpr>(this))
    353     return cast<UnresolvedLookupExpr>(this)->getNamingClass();
    354   else
    355     return cast<UnresolvedMemberExpr>(this)->getNamingClass();
    356 }
    357 
    358 // DependentScopeDeclRefExpr
    359 DependentScopeDeclRefExpr::DependentScopeDeclRefExpr(QualType T,
    360                             NestedNameSpecifierLoc QualifierLoc,
    361                             SourceLocation TemplateKWLoc,
    362                             const DeclarationNameInfo &NameInfo,
    363                             const TemplateArgumentListInfo *Args)
    364   : Expr(DependentScopeDeclRefExprClass, T, VK_LValue, OK_Ordinary,
    365          true, true,
    366          (NameInfo.isInstantiationDependent() ||
    367           (QualifierLoc &&
    368            QualifierLoc.getNestedNameSpecifier()->isInstantiationDependent())),
    369          (NameInfo.containsUnexpandedParameterPack() ||
    370           (QualifierLoc &&
    371            QualifierLoc.getNestedNameSpecifier()
    372                             ->containsUnexpandedParameterPack()))),
    373     QualifierLoc(QualifierLoc), NameInfo(NameInfo),
    374     HasTemplateKWAndArgsInfo(Args != 0 || TemplateKWLoc.isValid())
    375 {
    376   if (Args) {
    377     bool Dependent = true;
    378     bool InstantiationDependent = true;
    379     bool ContainsUnexpandedParameterPack
    380       = ExprBits.ContainsUnexpandedParameterPack;
    381     getTemplateKWAndArgsInfo()->initializeFrom(TemplateKWLoc, *Args,
    382                                                Dependent,
    383                                                InstantiationDependent,
    384                                                ContainsUnexpandedParameterPack);
    385     ExprBits.ContainsUnexpandedParameterPack = ContainsUnexpandedParameterPack;
    386   } else if (TemplateKWLoc.isValid()) {
    387     getTemplateKWAndArgsInfo()->initializeFrom(TemplateKWLoc);
    388   }
    389 }
    390 
    391 DependentScopeDeclRefExpr *
    392 DependentScopeDeclRefExpr::Create(ASTContext &C,
    393                                   NestedNameSpecifierLoc QualifierLoc,
    394                                   SourceLocation TemplateKWLoc,
    395                                   const DeclarationNameInfo &NameInfo,
    396                                   const TemplateArgumentListInfo *Args) {
    397   std::size_t size = sizeof(DependentScopeDeclRefExpr);
    398   if (Args)
    399     size += ASTTemplateKWAndArgsInfo::sizeFor(Args->size());
    400   else if (TemplateKWLoc.isValid())
    401     size += ASTTemplateKWAndArgsInfo::sizeFor(0);
    402   void *Mem = C.Allocate(size);
    403   return new (Mem) DependentScopeDeclRefExpr(C.DependentTy, QualifierLoc,
    404                                              TemplateKWLoc, NameInfo, Args);
    405 }
    406 
    407 DependentScopeDeclRefExpr *
    408 DependentScopeDeclRefExpr::CreateEmpty(ASTContext &C,
    409                                        bool HasTemplateKWAndArgsInfo,
    410                                        unsigned NumTemplateArgs) {
    411   std::size_t size = sizeof(DependentScopeDeclRefExpr);
    412   if (HasTemplateKWAndArgsInfo)
    413     size += ASTTemplateKWAndArgsInfo::sizeFor(NumTemplateArgs);
    414   void *Mem = C.Allocate(size);
    415   DependentScopeDeclRefExpr *E
    416     = new (Mem) DependentScopeDeclRefExpr(QualType(), NestedNameSpecifierLoc(),
    417                                           SourceLocation(),
    418                                           DeclarationNameInfo(), 0);
    419   E->HasTemplateKWAndArgsInfo = HasTemplateKWAndArgsInfo;
    420   return E;
    421 }
    422 
    423 SourceLocation CXXConstructExpr::getLocStart() const {
    424   if (isa<CXXTemporaryObjectExpr>(this))
    425     return cast<CXXTemporaryObjectExpr>(this)->getLocStart();
    426   return Loc;
    427 }
    428 
    429 SourceLocation CXXConstructExpr::getLocEnd() const {
    430   if (isa<CXXTemporaryObjectExpr>(this))
    431     return cast<CXXTemporaryObjectExpr>(this)->getLocEnd();
    432 
    433   if (ParenRange.isValid())
    434     return ParenRange.getEnd();
    435 
    436   SourceLocation End = Loc;
    437   for (unsigned I = getNumArgs(); I > 0; --I) {
    438     const Expr *Arg = getArg(I-1);
    439     if (!Arg->isDefaultArgument()) {
    440       SourceLocation NewEnd = Arg->getLocEnd();
    441       if (NewEnd.isValid()) {
    442         End = NewEnd;
    443         break;
    444       }
    445     }
    446   }
    447 
    448   return End;
    449 }
    450 
    451 SourceRange CXXOperatorCallExpr::getSourceRangeImpl() const {
    452   OverloadedOperatorKind Kind = getOperator();
    453   if (Kind == OO_PlusPlus || Kind == OO_MinusMinus) {
    454     if (getNumArgs() == 1)
    455       // Prefix operator
    456       return SourceRange(getOperatorLoc(), getArg(0)->getLocEnd());
    457     else
    458       // Postfix operator
    459       return SourceRange(getArg(0)->getLocStart(), getOperatorLoc());
    460   } else if (Kind == OO_Arrow) {
    461     return getArg(0)->getSourceRange();
    462   } else if (Kind == OO_Call) {
    463     return SourceRange(getArg(0)->getLocStart(), getRParenLoc());
    464   } else if (Kind == OO_Subscript) {
    465     return SourceRange(getArg(0)->getLocStart(), getRParenLoc());
    466   } else if (getNumArgs() == 1) {
    467     return SourceRange(getOperatorLoc(), getArg(0)->getLocEnd());
    468   } else if (getNumArgs() == 2) {
    469     return SourceRange(getArg(0)->getLocStart(), getArg(1)->getLocEnd());
    470   } else {
    471     return getOperatorLoc();
    472   }
    473 }
    474 
    475 Expr *CXXMemberCallExpr::getImplicitObjectArgument() const {
    476   const Expr *Callee = getCallee()->IgnoreParens();
    477   if (const MemberExpr *MemExpr = dyn_cast<MemberExpr>(Callee))
    478     return MemExpr->getBase();
    479   if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(Callee))
    480     if (BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI)
    481       return BO->getLHS();
    482 
    483   // FIXME: Will eventually need to cope with member pointers.
    484   return 0;
    485 }
    486 
    487 CXXMethodDecl *CXXMemberCallExpr::getMethodDecl() const {
    488   if (const MemberExpr *MemExpr =
    489       dyn_cast<MemberExpr>(getCallee()->IgnoreParens()))
    490     return cast<CXXMethodDecl>(MemExpr->getMemberDecl());
    491 
    492   // FIXME: Will eventually need to cope with member pointers.
    493   return 0;
    494 }
    495 
    496 
    497 CXXRecordDecl *CXXMemberCallExpr::getRecordDecl() const {
    498   Expr* ThisArg = getImplicitObjectArgument();
    499   if (!ThisArg)
    500     return 0;
    501 
    502   if (ThisArg->getType()->isAnyPointerType())
    503     return ThisArg->getType()->getPointeeType()->getAsCXXRecordDecl();
    504 
    505   return ThisArg->getType()->getAsCXXRecordDecl();
    506 }
    507 
    508 
    509 //===----------------------------------------------------------------------===//
    510 //  Named casts
    511 //===----------------------------------------------------------------------===//
    512 
    513 /// getCastName - Get the name of the C++ cast being used, e.g.,
    514 /// "static_cast", "dynamic_cast", "reinterpret_cast", or
    515 /// "const_cast". The returned pointer must not be freed.
    516 const char *CXXNamedCastExpr::getCastName() const {
    517   switch (getStmtClass()) {
    518   case CXXStaticCastExprClass:      return "static_cast";
    519   case CXXDynamicCastExprClass:     return "dynamic_cast";
    520   case CXXReinterpretCastExprClass: return "reinterpret_cast";
    521   case CXXConstCastExprClass:       return "const_cast";
    522   default:                          return "<invalid cast>";
    523   }
    524 }
    525 
    526 CXXStaticCastExpr *CXXStaticCastExpr::Create(ASTContext &C, QualType T,
    527                                              ExprValueKind VK,
    528                                              CastKind K, Expr *Op,
    529                                              const CXXCastPath *BasePath,
    530                                              TypeSourceInfo *WrittenTy,
    531                                              SourceLocation L,
    532                                              SourceLocation RParenLoc,
    533                                              SourceRange AngleBrackets) {
    534   unsigned PathSize = (BasePath ? BasePath->size() : 0);
    535   void *Buffer = C.Allocate(sizeof(CXXStaticCastExpr)
    536                             + PathSize * sizeof(CXXBaseSpecifier*));
    537   CXXStaticCastExpr *E =
    538     new (Buffer) CXXStaticCastExpr(T, VK, K, Op, PathSize, WrittenTy, L,
    539                                    RParenLoc, AngleBrackets);
    540   if (PathSize) E->setCastPath(*BasePath);
    541   return E;
    542 }
    543 
    544 CXXStaticCastExpr *CXXStaticCastExpr::CreateEmpty(ASTContext &C,
    545                                                   unsigned PathSize) {
    546   void *Buffer =
    547     C.Allocate(sizeof(CXXStaticCastExpr) + PathSize * sizeof(CXXBaseSpecifier*));
    548   return new (Buffer) CXXStaticCastExpr(EmptyShell(), PathSize);
    549 }
    550 
    551 CXXDynamicCastExpr *CXXDynamicCastExpr::Create(ASTContext &C, QualType T,
    552                                                ExprValueKind VK,
    553                                                CastKind K, Expr *Op,
    554                                                const CXXCastPath *BasePath,
    555                                                TypeSourceInfo *WrittenTy,
    556                                                SourceLocation L,
    557                                                SourceLocation RParenLoc,
    558                                                SourceRange AngleBrackets) {
    559   unsigned PathSize = (BasePath ? BasePath->size() : 0);
    560   void *Buffer = C.Allocate(sizeof(CXXDynamicCastExpr)
    561                             + PathSize * sizeof(CXXBaseSpecifier*));
    562   CXXDynamicCastExpr *E =
    563     new (Buffer) CXXDynamicCastExpr(T, VK, K, Op, PathSize, WrittenTy, L,
    564                                     RParenLoc, AngleBrackets);
    565   if (PathSize) E->setCastPath(*BasePath);
    566   return E;
    567 }
    568 
    569 CXXDynamicCastExpr *CXXDynamicCastExpr::CreateEmpty(ASTContext &C,
    570                                                     unsigned PathSize) {
    571   void *Buffer =
    572     C.Allocate(sizeof(CXXDynamicCastExpr) + PathSize * sizeof(CXXBaseSpecifier*));
    573   return new (Buffer) CXXDynamicCastExpr(EmptyShell(), PathSize);
    574 }
    575 
    576 /// isAlwaysNull - Return whether the result of the dynamic_cast is proven
    577 /// to always be null. For example:
    578 ///
    579 /// struct A { };
    580 /// struct B final : A { };
    581 /// struct C { };
    582 ///
    583 /// C *f(B* b) { return dynamic_cast<C*>(b); }
    584 bool CXXDynamicCastExpr::isAlwaysNull() const
    585 {
    586   QualType SrcType = getSubExpr()->getType();
    587   QualType DestType = getType();
    588 
    589   if (const PointerType *SrcPTy = SrcType->getAs<PointerType>()) {
    590     SrcType = SrcPTy->getPointeeType();
    591     DestType = DestType->castAs<PointerType>()->getPointeeType();
    592   }
    593 
    594   if (DestType->isVoidType())
    595     return false;
    596 
    597   const CXXRecordDecl *SrcRD =
    598     cast<CXXRecordDecl>(SrcType->castAs<RecordType>()->getDecl());
    599 
    600   if (!SrcRD->hasAttr<FinalAttr>())
    601     return false;
    602 
    603   const CXXRecordDecl *DestRD =
    604     cast<CXXRecordDecl>(DestType->castAs<RecordType>()->getDecl());
    605 
    606   return !DestRD->isDerivedFrom(SrcRD);
    607 }
    608 
    609 CXXReinterpretCastExpr *
    610 CXXReinterpretCastExpr::Create(ASTContext &C, QualType T, ExprValueKind VK,
    611                                CastKind K, Expr *Op,
    612                                const CXXCastPath *BasePath,
    613                                TypeSourceInfo *WrittenTy, SourceLocation L,
    614                                SourceLocation RParenLoc,
    615                                SourceRange AngleBrackets) {
    616   unsigned PathSize = (BasePath ? BasePath->size() : 0);
    617   void *Buffer =
    618     C.Allocate(sizeof(CXXReinterpretCastExpr) + PathSize * sizeof(CXXBaseSpecifier*));
    619   CXXReinterpretCastExpr *E =
    620     new (Buffer) CXXReinterpretCastExpr(T, VK, K, Op, PathSize, WrittenTy, L,
    621                                         RParenLoc, AngleBrackets);
    622   if (PathSize) E->setCastPath(*BasePath);
    623   return E;
    624 }
    625 
    626 CXXReinterpretCastExpr *
    627 CXXReinterpretCastExpr::CreateEmpty(ASTContext &C, unsigned PathSize) {
    628   void *Buffer = C.Allocate(sizeof(CXXReinterpretCastExpr)
    629                             + PathSize * sizeof(CXXBaseSpecifier*));
    630   return new (Buffer) CXXReinterpretCastExpr(EmptyShell(), PathSize);
    631 }
    632 
    633 CXXConstCastExpr *CXXConstCastExpr::Create(ASTContext &C, QualType T,
    634                                            ExprValueKind VK, Expr *Op,
    635                                            TypeSourceInfo *WrittenTy,
    636                                            SourceLocation L,
    637                                            SourceLocation RParenLoc,
    638                                            SourceRange AngleBrackets) {
    639   return new (C) CXXConstCastExpr(T, VK, Op, WrittenTy, L, RParenLoc, AngleBrackets);
    640 }
    641 
    642 CXXConstCastExpr *CXXConstCastExpr::CreateEmpty(ASTContext &C) {
    643   return new (C) CXXConstCastExpr(EmptyShell());
    644 }
    645 
    646 CXXFunctionalCastExpr *
    647 CXXFunctionalCastExpr::Create(ASTContext &C, QualType T, ExprValueKind VK,
    648                               TypeSourceInfo *Written, SourceLocation L,
    649                               CastKind K, Expr *Op, const CXXCastPath *BasePath,
    650                                SourceLocation R) {
    651   unsigned PathSize = (BasePath ? BasePath->size() : 0);
    652   void *Buffer = C.Allocate(sizeof(CXXFunctionalCastExpr)
    653                             + PathSize * sizeof(CXXBaseSpecifier*));
    654   CXXFunctionalCastExpr *E =
    655     new (Buffer) CXXFunctionalCastExpr(T, VK, Written, L, K, Op, PathSize, R);
    656   if (PathSize) E->setCastPath(*BasePath);
    657   return E;
    658 }
    659 
    660 CXXFunctionalCastExpr *
    661 CXXFunctionalCastExpr::CreateEmpty(ASTContext &C, unsigned PathSize) {
    662   void *Buffer = C.Allocate(sizeof(CXXFunctionalCastExpr)
    663                             + PathSize * sizeof(CXXBaseSpecifier*));
    664   return new (Buffer) CXXFunctionalCastExpr(EmptyShell(), PathSize);
    665 }
    666 
    667 UserDefinedLiteral::LiteralOperatorKind
    668 UserDefinedLiteral::getLiteralOperatorKind() const {
    669   if (getNumArgs() == 0)
    670     return LOK_Template;
    671   if (getNumArgs() == 2)
    672     return LOK_String;
    673 
    674   assert(getNumArgs() == 1 && "unexpected #args in literal operator call");
    675   QualType ParamTy =
    676     cast<FunctionDecl>(getCalleeDecl())->getParamDecl(0)->getType();
    677   if (ParamTy->isPointerType())
    678     return LOK_Raw;
    679   if (ParamTy->isAnyCharacterType())
    680     return LOK_Character;
    681   if (ParamTy->isIntegerType())
    682     return LOK_Integer;
    683   if (ParamTy->isFloatingType())
    684     return LOK_Floating;
    685 
    686   llvm_unreachable("unknown kind of literal operator");
    687 }
    688 
    689 Expr *UserDefinedLiteral::getCookedLiteral() {
    690 #ifndef NDEBUG
    691   LiteralOperatorKind LOK = getLiteralOperatorKind();
    692   assert(LOK != LOK_Template && LOK != LOK_Raw && "not a cooked literal");
    693 #endif
    694   return getArg(0);
    695 }
    696 
    697 const IdentifierInfo *UserDefinedLiteral::getUDSuffix() const {
    698   return cast<FunctionDecl>(getCalleeDecl())->getLiteralIdentifier();
    699 }
    700 
    701 CXXDefaultArgExpr *
    702 CXXDefaultArgExpr::Create(ASTContext &C, SourceLocation Loc,
    703                           ParmVarDecl *Param, Expr *SubExpr) {
    704   void *Mem = C.Allocate(sizeof(CXXDefaultArgExpr) + sizeof(Stmt *));
    705   return new (Mem) CXXDefaultArgExpr(CXXDefaultArgExprClass, Loc, Param,
    706                                      SubExpr);
    707 }
    708 
    709 CXXDefaultInitExpr::CXXDefaultInitExpr(ASTContext &C, SourceLocation Loc,
    710                                        FieldDecl *Field, QualType T)
    711     : Expr(CXXDefaultInitExprClass, T.getNonLValueExprType(C),
    712            T->isLValueReferenceType() ? VK_LValue : T->isRValueReferenceType()
    713                                                         ? VK_XValue
    714                                                         : VK_RValue,
    715            /*FIXME*/ OK_Ordinary, false, false, false, false),
    716       Field(Field), Loc(Loc) {
    717   assert(Field->hasInClassInitializer());
    718 }
    719 
    720 CXXTemporary *CXXTemporary::Create(ASTContext &C,
    721                                    const CXXDestructorDecl *Destructor) {
    722   return new (C) CXXTemporary(Destructor);
    723 }
    724 
    725 CXXBindTemporaryExpr *CXXBindTemporaryExpr::Create(ASTContext &C,
    726                                                    CXXTemporary *Temp,
    727                                                    Expr* SubExpr) {
    728   assert((SubExpr->getType()->isRecordType() ||
    729           SubExpr->getType()->isArrayType()) &&
    730          "Expression bound to a temporary must have record or array type!");
    731 
    732   return new (C) CXXBindTemporaryExpr(Temp, SubExpr);
    733 }
    734 
    735 CXXTemporaryObjectExpr::CXXTemporaryObjectExpr(ASTContext &C,
    736                                                CXXConstructorDecl *Cons,
    737                                                TypeSourceInfo *Type,
    738                                                ArrayRef<Expr*> Args,
    739                                                SourceRange parenRange,
    740                                                bool HadMultipleCandidates,
    741                                                bool ListInitialization,
    742                                                bool ZeroInitialization)
    743   : CXXConstructExpr(C, CXXTemporaryObjectExprClass,
    744                      Type->getType().getNonReferenceType(),
    745                      Type->getTypeLoc().getBeginLoc(),
    746                      Cons, false, Args,
    747                      HadMultipleCandidates,
    748                      ListInitialization, ZeroInitialization,
    749                      CXXConstructExpr::CK_Complete, parenRange),
    750     Type(Type) {
    751 }
    752 
    753 SourceLocation CXXTemporaryObjectExpr::getLocStart() const {
    754   return Type->getTypeLoc().getBeginLoc();
    755 }
    756 
    757 SourceLocation CXXTemporaryObjectExpr::getLocEnd() const {
    758   return getParenRange().getEnd();
    759 }
    760 
    761 CXXConstructExpr *CXXConstructExpr::Create(ASTContext &C, QualType T,
    762                                            SourceLocation Loc,
    763                                            CXXConstructorDecl *D, bool Elidable,
    764                                            ArrayRef<Expr*> Args,
    765                                            bool HadMultipleCandidates,
    766                                            bool ListInitialization,
    767                                            bool ZeroInitialization,
    768                                            ConstructionKind ConstructKind,
    769                                            SourceRange ParenRange) {
    770   return new (C) CXXConstructExpr(C, CXXConstructExprClass, T, Loc, D,
    771                                   Elidable, Args,
    772                                   HadMultipleCandidates, ListInitialization,
    773                                   ZeroInitialization, ConstructKind,
    774                                   ParenRange);
    775 }
    776 
    777 CXXConstructExpr::CXXConstructExpr(ASTContext &C, StmtClass SC, QualType T,
    778                                    SourceLocation Loc,
    779                                    CXXConstructorDecl *D, bool elidable,
    780                                    ArrayRef<Expr*> args,
    781                                    bool HadMultipleCandidates,
    782                                    bool ListInitialization,
    783                                    bool ZeroInitialization,
    784                                    ConstructionKind ConstructKind,
    785                                    SourceRange ParenRange)
    786   : Expr(SC, T, VK_RValue, OK_Ordinary,
    787          T->isDependentType(), T->isDependentType(),
    788          T->isInstantiationDependentType(),
    789          T->containsUnexpandedParameterPack()),
    790     Constructor(D), Loc(Loc), ParenRange(ParenRange),  NumArgs(args.size()),
    791     Elidable(elidable), HadMultipleCandidates(HadMultipleCandidates),
    792     ListInitialization(ListInitialization),
    793     ZeroInitialization(ZeroInitialization),
    794     ConstructKind(ConstructKind), Args(0)
    795 {
    796   if (NumArgs) {
    797     Args = new (C) Stmt*[args.size()];
    798 
    799     for (unsigned i = 0; i != args.size(); ++i) {
    800       assert(args[i] && "NULL argument in CXXConstructExpr");
    801 
    802       if (args[i]->isValueDependent())
    803         ExprBits.ValueDependent = true;
    804       if (args[i]->isInstantiationDependent())
    805         ExprBits.InstantiationDependent = true;
    806       if (args[i]->containsUnexpandedParameterPack())
    807         ExprBits.ContainsUnexpandedParameterPack = true;
    808 
    809       Args[i] = args[i];
    810     }
    811   }
    812 }
    813 
    814 LambdaExpr::Capture::Capture(SourceLocation Loc, bool Implicit,
    815                              LambdaCaptureKind Kind, VarDecl *Var,
    816                              SourceLocation EllipsisLoc)
    817   : DeclAndBits(Var, 0), Loc(Loc), EllipsisLoc(EllipsisLoc)
    818 {
    819   unsigned Bits = 0;
    820   if (Implicit)
    821     Bits |= Capture_Implicit;
    822 
    823   switch (Kind) {
    824   case LCK_This:
    825     assert(Var == 0 && "'this' capture cannot have a variable!");
    826     break;
    827 
    828   case LCK_ByCopy:
    829     Bits |= Capture_ByCopy;
    830     // Fall through
    831   case LCK_ByRef:
    832     assert(Var && "capture must have a variable!");
    833     break;
    834 
    835   case LCK_Init:
    836     llvm_unreachable("don't use this constructor for an init-capture");
    837   }
    838   DeclAndBits.setInt(Bits);
    839 }
    840 
    841 LambdaExpr::Capture::Capture(FieldDecl *Field)
    842     : DeclAndBits(Field,
    843                   Field->getType()->isReferenceType() ? 0 : Capture_ByCopy),
    844       Loc(Field->getLocation()), EllipsisLoc() {}
    845 
    846 LambdaCaptureKind LambdaExpr::Capture::getCaptureKind() const {
    847   Decl *D = DeclAndBits.getPointer();
    848   if (!D)
    849     return LCK_This;
    850 
    851   if (isa<FieldDecl>(D))
    852     return LCK_Init;
    853 
    854   return (DeclAndBits.getInt() & Capture_ByCopy) ? LCK_ByCopy : LCK_ByRef;
    855 }
    856 
    857 LambdaExpr::LambdaExpr(QualType T,
    858                        SourceRange IntroducerRange,
    859                        LambdaCaptureDefault CaptureDefault,
    860                        ArrayRef<Capture> Captures,
    861                        bool ExplicitParams,
    862                        bool ExplicitResultType,
    863                        ArrayRef<Expr *> CaptureInits,
    864                        ArrayRef<VarDecl *> ArrayIndexVars,
    865                        ArrayRef<unsigned> ArrayIndexStarts,
    866                        SourceLocation ClosingBrace,
    867                        bool ContainsUnexpandedParameterPack)
    868   : Expr(LambdaExprClass, T, VK_RValue, OK_Ordinary,
    869          T->isDependentType(), T->isDependentType(), T->isDependentType(),
    870          ContainsUnexpandedParameterPack),
    871     IntroducerRange(IntroducerRange),
    872     NumCaptures(Captures.size()),
    873     CaptureDefault(CaptureDefault),
    874     ExplicitParams(ExplicitParams),
    875     ExplicitResultType(ExplicitResultType),
    876     ClosingBrace(ClosingBrace)
    877 {
    878   assert(CaptureInits.size() == Captures.size() && "Wrong number of arguments");
    879   CXXRecordDecl *Class = getLambdaClass();
    880   CXXRecordDecl::LambdaDefinitionData &Data = Class->getLambdaData();
    881 
    882   // FIXME: Propagate "has unexpanded parameter pack" bit.
    883 
    884   // Copy captures.
    885   ASTContext &Context = Class->getASTContext();
    886   Data.NumCaptures = NumCaptures;
    887   Data.NumExplicitCaptures = 0;
    888   Data.Captures = (Capture *)Context.Allocate(sizeof(Capture) * NumCaptures);
    889   Capture *ToCapture = Data.Captures;
    890   for (unsigned I = 0, N = Captures.size(); I != N; ++I) {
    891     if (Captures[I].isExplicit())
    892       ++Data.NumExplicitCaptures;
    893 
    894     *ToCapture++ = Captures[I];
    895   }
    896 
    897   // Copy initialization expressions for the non-static data members.
    898   Stmt **Stored = getStoredStmts();
    899   for (unsigned I = 0, N = CaptureInits.size(); I != N; ++I)
    900     *Stored++ = CaptureInits[I];
    901 
    902   // Copy the body of the lambda.
    903   *Stored++ = getCallOperator()->getBody();
    904 
    905   // Copy the array index variables, if any.
    906   HasArrayIndexVars = !ArrayIndexVars.empty();
    907   if (HasArrayIndexVars) {
    908     assert(ArrayIndexStarts.size() == NumCaptures);
    909     memcpy(getArrayIndexVars(), ArrayIndexVars.data(),
    910            sizeof(VarDecl *) * ArrayIndexVars.size());
    911     memcpy(getArrayIndexStarts(), ArrayIndexStarts.data(),
    912            sizeof(unsigned) * Captures.size());
    913     getArrayIndexStarts()[Captures.size()] = ArrayIndexVars.size();
    914   }
    915 }
    916 
    917 LambdaExpr *LambdaExpr::Create(ASTContext &Context,
    918                                CXXRecordDecl *Class,
    919                                SourceRange IntroducerRange,
    920                                LambdaCaptureDefault CaptureDefault,
    921                                ArrayRef<Capture> Captures,
    922                                bool ExplicitParams,
    923                                bool ExplicitResultType,
    924                                ArrayRef<Expr *> CaptureInits,
    925                                ArrayRef<VarDecl *> ArrayIndexVars,
    926                                ArrayRef<unsigned> ArrayIndexStarts,
    927                                SourceLocation ClosingBrace,
    928                                bool ContainsUnexpandedParameterPack) {
    929   // Determine the type of the expression (i.e., the type of the
    930   // function object we're creating).
    931   QualType T = Context.getTypeDeclType(Class);
    932 
    933   unsigned Size = sizeof(LambdaExpr) + sizeof(Stmt *) * (Captures.size() + 1);
    934   if (!ArrayIndexVars.empty()) {
    935     Size += sizeof(unsigned) * (Captures.size() + 1);
    936     // Realign for following VarDecl array.
    937     Size = llvm::RoundUpToAlignment(Size, llvm::alignOf<VarDecl*>());
    938     Size += sizeof(VarDecl *) * ArrayIndexVars.size();
    939   }
    940   void *Mem = Context.Allocate(Size);
    941   return new (Mem) LambdaExpr(T, IntroducerRange, CaptureDefault,
    942                               Captures, ExplicitParams, ExplicitResultType,
    943                               CaptureInits, ArrayIndexVars, ArrayIndexStarts,
    944                               ClosingBrace, ContainsUnexpandedParameterPack);
    945 }
    946 
    947 LambdaExpr *LambdaExpr::CreateDeserialized(ASTContext &C, unsigned NumCaptures,
    948                                            unsigned NumArrayIndexVars) {
    949   unsigned Size = sizeof(LambdaExpr) + sizeof(Stmt *) * (NumCaptures + 1);
    950   if (NumArrayIndexVars)
    951     Size += sizeof(VarDecl) * NumArrayIndexVars
    952           + sizeof(unsigned) * (NumCaptures + 1);
    953   void *Mem = C.Allocate(Size);
    954   return new (Mem) LambdaExpr(EmptyShell(), NumCaptures, NumArrayIndexVars > 0);
    955 }
    956 
    957 LambdaExpr::capture_iterator LambdaExpr::capture_begin() const {
    958   return getLambdaClass()->getLambdaData().Captures;
    959 }
    960 
    961 LambdaExpr::capture_iterator LambdaExpr::capture_end() const {
    962   return capture_begin() + NumCaptures;
    963 }
    964 
    965 LambdaExpr::capture_iterator LambdaExpr::explicit_capture_begin() const {
    966   return capture_begin();
    967 }
    968 
    969 LambdaExpr::capture_iterator LambdaExpr::explicit_capture_end() const {
    970   struct CXXRecordDecl::LambdaDefinitionData &Data
    971     = getLambdaClass()->getLambdaData();
    972   return Data.Captures + Data.NumExplicitCaptures;
    973 }
    974 
    975 LambdaExpr::capture_iterator LambdaExpr::implicit_capture_begin() const {
    976   return explicit_capture_end();
    977 }
    978 
    979 LambdaExpr::capture_iterator LambdaExpr::implicit_capture_end() const {
    980   return capture_end();
    981 }
    982 
    983 ArrayRef<VarDecl *>
    984 LambdaExpr::getCaptureInitIndexVars(capture_init_iterator Iter) const {
    985   assert(HasArrayIndexVars && "No array index-var data?");
    986 
    987   unsigned Index = Iter - capture_init_begin();
    988   assert(Index < getLambdaClass()->getLambdaData().NumCaptures &&
    989          "Capture index out-of-range");
    990   VarDecl **IndexVars = getArrayIndexVars();
    991   unsigned *IndexStarts = getArrayIndexStarts();
    992   return ArrayRef<VarDecl *>(IndexVars + IndexStarts[Index],
    993                              IndexVars + IndexStarts[Index + 1]);
    994 }
    995 
    996 CXXRecordDecl *LambdaExpr::getLambdaClass() const {
    997   return getType()->getAsCXXRecordDecl();
    998 }
    999 
   1000 CXXMethodDecl *LambdaExpr::getCallOperator() const {
   1001   CXXRecordDecl *Record = getLambdaClass();
   1002   DeclarationName Name
   1003     = Record->getASTContext().DeclarationNames.getCXXOperatorName(OO_Call);
   1004   DeclContext::lookup_result Calls = Record->lookup(Name);
   1005   assert(!Calls.empty() && "Missing lambda call operator!");
   1006   assert(Calls.size() == 1 && "More than one lambda call operator!");
   1007   CXXMethodDecl *Result = cast<CXXMethodDecl>(Calls.front());
   1008   return Result;
   1009 }
   1010 
   1011 CompoundStmt *LambdaExpr::getBody() const {
   1012   if (!getStoredStmts()[NumCaptures])
   1013     getStoredStmts()[NumCaptures] = getCallOperator()->getBody();
   1014 
   1015   return reinterpret_cast<CompoundStmt *>(getStoredStmts()[NumCaptures]);
   1016 }
   1017 
   1018 bool LambdaExpr::isMutable() const {
   1019   return !getCallOperator()->isConst();
   1020 }
   1021 
   1022 ExprWithCleanups::ExprWithCleanups(Expr *subexpr,
   1023                                    ArrayRef<CleanupObject> objects)
   1024   : Expr(ExprWithCleanupsClass, subexpr->getType(),
   1025          subexpr->getValueKind(), subexpr->getObjectKind(),
   1026          subexpr->isTypeDependent(), subexpr->isValueDependent(),
   1027          subexpr->isInstantiationDependent(),
   1028          subexpr->containsUnexpandedParameterPack()),
   1029     SubExpr(subexpr) {
   1030   ExprWithCleanupsBits.NumObjects = objects.size();
   1031   for (unsigned i = 0, e = objects.size(); i != e; ++i)
   1032     getObjectsBuffer()[i] = objects[i];
   1033 }
   1034 
   1035 ExprWithCleanups *ExprWithCleanups::Create(ASTContext &C, Expr *subexpr,
   1036                                            ArrayRef<CleanupObject> objects) {
   1037   size_t size = sizeof(ExprWithCleanups)
   1038               + objects.size() * sizeof(CleanupObject);
   1039   void *buffer = C.Allocate(size, llvm::alignOf<ExprWithCleanups>());
   1040   return new (buffer) ExprWithCleanups(subexpr, objects);
   1041 }
   1042 
   1043 ExprWithCleanups::ExprWithCleanups(EmptyShell empty, unsigned numObjects)
   1044   : Expr(ExprWithCleanupsClass, empty) {
   1045   ExprWithCleanupsBits.NumObjects = numObjects;
   1046 }
   1047 
   1048 ExprWithCleanups *ExprWithCleanups::Create(ASTContext &C, EmptyShell empty,
   1049                                            unsigned numObjects) {
   1050   size_t size = sizeof(ExprWithCleanups) + numObjects * sizeof(CleanupObject);
   1051   void *buffer = C.Allocate(size, llvm::alignOf<ExprWithCleanups>());
   1052   return new (buffer) ExprWithCleanups(empty, numObjects);
   1053 }
   1054 
   1055 CXXUnresolvedConstructExpr::CXXUnresolvedConstructExpr(TypeSourceInfo *Type,
   1056                                                  SourceLocation LParenLoc,
   1057                                                  ArrayRef<Expr*> Args,
   1058                                                  SourceLocation RParenLoc)
   1059   : Expr(CXXUnresolvedConstructExprClass,
   1060          Type->getType().getNonReferenceType(),
   1061          (Type->getType()->isLValueReferenceType() ? VK_LValue
   1062           :Type->getType()->isRValueReferenceType()? VK_XValue
   1063           :VK_RValue),
   1064          OK_Ordinary,
   1065          Type->getType()->isDependentType(), true, true,
   1066          Type->getType()->containsUnexpandedParameterPack()),
   1067     Type(Type),
   1068     LParenLoc(LParenLoc),
   1069     RParenLoc(RParenLoc),
   1070     NumArgs(Args.size()) {
   1071   Stmt **StoredArgs = reinterpret_cast<Stmt **>(this + 1);
   1072   for (unsigned I = 0; I != Args.size(); ++I) {
   1073     if (Args[I]->containsUnexpandedParameterPack())
   1074       ExprBits.ContainsUnexpandedParameterPack = true;
   1075 
   1076     StoredArgs[I] = Args[I];
   1077   }
   1078 }
   1079 
   1080 CXXUnresolvedConstructExpr *
   1081 CXXUnresolvedConstructExpr::Create(ASTContext &C,
   1082                                    TypeSourceInfo *Type,
   1083                                    SourceLocation LParenLoc,
   1084                                    ArrayRef<Expr*> Args,
   1085                                    SourceLocation RParenLoc) {
   1086   void *Mem = C.Allocate(sizeof(CXXUnresolvedConstructExpr) +
   1087                          sizeof(Expr *) * Args.size());
   1088   return new (Mem) CXXUnresolvedConstructExpr(Type, LParenLoc, Args, RParenLoc);
   1089 }
   1090 
   1091 CXXUnresolvedConstructExpr *
   1092 CXXUnresolvedConstructExpr::CreateEmpty(ASTContext &C, unsigned NumArgs) {
   1093   Stmt::EmptyShell Empty;
   1094   void *Mem = C.Allocate(sizeof(CXXUnresolvedConstructExpr) +
   1095                          sizeof(Expr *) * NumArgs);
   1096   return new (Mem) CXXUnresolvedConstructExpr(Empty, NumArgs);
   1097 }
   1098 
   1099 SourceLocation CXXUnresolvedConstructExpr::getLocStart() const {
   1100   return Type->getTypeLoc().getBeginLoc();
   1101 }
   1102 
   1103 CXXDependentScopeMemberExpr::CXXDependentScopeMemberExpr(ASTContext &C,
   1104                                                  Expr *Base, QualType BaseType,
   1105                                                  bool IsArrow,
   1106                                                  SourceLocation OperatorLoc,
   1107                                           NestedNameSpecifierLoc QualifierLoc,
   1108                                           SourceLocation TemplateKWLoc,
   1109                                           NamedDecl *FirstQualifierFoundInScope,
   1110                                           DeclarationNameInfo MemberNameInfo,
   1111                                    const TemplateArgumentListInfo *TemplateArgs)
   1112   : Expr(CXXDependentScopeMemberExprClass, C.DependentTy,
   1113          VK_LValue, OK_Ordinary, true, true, true,
   1114          ((Base && Base->containsUnexpandedParameterPack()) ||
   1115           (QualifierLoc &&
   1116            QualifierLoc.getNestedNameSpecifier()
   1117                                        ->containsUnexpandedParameterPack()) ||
   1118           MemberNameInfo.containsUnexpandedParameterPack())),
   1119     Base(Base), BaseType(BaseType), IsArrow(IsArrow),
   1120     HasTemplateKWAndArgsInfo(TemplateArgs != 0 || TemplateKWLoc.isValid()),
   1121     OperatorLoc(OperatorLoc), QualifierLoc(QualifierLoc),
   1122     FirstQualifierFoundInScope(FirstQualifierFoundInScope),
   1123     MemberNameInfo(MemberNameInfo) {
   1124   if (TemplateArgs) {
   1125     bool Dependent = true;
   1126     bool InstantiationDependent = true;
   1127     bool ContainsUnexpandedParameterPack = false;
   1128     getTemplateKWAndArgsInfo()->initializeFrom(TemplateKWLoc, *TemplateArgs,
   1129                                                Dependent,
   1130                                                InstantiationDependent,
   1131                                                ContainsUnexpandedParameterPack);
   1132     if (ContainsUnexpandedParameterPack)
   1133       ExprBits.ContainsUnexpandedParameterPack = true;
   1134   } else if (TemplateKWLoc.isValid()) {
   1135     getTemplateKWAndArgsInfo()->initializeFrom(TemplateKWLoc);
   1136   }
   1137 }
   1138 
   1139 CXXDependentScopeMemberExpr::CXXDependentScopeMemberExpr(ASTContext &C,
   1140                           Expr *Base, QualType BaseType,
   1141                           bool IsArrow,
   1142                           SourceLocation OperatorLoc,
   1143                           NestedNameSpecifierLoc QualifierLoc,
   1144                           NamedDecl *FirstQualifierFoundInScope,
   1145                           DeclarationNameInfo MemberNameInfo)
   1146   : Expr(CXXDependentScopeMemberExprClass, C.DependentTy,
   1147          VK_LValue, OK_Ordinary, true, true, true,
   1148          ((Base && Base->containsUnexpandedParameterPack()) ||
   1149           (QualifierLoc &&
   1150            QualifierLoc.getNestedNameSpecifier()->
   1151                                          containsUnexpandedParameterPack()) ||
   1152           MemberNameInfo.containsUnexpandedParameterPack())),
   1153     Base(Base), BaseType(BaseType), IsArrow(IsArrow),
   1154     HasTemplateKWAndArgsInfo(false),
   1155     OperatorLoc(OperatorLoc), QualifierLoc(QualifierLoc),
   1156     FirstQualifierFoundInScope(FirstQualifierFoundInScope),
   1157     MemberNameInfo(MemberNameInfo) { }
   1158 
   1159 CXXDependentScopeMemberExpr *
   1160 CXXDependentScopeMemberExpr::Create(ASTContext &C,
   1161                                 Expr *Base, QualType BaseType, bool IsArrow,
   1162                                 SourceLocation OperatorLoc,
   1163                                 NestedNameSpecifierLoc QualifierLoc,
   1164                                 SourceLocation TemplateKWLoc,
   1165                                 NamedDecl *FirstQualifierFoundInScope,
   1166                                 DeclarationNameInfo MemberNameInfo,
   1167                                 const TemplateArgumentListInfo *TemplateArgs) {
   1168   if (!TemplateArgs && !TemplateKWLoc.isValid())
   1169     return new (C) CXXDependentScopeMemberExpr(C, Base, BaseType,
   1170                                                IsArrow, OperatorLoc,
   1171                                                QualifierLoc,
   1172                                                FirstQualifierFoundInScope,
   1173                                                MemberNameInfo);
   1174 
   1175   unsigned NumTemplateArgs = TemplateArgs ? TemplateArgs->size() : 0;
   1176   std::size_t size = sizeof(CXXDependentScopeMemberExpr)
   1177     + ASTTemplateKWAndArgsInfo::sizeFor(NumTemplateArgs);
   1178 
   1179   void *Mem = C.Allocate(size, llvm::alignOf<CXXDependentScopeMemberExpr>());
   1180   return new (Mem) CXXDependentScopeMemberExpr(C, Base, BaseType,
   1181                                                IsArrow, OperatorLoc,
   1182                                                QualifierLoc,
   1183                                                TemplateKWLoc,
   1184                                                FirstQualifierFoundInScope,
   1185                                                MemberNameInfo, TemplateArgs);
   1186 }
   1187 
   1188 CXXDependentScopeMemberExpr *
   1189 CXXDependentScopeMemberExpr::CreateEmpty(ASTContext &C,
   1190                                          bool HasTemplateKWAndArgsInfo,
   1191                                          unsigned NumTemplateArgs) {
   1192   if (!HasTemplateKWAndArgsInfo)
   1193     return new (C) CXXDependentScopeMemberExpr(C, 0, QualType(),
   1194                                                0, SourceLocation(),
   1195                                                NestedNameSpecifierLoc(), 0,
   1196                                                DeclarationNameInfo());
   1197 
   1198   std::size_t size = sizeof(CXXDependentScopeMemberExpr) +
   1199                      ASTTemplateKWAndArgsInfo::sizeFor(NumTemplateArgs);
   1200   void *Mem = C.Allocate(size, llvm::alignOf<CXXDependentScopeMemberExpr>());
   1201   CXXDependentScopeMemberExpr *E
   1202     =  new (Mem) CXXDependentScopeMemberExpr(C, 0, QualType(),
   1203                                              0, SourceLocation(),
   1204                                              NestedNameSpecifierLoc(),
   1205                                              SourceLocation(), 0,
   1206                                              DeclarationNameInfo(), 0);
   1207   E->HasTemplateKWAndArgsInfo = true;
   1208   return E;
   1209 }
   1210 
   1211 bool CXXDependentScopeMemberExpr::isImplicitAccess() const {
   1212   if (Base == 0)
   1213     return true;
   1214 
   1215   return cast<Expr>(Base)->isImplicitCXXThis();
   1216 }
   1217 
   1218 static bool hasOnlyNonStaticMemberFunctions(UnresolvedSetIterator begin,
   1219                                             UnresolvedSetIterator end) {
   1220   do {
   1221     NamedDecl *decl = *begin;
   1222     if (isa<UnresolvedUsingValueDecl>(decl))
   1223       return false;
   1224     if (isa<UsingShadowDecl>(decl))
   1225       decl = cast<UsingShadowDecl>(decl)->getUnderlyingDecl();
   1226 
   1227     // Unresolved member expressions should only contain methods and
   1228     // method templates.
   1229     assert(isa<CXXMethodDecl>(decl) || isa<FunctionTemplateDecl>(decl));
   1230 
   1231     if (isa<FunctionTemplateDecl>(decl))
   1232       decl = cast<FunctionTemplateDecl>(decl)->getTemplatedDecl();
   1233     if (cast<CXXMethodDecl>(decl)->isStatic())
   1234       return false;
   1235   } while (++begin != end);
   1236 
   1237   return true;
   1238 }
   1239 
   1240 UnresolvedMemberExpr::UnresolvedMemberExpr(ASTContext &C,
   1241                                            bool HasUnresolvedUsing,
   1242                                            Expr *Base, QualType BaseType,
   1243                                            bool IsArrow,
   1244                                            SourceLocation OperatorLoc,
   1245                                            NestedNameSpecifierLoc QualifierLoc,
   1246                                            SourceLocation TemplateKWLoc,
   1247                                    const DeclarationNameInfo &MemberNameInfo,
   1248                                    const TemplateArgumentListInfo *TemplateArgs,
   1249                                            UnresolvedSetIterator Begin,
   1250                                            UnresolvedSetIterator End)
   1251   : OverloadExpr(UnresolvedMemberExprClass, C, QualifierLoc, TemplateKWLoc,
   1252                  MemberNameInfo, TemplateArgs, Begin, End,
   1253                  // Dependent
   1254                  ((Base && Base->isTypeDependent()) ||
   1255                   BaseType->isDependentType()),
   1256                  ((Base && Base->isInstantiationDependent()) ||
   1257                    BaseType->isInstantiationDependentType()),
   1258                  // Contains unexpanded parameter pack
   1259                  ((Base && Base->containsUnexpandedParameterPack()) ||
   1260                   BaseType->containsUnexpandedParameterPack())),
   1261     IsArrow(IsArrow), HasUnresolvedUsing(HasUnresolvedUsing),
   1262     Base(Base), BaseType(BaseType), OperatorLoc(OperatorLoc) {
   1263 
   1264   // Check whether all of the members are non-static member functions,
   1265   // and if so, mark give this bound-member type instead of overload type.
   1266   if (hasOnlyNonStaticMemberFunctions(Begin, End))
   1267     setType(C.BoundMemberTy);
   1268 }
   1269 
   1270 bool UnresolvedMemberExpr::isImplicitAccess() const {
   1271   if (Base == 0)
   1272     return true;
   1273 
   1274   return cast<Expr>(Base)->isImplicitCXXThis();
   1275 }
   1276 
   1277 UnresolvedMemberExpr *
   1278 UnresolvedMemberExpr::Create(ASTContext &C,
   1279                              bool HasUnresolvedUsing,
   1280                              Expr *Base, QualType BaseType, bool IsArrow,
   1281                              SourceLocation OperatorLoc,
   1282                              NestedNameSpecifierLoc QualifierLoc,
   1283                              SourceLocation TemplateKWLoc,
   1284                              const DeclarationNameInfo &MemberNameInfo,
   1285                              const TemplateArgumentListInfo *TemplateArgs,
   1286                              UnresolvedSetIterator Begin,
   1287                              UnresolvedSetIterator End) {
   1288   std::size_t size = sizeof(UnresolvedMemberExpr);
   1289   if (TemplateArgs)
   1290     size += ASTTemplateKWAndArgsInfo::sizeFor(TemplateArgs->size());
   1291   else if (TemplateKWLoc.isValid())
   1292     size += ASTTemplateKWAndArgsInfo::sizeFor(0);
   1293 
   1294   void *Mem = C.Allocate(size, llvm::alignOf<UnresolvedMemberExpr>());
   1295   return new (Mem) UnresolvedMemberExpr(C,
   1296                              HasUnresolvedUsing, Base, BaseType,
   1297                              IsArrow, OperatorLoc, QualifierLoc, TemplateKWLoc,
   1298                              MemberNameInfo, TemplateArgs, Begin, End);
   1299 }
   1300 
   1301 UnresolvedMemberExpr *
   1302 UnresolvedMemberExpr::CreateEmpty(ASTContext &C, bool HasTemplateKWAndArgsInfo,
   1303                                   unsigned NumTemplateArgs) {
   1304   std::size_t size = sizeof(UnresolvedMemberExpr);
   1305   if (HasTemplateKWAndArgsInfo)
   1306     size += ASTTemplateKWAndArgsInfo::sizeFor(NumTemplateArgs);
   1307 
   1308   void *Mem = C.Allocate(size, llvm::alignOf<UnresolvedMemberExpr>());
   1309   UnresolvedMemberExpr *E = new (Mem) UnresolvedMemberExpr(EmptyShell());
   1310   E->HasTemplateKWAndArgsInfo = HasTemplateKWAndArgsInfo;
   1311   return E;
   1312 }
   1313 
   1314 CXXRecordDecl *UnresolvedMemberExpr::getNamingClass() const {
   1315   // Unlike for UnresolvedLookupExpr, it is very easy to re-derive this.
   1316 
   1317   // If there was a nested name specifier, it names the naming class.
   1318   // It can't be dependent: after all, we were actually able to do the
   1319   // lookup.
   1320   CXXRecordDecl *Record = 0;
   1321   if (getQualifier()) {
   1322     const Type *T = getQualifier()->getAsType();
   1323     assert(T && "qualifier in member expression does not name type");
   1324     Record = T->getAsCXXRecordDecl();
   1325     assert(Record && "qualifier in member expression does not name record");
   1326   }
   1327   // Otherwise the naming class must have been the base class.
   1328   else {
   1329     QualType BaseType = getBaseType().getNonReferenceType();
   1330     if (isArrow()) {
   1331       const PointerType *PT = BaseType->getAs<PointerType>();
   1332       assert(PT && "base of arrow member access is not pointer");
   1333       BaseType = PT->getPointeeType();
   1334     }
   1335 
   1336     Record = BaseType->getAsCXXRecordDecl();
   1337     assert(Record && "base of member expression does not name record");
   1338   }
   1339 
   1340   return Record;
   1341 }
   1342 
   1343 SubstNonTypeTemplateParmPackExpr::
   1344 SubstNonTypeTemplateParmPackExpr(QualType T,
   1345                                  NonTypeTemplateParmDecl *Param,
   1346                                  SourceLocation NameLoc,
   1347                                  const TemplateArgument &ArgPack)
   1348   : Expr(SubstNonTypeTemplateParmPackExprClass, T, VK_RValue, OK_Ordinary,
   1349          true, true, true, true),
   1350     Param(Param), Arguments(ArgPack.pack_begin()),
   1351     NumArguments(ArgPack.pack_size()), NameLoc(NameLoc) { }
   1352 
   1353 TemplateArgument SubstNonTypeTemplateParmPackExpr::getArgumentPack() const {
   1354   return TemplateArgument(Arguments, NumArguments);
   1355 }
   1356 
   1357 FunctionParmPackExpr::FunctionParmPackExpr(QualType T, ParmVarDecl *ParamPack,
   1358                                            SourceLocation NameLoc,
   1359                                            unsigned NumParams,
   1360                                            Decl * const *Params)
   1361   : Expr(FunctionParmPackExprClass, T, VK_LValue, OK_Ordinary,
   1362          true, true, true, true),
   1363     ParamPack(ParamPack), NameLoc(NameLoc), NumParameters(NumParams) {
   1364   if (Params)
   1365     std::uninitialized_copy(Params, Params + NumParams,
   1366                             reinterpret_cast<Decl**>(this+1));
   1367 }
   1368 
   1369 FunctionParmPackExpr *
   1370 FunctionParmPackExpr::Create(ASTContext &Context, QualType T,
   1371                              ParmVarDecl *ParamPack, SourceLocation NameLoc,
   1372                              ArrayRef<Decl *> Params) {
   1373   return new (Context.Allocate(sizeof(FunctionParmPackExpr) +
   1374                                sizeof(ParmVarDecl*) * Params.size()))
   1375     FunctionParmPackExpr(T, ParamPack, NameLoc, Params.size(), Params.data());
   1376 }
   1377 
   1378 FunctionParmPackExpr *
   1379 FunctionParmPackExpr::CreateEmpty(ASTContext &Context, unsigned NumParams) {
   1380   return new (Context.Allocate(sizeof(FunctionParmPackExpr) +
   1381                                sizeof(ParmVarDecl*) * NumParams))
   1382     FunctionParmPackExpr(QualType(), 0, SourceLocation(), 0, 0);
   1383 }
   1384 
   1385 TypeTraitExpr::TypeTraitExpr(QualType T, SourceLocation Loc, TypeTrait Kind,
   1386                              ArrayRef<TypeSourceInfo *> Args,
   1387                              SourceLocation RParenLoc,
   1388                              bool Value)
   1389   : Expr(TypeTraitExprClass, T, VK_RValue, OK_Ordinary,
   1390          /*TypeDependent=*/false,
   1391          /*ValueDependent=*/false,
   1392          /*InstantiationDependent=*/false,
   1393          /*ContainsUnexpandedParameterPack=*/false),
   1394     Loc(Loc), RParenLoc(RParenLoc)
   1395 {
   1396   TypeTraitExprBits.Kind = Kind;
   1397   TypeTraitExprBits.Value = Value;
   1398   TypeTraitExprBits.NumArgs = Args.size();
   1399 
   1400   TypeSourceInfo **ToArgs = getTypeSourceInfos();
   1401 
   1402   for (unsigned I = 0, N = Args.size(); I != N; ++I) {
   1403     if (Args[I]->getType()->isDependentType())
   1404       setValueDependent(true);
   1405     if (Args[I]->getType()->isInstantiationDependentType())
   1406       setInstantiationDependent(true);
   1407     if (Args[I]->getType()->containsUnexpandedParameterPack())
   1408       setContainsUnexpandedParameterPack(true);
   1409 
   1410     ToArgs[I] = Args[I];
   1411   }
   1412 }
   1413 
   1414 TypeTraitExpr *TypeTraitExpr::Create(ASTContext &C, QualType T,
   1415                                      SourceLocation Loc,
   1416                                      TypeTrait Kind,
   1417                                      ArrayRef<TypeSourceInfo *> Args,
   1418                                      SourceLocation RParenLoc,
   1419                                      bool Value) {
   1420   unsigned Size = sizeof(TypeTraitExpr) + sizeof(TypeSourceInfo*) * Args.size();
   1421   void *Mem = C.Allocate(Size);
   1422   return new (Mem) TypeTraitExpr(T, Loc, Kind, Args, RParenLoc, Value);
   1423 }
   1424 
   1425 TypeTraitExpr *TypeTraitExpr::CreateDeserialized(ASTContext &C,
   1426                                                  unsigned NumArgs) {
   1427   unsigned Size = sizeof(TypeTraitExpr) + sizeof(TypeSourceInfo*) * NumArgs;
   1428   void *Mem = C.Allocate(Size);
   1429   return new (Mem) TypeTraitExpr(EmptyShell());
   1430 }
   1431 
   1432 void ArrayTypeTraitExpr::anchor() { }
   1433