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