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