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