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