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