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