1//===- ExprCXX.cpp - (C++) Expression AST Node Implementation -------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the subclesses of Expr class declared in ExprCXX.h
10//
11//===----------------------------------------------------------------------===//
12
13#include "clang/AST/ExprCXX.h"
14#include "clang/AST/ASTContext.h"
15#include "clang/AST/Attr.h"
16#include "clang/AST/ComputeDependence.h"
17#include "clang/AST/Decl.h"
18#include "clang/AST/DeclAccessPair.h"
19#include "clang/AST/DeclBase.h"
20#include "clang/AST/DeclCXX.h"
21#include "clang/AST/DeclTemplate.h"
22#include "clang/AST/DeclarationName.h"
23#include "clang/AST/DependenceFlags.h"
24#include "clang/AST/Expr.h"
25#include "clang/AST/LambdaCapture.h"
26#include "clang/AST/NestedNameSpecifier.h"
27#include "clang/AST/TemplateBase.h"
28#include "clang/AST/Type.h"
29#include "clang/AST/TypeLoc.h"
30#include "clang/Basic/LLVM.h"
31#include "clang/Basic/OperatorKinds.h"
32#include "clang/Basic/SourceLocation.h"
33#include "clang/Basic/Specifiers.h"
34#include "llvm/ADT/ArrayRef.h"
35#include "llvm/Support/Casting.h"
36#include "llvm/Support/ErrorHandling.h"
37#include <cassert>
38#include <cstddef>
39#include <cstring>
40#include <memory>
41
42using namespace clang;
43
44//===----------------------------------------------------------------------===//
45//  Child Iterators for iterating over subexpressions/substatements
46//===----------------------------------------------------------------------===//
47
48bool CXXOperatorCallExpr::isInfixBinaryOp() const {
49  // An infix binary operator is any operator with two arguments other than
50  // operator() and operator[]. Note that none of these operators can have
51  // default arguments, so it suffices to check the number of argument
52  // expressions.
53  if (getNumArgs() != 2)
54    return false;
55
56  switch (getOperator()) {
57  case OO_Call: case OO_Subscript:
58    return false;
59  default:
60    return true;
61  }
62}
63
64CXXRewrittenBinaryOperator::DecomposedForm
65CXXRewrittenBinaryOperator::getDecomposedForm() const {
66  DecomposedForm Result = {};
67  const Expr *E = getSemanticForm()->IgnoreImplicit();
68
69  // Remove an outer '!' if it exists (only happens for a '!=' rewrite).
70  bool SkippedNot = false;
71  if (auto *NotEq = dyn_cast<UnaryOperator>(E)) {
72    assert(NotEq->getOpcode() == UO_LNot);
73    E = NotEq->getSubExpr()->IgnoreImplicit();
74    SkippedNot = true;
75  }
76
77  // Decompose the outer binary operator.
78  if (auto *BO = dyn_cast<BinaryOperator>(E)) {
79    assert(!SkippedNot || BO->getOpcode() == BO_EQ);
80    Result.Opcode = SkippedNot ? BO_NE : BO->getOpcode();
81    Result.LHS = BO->getLHS();
82    Result.RHS = BO->getRHS();
83    Result.InnerBinOp = BO;
84  } else if (auto *BO = dyn_cast<CXXOperatorCallExpr>(E)) {
85    assert(!SkippedNot || BO->getOperator() == OO_EqualEqual);
86    assert(BO->isInfixBinaryOp());
87    switch (BO->getOperator()) {
88    case OO_Less: Result.Opcode = BO_LT; break;
89    case OO_LessEqual: Result.Opcode = BO_LE; break;
90    case OO_Greater: Result.Opcode = BO_GT; break;
91    case OO_GreaterEqual: Result.Opcode = BO_GE; break;
92    case OO_Spaceship: Result.Opcode = BO_Cmp; break;
93    case OO_EqualEqual: Result.Opcode = SkippedNot ? BO_NE : BO_EQ; break;
94    default: llvm_unreachable("unexpected binop in rewritten operator expr");
95    }
96    Result.LHS = BO->getArg(0);
97    Result.RHS = BO->getArg(1);
98    Result.InnerBinOp = BO;
99  } else {
100    llvm_unreachable("unexpected rewritten operator form");
101  }
102
103  // Put the operands in the right order for == and !=, and canonicalize the
104  // <=> subexpression onto the LHS for all other forms.
105  if (isReversed())
106    std::swap(Result.LHS, Result.RHS);
107
108  // If this isn't a spaceship rewrite, we're done.
109  if (Result.Opcode == BO_EQ || Result.Opcode == BO_NE)
110    return Result;
111
112  // Otherwise, we expect a <=> to now be on the LHS.
113  E = Result.LHS->IgnoreImplicitAsWritten();
114  if (auto *BO = dyn_cast<BinaryOperator>(E)) {
115    assert(BO->getOpcode() == BO_Cmp);
116    Result.LHS = BO->getLHS();
117    Result.RHS = BO->getRHS();
118    Result.InnerBinOp = BO;
119  } else if (auto *BO = dyn_cast<CXXOperatorCallExpr>(E)) {
120    assert(BO->getOperator() == OO_Spaceship);
121    Result.LHS = BO->getArg(0);
122    Result.RHS = BO->getArg(1);
123    Result.InnerBinOp = BO;
124  } else {
125    llvm_unreachable("unexpected rewritten operator form");
126  }
127
128  // Put the comparison operands in the right order.
129  if (isReversed())
130    std::swap(Result.LHS, Result.RHS);
131  return Result;
132}
133
134bool CXXTypeidExpr::isPotentiallyEvaluated() const {
135  if (isTypeOperand())
136    return false;
137
138  // C++11 [expr.typeid]p3:
139  //   When typeid is applied to an expression other than a glvalue of
140  //   polymorphic class type, [...] the expression is an unevaluated operand.
141  const Expr *E = getExprOperand();
142  if (const CXXRecordDecl *RD = E->getType()->getAsCXXRecordDecl())
143    if (RD->isPolymorphic() && E->isGLValue())
144      return true;
145
146  return false;
147}
148
149QualType CXXTypeidExpr::getTypeOperand(ASTContext &Context) const {
150  assert(isTypeOperand() && "Cannot call getTypeOperand for typeid(expr)");
151  Qualifiers Quals;
152  return Context.getUnqualifiedArrayType(
153      Operand.get<TypeSourceInfo *>()->getType().getNonReferenceType(), Quals);
154}
155
156QualType CXXUuidofExpr::getTypeOperand(ASTContext &Context) const {
157  assert(isTypeOperand() && "Cannot call getTypeOperand for __uuidof(expr)");
158  Qualifiers Quals;
159  return Context.getUnqualifiedArrayType(
160      Operand.get<TypeSourceInfo *>()->getType().getNonReferenceType(), Quals);
161}
162
163// CXXScalarValueInitExpr
164SourceLocation CXXScalarValueInitExpr::getBeginLoc() const {
165  return TypeInfo ? TypeInfo->getTypeLoc().getBeginLoc() : getRParenLoc();
166}
167
168// CXXNewExpr
169CXXNewExpr::CXXNewExpr(bool IsGlobalNew, FunctionDecl *OperatorNew,
170                       FunctionDecl *OperatorDelete, bool ShouldPassAlignment,
171                       bool UsualArrayDeleteWantsSize,
172                       ArrayRef<Expr *> PlacementArgs, SourceRange TypeIdParens,
173                       Optional<Expr *> ArraySize,
174                       InitializationStyle InitializationStyle,
175                       Expr *Initializer, QualType Ty,
176                       TypeSourceInfo *AllocatedTypeInfo, SourceRange Range,
177                       SourceRange DirectInitRange)
178    : Expr(CXXNewExprClass, Ty, VK_RValue, OK_Ordinary),
179      OperatorNew(OperatorNew), OperatorDelete(OperatorDelete),
180      AllocatedTypeInfo(AllocatedTypeInfo), Range(Range),
181      DirectInitRange(DirectInitRange) {
182
183  assert((Initializer != nullptr || InitializationStyle == NoInit) &&
184         "Only NoInit can have no initializer!");
185
186  CXXNewExprBits.IsGlobalNew = IsGlobalNew;
187  CXXNewExprBits.IsArray = ArraySize.hasValue();
188  CXXNewExprBits.ShouldPassAlignment = ShouldPassAlignment;
189  CXXNewExprBits.UsualArrayDeleteWantsSize = UsualArrayDeleteWantsSize;
190  CXXNewExprBits.StoredInitializationStyle =
191      Initializer ? InitializationStyle + 1 : 0;
192  bool IsParenTypeId = TypeIdParens.isValid();
193  CXXNewExprBits.IsParenTypeId = IsParenTypeId;
194  CXXNewExprBits.NumPlacementArgs = PlacementArgs.size();
195
196  if (ArraySize)
197    getTrailingObjects<Stmt *>()[arraySizeOffset()] = *ArraySize;
198  if (Initializer)
199    getTrailingObjects<Stmt *>()[initExprOffset()] = Initializer;
200  for (unsigned I = 0; I != PlacementArgs.size(); ++I)
201    getTrailingObjects<Stmt *>()[placementNewArgsOffset() + I] =
202        PlacementArgs[I];
203  if (IsParenTypeId)
204    getTrailingObjects<SourceRange>()[0] = TypeIdParens;
205
206  switch (getInitializationStyle()) {
207  case CallInit:
208    this->Range.setEnd(DirectInitRange.getEnd());
209    break;
210  case ListInit:
211    this->Range.setEnd(getInitializer()->getSourceRange().getEnd());
212    break;
213  default:
214    if (IsParenTypeId)
215      this->Range.setEnd(TypeIdParens.getEnd());
216    break;
217  }
218
219  setDependence(computeDependence(this));
220}
221
222CXXNewExpr::CXXNewExpr(EmptyShell Empty, bool IsArray,
223                       unsigned NumPlacementArgs, bool IsParenTypeId)
224    : Expr(CXXNewExprClass, Empty) {
225  CXXNewExprBits.IsArray = IsArray;
226  CXXNewExprBits.NumPlacementArgs = NumPlacementArgs;
227  CXXNewExprBits.IsParenTypeId = IsParenTypeId;
228}
229
230CXXNewExpr *
231CXXNewExpr::Create(const ASTContext &Ctx, bool IsGlobalNew,
232                   FunctionDecl *OperatorNew, FunctionDecl *OperatorDelete,
233                   bool ShouldPassAlignment, bool UsualArrayDeleteWantsSize,
234                   ArrayRef<Expr *> PlacementArgs, SourceRange TypeIdParens,
235                   Optional<Expr *> ArraySize,
236                   InitializationStyle InitializationStyle, Expr *Initializer,
237                   QualType Ty, TypeSourceInfo *AllocatedTypeInfo,
238                   SourceRange Range, SourceRange DirectInitRange) {
239  bool IsArray = ArraySize.hasValue();
240  bool HasInit = Initializer != nullptr;
241  unsigned NumPlacementArgs = PlacementArgs.size();
242  bool IsParenTypeId = TypeIdParens.isValid();
243  void *Mem =
244      Ctx.Allocate(totalSizeToAlloc<Stmt *, SourceRange>(
245                       IsArray + HasInit + NumPlacementArgs, IsParenTypeId),
246                   alignof(CXXNewExpr));
247  return new (Mem)
248      CXXNewExpr(IsGlobalNew, OperatorNew, OperatorDelete, ShouldPassAlignment,
249                 UsualArrayDeleteWantsSize, PlacementArgs, TypeIdParens,
250                 ArraySize, InitializationStyle, Initializer, Ty,
251                 AllocatedTypeInfo, Range, DirectInitRange);
252}
253
254CXXNewExpr *CXXNewExpr::CreateEmpty(const ASTContext &Ctx, bool IsArray,
255                                    bool HasInit, unsigned NumPlacementArgs,
256                                    bool IsParenTypeId) {
257  void *Mem =
258      Ctx.Allocate(totalSizeToAlloc<Stmt *, SourceRange>(
259                       IsArray + HasInit + NumPlacementArgs, IsParenTypeId),
260                   alignof(CXXNewExpr));
261  return new (Mem)
262      CXXNewExpr(EmptyShell(), IsArray, NumPlacementArgs, IsParenTypeId);
263}
264
265bool CXXNewExpr::shouldNullCheckAllocation() const {
266  return getOperatorNew()
267             ->getType()
268             ->castAs<FunctionProtoType>()
269             ->isNothrow() &&
270         !getOperatorNew()->isReservedGlobalPlacementOperator();
271}
272
273// CXXDeleteExpr
274QualType CXXDeleteExpr::getDestroyedType() const {
275  const Expr *Arg = getArgument();
276
277  // For a destroying operator delete, we may have implicitly converted the
278  // pointer type to the type of the parameter of the 'operator delete'
279  // function.
280  while (const auto *ICE = dyn_cast<ImplicitCastExpr>(Arg)) {
281    if (ICE->getCastKind() == CK_DerivedToBase ||
282        ICE->getCastKind() == CK_UncheckedDerivedToBase ||
283        ICE->getCastKind() == CK_NoOp) {
284      assert((ICE->getCastKind() == CK_NoOp ||
285              getOperatorDelete()->isDestroyingOperatorDelete()) &&
286             "only a destroying operator delete can have a converted arg");
287      Arg = ICE->getSubExpr();
288    } else
289      break;
290  }
291
292  // The type-to-delete may not be a pointer if it's a dependent type.
293  const QualType ArgType = Arg->getType();
294
295  if (ArgType->isDependentType() && !ArgType->isPointerType())
296    return QualType();
297
298  return ArgType->castAs<PointerType>()->getPointeeType();
299}
300
301// CXXPseudoDestructorExpr
302PseudoDestructorTypeStorage::PseudoDestructorTypeStorage(TypeSourceInfo *Info)
303    : Type(Info) {
304  Location = Info->getTypeLoc().getLocalSourceRange().getBegin();
305}
306
307CXXPseudoDestructorExpr::CXXPseudoDestructorExpr(
308    const ASTContext &Context, Expr *Base, bool isArrow,
309    SourceLocation OperatorLoc, NestedNameSpecifierLoc QualifierLoc,
310    TypeSourceInfo *ScopeType, SourceLocation ColonColonLoc,
311    SourceLocation TildeLoc, PseudoDestructorTypeStorage DestroyedType)
312    : Expr(CXXPseudoDestructorExprClass, Context.BoundMemberTy, VK_RValue,
313           OK_Ordinary),
314      Base(static_cast<Stmt *>(Base)), IsArrow(isArrow),
315      OperatorLoc(OperatorLoc), QualifierLoc(QualifierLoc),
316      ScopeType(ScopeType), ColonColonLoc(ColonColonLoc), TildeLoc(TildeLoc),
317      DestroyedType(DestroyedType) {
318  setDependence(computeDependence(this));
319}
320
321QualType CXXPseudoDestructorExpr::getDestroyedType() const {
322  if (TypeSourceInfo *TInfo = DestroyedType.getTypeSourceInfo())
323    return TInfo->getType();
324
325  return QualType();
326}
327
328SourceLocation CXXPseudoDestructorExpr::getEndLoc() const {
329  SourceLocation End = DestroyedType.getLocation();
330  if (TypeSourceInfo *TInfo = DestroyedType.getTypeSourceInfo())
331    End = TInfo->getTypeLoc().getLocalSourceRange().getEnd();
332  return End;
333}
334
335// UnresolvedLookupExpr
336UnresolvedLookupExpr::UnresolvedLookupExpr(
337    const ASTContext &Context, CXXRecordDecl *NamingClass,
338    NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc,
339    const DeclarationNameInfo &NameInfo, bool RequiresADL, bool Overloaded,
340    const TemplateArgumentListInfo *TemplateArgs, UnresolvedSetIterator Begin,
341    UnresolvedSetIterator End)
342    : OverloadExpr(UnresolvedLookupExprClass, Context, QualifierLoc,
343                   TemplateKWLoc, NameInfo, TemplateArgs, Begin, End, false,
344                   false, false),
345      NamingClass(NamingClass) {
346  UnresolvedLookupExprBits.RequiresADL = RequiresADL;
347  UnresolvedLookupExprBits.Overloaded = Overloaded;
348}
349
350UnresolvedLookupExpr::UnresolvedLookupExpr(EmptyShell Empty,
351                                           unsigned NumResults,
352                                           bool HasTemplateKWAndArgsInfo)
353    : OverloadExpr(UnresolvedLookupExprClass, Empty, NumResults,
354                   HasTemplateKWAndArgsInfo) {}
355
356UnresolvedLookupExpr *UnresolvedLookupExpr::Create(
357    const ASTContext &Context, CXXRecordDecl *NamingClass,
358    NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo,
359    bool RequiresADL, bool Overloaded, UnresolvedSetIterator Begin,
360    UnresolvedSetIterator End) {
361  unsigned NumResults = End - Begin;
362  unsigned Size = totalSizeToAlloc<DeclAccessPair, ASTTemplateKWAndArgsInfo,
363                                   TemplateArgumentLoc>(NumResults, 0, 0);
364  void *Mem = Context.Allocate(Size, alignof(UnresolvedLookupExpr));
365  return new (Mem) UnresolvedLookupExpr(Context, NamingClass, QualifierLoc,
366                                        SourceLocation(), NameInfo, RequiresADL,
367                                        Overloaded, nullptr, Begin, End);
368}
369
370UnresolvedLookupExpr *UnresolvedLookupExpr::Create(
371    const ASTContext &Context, CXXRecordDecl *NamingClass,
372    NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc,
373    const DeclarationNameInfo &NameInfo, bool RequiresADL,
374    const TemplateArgumentListInfo *Args, UnresolvedSetIterator Begin,
375    UnresolvedSetIterator End) {
376  assert(Args || TemplateKWLoc.isValid());
377  unsigned NumResults = End - Begin;
378  unsigned NumTemplateArgs = Args ? Args->size() : 0;
379  unsigned Size =
380      totalSizeToAlloc<DeclAccessPair, ASTTemplateKWAndArgsInfo,
381                       TemplateArgumentLoc>(NumResults, 1, NumTemplateArgs);
382  void *Mem = Context.Allocate(Size, alignof(UnresolvedLookupExpr));
383  return new (Mem) UnresolvedLookupExpr(Context, NamingClass, QualifierLoc,
384                                        TemplateKWLoc, NameInfo, RequiresADL,
385                                        /*Overloaded*/ true, Args, Begin, End);
386}
387
388UnresolvedLookupExpr *UnresolvedLookupExpr::CreateEmpty(
389    const ASTContext &Context, unsigned NumResults,
390    bool HasTemplateKWAndArgsInfo, unsigned NumTemplateArgs) {
391  assert(NumTemplateArgs == 0 || HasTemplateKWAndArgsInfo);
392  unsigned Size = totalSizeToAlloc<DeclAccessPair, ASTTemplateKWAndArgsInfo,
393                                   TemplateArgumentLoc>(
394      NumResults, HasTemplateKWAndArgsInfo, NumTemplateArgs);
395  void *Mem = Context.Allocate(Size, alignof(UnresolvedLookupExpr));
396  return new (Mem)
397      UnresolvedLookupExpr(EmptyShell(), NumResults, HasTemplateKWAndArgsInfo);
398}
399
400OverloadExpr::OverloadExpr(StmtClass SC, const ASTContext &Context,
401                           NestedNameSpecifierLoc QualifierLoc,
402                           SourceLocation TemplateKWLoc,
403                           const DeclarationNameInfo &NameInfo,
404                           const TemplateArgumentListInfo *TemplateArgs,
405                           UnresolvedSetIterator Begin,
406                           UnresolvedSetIterator End, bool KnownDependent,
407                           bool KnownInstantiationDependent,
408                           bool KnownContainsUnexpandedParameterPack)
409    : Expr(SC, Context.OverloadTy, VK_LValue, OK_Ordinary), NameInfo(NameInfo),
410      QualifierLoc(QualifierLoc) {
411  unsigned NumResults = End - Begin;
412  OverloadExprBits.NumResults = NumResults;
413  OverloadExprBits.HasTemplateKWAndArgsInfo =
414      (TemplateArgs != nullptr ) || TemplateKWLoc.isValid();
415
416  if (NumResults) {
417    // Copy the results to the trailing array past UnresolvedLookupExpr
418    // or UnresolvedMemberExpr.
419    DeclAccessPair *Results = getTrailingResults();
420    memcpy(Results, Begin.I, NumResults * sizeof(DeclAccessPair));
421  }
422
423  if (TemplateArgs) {
424    auto Deps = TemplateArgumentDependence::None;
425    getTrailingASTTemplateKWAndArgsInfo()->initializeFrom(
426        TemplateKWLoc, *TemplateArgs, getTrailingTemplateArgumentLoc(), Deps);
427  } else if (TemplateKWLoc.isValid()) {
428    getTrailingASTTemplateKWAndArgsInfo()->initializeFrom(TemplateKWLoc);
429  }
430
431  setDependence(computeDependence(this, KnownDependent,
432                                  KnownInstantiationDependent,
433                                  KnownContainsUnexpandedParameterPack));
434  if (isTypeDependent())
435    setType(Context.DependentTy);
436}
437
438OverloadExpr::OverloadExpr(StmtClass SC, EmptyShell Empty, unsigned NumResults,
439                           bool HasTemplateKWAndArgsInfo)
440    : Expr(SC, Empty) {
441  OverloadExprBits.NumResults = NumResults;
442  OverloadExprBits.HasTemplateKWAndArgsInfo = HasTemplateKWAndArgsInfo;
443}
444
445// DependentScopeDeclRefExpr
446DependentScopeDeclRefExpr::DependentScopeDeclRefExpr(
447    QualType Ty, NestedNameSpecifierLoc QualifierLoc,
448    SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo,
449    const TemplateArgumentListInfo *Args)
450    : Expr(DependentScopeDeclRefExprClass, Ty, VK_LValue, OK_Ordinary),
451      QualifierLoc(QualifierLoc), NameInfo(NameInfo) {
452  DependentScopeDeclRefExprBits.HasTemplateKWAndArgsInfo =
453      (Args != nullptr) || TemplateKWLoc.isValid();
454  if (Args) {
455    auto Deps = TemplateArgumentDependence::None;
456    getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
457        TemplateKWLoc, *Args, getTrailingObjects<TemplateArgumentLoc>(), Deps);
458  } else if (TemplateKWLoc.isValid()) {
459    getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
460        TemplateKWLoc);
461  }
462  setDependence(computeDependence(this));
463}
464
465DependentScopeDeclRefExpr *DependentScopeDeclRefExpr::Create(
466    const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc,
467    SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo,
468    const TemplateArgumentListInfo *Args) {
469  assert(QualifierLoc && "should be created for dependent qualifiers");
470  bool HasTemplateKWAndArgsInfo = Args || TemplateKWLoc.isValid();
471  std::size_t Size =
472      totalSizeToAlloc<ASTTemplateKWAndArgsInfo, TemplateArgumentLoc>(
473          HasTemplateKWAndArgsInfo, Args ? Args->size() : 0);
474  void *Mem = Context.Allocate(Size);
475  return new (Mem) DependentScopeDeclRefExpr(Context.DependentTy, QualifierLoc,
476                                             TemplateKWLoc, NameInfo, Args);
477}
478
479DependentScopeDeclRefExpr *
480DependentScopeDeclRefExpr::CreateEmpty(const ASTContext &Context,
481                                       bool HasTemplateKWAndArgsInfo,
482                                       unsigned NumTemplateArgs) {
483  assert(NumTemplateArgs == 0 || HasTemplateKWAndArgsInfo);
484  std::size_t Size =
485      totalSizeToAlloc<ASTTemplateKWAndArgsInfo, TemplateArgumentLoc>(
486          HasTemplateKWAndArgsInfo, NumTemplateArgs);
487  void *Mem = Context.Allocate(Size);
488  auto *E = new (Mem) DependentScopeDeclRefExpr(
489      QualType(), NestedNameSpecifierLoc(), SourceLocation(),
490      DeclarationNameInfo(), nullptr);
491  E->DependentScopeDeclRefExprBits.HasTemplateKWAndArgsInfo =
492      HasTemplateKWAndArgsInfo;
493  return E;
494}
495
496SourceLocation CXXConstructExpr::getBeginLoc() const {
497  if (isa<CXXTemporaryObjectExpr>(this))
498    return cast<CXXTemporaryObjectExpr>(this)->getBeginLoc();
499  return getLocation();
500}
501
502SourceLocation CXXConstructExpr::getEndLoc() const {
503  if (isa<CXXTemporaryObjectExpr>(this))
504    return cast<CXXTemporaryObjectExpr>(this)->getEndLoc();
505
506  if (ParenOrBraceRange.isValid())
507    return ParenOrBraceRange.getEnd();
508
509  SourceLocation End = getLocation();
510  for (unsigned I = getNumArgs(); I > 0; --I) {
511    const Expr *Arg = getArg(I-1);
512    if (!Arg->isDefaultArgument()) {
513      SourceLocation NewEnd = Arg->getEndLoc();
514      if (NewEnd.isValid()) {
515        End = NewEnd;
516        break;
517      }
518    }
519  }
520
521  return End;
522}
523
524CXXOperatorCallExpr::CXXOperatorCallExpr(OverloadedOperatorKind OpKind,
525                                         Expr *Fn, ArrayRef<Expr *> Args,
526                                         QualType Ty, ExprValueKind VK,
527                                         SourceLocation OperatorLoc,
528                                         FPOptionsOverride FPFeatures,
529                                         ADLCallKind UsesADL)
530    : CallExpr(CXXOperatorCallExprClass, Fn, /*PreArgs=*/{}, Args, Ty, VK,
531               OperatorLoc, /*MinNumArgs=*/0, UsesADL) {
532  CXXOperatorCallExprBits.OperatorKind = OpKind;
533  assert(
534      (CXXOperatorCallExprBits.OperatorKind == static_cast<unsigned>(OpKind)) &&
535      "OperatorKind overflow!");
536  Range = getSourceRangeImpl();
537  Overrides = FPFeatures;
538}
539
540CXXOperatorCallExpr::CXXOperatorCallExpr(unsigned NumArgs, EmptyShell Empty)
541    : CallExpr(CXXOperatorCallExprClass, /*NumPreArgs=*/0, NumArgs, Empty) {}
542
543CXXOperatorCallExpr *
544CXXOperatorCallExpr::Create(const ASTContext &Ctx,
545                            OverloadedOperatorKind OpKind, Expr *Fn,
546                            ArrayRef<Expr *> Args, QualType Ty,
547                            ExprValueKind VK, SourceLocation OperatorLoc,
548                            FPOptionsOverride FPFeatures, ADLCallKind UsesADL) {
549  // Allocate storage for the trailing objects of CallExpr.
550  unsigned NumArgs = Args.size();
551  unsigned SizeOfTrailingObjects =
552      CallExpr::sizeOfTrailingObjects(/*NumPreArgs=*/0, NumArgs);
553  void *Mem = Ctx.Allocate(sizeof(CXXOperatorCallExpr) + SizeOfTrailingObjects,
554                           alignof(CXXOperatorCallExpr));
555  return new (Mem) CXXOperatorCallExpr(OpKind, Fn, Args, Ty, VK, OperatorLoc,
556                                       FPFeatures, UsesADL);
557}
558
559CXXOperatorCallExpr *CXXOperatorCallExpr::CreateEmpty(const ASTContext &Ctx,
560                                                      unsigned NumArgs,
561                                                      EmptyShell Empty) {
562  // Allocate storage for the trailing objects of CallExpr.
563  unsigned SizeOfTrailingObjects =
564      CallExpr::sizeOfTrailingObjects(/*NumPreArgs=*/0, NumArgs);
565  void *Mem = Ctx.Allocate(sizeof(CXXOperatorCallExpr) + SizeOfTrailingObjects,
566                           alignof(CXXOperatorCallExpr));
567  return new (Mem) CXXOperatorCallExpr(NumArgs, Empty);
568}
569
570SourceRange CXXOperatorCallExpr::getSourceRangeImpl() const {
571  OverloadedOperatorKind Kind = getOperator();
572  if (Kind == OO_PlusPlus || Kind == OO_MinusMinus) {
573    if (getNumArgs() == 1)
574      // Prefix operator
575      return SourceRange(getOperatorLoc(), getArg(0)->getEndLoc());
576    else
577      // Postfix operator
578      return SourceRange(getArg(0)->getBeginLoc(), getOperatorLoc());
579  } else if (Kind == OO_Arrow) {
580    return SourceRange(getArg(0)->getBeginLoc(), getOperatorLoc());
581  } else if (Kind == OO_Call) {
582    return SourceRange(getArg(0)->getBeginLoc(), getRParenLoc());
583  } else if (Kind == OO_Subscript) {
584    return SourceRange(getArg(0)->getBeginLoc(), getRParenLoc());
585  } else if (getNumArgs() == 1) {
586    return SourceRange(getOperatorLoc(), getArg(0)->getEndLoc());
587  } else if (getNumArgs() == 2) {
588    return SourceRange(getArg(0)->getBeginLoc(), getArg(1)->getEndLoc());
589  } else {
590    return getOperatorLoc();
591  }
592}
593
594CXXMemberCallExpr::CXXMemberCallExpr(Expr *Fn, ArrayRef<Expr *> Args,
595                                     QualType Ty, ExprValueKind VK,
596                                     SourceLocation RP, unsigned MinNumArgs)
597    : CallExpr(CXXMemberCallExprClass, Fn, /*PreArgs=*/{}, Args, Ty, VK, RP,
598               MinNumArgs, NotADL) {}
599
600CXXMemberCallExpr::CXXMemberCallExpr(unsigned NumArgs, EmptyShell Empty)
601    : CallExpr(CXXMemberCallExprClass, /*NumPreArgs=*/0, NumArgs, Empty) {}
602
603CXXMemberCallExpr *CXXMemberCallExpr::Create(const ASTContext &Ctx, Expr *Fn,
604                                             ArrayRef<Expr *> Args, QualType Ty,
605                                             ExprValueKind VK,
606                                             SourceLocation RP,
607                                             unsigned MinNumArgs) {
608  // Allocate storage for the trailing objects of CallExpr.
609  unsigned NumArgs = std::max<unsigned>(Args.size(), MinNumArgs);
610  unsigned SizeOfTrailingObjects =
611      CallExpr::sizeOfTrailingObjects(/*NumPreArgs=*/0, NumArgs);
612  void *Mem = Ctx.Allocate(sizeof(CXXMemberCallExpr) + SizeOfTrailingObjects,
613                           alignof(CXXMemberCallExpr));
614  return new (Mem) CXXMemberCallExpr(Fn, Args, Ty, VK, RP, MinNumArgs);
615}
616
617CXXMemberCallExpr *CXXMemberCallExpr::CreateEmpty(const ASTContext &Ctx,
618                                                  unsigned NumArgs,
619                                                  EmptyShell Empty) {
620  // Allocate storage for the trailing objects of CallExpr.
621  unsigned SizeOfTrailingObjects =
622      CallExpr::sizeOfTrailingObjects(/*NumPreArgs=*/0, NumArgs);
623  void *Mem = Ctx.Allocate(sizeof(CXXMemberCallExpr) + SizeOfTrailingObjects,
624                           alignof(CXXMemberCallExpr));
625  return new (Mem) CXXMemberCallExpr(NumArgs, Empty);
626}
627
628Expr *CXXMemberCallExpr::getImplicitObjectArgument() const {
629  const Expr *Callee = getCallee()->IgnoreParens();
630  if (const auto *MemExpr = dyn_cast<MemberExpr>(Callee))
631    return MemExpr->getBase();
632  if (const auto *BO = dyn_cast<BinaryOperator>(Callee))
633    if (BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI)
634      return BO->getLHS();
635
636  // FIXME: Will eventually need to cope with member pointers.
637  return nullptr;
638}
639
640QualType CXXMemberCallExpr::getObjectType() const {
641  QualType Ty = getImplicitObjectArgument()->getType();
642  if (Ty->isPointerType())
643    Ty = Ty->getPointeeType();
644  return Ty;
645}
646
647CXXMethodDecl *CXXMemberCallExpr::getMethodDecl() const {
648  if (const auto *MemExpr = dyn_cast<MemberExpr>(getCallee()->IgnoreParens()))
649    return cast<CXXMethodDecl>(MemExpr->getMemberDecl());
650
651  // FIXME: Will eventually need to cope with member pointers.
652  return nullptr;
653}
654
655CXXRecordDecl *CXXMemberCallExpr::getRecordDecl() const {
656  Expr* ThisArg = getImplicitObjectArgument();
657  if (!ThisArg)
658    return nullptr;
659
660  if (ThisArg->getType()->isAnyPointerType())
661    return ThisArg->getType()->getPointeeType()->getAsCXXRecordDecl();
662
663  return ThisArg->getType()->getAsCXXRecordDecl();
664}
665
666//===----------------------------------------------------------------------===//
667//  Named casts
668//===----------------------------------------------------------------------===//
669
670/// getCastName - Get the name of the C++ cast being used, e.g.,
671/// "static_cast", "dynamic_cast", "reinterpret_cast", or
672/// "const_cast". The returned pointer must not be freed.
673const char *CXXNamedCastExpr::getCastName() const {
674  switch (getStmtClass()) {
675  case CXXStaticCastExprClass:      return "static_cast";
676  case CXXDynamicCastExprClass:     return "dynamic_cast";
677  case CXXReinterpretCastExprClass: return "reinterpret_cast";
678  case CXXConstCastExprClass:       return "const_cast";
679  case CXXAddrspaceCastExprClass:   return "addrspace_cast";
680  default:                          return "<invalid cast>";
681  }
682}
683
684CXXStaticCastExpr *CXXStaticCastExpr::Create(const ASTContext &C, QualType T,
685                                             ExprValueKind VK,
686                                             CastKind K, Expr *Op,
687                                             const CXXCastPath *BasePath,
688                                             TypeSourceInfo *WrittenTy,
689                                             SourceLocation L,
690                                             SourceLocation RParenLoc,
691                                             SourceRange AngleBrackets) {
692  unsigned PathSize = (BasePath ? BasePath->size() : 0);
693  void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize));
694  auto *E =
695      new (Buffer) CXXStaticCastExpr(T, VK, K, Op, PathSize, WrittenTy, L,
696                                     RParenLoc, AngleBrackets);
697  if (PathSize)
698    std::uninitialized_copy_n(BasePath->data(), BasePath->size(),
699                              E->getTrailingObjects<CXXBaseSpecifier *>());
700  return E;
701}
702
703CXXStaticCastExpr *CXXStaticCastExpr::CreateEmpty(const ASTContext &C,
704                                                  unsigned PathSize) {
705  void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize));
706  return new (Buffer) CXXStaticCastExpr(EmptyShell(), PathSize);
707}
708
709CXXDynamicCastExpr *CXXDynamicCastExpr::Create(const ASTContext &C, QualType T,
710                                               ExprValueKind VK,
711                                               CastKind K, Expr *Op,
712                                               const CXXCastPath *BasePath,
713                                               TypeSourceInfo *WrittenTy,
714                                               SourceLocation L,
715                                               SourceLocation RParenLoc,
716                                               SourceRange AngleBrackets) {
717  unsigned PathSize = (BasePath ? BasePath->size() : 0);
718  void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize));
719  auto *E =
720      new (Buffer) CXXDynamicCastExpr(T, VK, K, Op, PathSize, WrittenTy, L,
721                                      RParenLoc, AngleBrackets);
722  if (PathSize)
723    std::uninitialized_copy_n(BasePath->data(), BasePath->size(),
724                              E->getTrailingObjects<CXXBaseSpecifier *>());
725  return E;
726}
727
728CXXDynamicCastExpr *CXXDynamicCastExpr::CreateEmpty(const ASTContext &C,
729                                                    unsigned PathSize) {
730  void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize));
731  return new (Buffer) CXXDynamicCastExpr(EmptyShell(), PathSize);
732}
733
734/// isAlwaysNull - Return whether the result of the dynamic_cast is proven
735/// to always be null. For example:
736///
737/// struct A { };
738/// struct B final : A { };
739/// struct C { };
740///
741/// C *f(B* b) { return dynamic_cast<C*>(b); }
742bool CXXDynamicCastExpr::isAlwaysNull() const
743{
744  QualType SrcType = getSubExpr()->getType();
745  QualType DestType = getType();
746
747  if (const auto *SrcPTy = SrcType->getAs<PointerType>()) {
748    SrcType = SrcPTy->getPointeeType();
749    DestType = DestType->castAs<PointerType>()->getPointeeType();
750  }
751
752  if (DestType->isVoidType())
753    return false;
754
755  const auto *SrcRD =
756      cast<CXXRecordDecl>(SrcType->castAs<RecordType>()->getDecl());
757
758  if (!SrcRD->hasAttr<FinalAttr>())
759    return false;
760
761  const auto *DestRD =
762      cast<CXXRecordDecl>(DestType->castAs<RecordType>()->getDecl());
763
764  return !DestRD->isDerivedFrom(SrcRD);
765}
766
767CXXReinterpretCastExpr *
768CXXReinterpretCastExpr::Create(const ASTContext &C, QualType T,
769                               ExprValueKind VK, CastKind K, Expr *Op,
770                               const CXXCastPath *BasePath,
771                               TypeSourceInfo *WrittenTy, SourceLocation L,
772                               SourceLocation RParenLoc,
773                               SourceRange AngleBrackets) {
774  unsigned PathSize = (BasePath ? BasePath->size() : 0);
775  void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize));
776  auto *E =
777      new (Buffer) CXXReinterpretCastExpr(T, VK, K, Op, PathSize, WrittenTy, L,
778                                          RParenLoc, AngleBrackets);
779  if (PathSize)
780    std::uninitialized_copy_n(BasePath->data(), BasePath->size(),
781                              E->getTrailingObjects<CXXBaseSpecifier *>());
782  return E;
783}
784
785CXXReinterpretCastExpr *
786CXXReinterpretCastExpr::CreateEmpty(const ASTContext &C, unsigned PathSize) {
787  void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize));
788  return new (Buffer) CXXReinterpretCastExpr(EmptyShell(), PathSize);
789}
790
791CXXConstCastExpr *CXXConstCastExpr::Create(const ASTContext &C, QualType T,
792                                           ExprValueKind VK, Expr *Op,
793                                           TypeSourceInfo *WrittenTy,
794                                           SourceLocation L,
795                                           SourceLocation RParenLoc,
796                                           SourceRange AngleBrackets) {
797  return new (C) CXXConstCastExpr(T, VK, Op, WrittenTy, L, RParenLoc, AngleBrackets);
798}
799
800CXXConstCastExpr *CXXConstCastExpr::CreateEmpty(const ASTContext &C) {
801  return new (C) CXXConstCastExpr(EmptyShell());
802}
803
804CXXAddrspaceCastExpr *
805CXXAddrspaceCastExpr::Create(const ASTContext &C, QualType T, ExprValueKind VK,
806                             CastKind K, Expr *Op, TypeSourceInfo *WrittenTy,
807                             SourceLocation L, SourceLocation RParenLoc,
808                             SourceRange AngleBrackets) {
809  return new (C) CXXAddrspaceCastExpr(T, VK, K, Op, WrittenTy, L, RParenLoc,
810                                      AngleBrackets);
811}
812
813CXXAddrspaceCastExpr *CXXAddrspaceCastExpr::CreateEmpty(const ASTContext &C) {
814  return new (C) CXXAddrspaceCastExpr(EmptyShell());
815}
816
817CXXFunctionalCastExpr *
818CXXFunctionalCastExpr::Create(const ASTContext &C, QualType T, ExprValueKind VK,
819                              TypeSourceInfo *Written, CastKind K, Expr *Op,
820                              const CXXCastPath *BasePath,
821                              SourceLocation L, SourceLocation R) {
822  unsigned PathSize = (BasePath ? BasePath->size() : 0);
823  void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize));
824  auto *E =
825      new (Buffer) CXXFunctionalCastExpr(T, VK, Written, K, Op, PathSize, L, R);
826  if (PathSize)
827    std::uninitialized_copy_n(BasePath->data(), BasePath->size(),
828                              E->getTrailingObjects<CXXBaseSpecifier *>());
829  return E;
830}
831
832CXXFunctionalCastExpr *
833CXXFunctionalCastExpr::CreateEmpty(const ASTContext &C, unsigned PathSize) {
834  void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize));
835  return new (Buffer) CXXFunctionalCastExpr(EmptyShell(), PathSize);
836}
837
838SourceLocation CXXFunctionalCastExpr::getBeginLoc() const {
839  return getTypeInfoAsWritten()->getTypeLoc().getBeginLoc();
840}
841
842SourceLocation CXXFunctionalCastExpr::getEndLoc() const {
843  return RParenLoc.isValid() ? RParenLoc : getSubExpr()->getEndLoc();
844}
845
846UserDefinedLiteral::UserDefinedLiteral(Expr *Fn, ArrayRef<Expr *> Args,
847                                       QualType Ty, ExprValueKind VK,
848                                       SourceLocation LitEndLoc,
849                                       SourceLocation SuffixLoc)
850    : CallExpr(UserDefinedLiteralClass, Fn, /*PreArgs=*/{}, Args, Ty, VK,
851               LitEndLoc, /*MinNumArgs=*/0, NotADL),
852      UDSuffixLoc(SuffixLoc) {}
853
854UserDefinedLiteral::UserDefinedLiteral(unsigned NumArgs, EmptyShell Empty)
855    : CallExpr(UserDefinedLiteralClass, /*NumPreArgs=*/0, NumArgs, Empty) {}
856
857UserDefinedLiteral *UserDefinedLiteral::Create(const ASTContext &Ctx, Expr *Fn,
858                                               ArrayRef<Expr *> Args,
859                                               QualType Ty, ExprValueKind VK,
860                                               SourceLocation LitEndLoc,
861                                               SourceLocation SuffixLoc) {
862  // Allocate storage for the trailing objects of CallExpr.
863  unsigned NumArgs = Args.size();
864  unsigned SizeOfTrailingObjects =
865      CallExpr::sizeOfTrailingObjects(/*NumPreArgs=*/0, NumArgs);
866  void *Mem = Ctx.Allocate(sizeof(UserDefinedLiteral) + SizeOfTrailingObjects,
867                           alignof(UserDefinedLiteral));
868  return new (Mem) UserDefinedLiteral(Fn, Args, Ty, VK, LitEndLoc, SuffixLoc);
869}
870
871UserDefinedLiteral *UserDefinedLiteral::CreateEmpty(const ASTContext &Ctx,
872                                                    unsigned NumArgs,
873                                                    EmptyShell Empty) {
874  // Allocate storage for the trailing objects of CallExpr.
875  unsigned SizeOfTrailingObjects =
876      CallExpr::sizeOfTrailingObjects(/*NumPreArgs=*/0, NumArgs);
877  void *Mem = Ctx.Allocate(sizeof(UserDefinedLiteral) + SizeOfTrailingObjects,
878                           alignof(UserDefinedLiteral));
879  return new (Mem) UserDefinedLiteral(NumArgs, Empty);
880}
881
882UserDefinedLiteral::LiteralOperatorKind
883UserDefinedLiteral::getLiteralOperatorKind() const {
884  if (getNumArgs() == 0)
885    return LOK_Template;
886  if (getNumArgs() == 2)
887    return LOK_String;
888
889  assert(getNumArgs() == 1 && "unexpected #args in literal operator call");
890  QualType ParamTy =
891    cast<FunctionDecl>(getCalleeDecl())->getParamDecl(0)->getType();
892  if (ParamTy->isPointerType())
893    return LOK_Raw;
894  if (ParamTy->isAnyCharacterType())
895    return LOK_Character;
896  if (ParamTy->isIntegerType())
897    return LOK_Integer;
898  if (ParamTy->isFloatingType())
899    return LOK_Floating;
900
901  llvm_unreachable("unknown kind of literal operator");
902}
903
904Expr *UserDefinedLiteral::getCookedLiteral() {
905#ifndef NDEBUG
906  LiteralOperatorKind LOK = getLiteralOperatorKind();
907  assert(LOK != LOK_Template && LOK != LOK_Raw && "not a cooked literal");
908#endif
909  return getArg(0);
910}
911
912const IdentifierInfo *UserDefinedLiteral::getUDSuffix() const {
913  return cast<FunctionDecl>(getCalleeDecl())->getLiteralIdentifier();
914}
915
916CXXDefaultInitExpr::CXXDefaultInitExpr(const ASTContext &Ctx,
917                                       SourceLocation Loc, FieldDecl *Field,
918                                       QualType Ty, DeclContext *UsedContext)
919    : Expr(CXXDefaultInitExprClass, Ty.getNonLValueExprType(Ctx),
920           Ty->isLValueReferenceType()
921               ? VK_LValue
922               : Ty->isRValueReferenceType() ? VK_XValue : VK_RValue,
923           /*FIXME*/ OK_Ordinary),
924      Field(Field), UsedContext(UsedContext) {
925  CXXDefaultInitExprBits.Loc = Loc;
926  assert(Field->hasInClassInitializer());
927
928  setDependence(ExprDependence::None);
929}
930
931CXXTemporary *CXXTemporary::Create(const ASTContext &C,
932                                   const CXXDestructorDecl *Destructor) {
933  return new (C) CXXTemporary(Destructor);
934}
935
936CXXBindTemporaryExpr *CXXBindTemporaryExpr::Create(const ASTContext &C,
937                                                   CXXTemporary *Temp,
938                                                   Expr* SubExpr) {
939  assert((SubExpr->getType()->isRecordType() ||
940          SubExpr->getType()->isArrayType()) &&
941         "Expression bound to a temporary must have record or array type!");
942
943  return new (C) CXXBindTemporaryExpr(Temp, SubExpr);
944}
945
946CXXTemporaryObjectExpr::CXXTemporaryObjectExpr(
947    CXXConstructorDecl *Cons, QualType Ty, TypeSourceInfo *TSI,
948    ArrayRef<Expr *> Args, SourceRange ParenOrBraceRange,
949    bool HadMultipleCandidates, bool ListInitialization,
950    bool StdInitListInitialization, bool ZeroInitialization)
951    : CXXConstructExpr(
952          CXXTemporaryObjectExprClass, Ty, TSI->getTypeLoc().getBeginLoc(),
953          Cons, /* Elidable=*/false, Args, HadMultipleCandidates,
954          ListInitialization, StdInitListInitialization, ZeroInitialization,
955          CXXConstructExpr::CK_Complete, ParenOrBraceRange),
956      TSI(TSI) {}
957
958CXXTemporaryObjectExpr::CXXTemporaryObjectExpr(EmptyShell Empty,
959                                               unsigned NumArgs)
960    : CXXConstructExpr(CXXTemporaryObjectExprClass, Empty, NumArgs) {}
961
962CXXTemporaryObjectExpr *CXXTemporaryObjectExpr::Create(
963    const ASTContext &Ctx, CXXConstructorDecl *Cons, QualType Ty,
964    TypeSourceInfo *TSI, ArrayRef<Expr *> Args, SourceRange ParenOrBraceRange,
965    bool HadMultipleCandidates, bool ListInitialization,
966    bool StdInitListInitialization, bool ZeroInitialization) {
967  unsigned SizeOfTrailingObjects = sizeOfTrailingObjects(Args.size());
968  void *Mem =
969      Ctx.Allocate(sizeof(CXXTemporaryObjectExpr) + SizeOfTrailingObjects,
970                   alignof(CXXTemporaryObjectExpr));
971  return new (Mem) CXXTemporaryObjectExpr(
972      Cons, Ty, TSI, Args, ParenOrBraceRange, HadMultipleCandidates,
973      ListInitialization, StdInitListInitialization, ZeroInitialization);
974}
975
976CXXTemporaryObjectExpr *
977CXXTemporaryObjectExpr::CreateEmpty(const ASTContext &Ctx, unsigned NumArgs) {
978  unsigned SizeOfTrailingObjects = sizeOfTrailingObjects(NumArgs);
979  void *Mem =
980      Ctx.Allocate(sizeof(CXXTemporaryObjectExpr) + SizeOfTrailingObjects,
981                   alignof(CXXTemporaryObjectExpr));
982  return new (Mem) CXXTemporaryObjectExpr(EmptyShell(), NumArgs);
983}
984
985SourceLocation CXXTemporaryObjectExpr::getBeginLoc() const {
986  return getTypeSourceInfo()->getTypeLoc().getBeginLoc();
987}
988
989SourceLocation CXXTemporaryObjectExpr::getEndLoc() const {
990  SourceLocation Loc = getParenOrBraceRange().getEnd();
991  if (Loc.isInvalid() && getNumArgs())
992    Loc = getArg(getNumArgs() - 1)->getEndLoc();
993  return Loc;
994}
995
996CXXConstructExpr *CXXConstructExpr::Create(
997    const ASTContext &Ctx, QualType Ty, SourceLocation Loc,
998    CXXConstructorDecl *Ctor, bool Elidable, ArrayRef<Expr *> Args,
999    bool HadMultipleCandidates, bool ListInitialization,
1000    bool StdInitListInitialization, bool ZeroInitialization,
1001    ConstructionKind ConstructKind, SourceRange ParenOrBraceRange) {
1002  unsigned SizeOfTrailingObjects = sizeOfTrailingObjects(Args.size());
1003  void *Mem = Ctx.Allocate(sizeof(CXXConstructExpr) + SizeOfTrailingObjects,
1004                           alignof(CXXConstructExpr));
1005  return new (Mem) CXXConstructExpr(
1006      CXXConstructExprClass, Ty, Loc, Ctor, Elidable, Args,
1007      HadMultipleCandidates, ListInitialization, StdInitListInitialization,
1008      ZeroInitialization, ConstructKind, ParenOrBraceRange);
1009}
1010
1011CXXConstructExpr *CXXConstructExpr::CreateEmpty(const ASTContext &Ctx,
1012                                                unsigned NumArgs) {
1013  unsigned SizeOfTrailingObjects = sizeOfTrailingObjects(NumArgs);
1014  void *Mem = Ctx.Allocate(sizeof(CXXConstructExpr) + SizeOfTrailingObjects,
1015                           alignof(CXXConstructExpr));
1016  return new (Mem)
1017      CXXConstructExpr(CXXConstructExprClass, EmptyShell(), NumArgs);
1018}
1019
1020CXXConstructExpr::CXXConstructExpr(
1021    StmtClass SC, QualType Ty, SourceLocation Loc, CXXConstructorDecl *Ctor,
1022    bool Elidable, ArrayRef<Expr *> Args, bool HadMultipleCandidates,
1023    bool ListInitialization, bool StdInitListInitialization,
1024    bool ZeroInitialization, ConstructionKind ConstructKind,
1025    SourceRange ParenOrBraceRange)
1026    : Expr(SC, Ty, VK_RValue, OK_Ordinary), Constructor(Ctor),
1027      ParenOrBraceRange(ParenOrBraceRange), NumArgs(Args.size()) {
1028  CXXConstructExprBits.Elidable = Elidable;
1029  CXXConstructExprBits.HadMultipleCandidates = HadMultipleCandidates;
1030  CXXConstructExprBits.ListInitialization = ListInitialization;
1031  CXXConstructExprBits.StdInitListInitialization = StdInitListInitialization;
1032  CXXConstructExprBits.ZeroInitialization = ZeroInitialization;
1033  CXXConstructExprBits.ConstructionKind = ConstructKind;
1034  CXXConstructExprBits.Loc = Loc;
1035
1036  Stmt **TrailingArgs = getTrailingArgs();
1037  for (unsigned I = 0, N = Args.size(); I != N; ++I) {
1038    assert(Args[I] && "NULL argument in CXXConstructExpr!");
1039    TrailingArgs[I] = Args[I];
1040  }
1041
1042  setDependence(computeDependence(this));
1043}
1044
1045CXXConstructExpr::CXXConstructExpr(StmtClass SC, EmptyShell Empty,
1046                                   unsigned NumArgs)
1047    : Expr(SC, Empty), NumArgs(NumArgs) {}
1048
1049LambdaCapture::LambdaCapture(SourceLocation Loc, bool Implicit,
1050                             LambdaCaptureKind Kind, VarDecl *Var,
1051                             SourceLocation EllipsisLoc)
1052    : DeclAndBits(Var, 0), Loc(Loc), EllipsisLoc(EllipsisLoc) {
1053  unsigned Bits = 0;
1054  if (Implicit)
1055    Bits |= Capture_Implicit;
1056
1057  switch (Kind) {
1058  case LCK_StarThis:
1059    Bits |= Capture_ByCopy;
1060    LLVM_FALLTHROUGH;
1061  case LCK_This:
1062    assert(!Var && "'this' capture cannot have a variable!");
1063    Bits |= Capture_This;
1064    break;
1065
1066  case LCK_ByCopy:
1067    Bits |= Capture_ByCopy;
1068    LLVM_FALLTHROUGH;
1069  case LCK_ByRef:
1070    assert(Var && "capture must have a variable!");
1071    break;
1072  case LCK_VLAType:
1073    assert(!Var && "VLA type capture cannot have a variable!");
1074    break;
1075  }
1076  DeclAndBits.setInt(Bits);
1077}
1078
1079LambdaCaptureKind LambdaCapture::getCaptureKind() const {
1080  if (capturesVLAType())
1081    return LCK_VLAType;
1082  bool CapByCopy = DeclAndBits.getInt() & Capture_ByCopy;
1083  if (capturesThis())
1084    return CapByCopy ? LCK_StarThis : LCK_This;
1085  return CapByCopy ? LCK_ByCopy : LCK_ByRef;
1086}
1087
1088LambdaExpr::LambdaExpr(QualType T, SourceRange IntroducerRange,
1089                       LambdaCaptureDefault CaptureDefault,
1090                       SourceLocation CaptureDefaultLoc, bool ExplicitParams,
1091                       bool ExplicitResultType, ArrayRef<Expr *> CaptureInits,
1092                       SourceLocation ClosingBrace,
1093                       bool ContainsUnexpandedParameterPack)
1094    : Expr(LambdaExprClass, T, VK_RValue, OK_Ordinary),
1095      IntroducerRange(IntroducerRange), CaptureDefaultLoc(CaptureDefaultLoc),
1096      ClosingBrace(ClosingBrace) {
1097  LambdaExprBits.NumCaptures = CaptureInits.size();
1098  LambdaExprBits.CaptureDefault = CaptureDefault;
1099  LambdaExprBits.ExplicitParams = ExplicitParams;
1100  LambdaExprBits.ExplicitResultType = ExplicitResultType;
1101
1102  CXXRecordDecl *Class = getLambdaClass();
1103  (void)Class;
1104  assert(capture_size() == Class->capture_size() && "Wrong number of captures");
1105  assert(getCaptureDefault() == Class->getLambdaCaptureDefault());
1106
1107  // Copy initialization expressions for the non-static data members.
1108  Stmt **Stored = getStoredStmts();
1109  for (unsigned I = 0, N = CaptureInits.size(); I != N; ++I)
1110    *Stored++ = CaptureInits[I];
1111
1112  // Copy the body of the lambda.
1113  *Stored++ = getCallOperator()->getBody();
1114
1115  setDependence(computeDependence(this, ContainsUnexpandedParameterPack));
1116}
1117
1118LambdaExpr::LambdaExpr(EmptyShell Empty, unsigned NumCaptures)
1119    : Expr(LambdaExprClass, Empty) {
1120  LambdaExprBits.NumCaptures = NumCaptures;
1121
1122  // Initially don't initialize the body of the LambdaExpr. The body will
1123  // be lazily deserialized when needed.
1124  getStoredStmts()[NumCaptures] = nullptr; // Not one past the end.
1125}
1126
1127LambdaExpr *LambdaExpr::Create(const ASTContext &Context, CXXRecordDecl *Class,
1128                               SourceRange IntroducerRange,
1129                               LambdaCaptureDefault CaptureDefault,
1130                               SourceLocation CaptureDefaultLoc,
1131                               bool ExplicitParams, bool ExplicitResultType,
1132                               ArrayRef<Expr *> CaptureInits,
1133                               SourceLocation ClosingBrace,
1134                               bool ContainsUnexpandedParameterPack) {
1135  // Determine the type of the expression (i.e., the type of the
1136  // function object we're creating).
1137  QualType T = Context.getTypeDeclType(Class);
1138
1139  unsigned Size = totalSizeToAlloc<Stmt *>(CaptureInits.size() + 1);
1140  void *Mem = Context.Allocate(Size);
1141  return new (Mem)
1142      LambdaExpr(T, IntroducerRange, CaptureDefault, CaptureDefaultLoc,
1143                 ExplicitParams, ExplicitResultType, CaptureInits, ClosingBrace,
1144                 ContainsUnexpandedParameterPack);
1145}
1146
1147LambdaExpr *LambdaExpr::CreateDeserialized(const ASTContext &C,
1148                                           unsigned NumCaptures) {
1149  unsigned Size = totalSizeToAlloc<Stmt *>(NumCaptures + 1);
1150  void *Mem = C.Allocate(Size);
1151  return new (Mem) LambdaExpr(EmptyShell(), NumCaptures);
1152}
1153
1154void LambdaExpr::initBodyIfNeeded() const {
1155  if (!getStoredStmts()[capture_size()]) {
1156    auto *This = const_cast<LambdaExpr *>(this);
1157    This->getStoredStmts()[capture_size()] = getCallOperator()->getBody();
1158  }
1159}
1160
1161Stmt *LambdaExpr::getBody() const {
1162  initBodyIfNeeded();
1163  return getStoredStmts()[capture_size()];
1164}
1165
1166const CompoundStmt *LambdaExpr::getCompoundStmtBody() const {
1167  Stmt *Body = getBody();
1168  if (const auto *CoroBody = dyn_cast<CoroutineBodyStmt>(Body))
1169    return cast<CompoundStmt>(CoroBody->getBody());
1170  return cast<CompoundStmt>(Body);
1171}
1172
1173bool LambdaExpr::isInitCapture(const LambdaCapture *C) const {
1174  return (C->capturesVariable() && C->getCapturedVar()->isInitCapture() &&
1175          (getCallOperator() == C->getCapturedVar()->getDeclContext()));
1176}
1177
1178LambdaExpr::capture_iterator LambdaExpr::capture_begin() const {
1179  return getLambdaClass()->getLambdaData().Captures;
1180}
1181
1182LambdaExpr::capture_iterator LambdaExpr::capture_end() const {
1183  return capture_begin() + capture_size();
1184}
1185
1186LambdaExpr::capture_range LambdaExpr::captures() const {
1187  return capture_range(capture_begin(), capture_end());
1188}
1189
1190LambdaExpr::capture_iterator LambdaExpr::explicit_capture_begin() const {
1191  return capture_begin();
1192}
1193
1194LambdaExpr::capture_iterator LambdaExpr::explicit_capture_end() const {
1195  struct CXXRecordDecl::LambdaDefinitionData &Data
1196    = getLambdaClass()->getLambdaData();
1197  return Data.Captures + Data.NumExplicitCaptures;
1198}
1199
1200LambdaExpr::capture_range LambdaExpr::explicit_captures() const {
1201  return capture_range(explicit_capture_begin(), explicit_capture_end());
1202}
1203
1204LambdaExpr::capture_iterator LambdaExpr::implicit_capture_begin() const {
1205  return explicit_capture_end();
1206}
1207
1208LambdaExpr::capture_iterator LambdaExpr::implicit_capture_end() const {
1209  return capture_end();
1210}
1211
1212LambdaExpr::capture_range LambdaExpr::implicit_captures() const {
1213  return capture_range(implicit_capture_begin(), implicit_capture_end());
1214}
1215
1216CXXRecordDecl *LambdaExpr::getLambdaClass() const {
1217  return getType()->getAsCXXRecordDecl();
1218}
1219
1220CXXMethodDecl *LambdaExpr::getCallOperator() const {
1221  CXXRecordDecl *Record = getLambdaClass();
1222  return Record->getLambdaCallOperator();
1223}
1224
1225FunctionTemplateDecl *LambdaExpr::getDependentCallOperator() const {
1226  CXXRecordDecl *Record = getLambdaClass();
1227  return Record->getDependentLambdaCallOperator();
1228}
1229
1230TemplateParameterList *LambdaExpr::getTemplateParameterList() const {
1231  CXXRecordDecl *Record = getLambdaClass();
1232  return Record->getGenericLambdaTemplateParameterList();
1233}
1234
1235ArrayRef<NamedDecl *> LambdaExpr::getExplicitTemplateParameters() const {
1236  const CXXRecordDecl *Record = getLambdaClass();
1237  return Record->getLambdaExplicitTemplateParameters();
1238}
1239
1240bool LambdaExpr::isMutable() const { return !getCallOperator()->isConst(); }
1241
1242LambdaExpr::child_range LambdaExpr::children() {
1243  initBodyIfNeeded();
1244  return child_range(getStoredStmts(), getStoredStmts() + capture_size() + 1);
1245}
1246
1247LambdaExpr::const_child_range LambdaExpr::children() const {
1248  initBodyIfNeeded();
1249  return const_child_range(getStoredStmts(),
1250                           getStoredStmts() + capture_size() + 1);
1251}
1252
1253ExprWithCleanups::ExprWithCleanups(Expr *subexpr,
1254                                   bool CleanupsHaveSideEffects,
1255                                   ArrayRef<CleanupObject> objects)
1256    : FullExpr(ExprWithCleanupsClass, subexpr) {
1257  ExprWithCleanupsBits.CleanupsHaveSideEffects = CleanupsHaveSideEffects;
1258  ExprWithCleanupsBits.NumObjects = objects.size();
1259  for (unsigned i = 0, e = objects.size(); i != e; ++i)
1260    getTrailingObjects<CleanupObject>()[i] = objects[i];
1261}
1262
1263ExprWithCleanups *ExprWithCleanups::Create(const ASTContext &C, Expr *subexpr,
1264                                           bool CleanupsHaveSideEffects,
1265                                           ArrayRef<CleanupObject> objects) {
1266  void *buffer = C.Allocate(totalSizeToAlloc<CleanupObject>(objects.size()),
1267                            alignof(ExprWithCleanups));
1268  return new (buffer)
1269      ExprWithCleanups(subexpr, CleanupsHaveSideEffects, objects);
1270}
1271
1272ExprWithCleanups::ExprWithCleanups(EmptyShell empty, unsigned numObjects)
1273    : FullExpr(ExprWithCleanupsClass, empty) {
1274  ExprWithCleanupsBits.NumObjects = numObjects;
1275}
1276
1277ExprWithCleanups *ExprWithCleanups::Create(const ASTContext &C,
1278                                           EmptyShell empty,
1279                                           unsigned numObjects) {
1280  void *buffer = C.Allocate(totalSizeToAlloc<CleanupObject>(numObjects),
1281                            alignof(ExprWithCleanups));
1282  return new (buffer) ExprWithCleanups(empty, numObjects);
1283}
1284
1285CXXUnresolvedConstructExpr::CXXUnresolvedConstructExpr(TypeSourceInfo *TSI,
1286                                                       SourceLocation LParenLoc,
1287                                                       ArrayRef<Expr *> Args,
1288                                                       SourceLocation RParenLoc)
1289    : Expr(CXXUnresolvedConstructExprClass,
1290           TSI->getType().getNonReferenceType(),
1291           (TSI->getType()->isLValueReferenceType()
1292                ? VK_LValue
1293                : TSI->getType()->isRValueReferenceType() ? VK_XValue
1294                                                          : VK_RValue),
1295           OK_Ordinary),
1296      TSI(TSI), LParenLoc(LParenLoc), RParenLoc(RParenLoc) {
1297  CXXUnresolvedConstructExprBits.NumArgs = Args.size();
1298  auto **StoredArgs = getTrailingObjects<Expr *>();
1299  for (unsigned I = 0; I != Args.size(); ++I)
1300    StoredArgs[I] = Args[I];
1301  setDependence(computeDependence(this));
1302}
1303
1304CXXUnresolvedConstructExpr *CXXUnresolvedConstructExpr::Create(
1305    const ASTContext &Context, TypeSourceInfo *TSI, SourceLocation LParenLoc,
1306    ArrayRef<Expr *> Args, SourceLocation RParenLoc) {
1307  void *Mem = Context.Allocate(totalSizeToAlloc<Expr *>(Args.size()));
1308  return new (Mem) CXXUnresolvedConstructExpr(TSI, LParenLoc, Args, RParenLoc);
1309}
1310
1311CXXUnresolvedConstructExpr *
1312CXXUnresolvedConstructExpr::CreateEmpty(const ASTContext &Context,
1313                                        unsigned NumArgs) {
1314  void *Mem = Context.Allocate(totalSizeToAlloc<Expr *>(NumArgs));
1315  return new (Mem) CXXUnresolvedConstructExpr(EmptyShell(), NumArgs);
1316}
1317
1318SourceLocation CXXUnresolvedConstructExpr::getBeginLoc() const {
1319  return TSI->getTypeLoc().getBeginLoc();
1320}
1321
1322CXXDependentScopeMemberExpr::CXXDependentScopeMemberExpr(
1323    const ASTContext &Ctx, Expr *Base, QualType BaseType, bool IsArrow,
1324    SourceLocation OperatorLoc, NestedNameSpecifierLoc QualifierLoc,
1325    SourceLocation TemplateKWLoc, NamedDecl *FirstQualifierFoundInScope,
1326    DeclarationNameInfo MemberNameInfo,
1327    const TemplateArgumentListInfo *TemplateArgs)
1328    : Expr(CXXDependentScopeMemberExprClass, Ctx.DependentTy, VK_LValue,
1329           OK_Ordinary),
1330      Base(Base), BaseType(BaseType), QualifierLoc(QualifierLoc),
1331      MemberNameInfo(MemberNameInfo) {
1332  CXXDependentScopeMemberExprBits.IsArrow = IsArrow;
1333  CXXDependentScopeMemberExprBits.HasTemplateKWAndArgsInfo =
1334      (TemplateArgs != nullptr) || TemplateKWLoc.isValid();
1335  CXXDependentScopeMemberExprBits.HasFirstQualifierFoundInScope =
1336      FirstQualifierFoundInScope != nullptr;
1337  CXXDependentScopeMemberExprBits.OperatorLoc = OperatorLoc;
1338
1339  if (TemplateArgs) {
1340    auto Deps = TemplateArgumentDependence::None;
1341    getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
1342        TemplateKWLoc, *TemplateArgs, getTrailingObjects<TemplateArgumentLoc>(),
1343        Deps);
1344  } else if (TemplateKWLoc.isValid()) {
1345    getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
1346        TemplateKWLoc);
1347  }
1348
1349  if (hasFirstQualifierFoundInScope())
1350    *getTrailingObjects<NamedDecl *>() = FirstQualifierFoundInScope;
1351  setDependence(computeDependence(this));
1352}
1353
1354CXXDependentScopeMemberExpr::CXXDependentScopeMemberExpr(
1355    EmptyShell Empty, bool HasTemplateKWAndArgsInfo,
1356    bool HasFirstQualifierFoundInScope)
1357    : Expr(CXXDependentScopeMemberExprClass, Empty) {
1358  CXXDependentScopeMemberExprBits.HasTemplateKWAndArgsInfo =
1359      HasTemplateKWAndArgsInfo;
1360  CXXDependentScopeMemberExprBits.HasFirstQualifierFoundInScope =
1361      HasFirstQualifierFoundInScope;
1362}
1363
1364CXXDependentScopeMemberExpr *CXXDependentScopeMemberExpr::Create(
1365    const ASTContext &Ctx, Expr *Base, QualType BaseType, bool IsArrow,
1366    SourceLocation OperatorLoc, NestedNameSpecifierLoc QualifierLoc,
1367    SourceLocation TemplateKWLoc, NamedDecl *FirstQualifierFoundInScope,
1368    DeclarationNameInfo MemberNameInfo,
1369    const TemplateArgumentListInfo *TemplateArgs) {
1370  bool HasTemplateKWAndArgsInfo =
1371      (TemplateArgs != nullptr) || TemplateKWLoc.isValid();
1372  unsigned NumTemplateArgs = TemplateArgs ? TemplateArgs->size() : 0;
1373  bool HasFirstQualifierFoundInScope = FirstQualifierFoundInScope != nullptr;
1374
1375  unsigned Size = totalSizeToAlloc<ASTTemplateKWAndArgsInfo,
1376                                   TemplateArgumentLoc, NamedDecl *>(
1377      HasTemplateKWAndArgsInfo, NumTemplateArgs, HasFirstQualifierFoundInScope);
1378
1379  void *Mem = Ctx.Allocate(Size, alignof(CXXDependentScopeMemberExpr));
1380  return new (Mem) CXXDependentScopeMemberExpr(
1381      Ctx, Base, BaseType, IsArrow, OperatorLoc, QualifierLoc, TemplateKWLoc,
1382      FirstQualifierFoundInScope, MemberNameInfo, TemplateArgs);
1383}
1384
1385CXXDependentScopeMemberExpr *CXXDependentScopeMemberExpr::CreateEmpty(
1386    const ASTContext &Ctx, bool HasTemplateKWAndArgsInfo,
1387    unsigned NumTemplateArgs, bool HasFirstQualifierFoundInScope) {
1388  assert(NumTemplateArgs == 0 || HasTemplateKWAndArgsInfo);
1389
1390  unsigned Size = totalSizeToAlloc<ASTTemplateKWAndArgsInfo,
1391                                   TemplateArgumentLoc, NamedDecl *>(
1392      HasTemplateKWAndArgsInfo, NumTemplateArgs, HasFirstQualifierFoundInScope);
1393
1394  void *Mem = Ctx.Allocate(Size, alignof(CXXDependentScopeMemberExpr));
1395  return new (Mem) CXXDependentScopeMemberExpr(
1396      EmptyShell(), HasTemplateKWAndArgsInfo, HasFirstQualifierFoundInScope);
1397}
1398
1399static bool hasOnlyNonStaticMemberFunctions(UnresolvedSetIterator begin,
1400                                            UnresolvedSetIterator end) {
1401  do {
1402    NamedDecl *decl = *begin;
1403    if (isa<UnresolvedUsingValueDecl>(decl))
1404      return false;
1405
1406    // Unresolved member expressions should only contain methods and
1407    // method templates.
1408    if (cast<CXXMethodDecl>(decl->getUnderlyingDecl()->getAsFunction())
1409            ->isStatic())
1410      return false;
1411  } while (++begin != end);
1412
1413  return true;
1414}
1415
1416UnresolvedMemberExpr::UnresolvedMemberExpr(
1417    const ASTContext &Context, bool HasUnresolvedUsing, Expr *Base,
1418    QualType BaseType, bool IsArrow, SourceLocation OperatorLoc,
1419    NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc,
1420    const DeclarationNameInfo &MemberNameInfo,
1421    const TemplateArgumentListInfo *TemplateArgs, UnresolvedSetIterator Begin,
1422    UnresolvedSetIterator End)
1423    : OverloadExpr(
1424          UnresolvedMemberExprClass, Context, QualifierLoc, TemplateKWLoc,
1425          MemberNameInfo, TemplateArgs, Begin, End,
1426          // Dependent
1427          ((Base && Base->isTypeDependent()) || BaseType->isDependentType()),
1428          ((Base && Base->isInstantiationDependent()) ||
1429           BaseType->isInstantiationDependentType()),
1430          // Contains unexpanded parameter pack
1431          ((Base && Base->containsUnexpandedParameterPack()) ||
1432           BaseType->containsUnexpandedParameterPack())),
1433      Base(Base), BaseType(BaseType), OperatorLoc(OperatorLoc) {
1434  UnresolvedMemberExprBits.IsArrow = IsArrow;
1435  UnresolvedMemberExprBits.HasUnresolvedUsing = HasUnresolvedUsing;
1436
1437  // Check whether all of the members are non-static member functions,
1438  // and if so, mark give this bound-member type instead of overload type.
1439  if (hasOnlyNonStaticMemberFunctions(Begin, End))
1440    setType(Context.BoundMemberTy);
1441}
1442
1443UnresolvedMemberExpr::UnresolvedMemberExpr(EmptyShell Empty,
1444                                           unsigned NumResults,
1445                                           bool HasTemplateKWAndArgsInfo)
1446    : OverloadExpr(UnresolvedMemberExprClass, Empty, NumResults,
1447                   HasTemplateKWAndArgsInfo) {}
1448
1449bool UnresolvedMemberExpr::isImplicitAccess() const {
1450  if (!Base)
1451    return true;
1452
1453  return cast<Expr>(Base)->isImplicitCXXThis();
1454}
1455
1456UnresolvedMemberExpr *UnresolvedMemberExpr::Create(
1457    const ASTContext &Context, bool HasUnresolvedUsing, Expr *Base,
1458    QualType BaseType, bool IsArrow, SourceLocation OperatorLoc,
1459    NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc,
1460    const DeclarationNameInfo &MemberNameInfo,
1461    const TemplateArgumentListInfo *TemplateArgs, UnresolvedSetIterator Begin,
1462    UnresolvedSetIterator End) {
1463  unsigned NumResults = End - Begin;
1464  bool HasTemplateKWAndArgsInfo = TemplateArgs || TemplateKWLoc.isValid();
1465  unsigned NumTemplateArgs = TemplateArgs ? TemplateArgs->size() : 0;
1466  unsigned Size = totalSizeToAlloc<DeclAccessPair, ASTTemplateKWAndArgsInfo,
1467                                   TemplateArgumentLoc>(
1468      NumResults, HasTemplateKWAndArgsInfo, NumTemplateArgs);
1469  void *Mem = Context.Allocate(Size, alignof(UnresolvedMemberExpr));
1470  return new (Mem) UnresolvedMemberExpr(
1471      Context, HasUnresolvedUsing, Base, BaseType, IsArrow, OperatorLoc,
1472      QualifierLoc, TemplateKWLoc, MemberNameInfo, TemplateArgs, Begin, End);
1473}
1474
1475UnresolvedMemberExpr *UnresolvedMemberExpr::CreateEmpty(
1476    const ASTContext &Context, unsigned NumResults,
1477    bool HasTemplateKWAndArgsInfo, unsigned NumTemplateArgs) {
1478  assert(NumTemplateArgs == 0 || HasTemplateKWAndArgsInfo);
1479  unsigned Size = totalSizeToAlloc<DeclAccessPair, ASTTemplateKWAndArgsInfo,
1480                                   TemplateArgumentLoc>(
1481      NumResults, HasTemplateKWAndArgsInfo, NumTemplateArgs);
1482  void *Mem = Context.Allocate(Size, alignof(UnresolvedMemberExpr));
1483  return new (Mem)
1484      UnresolvedMemberExpr(EmptyShell(), NumResults, HasTemplateKWAndArgsInfo);
1485}
1486
1487CXXRecordDecl *UnresolvedMemberExpr::getNamingClass() {
1488  // Unlike for UnresolvedLookupExpr, it is very easy to re-derive this.
1489
1490  // If there was a nested name specifier, it names the naming class.
1491  // It can't be dependent: after all, we were actually able to do the
1492  // lookup.
1493  CXXRecordDecl *Record = nullptr;
1494  auto *NNS = getQualifier();
1495  if (NNS && NNS->getKind() != NestedNameSpecifier::Super) {
1496    const Type *T = getQualifier()->getAsType();
1497    assert(T && "qualifier in member expression does not name type");
1498    Record = T->getAsCXXRecordDecl();
1499    assert(Record && "qualifier in member expression does not name record");
1500  }
1501  // Otherwise the naming class must have been the base class.
1502  else {
1503    QualType BaseType = getBaseType().getNonReferenceType();
1504    if (isArrow())
1505      BaseType = BaseType->castAs<PointerType>()->getPointeeType();
1506
1507    Record = BaseType->getAsCXXRecordDecl();
1508    assert(Record && "base of member expression does not name record");
1509  }
1510
1511  return Record;
1512}
1513
1514SizeOfPackExpr *
1515SizeOfPackExpr::Create(ASTContext &Context, SourceLocation OperatorLoc,
1516                       NamedDecl *Pack, SourceLocation PackLoc,
1517                       SourceLocation RParenLoc,
1518                       Optional<unsigned> Length,
1519                       ArrayRef<TemplateArgument> PartialArgs) {
1520  void *Storage =
1521      Context.Allocate(totalSizeToAlloc<TemplateArgument>(PartialArgs.size()));
1522  return new (Storage) SizeOfPackExpr(Context.getSizeType(), OperatorLoc, Pack,
1523                                      PackLoc, RParenLoc, Length, PartialArgs);
1524}
1525
1526SizeOfPackExpr *SizeOfPackExpr::CreateDeserialized(ASTContext &Context,
1527                                                   unsigned NumPartialArgs) {
1528  void *Storage =
1529      Context.Allocate(totalSizeToAlloc<TemplateArgument>(NumPartialArgs));
1530  return new (Storage) SizeOfPackExpr(EmptyShell(), NumPartialArgs);
1531}
1532
1533SubstNonTypeTemplateParmPackExpr::SubstNonTypeTemplateParmPackExpr(
1534    QualType T, ExprValueKind ValueKind, NonTypeTemplateParmDecl *Param,
1535    SourceLocation NameLoc, const TemplateArgument &ArgPack)
1536    : Expr(SubstNonTypeTemplateParmPackExprClass, T, ValueKind, OK_Ordinary),
1537      Param(Param), Arguments(ArgPack.pack_begin()),
1538      NumArguments(ArgPack.pack_size()), NameLoc(NameLoc) {
1539  setDependence(ExprDependence::TypeValueInstantiation |
1540                ExprDependence::UnexpandedPack);
1541}
1542
1543TemplateArgument SubstNonTypeTemplateParmPackExpr::getArgumentPack() const {
1544  return TemplateArgument(llvm::makeArrayRef(Arguments, NumArguments));
1545}
1546
1547FunctionParmPackExpr::FunctionParmPackExpr(QualType T, VarDecl *ParamPack,
1548                                           SourceLocation NameLoc,
1549                                           unsigned NumParams,
1550                                           VarDecl *const *Params)
1551    : Expr(FunctionParmPackExprClass, T, VK_LValue, OK_Ordinary),
1552      ParamPack(ParamPack), NameLoc(NameLoc), NumParameters(NumParams) {
1553  if (Params)
1554    std::uninitialized_copy(Params, Params + NumParams,
1555                            getTrailingObjects<VarDecl *>());
1556  setDependence(ExprDependence::TypeValueInstantiation |
1557                ExprDependence::UnexpandedPack);
1558}
1559
1560FunctionParmPackExpr *
1561FunctionParmPackExpr::Create(const ASTContext &Context, QualType T,
1562                             VarDecl *ParamPack, SourceLocation NameLoc,
1563                             ArrayRef<VarDecl *> Params) {
1564  return new (Context.Allocate(totalSizeToAlloc<VarDecl *>(Params.size())))
1565      FunctionParmPackExpr(T, ParamPack, NameLoc, Params.size(), Params.data());
1566}
1567
1568FunctionParmPackExpr *
1569FunctionParmPackExpr::CreateEmpty(const ASTContext &Context,
1570                                  unsigned NumParams) {
1571  return new (Context.Allocate(totalSizeToAlloc<VarDecl *>(NumParams)))
1572      FunctionParmPackExpr(QualType(), nullptr, SourceLocation(), 0, nullptr);
1573}
1574
1575MaterializeTemporaryExpr::MaterializeTemporaryExpr(
1576    QualType T, Expr *Temporary, bool BoundToLvalueReference,
1577    LifetimeExtendedTemporaryDecl *MTD)
1578    : Expr(MaterializeTemporaryExprClass, T,
1579           BoundToLvalueReference ? VK_LValue : VK_XValue, OK_Ordinary) {
1580  if (MTD) {
1581    State = MTD;
1582    MTD->ExprWithTemporary = Temporary;
1583    return;
1584  }
1585  State = Temporary;
1586  setDependence(computeDependence(this));
1587}
1588
1589void MaterializeTemporaryExpr::setExtendingDecl(ValueDecl *ExtendedBy,
1590                                                unsigned ManglingNumber) {
1591  // We only need extra state if we have to remember more than just the Stmt.
1592  if (!ExtendedBy)
1593    return;
1594
1595  // We may need to allocate extra storage for the mangling number and the
1596  // extended-by ValueDecl.
1597  if (!State.is<LifetimeExtendedTemporaryDecl *>())
1598    State = LifetimeExtendedTemporaryDecl::Create(
1599        cast<Expr>(State.get<Stmt *>()), ExtendedBy, ManglingNumber);
1600
1601  auto ES = State.get<LifetimeExtendedTemporaryDecl *>();
1602  ES->ExtendingDecl = ExtendedBy;
1603  ES->ManglingNumber = ManglingNumber;
1604}
1605
1606TypeTraitExpr::TypeTraitExpr(QualType T, SourceLocation Loc, TypeTrait Kind,
1607                             ArrayRef<TypeSourceInfo *> Args,
1608                             SourceLocation RParenLoc, bool Value)
1609    : Expr(TypeTraitExprClass, T, VK_RValue, OK_Ordinary), Loc(Loc),
1610      RParenLoc(RParenLoc) {
1611  assert(Kind <= TT_Last && "invalid enum value!");
1612  TypeTraitExprBits.Kind = Kind;
1613  assert(static_cast<unsigned>(Kind) == TypeTraitExprBits.Kind &&
1614         "TypeTraitExprBits.Kind overflow!");
1615  TypeTraitExprBits.Value = Value;
1616  TypeTraitExprBits.NumArgs = Args.size();
1617  assert(Args.size() == TypeTraitExprBits.NumArgs &&
1618         "TypeTraitExprBits.NumArgs overflow!");
1619
1620  auto **ToArgs = getTrailingObjects<TypeSourceInfo *>();
1621  for (unsigned I = 0, N = Args.size(); I != N; ++I)
1622    ToArgs[I] = Args[I];
1623
1624  setDependence(computeDependence(this));
1625}
1626
1627TypeTraitExpr *TypeTraitExpr::Create(const ASTContext &C, QualType T,
1628                                     SourceLocation Loc,
1629                                     TypeTrait Kind,
1630                                     ArrayRef<TypeSourceInfo *> Args,
1631                                     SourceLocation RParenLoc,
1632                                     bool Value) {
1633  void *Mem = C.Allocate(totalSizeToAlloc<TypeSourceInfo *>(Args.size()));
1634  return new (Mem) TypeTraitExpr(T, Loc, Kind, Args, RParenLoc, Value);
1635}
1636
1637TypeTraitExpr *TypeTraitExpr::CreateDeserialized(const ASTContext &C,
1638                                                 unsigned NumArgs) {
1639  void *Mem = C.Allocate(totalSizeToAlloc<TypeSourceInfo *>(NumArgs));
1640  return new (Mem) TypeTraitExpr(EmptyShell());
1641}
1642
1643CUDAKernelCallExpr::CUDAKernelCallExpr(Expr *Fn, CallExpr *Config,
1644                                       ArrayRef<Expr *> Args, QualType Ty,
1645                                       ExprValueKind VK, SourceLocation RP,
1646                                       unsigned MinNumArgs)
1647    : CallExpr(CUDAKernelCallExprClass, Fn, /*PreArgs=*/Config, Args, Ty, VK,
1648               RP, MinNumArgs, NotADL) {}
1649
1650CUDAKernelCallExpr::CUDAKernelCallExpr(unsigned NumArgs, EmptyShell Empty)
1651    : CallExpr(CUDAKernelCallExprClass, /*NumPreArgs=*/END_PREARG, NumArgs,
1652               Empty) {}
1653
1654CUDAKernelCallExpr *
1655CUDAKernelCallExpr::Create(const ASTContext &Ctx, Expr *Fn, CallExpr *Config,
1656                           ArrayRef<Expr *> Args, QualType Ty, ExprValueKind VK,
1657                           SourceLocation RP, unsigned MinNumArgs) {
1658  // Allocate storage for the trailing objects of CallExpr.
1659  unsigned NumArgs = std::max<unsigned>(Args.size(), MinNumArgs);
1660  unsigned SizeOfTrailingObjects =
1661      CallExpr::sizeOfTrailingObjects(/*NumPreArgs=*/END_PREARG, NumArgs);
1662  void *Mem = Ctx.Allocate(sizeof(CUDAKernelCallExpr) + SizeOfTrailingObjects,
1663                           alignof(CUDAKernelCallExpr));
1664  return new (Mem) CUDAKernelCallExpr(Fn, Config, Args, Ty, VK, RP, MinNumArgs);
1665}
1666
1667CUDAKernelCallExpr *CUDAKernelCallExpr::CreateEmpty(const ASTContext &Ctx,
1668                                                    unsigned NumArgs,
1669                                                    EmptyShell Empty) {
1670  // Allocate storage for the trailing objects of CallExpr.
1671  unsigned SizeOfTrailingObjects =
1672      CallExpr::sizeOfTrailingObjects(/*NumPreArgs=*/END_PREARG, NumArgs);
1673  void *Mem = Ctx.Allocate(sizeof(CUDAKernelCallExpr) + SizeOfTrailingObjects,
1674                           alignof(CUDAKernelCallExpr));
1675  return new (Mem) CUDAKernelCallExpr(NumArgs, Empty);
1676}
1677