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 
isInitCapture(const LambdaCapture * C) const1030 bool LambdaExpr::isInitCapture(const LambdaCapture *C) const {
1031   return (C->capturesVariable() && C->getCapturedVar()->isInitCapture() &&
1032           (getCallOperator() == C->getCapturedVar()->getDeclContext()));
1033 }
1034 
capture_begin() const1035 LambdaExpr::capture_iterator LambdaExpr::capture_begin() const {
1036   return getLambdaClass()->getLambdaData().Captures;
1037 }
1038 
capture_end() const1039 LambdaExpr::capture_iterator LambdaExpr::capture_end() const {
1040   return capture_begin() + NumCaptures;
1041 }
1042 
captures() const1043 LambdaExpr::capture_range LambdaExpr::captures() const {
1044   return capture_range(capture_begin(), capture_end());
1045 }
1046 
explicit_capture_begin() const1047 LambdaExpr::capture_iterator LambdaExpr::explicit_capture_begin() const {
1048   return capture_begin();
1049 }
1050 
explicit_capture_end() const1051 LambdaExpr::capture_iterator LambdaExpr::explicit_capture_end() const {
1052   struct CXXRecordDecl::LambdaDefinitionData &Data
1053     = getLambdaClass()->getLambdaData();
1054   return Data.Captures + Data.NumExplicitCaptures;
1055 }
1056 
explicit_captures() const1057 LambdaExpr::capture_range LambdaExpr::explicit_captures() const {
1058   return capture_range(explicit_capture_begin(), explicit_capture_end());
1059 }
1060 
implicit_capture_begin() const1061 LambdaExpr::capture_iterator LambdaExpr::implicit_capture_begin() const {
1062   return explicit_capture_end();
1063 }
1064 
implicit_capture_end() const1065 LambdaExpr::capture_iterator LambdaExpr::implicit_capture_end() const {
1066   return capture_end();
1067 }
1068 
implicit_captures() const1069 LambdaExpr::capture_range LambdaExpr::implicit_captures() const {
1070   return capture_range(implicit_capture_begin(), implicit_capture_end());
1071 }
1072 
1073 ArrayRef<VarDecl *>
getCaptureInitIndexVars(const_capture_init_iterator Iter) const1074 LambdaExpr::getCaptureInitIndexVars(const_capture_init_iterator Iter) const {
1075   assert(HasArrayIndexVars && "No array index-var data?");
1076 
1077   unsigned Index = Iter - capture_init_begin();
1078   assert(Index < getLambdaClass()->getLambdaData().NumCaptures &&
1079          "Capture index out-of-range");
1080   VarDecl *const *IndexVars = getArrayIndexVars();
1081   const unsigned *IndexStarts = getArrayIndexStarts();
1082   return llvm::makeArrayRef(IndexVars + IndexStarts[Index],
1083                             IndexVars + IndexStarts[Index + 1]);
1084 }
1085 
getLambdaClass() const1086 CXXRecordDecl *LambdaExpr::getLambdaClass() const {
1087   return getType()->getAsCXXRecordDecl();
1088 }
1089 
getCallOperator() const1090 CXXMethodDecl *LambdaExpr::getCallOperator() const {
1091   CXXRecordDecl *Record = getLambdaClass();
1092   return Record->getLambdaCallOperator();
1093 }
1094 
getTemplateParameterList() const1095 TemplateParameterList *LambdaExpr::getTemplateParameterList() const {
1096   CXXRecordDecl *Record = getLambdaClass();
1097   return Record->getGenericLambdaTemplateParameterList();
1098 
1099 }
1100 
getBody() const1101 CompoundStmt *LambdaExpr::getBody() const {
1102   // FIXME: this mutation in getBody is bogus. It should be
1103   // initialized in ASTStmtReader::VisitLambdaExpr, but for reasons I
1104   // don't understand, that doesn't work.
1105   if (!getStoredStmts()[NumCaptures])
1106     *const_cast<clang::Stmt **>(&getStoredStmts()[NumCaptures]) =
1107         getCallOperator()->getBody();
1108 
1109   return reinterpret_cast<CompoundStmt *>(getStoredStmts()[NumCaptures]);
1110 }
1111 
isMutable() const1112 bool LambdaExpr::isMutable() const {
1113   return !getCallOperator()->isConst();
1114 }
1115 
ExprWithCleanups(Expr * subexpr,ArrayRef<CleanupObject> objects)1116 ExprWithCleanups::ExprWithCleanups(Expr *subexpr,
1117                                    ArrayRef<CleanupObject> objects)
1118   : Expr(ExprWithCleanupsClass, subexpr->getType(),
1119          subexpr->getValueKind(), subexpr->getObjectKind(),
1120          subexpr->isTypeDependent(), subexpr->isValueDependent(),
1121          subexpr->isInstantiationDependent(),
1122          subexpr->containsUnexpandedParameterPack()),
1123     SubExpr(subexpr) {
1124   ExprWithCleanupsBits.NumObjects = objects.size();
1125   for (unsigned i = 0, e = objects.size(); i != e; ++i)
1126     getObjectsBuffer()[i] = objects[i];
1127 }
1128 
Create(const ASTContext & C,Expr * subexpr,ArrayRef<CleanupObject> objects)1129 ExprWithCleanups *ExprWithCleanups::Create(const ASTContext &C, Expr *subexpr,
1130                                            ArrayRef<CleanupObject> objects) {
1131   size_t size = sizeof(ExprWithCleanups)
1132               + objects.size() * sizeof(CleanupObject);
1133   void *buffer = C.Allocate(size, llvm::alignOf<ExprWithCleanups>());
1134   return new (buffer) ExprWithCleanups(subexpr, objects);
1135 }
1136 
ExprWithCleanups(EmptyShell empty,unsigned numObjects)1137 ExprWithCleanups::ExprWithCleanups(EmptyShell empty, unsigned numObjects)
1138   : Expr(ExprWithCleanupsClass, empty) {
1139   ExprWithCleanupsBits.NumObjects = numObjects;
1140 }
1141 
Create(const ASTContext & C,EmptyShell empty,unsigned numObjects)1142 ExprWithCleanups *ExprWithCleanups::Create(const ASTContext &C,
1143                                            EmptyShell empty,
1144                                            unsigned numObjects) {
1145   size_t size = sizeof(ExprWithCleanups) + numObjects * sizeof(CleanupObject);
1146   void *buffer = C.Allocate(size, llvm::alignOf<ExprWithCleanups>());
1147   return new (buffer) ExprWithCleanups(empty, numObjects);
1148 }
1149 
CXXUnresolvedConstructExpr(TypeSourceInfo * Type,SourceLocation LParenLoc,ArrayRef<Expr * > Args,SourceLocation RParenLoc)1150 CXXUnresolvedConstructExpr::CXXUnresolvedConstructExpr(TypeSourceInfo *Type,
1151                                                  SourceLocation LParenLoc,
1152                                                  ArrayRef<Expr*> Args,
1153                                                  SourceLocation RParenLoc)
1154   : Expr(CXXUnresolvedConstructExprClass,
1155          Type->getType().getNonReferenceType(),
1156          (Type->getType()->isLValueReferenceType() ? VK_LValue
1157           :Type->getType()->isRValueReferenceType()? VK_XValue
1158           :VK_RValue),
1159          OK_Ordinary,
1160          Type->getType()->isDependentType(), true, true,
1161          Type->getType()->containsUnexpandedParameterPack()),
1162     Type(Type),
1163     LParenLoc(LParenLoc),
1164     RParenLoc(RParenLoc),
1165     NumArgs(Args.size()) {
1166   Stmt **StoredArgs = reinterpret_cast<Stmt **>(this + 1);
1167   for (unsigned I = 0; I != Args.size(); ++I) {
1168     if (Args[I]->containsUnexpandedParameterPack())
1169       ExprBits.ContainsUnexpandedParameterPack = true;
1170 
1171     StoredArgs[I] = Args[I];
1172   }
1173 }
1174 
1175 CXXUnresolvedConstructExpr *
Create(const ASTContext & C,TypeSourceInfo * Type,SourceLocation LParenLoc,ArrayRef<Expr * > Args,SourceLocation RParenLoc)1176 CXXUnresolvedConstructExpr::Create(const ASTContext &C,
1177                                    TypeSourceInfo *Type,
1178                                    SourceLocation LParenLoc,
1179                                    ArrayRef<Expr*> Args,
1180                                    SourceLocation RParenLoc) {
1181   void *Mem = C.Allocate(sizeof(CXXUnresolvedConstructExpr) +
1182                          sizeof(Expr *) * Args.size());
1183   return new (Mem) CXXUnresolvedConstructExpr(Type, LParenLoc, Args, RParenLoc);
1184 }
1185 
1186 CXXUnresolvedConstructExpr *
CreateEmpty(const ASTContext & C,unsigned NumArgs)1187 CXXUnresolvedConstructExpr::CreateEmpty(const ASTContext &C, unsigned NumArgs) {
1188   Stmt::EmptyShell Empty;
1189   void *Mem = C.Allocate(sizeof(CXXUnresolvedConstructExpr) +
1190                          sizeof(Expr *) * NumArgs);
1191   return new (Mem) CXXUnresolvedConstructExpr(Empty, NumArgs);
1192 }
1193 
getLocStart() const1194 SourceLocation CXXUnresolvedConstructExpr::getLocStart() const {
1195   return Type->getTypeLoc().getBeginLoc();
1196 }
1197 
CXXDependentScopeMemberExpr(const ASTContext & C,Expr * Base,QualType BaseType,bool IsArrow,SourceLocation OperatorLoc,NestedNameSpecifierLoc QualifierLoc,SourceLocation TemplateKWLoc,NamedDecl * FirstQualifierFoundInScope,DeclarationNameInfo MemberNameInfo,const TemplateArgumentListInfo * TemplateArgs)1198 CXXDependentScopeMemberExpr::CXXDependentScopeMemberExpr(const ASTContext &C,
1199                                                  Expr *Base, QualType BaseType,
1200                                                  bool IsArrow,
1201                                                  SourceLocation OperatorLoc,
1202                                           NestedNameSpecifierLoc QualifierLoc,
1203                                           SourceLocation TemplateKWLoc,
1204                                           NamedDecl *FirstQualifierFoundInScope,
1205                                           DeclarationNameInfo MemberNameInfo,
1206                                    const TemplateArgumentListInfo *TemplateArgs)
1207   : Expr(CXXDependentScopeMemberExprClass, C.DependentTy,
1208          VK_LValue, OK_Ordinary, true, true, true,
1209          ((Base && Base->containsUnexpandedParameterPack()) ||
1210           (QualifierLoc &&
1211            QualifierLoc.getNestedNameSpecifier()
1212                                        ->containsUnexpandedParameterPack()) ||
1213           MemberNameInfo.containsUnexpandedParameterPack())),
1214     Base(Base), BaseType(BaseType), IsArrow(IsArrow),
1215     HasTemplateKWAndArgsInfo(TemplateArgs != nullptr ||
1216                              TemplateKWLoc.isValid()),
1217     OperatorLoc(OperatorLoc), QualifierLoc(QualifierLoc),
1218     FirstQualifierFoundInScope(FirstQualifierFoundInScope),
1219     MemberNameInfo(MemberNameInfo) {
1220   if (TemplateArgs) {
1221     bool Dependent = true;
1222     bool InstantiationDependent = true;
1223     bool ContainsUnexpandedParameterPack = false;
1224     getTemplateKWAndArgsInfo()->initializeFrom(TemplateKWLoc, *TemplateArgs,
1225                                                Dependent,
1226                                                InstantiationDependent,
1227                                                ContainsUnexpandedParameterPack);
1228     if (ContainsUnexpandedParameterPack)
1229       ExprBits.ContainsUnexpandedParameterPack = true;
1230   } else if (TemplateKWLoc.isValid()) {
1231     getTemplateKWAndArgsInfo()->initializeFrom(TemplateKWLoc);
1232   }
1233 }
1234 
CXXDependentScopeMemberExpr(const ASTContext & C,Expr * Base,QualType BaseType,bool IsArrow,SourceLocation OperatorLoc,NestedNameSpecifierLoc QualifierLoc,NamedDecl * FirstQualifierFoundInScope,DeclarationNameInfo MemberNameInfo)1235 CXXDependentScopeMemberExpr::CXXDependentScopeMemberExpr(const ASTContext &C,
1236                           Expr *Base, QualType BaseType,
1237                           bool IsArrow,
1238                           SourceLocation OperatorLoc,
1239                           NestedNameSpecifierLoc QualifierLoc,
1240                           NamedDecl *FirstQualifierFoundInScope,
1241                           DeclarationNameInfo MemberNameInfo)
1242   : Expr(CXXDependentScopeMemberExprClass, C.DependentTy,
1243          VK_LValue, OK_Ordinary, true, true, true,
1244          ((Base && Base->containsUnexpandedParameterPack()) ||
1245           (QualifierLoc &&
1246            QualifierLoc.getNestedNameSpecifier()->
1247                                          containsUnexpandedParameterPack()) ||
1248           MemberNameInfo.containsUnexpandedParameterPack())),
1249     Base(Base), BaseType(BaseType), IsArrow(IsArrow),
1250     HasTemplateKWAndArgsInfo(false),
1251     OperatorLoc(OperatorLoc), QualifierLoc(QualifierLoc),
1252     FirstQualifierFoundInScope(FirstQualifierFoundInScope),
1253     MemberNameInfo(MemberNameInfo) { }
1254 
1255 CXXDependentScopeMemberExpr *
Create(const ASTContext & C,Expr * Base,QualType BaseType,bool IsArrow,SourceLocation OperatorLoc,NestedNameSpecifierLoc QualifierLoc,SourceLocation TemplateKWLoc,NamedDecl * FirstQualifierFoundInScope,DeclarationNameInfo MemberNameInfo,const TemplateArgumentListInfo * TemplateArgs)1256 CXXDependentScopeMemberExpr::Create(const ASTContext &C,
1257                                 Expr *Base, QualType BaseType, bool IsArrow,
1258                                 SourceLocation OperatorLoc,
1259                                 NestedNameSpecifierLoc QualifierLoc,
1260                                 SourceLocation TemplateKWLoc,
1261                                 NamedDecl *FirstQualifierFoundInScope,
1262                                 DeclarationNameInfo MemberNameInfo,
1263                                 const TemplateArgumentListInfo *TemplateArgs) {
1264   if (!TemplateArgs && !TemplateKWLoc.isValid())
1265     return new (C) CXXDependentScopeMemberExpr(C, Base, BaseType,
1266                                                IsArrow, OperatorLoc,
1267                                                QualifierLoc,
1268                                                FirstQualifierFoundInScope,
1269                                                MemberNameInfo);
1270 
1271   unsigned NumTemplateArgs = TemplateArgs ? TemplateArgs->size() : 0;
1272   std::size_t size = sizeof(CXXDependentScopeMemberExpr)
1273     + ASTTemplateKWAndArgsInfo::sizeFor(NumTemplateArgs);
1274 
1275   void *Mem = C.Allocate(size, llvm::alignOf<CXXDependentScopeMemberExpr>());
1276   return new (Mem) CXXDependentScopeMemberExpr(C, Base, BaseType,
1277                                                IsArrow, OperatorLoc,
1278                                                QualifierLoc,
1279                                                TemplateKWLoc,
1280                                                FirstQualifierFoundInScope,
1281                                                MemberNameInfo, TemplateArgs);
1282 }
1283 
1284 CXXDependentScopeMemberExpr *
CreateEmpty(const ASTContext & C,bool HasTemplateKWAndArgsInfo,unsigned NumTemplateArgs)1285 CXXDependentScopeMemberExpr::CreateEmpty(const ASTContext &C,
1286                                          bool HasTemplateKWAndArgsInfo,
1287                                          unsigned NumTemplateArgs) {
1288   if (!HasTemplateKWAndArgsInfo)
1289     return new (C) CXXDependentScopeMemberExpr(C, nullptr, QualType(),
1290                                                0, SourceLocation(),
1291                                                NestedNameSpecifierLoc(),
1292                                                nullptr, DeclarationNameInfo());
1293 
1294   std::size_t size = sizeof(CXXDependentScopeMemberExpr) +
1295                      ASTTemplateKWAndArgsInfo::sizeFor(NumTemplateArgs);
1296   void *Mem = C.Allocate(size, llvm::alignOf<CXXDependentScopeMemberExpr>());
1297   CXXDependentScopeMemberExpr *E
1298     =  new (Mem) CXXDependentScopeMemberExpr(C, nullptr, QualType(),
1299                                              0, SourceLocation(),
1300                                              NestedNameSpecifierLoc(),
1301                                              SourceLocation(), nullptr,
1302                                              DeclarationNameInfo(), nullptr);
1303   E->HasTemplateKWAndArgsInfo = true;
1304   return E;
1305 }
1306 
isImplicitAccess() const1307 bool CXXDependentScopeMemberExpr::isImplicitAccess() const {
1308   if (!Base)
1309     return true;
1310 
1311   return cast<Expr>(Base)->isImplicitCXXThis();
1312 }
1313 
hasOnlyNonStaticMemberFunctions(UnresolvedSetIterator begin,UnresolvedSetIterator end)1314 static bool hasOnlyNonStaticMemberFunctions(UnresolvedSetIterator begin,
1315                                             UnresolvedSetIterator end) {
1316   do {
1317     NamedDecl *decl = *begin;
1318     if (isa<UnresolvedUsingValueDecl>(decl))
1319       return false;
1320 
1321     // Unresolved member expressions should only contain methods and
1322     // method templates.
1323     if (cast<CXXMethodDecl>(decl->getUnderlyingDecl()->getAsFunction())
1324             ->isStatic())
1325       return false;
1326   } while (++begin != end);
1327 
1328   return true;
1329 }
1330 
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)1331 UnresolvedMemberExpr::UnresolvedMemberExpr(const ASTContext &C,
1332                                            bool HasUnresolvedUsing,
1333                                            Expr *Base, QualType BaseType,
1334                                            bool IsArrow,
1335                                            SourceLocation OperatorLoc,
1336                                            NestedNameSpecifierLoc QualifierLoc,
1337                                            SourceLocation TemplateKWLoc,
1338                                    const DeclarationNameInfo &MemberNameInfo,
1339                                    const TemplateArgumentListInfo *TemplateArgs,
1340                                            UnresolvedSetIterator Begin,
1341                                            UnresolvedSetIterator End)
1342   : OverloadExpr(UnresolvedMemberExprClass, C, QualifierLoc, TemplateKWLoc,
1343                  MemberNameInfo, TemplateArgs, Begin, End,
1344                  // Dependent
1345                  ((Base && Base->isTypeDependent()) ||
1346                   BaseType->isDependentType()),
1347                  ((Base && Base->isInstantiationDependent()) ||
1348                    BaseType->isInstantiationDependentType()),
1349                  // Contains unexpanded parameter pack
1350                  ((Base && Base->containsUnexpandedParameterPack()) ||
1351                   BaseType->containsUnexpandedParameterPack())),
1352     IsArrow(IsArrow), HasUnresolvedUsing(HasUnresolvedUsing),
1353     Base(Base), BaseType(BaseType), OperatorLoc(OperatorLoc) {
1354 
1355   // Check whether all of the members are non-static member functions,
1356   // and if so, mark give this bound-member type instead of overload type.
1357   if (hasOnlyNonStaticMemberFunctions(Begin, End))
1358     setType(C.BoundMemberTy);
1359 }
1360 
isImplicitAccess() const1361 bool UnresolvedMemberExpr::isImplicitAccess() const {
1362   if (!Base)
1363     return true;
1364 
1365   return cast<Expr>(Base)->isImplicitCXXThis();
1366 }
1367 
1368 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)1369 UnresolvedMemberExpr::Create(const ASTContext &C, bool HasUnresolvedUsing,
1370                              Expr *Base, QualType BaseType, bool IsArrow,
1371                              SourceLocation OperatorLoc,
1372                              NestedNameSpecifierLoc QualifierLoc,
1373                              SourceLocation TemplateKWLoc,
1374                              const DeclarationNameInfo &MemberNameInfo,
1375                              const TemplateArgumentListInfo *TemplateArgs,
1376                              UnresolvedSetIterator Begin,
1377                              UnresolvedSetIterator End) {
1378   std::size_t size = sizeof(UnresolvedMemberExpr);
1379   if (TemplateArgs)
1380     size += ASTTemplateKWAndArgsInfo::sizeFor(TemplateArgs->size());
1381   else if (TemplateKWLoc.isValid())
1382     size += ASTTemplateKWAndArgsInfo::sizeFor(0);
1383 
1384   void *Mem = C.Allocate(size, llvm::alignOf<UnresolvedMemberExpr>());
1385   return new (Mem) UnresolvedMemberExpr(C,
1386                              HasUnresolvedUsing, Base, BaseType,
1387                              IsArrow, OperatorLoc, QualifierLoc, TemplateKWLoc,
1388                              MemberNameInfo, TemplateArgs, Begin, End);
1389 }
1390 
1391 UnresolvedMemberExpr *
CreateEmpty(const ASTContext & C,bool HasTemplateKWAndArgsInfo,unsigned NumTemplateArgs)1392 UnresolvedMemberExpr::CreateEmpty(const ASTContext &C,
1393                                   bool HasTemplateKWAndArgsInfo,
1394                                   unsigned NumTemplateArgs) {
1395   std::size_t size = sizeof(UnresolvedMemberExpr);
1396   if (HasTemplateKWAndArgsInfo)
1397     size += ASTTemplateKWAndArgsInfo::sizeFor(NumTemplateArgs);
1398 
1399   void *Mem = C.Allocate(size, llvm::alignOf<UnresolvedMemberExpr>());
1400   UnresolvedMemberExpr *E = new (Mem) UnresolvedMemberExpr(EmptyShell());
1401   E->HasTemplateKWAndArgsInfo = HasTemplateKWAndArgsInfo;
1402   return E;
1403 }
1404 
getNamingClass() const1405 CXXRecordDecl *UnresolvedMemberExpr::getNamingClass() const {
1406   // Unlike for UnresolvedLookupExpr, it is very easy to re-derive this.
1407 
1408   // If there was a nested name specifier, it names the naming class.
1409   // It can't be dependent: after all, we were actually able to do the
1410   // lookup.
1411   CXXRecordDecl *Record = nullptr;
1412   auto *NNS = getQualifier();
1413   if (NNS && NNS->getKind() != NestedNameSpecifier::Super) {
1414     const Type *T = getQualifier()->getAsType();
1415     assert(T && "qualifier in member expression does not name type");
1416     Record = T->getAsCXXRecordDecl();
1417     assert(Record && "qualifier in member expression does not name record");
1418   }
1419   // Otherwise the naming class must have been the base class.
1420   else {
1421     QualType BaseType = getBaseType().getNonReferenceType();
1422     if (isArrow()) {
1423       const PointerType *PT = BaseType->getAs<PointerType>();
1424       assert(PT && "base of arrow member access is not pointer");
1425       BaseType = PT->getPointeeType();
1426     }
1427 
1428     Record = BaseType->getAsCXXRecordDecl();
1429     assert(Record && "base of member expression does not name record");
1430   }
1431 
1432   return Record;
1433 }
1434 
1435 SizeOfPackExpr *
Create(ASTContext & Context,SourceLocation OperatorLoc,NamedDecl * Pack,SourceLocation PackLoc,SourceLocation RParenLoc,Optional<unsigned> Length,ArrayRef<TemplateArgument> PartialArgs)1436 SizeOfPackExpr::Create(ASTContext &Context, SourceLocation OperatorLoc,
1437                        NamedDecl *Pack, SourceLocation PackLoc,
1438                        SourceLocation RParenLoc,
1439                        Optional<unsigned> Length,
1440                        ArrayRef<TemplateArgument> PartialArgs) {
1441   void *Storage = Context.Allocate(
1442       sizeof(SizeOfPackExpr) + sizeof(TemplateArgument) * PartialArgs.size());
1443   return new (Storage) SizeOfPackExpr(Context.getSizeType(), OperatorLoc, Pack,
1444                                       PackLoc, RParenLoc, Length, PartialArgs);
1445 }
1446 
CreateDeserialized(ASTContext & Context,unsigned NumPartialArgs)1447 SizeOfPackExpr *SizeOfPackExpr::CreateDeserialized(ASTContext &Context,
1448                                                    unsigned NumPartialArgs) {
1449   void *Storage = Context.Allocate(
1450       sizeof(SizeOfPackExpr) + sizeof(TemplateArgument) * NumPartialArgs);
1451   return new (Storage) SizeOfPackExpr(EmptyShell(), NumPartialArgs);
1452 }
1453 
1454 SubstNonTypeTemplateParmPackExpr::
SubstNonTypeTemplateParmPackExpr(QualType T,NonTypeTemplateParmDecl * Param,SourceLocation NameLoc,const TemplateArgument & ArgPack)1455 SubstNonTypeTemplateParmPackExpr(QualType T,
1456                                  NonTypeTemplateParmDecl *Param,
1457                                  SourceLocation NameLoc,
1458                                  const TemplateArgument &ArgPack)
1459   : Expr(SubstNonTypeTemplateParmPackExprClass, T, VK_RValue, OK_Ordinary,
1460          true, true, true, true),
1461     Param(Param), Arguments(ArgPack.pack_begin()),
1462     NumArguments(ArgPack.pack_size()), NameLoc(NameLoc) { }
1463 
getArgumentPack() const1464 TemplateArgument SubstNonTypeTemplateParmPackExpr::getArgumentPack() const {
1465   return TemplateArgument(llvm::makeArrayRef(Arguments, NumArguments));
1466 }
1467 
FunctionParmPackExpr(QualType T,ParmVarDecl * ParamPack,SourceLocation NameLoc,unsigned NumParams,ParmVarDecl * const * Params)1468 FunctionParmPackExpr::FunctionParmPackExpr(QualType T, ParmVarDecl *ParamPack,
1469                                            SourceLocation NameLoc,
1470                                            unsigned NumParams,
1471                                            ParmVarDecl *const *Params)
1472     : Expr(FunctionParmPackExprClass, T, VK_LValue, OK_Ordinary, true, true,
1473            true, true),
1474       ParamPack(ParamPack), NameLoc(NameLoc), NumParameters(NumParams) {
1475   if (Params)
1476     std::uninitialized_copy(Params, Params + NumParams,
1477                             reinterpret_cast<ParmVarDecl **>(this + 1));
1478 }
1479 
1480 FunctionParmPackExpr *
Create(const ASTContext & Context,QualType T,ParmVarDecl * ParamPack,SourceLocation NameLoc,ArrayRef<ParmVarDecl * > Params)1481 FunctionParmPackExpr::Create(const ASTContext &Context, QualType T,
1482                              ParmVarDecl *ParamPack, SourceLocation NameLoc,
1483                              ArrayRef<ParmVarDecl *> Params) {
1484   return new (Context.Allocate(sizeof(FunctionParmPackExpr) +
1485                                sizeof(ParmVarDecl*) * Params.size()))
1486     FunctionParmPackExpr(T, ParamPack, NameLoc, Params.size(), Params.data());
1487 }
1488 
1489 FunctionParmPackExpr *
CreateEmpty(const ASTContext & Context,unsigned NumParams)1490 FunctionParmPackExpr::CreateEmpty(const ASTContext &Context,
1491                                   unsigned NumParams) {
1492   return new (Context.Allocate(sizeof(FunctionParmPackExpr) +
1493                                sizeof(ParmVarDecl*) * NumParams))
1494     FunctionParmPackExpr(QualType(), nullptr, SourceLocation(), 0, nullptr);
1495 }
1496 
setExtendingDecl(const ValueDecl * ExtendedBy,unsigned ManglingNumber)1497 void MaterializeTemporaryExpr::setExtendingDecl(const ValueDecl *ExtendedBy,
1498                                                 unsigned ManglingNumber) {
1499   // We only need extra state if we have to remember more than just the Stmt.
1500   if (!ExtendedBy)
1501     return;
1502 
1503   // We may need to allocate extra storage for the mangling number and the
1504   // extended-by ValueDecl.
1505   if (!State.is<ExtraState *>()) {
1506     auto ES = new (ExtendedBy->getASTContext()) ExtraState;
1507     ES->Temporary = State.get<Stmt *>();
1508     State = ES;
1509   }
1510 
1511   auto ES = State.get<ExtraState *>();
1512   ES->ExtendingDecl = ExtendedBy;
1513   ES->ManglingNumber = ManglingNumber;
1514 }
1515 
TypeTraitExpr(QualType T,SourceLocation Loc,TypeTrait Kind,ArrayRef<TypeSourceInfo * > Args,SourceLocation RParenLoc,bool Value)1516 TypeTraitExpr::TypeTraitExpr(QualType T, SourceLocation Loc, TypeTrait Kind,
1517                              ArrayRef<TypeSourceInfo *> Args,
1518                              SourceLocation RParenLoc,
1519                              bool Value)
1520   : Expr(TypeTraitExprClass, T, VK_RValue, OK_Ordinary,
1521          /*TypeDependent=*/false,
1522          /*ValueDependent=*/false,
1523          /*InstantiationDependent=*/false,
1524          /*ContainsUnexpandedParameterPack=*/false),
1525     Loc(Loc), RParenLoc(RParenLoc)
1526 {
1527   TypeTraitExprBits.Kind = Kind;
1528   TypeTraitExprBits.Value = Value;
1529   TypeTraitExprBits.NumArgs = Args.size();
1530 
1531   TypeSourceInfo **ToArgs = getTypeSourceInfos();
1532 
1533   for (unsigned I = 0, N = Args.size(); I != N; ++I) {
1534     if (Args[I]->getType()->isDependentType())
1535       setValueDependent(true);
1536     if (Args[I]->getType()->isInstantiationDependentType())
1537       setInstantiationDependent(true);
1538     if (Args[I]->getType()->containsUnexpandedParameterPack())
1539       setContainsUnexpandedParameterPack(true);
1540 
1541     ToArgs[I] = Args[I];
1542   }
1543 }
1544 
Create(const ASTContext & C,QualType T,SourceLocation Loc,TypeTrait Kind,ArrayRef<TypeSourceInfo * > Args,SourceLocation RParenLoc,bool Value)1545 TypeTraitExpr *TypeTraitExpr::Create(const ASTContext &C, QualType T,
1546                                      SourceLocation Loc,
1547                                      TypeTrait Kind,
1548                                      ArrayRef<TypeSourceInfo *> Args,
1549                                      SourceLocation RParenLoc,
1550                                      bool Value) {
1551   unsigned Size = sizeof(TypeTraitExpr) + sizeof(TypeSourceInfo*) * Args.size();
1552   void *Mem = C.Allocate(Size);
1553   return new (Mem) TypeTraitExpr(T, Loc, Kind, Args, RParenLoc, Value);
1554 }
1555 
CreateDeserialized(const ASTContext & C,unsigned NumArgs)1556 TypeTraitExpr *TypeTraitExpr::CreateDeserialized(const ASTContext &C,
1557                                                  unsigned NumArgs) {
1558   unsigned Size = sizeof(TypeTraitExpr) + sizeof(TypeSourceInfo*) * NumArgs;
1559   void *Mem = C.Allocate(Size);
1560   return new (Mem) TypeTraitExpr(EmptyShell());
1561 }
1562 
anchor()1563 void ArrayTypeTraitExpr::anchor() { }
1564