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