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