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