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