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