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