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