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