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