Path: blob/main/contrib/llvm-project/clang/lib/AST/ExprCXX.cpp
35259 views
//===- ExprCXX.cpp - (C++) Expression AST Node Implementation -------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// This file implements the subclesses of Expr class declared in ExprCXX.h9//10//===----------------------------------------------------------------------===//1112#include "clang/AST/ExprCXX.h"13#include "clang/AST/ASTContext.h"14#include "clang/AST/Attr.h"15#include "clang/AST/ComputeDependence.h"16#include "clang/AST/Decl.h"17#include "clang/AST/DeclAccessPair.h"18#include "clang/AST/DeclBase.h"19#include "clang/AST/DeclCXX.h"20#include "clang/AST/DeclTemplate.h"21#include "clang/AST/DeclarationName.h"22#include "clang/AST/DependenceFlags.h"23#include "clang/AST/Expr.h"24#include "clang/AST/LambdaCapture.h"25#include "clang/AST/NestedNameSpecifier.h"26#include "clang/AST/TemplateBase.h"27#include "clang/AST/Type.h"28#include "clang/AST/TypeLoc.h"29#include "clang/Basic/LLVM.h"30#include "clang/Basic/OperatorKinds.h"31#include "clang/Basic/SourceLocation.h"32#include "clang/Basic/Specifiers.h"33#include "llvm/ADT/ArrayRef.h"34#include "llvm/Support/Casting.h"35#include "llvm/Support/ErrorHandling.h"36#include <cassert>37#include <cstddef>38#include <cstring>39#include <memory>40#include <optional>4142using namespace clang;4344//===----------------------------------------------------------------------===//45// Child Iterators for iterating over subexpressions/substatements46//===----------------------------------------------------------------------===//4748bool CXXOperatorCallExpr::isInfixBinaryOp() const {49// An infix binary operator is any operator with two arguments other than50// operator() and operator[]. Note that none of these operators can have51// default arguments, so it suffices to check the number of argument52// expressions.53if (getNumArgs() != 2)54return false;5556switch (getOperator()) {57case OO_Call: case OO_Subscript:58return false;59default:60return true;61}62}6364CXXRewrittenBinaryOperator::DecomposedForm65CXXRewrittenBinaryOperator::getDecomposedForm() const {66DecomposedForm Result = {};67const Expr *E = getSemanticForm()->IgnoreImplicit();6869// Remove an outer '!' if it exists (only happens for a '!=' rewrite).70bool SkippedNot = false;71if (auto *NotEq = dyn_cast<UnaryOperator>(E)) {72assert(NotEq->getOpcode() == UO_LNot);73E = NotEq->getSubExpr()->IgnoreImplicit();74SkippedNot = true;75}7677// Decompose the outer binary operator.78if (auto *BO = dyn_cast<BinaryOperator>(E)) {79assert(!SkippedNot || BO->getOpcode() == BO_EQ);80Result.Opcode = SkippedNot ? BO_NE : BO->getOpcode();81Result.LHS = BO->getLHS();82Result.RHS = BO->getRHS();83Result.InnerBinOp = BO;84} else if (auto *BO = dyn_cast<CXXOperatorCallExpr>(E)) {85assert(!SkippedNot || BO->getOperator() == OO_EqualEqual);86assert(BO->isInfixBinaryOp());87switch (BO->getOperator()) {88case OO_Less: Result.Opcode = BO_LT; break;89case OO_LessEqual: Result.Opcode = BO_LE; break;90case OO_Greater: Result.Opcode = BO_GT; break;91case OO_GreaterEqual: Result.Opcode = BO_GE; break;92case OO_Spaceship: Result.Opcode = BO_Cmp; break;93case OO_EqualEqual: Result.Opcode = SkippedNot ? BO_NE : BO_EQ; break;94default: llvm_unreachable("unexpected binop in rewritten operator expr");95}96Result.LHS = BO->getArg(0);97Result.RHS = BO->getArg(1);98Result.InnerBinOp = BO;99} else {100llvm_unreachable("unexpected rewritten operator form");101}102103// Put the operands in the right order for == and !=, and canonicalize the104// <=> subexpression onto the LHS for all other forms.105if (isReversed())106std::swap(Result.LHS, Result.RHS);107108// If this isn't a spaceship rewrite, we're done.109if (Result.Opcode == BO_EQ || Result.Opcode == BO_NE)110return Result;111112// Otherwise, we expect a <=> to now be on the LHS.113E = Result.LHS->IgnoreUnlessSpelledInSource();114if (auto *BO = dyn_cast<BinaryOperator>(E)) {115assert(BO->getOpcode() == BO_Cmp);116Result.LHS = BO->getLHS();117Result.RHS = BO->getRHS();118Result.InnerBinOp = BO;119} else if (auto *BO = dyn_cast<CXXOperatorCallExpr>(E)) {120assert(BO->getOperator() == OO_Spaceship);121Result.LHS = BO->getArg(0);122Result.RHS = BO->getArg(1);123Result.InnerBinOp = BO;124} else {125llvm_unreachable("unexpected rewritten operator form");126}127128// Put the comparison operands in the right order.129if (isReversed())130std::swap(Result.LHS, Result.RHS);131return Result;132}133134bool CXXTypeidExpr::isPotentiallyEvaluated() const {135if (isTypeOperand())136return false;137138// C++11 [expr.typeid]p3:139// When typeid is applied to an expression other than a glvalue of140// polymorphic class type, [...] the expression is an unevaluated operand.141const Expr *E = getExprOperand();142if (const CXXRecordDecl *RD = E->getType()->getAsCXXRecordDecl())143if (RD->isPolymorphic() && E->isGLValue())144return true;145146return false;147}148149bool CXXTypeidExpr::isMostDerived(ASTContext &Context) const {150assert(!isTypeOperand() && "Cannot call isMostDerived for typeid(type)");151const Expr *E = getExprOperand()->IgnoreParenNoopCasts(Context);152if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) {153QualType Ty = DRE->getDecl()->getType();154if (!Ty->isPointerType() && !Ty->isReferenceType())155return true;156}157158return false;159}160161QualType CXXTypeidExpr::getTypeOperand(ASTContext &Context) const {162assert(isTypeOperand() && "Cannot call getTypeOperand for typeid(expr)");163Qualifiers Quals;164return Context.getUnqualifiedArrayType(165Operand.get<TypeSourceInfo *>()->getType().getNonReferenceType(), Quals);166}167168static bool isGLValueFromPointerDeref(const Expr *E) {169E = E->IgnoreParens();170171if (const auto *CE = dyn_cast<CastExpr>(E)) {172if (!CE->getSubExpr()->isGLValue())173return false;174return isGLValueFromPointerDeref(CE->getSubExpr());175}176177if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))178return isGLValueFromPointerDeref(OVE->getSourceExpr());179180if (const auto *BO = dyn_cast<BinaryOperator>(E))181if (BO->getOpcode() == BO_Comma)182return isGLValueFromPointerDeref(BO->getRHS());183184if (const auto *ACO = dyn_cast<AbstractConditionalOperator>(E))185return isGLValueFromPointerDeref(ACO->getTrueExpr()) ||186isGLValueFromPointerDeref(ACO->getFalseExpr());187188// C++11 [expr.sub]p1:189// The expression E1[E2] is identical (by definition) to *((E1)+(E2))190if (isa<ArraySubscriptExpr>(E))191return true;192193if (const auto *UO = dyn_cast<UnaryOperator>(E))194if (UO->getOpcode() == UO_Deref)195return true;196197return false;198}199200bool CXXTypeidExpr::hasNullCheck() const {201if (!isPotentiallyEvaluated())202return false;203204// C++ [expr.typeid]p2:205// If the glvalue expression is obtained by applying the unary * operator to206// a pointer and the pointer is a null pointer value, the typeid expression207// throws the std::bad_typeid exception.208//209// However, this paragraph's intent is not clear. We choose a very generous210// interpretation which implores us to consider comma operators, conditional211// operators, parentheses and other such constructs.212return isGLValueFromPointerDeref(getExprOperand());213}214215QualType CXXUuidofExpr::getTypeOperand(ASTContext &Context) const {216assert(isTypeOperand() && "Cannot call getTypeOperand for __uuidof(expr)");217Qualifiers Quals;218return Context.getUnqualifiedArrayType(219Operand.get<TypeSourceInfo *>()->getType().getNonReferenceType(), Quals);220}221222// CXXScalarValueInitExpr223SourceLocation CXXScalarValueInitExpr::getBeginLoc() const {224return TypeInfo ? TypeInfo->getTypeLoc().getBeginLoc() : getRParenLoc();225}226227// CXXNewExpr228CXXNewExpr::CXXNewExpr(bool IsGlobalNew, FunctionDecl *OperatorNew,229FunctionDecl *OperatorDelete, bool ShouldPassAlignment,230bool UsualArrayDeleteWantsSize,231ArrayRef<Expr *> PlacementArgs, SourceRange TypeIdParens,232std::optional<Expr *> ArraySize,233CXXNewInitializationStyle InitializationStyle,234Expr *Initializer, QualType Ty,235TypeSourceInfo *AllocatedTypeInfo, SourceRange Range,236SourceRange DirectInitRange)237: Expr(CXXNewExprClass, Ty, VK_PRValue, OK_Ordinary),238OperatorNew(OperatorNew), OperatorDelete(OperatorDelete),239AllocatedTypeInfo(AllocatedTypeInfo), Range(Range),240DirectInitRange(DirectInitRange) {241242assert((Initializer != nullptr ||243InitializationStyle == CXXNewInitializationStyle::None) &&244"Only CXXNewInitializationStyle::None can have no initializer!");245246CXXNewExprBits.IsGlobalNew = IsGlobalNew;247CXXNewExprBits.IsArray = ArraySize.has_value();248CXXNewExprBits.ShouldPassAlignment = ShouldPassAlignment;249CXXNewExprBits.UsualArrayDeleteWantsSize = UsualArrayDeleteWantsSize;250CXXNewExprBits.HasInitializer = Initializer != nullptr;251CXXNewExprBits.StoredInitializationStyle =252llvm::to_underlying(InitializationStyle);253bool IsParenTypeId = TypeIdParens.isValid();254CXXNewExprBits.IsParenTypeId = IsParenTypeId;255CXXNewExprBits.NumPlacementArgs = PlacementArgs.size();256257if (ArraySize)258getTrailingObjects<Stmt *>()[arraySizeOffset()] = *ArraySize;259if (Initializer)260getTrailingObjects<Stmt *>()[initExprOffset()] = Initializer;261for (unsigned I = 0; I != PlacementArgs.size(); ++I)262getTrailingObjects<Stmt *>()[placementNewArgsOffset() + I] =263PlacementArgs[I];264if (IsParenTypeId)265getTrailingObjects<SourceRange>()[0] = TypeIdParens;266267switch (getInitializationStyle()) {268case CXXNewInitializationStyle::Parens:269this->Range.setEnd(DirectInitRange.getEnd());270break;271case CXXNewInitializationStyle::Braces:272this->Range.setEnd(getInitializer()->getSourceRange().getEnd());273break;274default:275if (IsParenTypeId)276this->Range.setEnd(TypeIdParens.getEnd());277break;278}279280setDependence(computeDependence(this));281}282283CXXNewExpr::CXXNewExpr(EmptyShell Empty, bool IsArray,284unsigned NumPlacementArgs, bool IsParenTypeId)285: Expr(CXXNewExprClass, Empty) {286CXXNewExprBits.IsArray = IsArray;287CXXNewExprBits.NumPlacementArgs = NumPlacementArgs;288CXXNewExprBits.IsParenTypeId = IsParenTypeId;289}290291CXXNewExpr *CXXNewExpr::Create(292const ASTContext &Ctx, bool IsGlobalNew, FunctionDecl *OperatorNew,293FunctionDecl *OperatorDelete, bool ShouldPassAlignment,294bool UsualArrayDeleteWantsSize, ArrayRef<Expr *> PlacementArgs,295SourceRange TypeIdParens, std::optional<Expr *> ArraySize,296CXXNewInitializationStyle InitializationStyle, Expr *Initializer,297QualType Ty, TypeSourceInfo *AllocatedTypeInfo, SourceRange Range,298SourceRange DirectInitRange) {299bool IsArray = ArraySize.has_value();300bool HasInit = Initializer != nullptr;301unsigned NumPlacementArgs = PlacementArgs.size();302bool IsParenTypeId = TypeIdParens.isValid();303void *Mem =304Ctx.Allocate(totalSizeToAlloc<Stmt *, SourceRange>(305IsArray + HasInit + NumPlacementArgs, IsParenTypeId),306alignof(CXXNewExpr));307return new (Mem)308CXXNewExpr(IsGlobalNew, OperatorNew, OperatorDelete, ShouldPassAlignment,309UsualArrayDeleteWantsSize, PlacementArgs, TypeIdParens,310ArraySize, InitializationStyle, Initializer, Ty,311AllocatedTypeInfo, Range, DirectInitRange);312}313314CXXNewExpr *CXXNewExpr::CreateEmpty(const ASTContext &Ctx, bool IsArray,315bool HasInit, unsigned NumPlacementArgs,316bool IsParenTypeId) {317void *Mem =318Ctx.Allocate(totalSizeToAlloc<Stmt *, SourceRange>(319IsArray + HasInit + NumPlacementArgs, IsParenTypeId),320alignof(CXXNewExpr));321return new (Mem)322CXXNewExpr(EmptyShell(), IsArray, NumPlacementArgs, IsParenTypeId);323}324325bool CXXNewExpr::shouldNullCheckAllocation() const {326if (getOperatorNew()->getLangOpts().CheckNew)327return true;328return !getOperatorNew()->hasAttr<ReturnsNonNullAttr>() &&329getOperatorNew()330->getType()331->castAs<FunctionProtoType>()332->isNothrow() &&333!getOperatorNew()->isReservedGlobalPlacementOperator();334}335336// CXXDeleteExpr337QualType CXXDeleteExpr::getDestroyedType() const {338const Expr *Arg = getArgument();339340// For a destroying operator delete, we may have implicitly converted the341// pointer type to the type of the parameter of the 'operator delete'342// function.343while (const auto *ICE = dyn_cast<ImplicitCastExpr>(Arg)) {344if (ICE->getCastKind() == CK_DerivedToBase ||345ICE->getCastKind() == CK_UncheckedDerivedToBase ||346ICE->getCastKind() == CK_NoOp) {347assert((ICE->getCastKind() == CK_NoOp ||348getOperatorDelete()->isDestroyingOperatorDelete()) &&349"only a destroying operator delete can have a converted arg");350Arg = ICE->getSubExpr();351} else352break;353}354355// The type-to-delete may not be a pointer if it's a dependent type.356const QualType ArgType = Arg->getType();357358if (ArgType->isDependentType() && !ArgType->isPointerType())359return QualType();360361return ArgType->castAs<PointerType>()->getPointeeType();362}363364// CXXPseudoDestructorExpr365PseudoDestructorTypeStorage::PseudoDestructorTypeStorage(TypeSourceInfo *Info)366: Type(Info) {367Location = Info->getTypeLoc().getBeginLoc();368}369370CXXPseudoDestructorExpr::CXXPseudoDestructorExpr(371const ASTContext &Context, Expr *Base, bool isArrow,372SourceLocation OperatorLoc, NestedNameSpecifierLoc QualifierLoc,373TypeSourceInfo *ScopeType, SourceLocation ColonColonLoc,374SourceLocation TildeLoc, PseudoDestructorTypeStorage DestroyedType)375: Expr(CXXPseudoDestructorExprClass, Context.BoundMemberTy, VK_PRValue,376OK_Ordinary),377Base(static_cast<Stmt *>(Base)), IsArrow(isArrow),378OperatorLoc(OperatorLoc), QualifierLoc(QualifierLoc),379ScopeType(ScopeType), ColonColonLoc(ColonColonLoc), TildeLoc(TildeLoc),380DestroyedType(DestroyedType) {381setDependence(computeDependence(this));382}383384QualType CXXPseudoDestructorExpr::getDestroyedType() const {385if (TypeSourceInfo *TInfo = DestroyedType.getTypeSourceInfo())386return TInfo->getType();387388return QualType();389}390391SourceLocation CXXPseudoDestructorExpr::getEndLoc() const {392SourceLocation End = DestroyedType.getLocation();393if (TypeSourceInfo *TInfo = DestroyedType.getTypeSourceInfo())394End = TInfo->getTypeLoc().getSourceRange().getEnd();395return End;396}397398// UnresolvedLookupExpr399UnresolvedLookupExpr::UnresolvedLookupExpr(400const ASTContext &Context, CXXRecordDecl *NamingClass,401NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc,402const DeclarationNameInfo &NameInfo, bool RequiresADL,403const TemplateArgumentListInfo *TemplateArgs, UnresolvedSetIterator Begin,404UnresolvedSetIterator End, bool KnownDependent,405bool KnownInstantiationDependent)406: OverloadExpr(UnresolvedLookupExprClass, Context, QualifierLoc,407TemplateKWLoc, NameInfo, TemplateArgs, Begin, End,408KnownDependent, KnownInstantiationDependent, false),409NamingClass(NamingClass) {410UnresolvedLookupExprBits.RequiresADL = RequiresADL;411}412413UnresolvedLookupExpr::UnresolvedLookupExpr(EmptyShell Empty,414unsigned NumResults,415bool HasTemplateKWAndArgsInfo)416: OverloadExpr(UnresolvedLookupExprClass, Empty, NumResults,417HasTemplateKWAndArgsInfo) {}418419UnresolvedLookupExpr *UnresolvedLookupExpr::Create(420const ASTContext &Context, CXXRecordDecl *NamingClass,421NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo,422bool RequiresADL, UnresolvedSetIterator Begin, UnresolvedSetIterator End,423bool KnownDependent, bool KnownInstantiationDependent) {424unsigned NumResults = End - Begin;425unsigned Size = totalSizeToAlloc<DeclAccessPair, ASTTemplateKWAndArgsInfo,426TemplateArgumentLoc>(NumResults, 0, 0);427void *Mem = Context.Allocate(Size, alignof(UnresolvedLookupExpr));428return new (Mem) UnresolvedLookupExpr(429Context, NamingClass, QualifierLoc,430/*TemplateKWLoc=*/SourceLocation(), NameInfo, RequiresADL,431/*TemplateArgs=*/nullptr, Begin, End, KnownDependent,432KnownInstantiationDependent);433}434435UnresolvedLookupExpr *UnresolvedLookupExpr::Create(436const ASTContext &Context, CXXRecordDecl *NamingClass,437NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc,438const DeclarationNameInfo &NameInfo, bool RequiresADL,439const TemplateArgumentListInfo *Args, UnresolvedSetIterator Begin,440UnresolvedSetIterator End, bool KnownDependent,441bool KnownInstantiationDependent) {442unsigned NumResults = End - Begin;443bool HasTemplateKWAndArgsInfo = Args || TemplateKWLoc.isValid();444unsigned NumTemplateArgs = Args ? Args->size() : 0;445unsigned Size = totalSizeToAlloc<DeclAccessPair, ASTTemplateKWAndArgsInfo,446TemplateArgumentLoc>(447NumResults, HasTemplateKWAndArgsInfo, NumTemplateArgs);448void *Mem = Context.Allocate(Size, alignof(UnresolvedLookupExpr));449return new (Mem) UnresolvedLookupExpr(450Context, NamingClass, QualifierLoc, TemplateKWLoc, NameInfo, RequiresADL,451Args, Begin, End, KnownDependent, KnownInstantiationDependent);452}453454UnresolvedLookupExpr *UnresolvedLookupExpr::CreateEmpty(455const ASTContext &Context, unsigned NumResults,456bool HasTemplateKWAndArgsInfo, unsigned NumTemplateArgs) {457assert(NumTemplateArgs == 0 || HasTemplateKWAndArgsInfo);458unsigned Size = totalSizeToAlloc<DeclAccessPair, ASTTemplateKWAndArgsInfo,459TemplateArgumentLoc>(460NumResults, HasTemplateKWAndArgsInfo, NumTemplateArgs);461void *Mem = Context.Allocate(Size, alignof(UnresolvedLookupExpr));462return new (Mem)463UnresolvedLookupExpr(EmptyShell(), NumResults, HasTemplateKWAndArgsInfo);464}465466OverloadExpr::OverloadExpr(StmtClass SC, const ASTContext &Context,467NestedNameSpecifierLoc QualifierLoc,468SourceLocation TemplateKWLoc,469const DeclarationNameInfo &NameInfo,470const TemplateArgumentListInfo *TemplateArgs,471UnresolvedSetIterator Begin,472UnresolvedSetIterator End, bool KnownDependent,473bool KnownInstantiationDependent,474bool KnownContainsUnexpandedParameterPack)475: Expr(SC, Context.OverloadTy, VK_LValue, OK_Ordinary), NameInfo(NameInfo),476QualifierLoc(QualifierLoc) {477unsigned NumResults = End - Begin;478OverloadExprBits.NumResults = NumResults;479OverloadExprBits.HasTemplateKWAndArgsInfo =480(TemplateArgs != nullptr ) || TemplateKWLoc.isValid();481482if (NumResults) {483// Copy the results to the trailing array past UnresolvedLookupExpr484// or UnresolvedMemberExpr.485DeclAccessPair *Results = getTrailingResults();486memcpy(Results, Begin.I, NumResults * sizeof(DeclAccessPair));487}488489if (TemplateArgs) {490auto Deps = TemplateArgumentDependence::None;491getTrailingASTTemplateKWAndArgsInfo()->initializeFrom(492TemplateKWLoc, *TemplateArgs, getTrailingTemplateArgumentLoc(), Deps);493} else if (TemplateKWLoc.isValid()) {494getTrailingASTTemplateKWAndArgsInfo()->initializeFrom(TemplateKWLoc);495}496497setDependence(computeDependence(this, KnownDependent,498KnownInstantiationDependent,499KnownContainsUnexpandedParameterPack));500if (isTypeDependent())501setType(Context.DependentTy);502}503504OverloadExpr::OverloadExpr(StmtClass SC, EmptyShell Empty, unsigned NumResults,505bool HasTemplateKWAndArgsInfo)506: Expr(SC, Empty) {507OverloadExprBits.NumResults = NumResults;508OverloadExprBits.HasTemplateKWAndArgsInfo = HasTemplateKWAndArgsInfo;509}510511// DependentScopeDeclRefExpr512DependentScopeDeclRefExpr::DependentScopeDeclRefExpr(513QualType Ty, NestedNameSpecifierLoc QualifierLoc,514SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo,515const TemplateArgumentListInfo *Args)516: Expr(DependentScopeDeclRefExprClass, Ty, VK_LValue, OK_Ordinary),517QualifierLoc(QualifierLoc), NameInfo(NameInfo) {518DependentScopeDeclRefExprBits.HasTemplateKWAndArgsInfo =519(Args != nullptr) || TemplateKWLoc.isValid();520if (Args) {521auto Deps = TemplateArgumentDependence::None;522getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(523TemplateKWLoc, *Args, getTrailingObjects<TemplateArgumentLoc>(), Deps);524} else if (TemplateKWLoc.isValid()) {525getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(526TemplateKWLoc);527}528setDependence(computeDependence(this));529}530531DependentScopeDeclRefExpr *DependentScopeDeclRefExpr::Create(532const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc,533SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo,534const TemplateArgumentListInfo *Args) {535assert(QualifierLoc && "should be created for dependent qualifiers");536bool HasTemplateKWAndArgsInfo = Args || TemplateKWLoc.isValid();537std::size_t Size =538totalSizeToAlloc<ASTTemplateKWAndArgsInfo, TemplateArgumentLoc>(539HasTemplateKWAndArgsInfo, Args ? Args->size() : 0);540void *Mem = Context.Allocate(Size);541return new (Mem) DependentScopeDeclRefExpr(Context.DependentTy, QualifierLoc,542TemplateKWLoc, NameInfo, Args);543}544545DependentScopeDeclRefExpr *546DependentScopeDeclRefExpr::CreateEmpty(const ASTContext &Context,547bool HasTemplateKWAndArgsInfo,548unsigned NumTemplateArgs) {549assert(NumTemplateArgs == 0 || HasTemplateKWAndArgsInfo);550std::size_t Size =551totalSizeToAlloc<ASTTemplateKWAndArgsInfo, TemplateArgumentLoc>(552HasTemplateKWAndArgsInfo, NumTemplateArgs);553void *Mem = Context.Allocate(Size);554auto *E = new (Mem) DependentScopeDeclRefExpr(555QualType(), NestedNameSpecifierLoc(), SourceLocation(),556DeclarationNameInfo(), nullptr);557E->DependentScopeDeclRefExprBits.HasTemplateKWAndArgsInfo =558HasTemplateKWAndArgsInfo;559return E;560}561562SourceLocation CXXConstructExpr::getBeginLoc() const {563if (const auto *TOE = dyn_cast<CXXTemporaryObjectExpr>(this))564return TOE->getBeginLoc();565return getLocation();566}567568SourceLocation CXXConstructExpr::getEndLoc() const {569if (const auto *TOE = dyn_cast<CXXTemporaryObjectExpr>(this))570return TOE->getEndLoc();571572if (ParenOrBraceRange.isValid())573return ParenOrBraceRange.getEnd();574575SourceLocation End = getLocation();576for (unsigned I = getNumArgs(); I > 0; --I) {577const Expr *Arg = getArg(I-1);578if (!Arg->isDefaultArgument()) {579SourceLocation NewEnd = Arg->getEndLoc();580if (NewEnd.isValid()) {581End = NewEnd;582break;583}584}585}586587return End;588}589590CXXOperatorCallExpr::CXXOperatorCallExpr(OverloadedOperatorKind OpKind,591Expr *Fn, ArrayRef<Expr *> Args,592QualType Ty, ExprValueKind VK,593SourceLocation OperatorLoc,594FPOptionsOverride FPFeatures,595ADLCallKind UsesADL)596: CallExpr(CXXOperatorCallExprClass, Fn, /*PreArgs=*/{}, Args, Ty, VK,597OperatorLoc, FPFeatures, /*MinNumArgs=*/0, UsesADL) {598CXXOperatorCallExprBits.OperatorKind = OpKind;599assert(600(CXXOperatorCallExprBits.OperatorKind == static_cast<unsigned>(OpKind)) &&601"OperatorKind overflow!");602Range = getSourceRangeImpl();603}604605CXXOperatorCallExpr::CXXOperatorCallExpr(unsigned NumArgs, bool HasFPFeatures,606EmptyShell Empty)607: CallExpr(CXXOperatorCallExprClass, /*NumPreArgs=*/0, NumArgs,608HasFPFeatures, Empty) {}609610CXXOperatorCallExpr *611CXXOperatorCallExpr::Create(const ASTContext &Ctx,612OverloadedOperatorKind OpKind, Expr *Fn,613ArrayRef<Expr *> Args, QualType Ty,614ExprValueKind VK, SourceLocation OperatorLoc,615FPOptionsOverride FPFeatures, ADLCallKind UsesADL) {616// Allocate storage for the trailing objects of CallExpr.617unsigned NumArgs = Args.size();618unsigned SizeOfTrailingObjects = CallExpr::sizeOfTrailingObjects(619/*NumPreArgs=*/0, NumArgs, FPFeatures.requiresTrailingStorage());620void *Mem = Ctx.Allocate(sizeof(CXXOperatorCallExpr) + SizeOfTrailingObjects,621alignof(CXXOperatorCallExpr));622return new (Mem) CXXOperatorCallExpr(OpKind, Fn, Args, Ty, VK, OperatorLoc,623FPFeatures, UsesADL);624}625626CXXOperatorCallExpr *CXXOperatorCallExpr::CreateEmpty(const ASTContext &Ctx,627unsigned NumArgs,628bool HasFPFeatures,629EmptyShell Empty) {630// Allocate storage for the trailing objects of CallExpr.631unsigned SizeOfTrailingObjects =632CallExpr::sizeOfTrailingObjects(/*NumPreArgs=*/0, NumArgs, HasFPFeatures);633void *Mem = Ctx.Allocate(sizeof(CXXOperatorCallExpr) + SizeOfTrailingObjects,634alignof(CXXOperatorCallExpr));635return new (Mem) CXXOperatorCallExpr(NumArgs, HasFPFeatures, Empty);636}637638SourceRange CXXOperatorCallExpr::getSourceRangeImpl() const {639OverloadedOperatorKind Kind = getOperator();640if (Kind == OO_PlusPlus || Kind == OO_MinusMinus) {641if (getNumArgs() == 1)642// Prefix operator643return SourceRange(getOperatorLoc(), getArg(0)->getEndLoc());644else645// Postfix operator646return SourceRange(getArg(0)->getBeginLoc(), getOperatorLoc());647} else if (Kind == OO_Arrow) {648return SourceRange(getArg(0)->getBeginLoc(), getOperatorLoc());649} else if (Kind == OO_Call) {650return SourceRange(getArg(0)->getBeginLoc(), getRParenLoc());651} else if (Kind == OO_Subscript) {652return SourceRange(getArg(0)->getBeginLoc(), getRParenLoc());653} else if (getNumArgs() == 1) {654return SourceRange(getOperatorLoc(), getArg(0)->getEndLoc());655} else if (getNumArgs() == 2) {656return SourceRange(getArg(0)->getBeginLoc(), getArg(1)->getEndLoc());657} else {658return getOperatorLoc();659}660}661662CXXMemberCallExpr::CXXMemberCallExpr(Expr *Fn, ArrayRef<Expr *> Args,663QualType Ty, ExprValueKind VK,664SourceLocation RP,665FPOptionsOverride FPOptions,666unsigned MinNumArgs)667: CallExpr(CXXMemberCallExprClass, Fn, /*PreArgs=*/{}, Args, Ty, VK, RP,668FPOptions, MinNumArgs, NotADL) {}669670CXXMemberCallExpr::CXXMemberCallExpr(unsigned NumArgs, bool HasFPFeatures,671EmptyShell Empty)672: CallExpr(CXXMemberCallExprClass, /*NumPreArgs=*/0, NumArgs, HasFPFeatures,673Empty) {}674675CXXMemberCallExpr *CXXMemberCallExpr::Create(const ASTContext &Ctx, Expr *Fn,676ArrayRef<Expr *> Args, QualType Ty,677ExprValueKind VK,678SourceLocation RP,679FPOptionsOverride FPFeatures,680unsigned MinNumArgs) {681// Allocate storage for the trailing objects of CallExpr.682unsigned NumArgs = std::max<unsigned>(Args.size(), MinNumArgs);683unsigned SizeOfTrailingObjects = CallExpr::sizeOfTrailingObjects(684/*NumPreArgs=*/0, NumArgs, FPFeatures.requiresTrailingStorage());685void *Mem = Ctx.Allocate(sizeof(CXXMemberCallExpr) + SizeOfTrailingObjects,686alignof(CXXMemberCallExpr));687return new (Mem)688CXXMemberCallExpr(Fn, Args, Ty, VK, RP, FPFeatures, MinNumArgs);689}690691CXXMemberCallExpr *CXXMemberCallExpr::CreateEmpty(const ASTContext &Ctx,692unsigned NumArgs,693bool HasFPFeatures,694EmptyShell Empty) {695// Allocate storage for the trailing objects of CallExpr.696unsigned SizeOfTrailingObjects =697CallExpr::sizeOfTrailingObjects(/*NumPreArgs=*/0, NumArgs, HasFPFeatures);698void *Mem = Ctx.Allocate(sizeof(CXXMemberCallExpr) + SizeOfTrailingObjects,699alignof(CXXMemberCallExpr));700return new (Mem) CXXMemberCallExpr(NumArgs, HasFPFeatures, Empty);701}702703Expr *CXXMemberCallExpr::getImplicitObjectArgument() const {704const Expr *Callee = getCallee()->IgnoreParens();705if (const auto *MemExpr = dyn_cast<MemberExpr>(Callee))706return MemExpr->getBase();707if (const auto *BO = dyn_cast<BinaryOperator>(Callee))708if (BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI)709return BO->getLHS();710711// FIXME: Will eventually need to cope with member pointers.712return nullptr;713}714715QualType CXXMemberCallExpr::getObjectType() const {716QualType Ty = getImplicitObjectArgument()->getType();717if (Ty->isPointerType())718Ty = Ty->getPointeeType();719return Ty;720}721722CXXMethodDecl *CXXMemberCallExpr::getMethodDecl() const {723if (const auto *MemExpr = dyn_cast<MemberExpr>(getCallee()->IgnoreParens()))724return cast<CXXMethodDecl>(MemExpr->getMemberDecl());725726// FIXME: Will eventually need to cope with member pointers.727// NOTE: Update makeTailCallIfSwiftAsync on fixing this.728return nullptr;729}730731CXXRecordDecl *CXXMemberCallExpr::getRecordDecl() const {732Expr* ThisArg = getImplicitObjectArgument();733if (!ThisArg)734return nullptr;735736if (ThisArg->getType()->isAnyPointerType())737return ThisArg->getType()->getPointeeType()->getAsCXXRecordDecl();738739return ThisArg->getType()->getAsCXXRecordDecl();740}741742//===----------------------------------------------------------------------===//743// Named casts744//===----------------------------------------------------------------------===//745746/// getCastName - Get the name of the C++ cast being used, e.g.,747/// "static_cast", "dynamic_cast", "reinterpret_cast", or748/// "const_cast". The returned pointer must not be freed.749const char *CXXNamedCastExpr::getCastName() const {750switch (getStmtClass()) {751case CXXStaticCastExprClass: return "static_cast";752case CXXDynamicCastExprClass: return "dynamic_cast";753case CXXReinterpretCastExprClass: return "reinterpret_cast";754case CXXConstCastExprClass: return "const_cast";755case CXXAddrspaceCastExprClass: return "addrspace_cast";756default: return "<invalid cast>";757}758}759760CXXStaticCastExpr *761CXXStaticCastExpr::Create(const ASTContext &C, QualType T, ExprValueKind VK,762CastKind K, Expr *Op, const CXXCastPath *BasePath,763TypeSourceInfo *WrittenTy, FPOptionsOverride FPO,764SourceLocation L, SourceLocation RParenLoc,765SourceRange AngleBrackets) {766unsigned PathSize = (BasePath ? BasePath->size() : 0);767void *Buffer =768C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *, FPOptionsOverride>(769PathSize, FPO.requiresTrailingStorage()));770auto *E = new (Buffer) CXXStaticCastExpr(T, VK, K, Op, PathSize, WrittenTy,771FPO, L, RParenLoc, AngleBrackets);772if (PathSize)773std::uninitialized_copy_n(BasePath->data(), BasePath->size(),774E->getTrailingObjects<CXXBaseSpecifier *>());775return E;776}777778CXXStaticCastExpr *CXXStaticCastExpr::CreateEmpty(const ASTContext &C,779unsigned PathSize,780bool HasFPFeatures) {781void *Buffer =782C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *, FPOptionsOverride>(783PathSize, HasFPFeatures));784return new (Buffer) CXXStaticCastExpr(EmptyShell(), PathSize, HasFPFeatures);785}786787CXXDynamicCastExpr *CXXDynamicCastExpr::Create(const ASTContext &C, QualType T,788ExprValueKind VK,789CastKind K, Expr *Op,790const CXXCastPath *BasePath,791TypeSourceInfo *WrittenTy,792SourceLocation L,793SourceLocation RParenLoc,794SourceRange AngleBrackets) {795unsigned PathSize = (BasePath ? BasePath->size() : 0);796void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize));797auto *E =798new (Buffer) CXXDynamicCastExpr(T, VK, K, Op, PathSize, WrittenTy, L,799RParenLoc, AngleBrackets);800if (PathSize)801std::uninitialized_copy_n(BasePath->data(), BasePath->size(),802E->getTrailingObjects<CXXBaseSpecifier *>());803return E;804}805806CXXDynamicCastExpr *CXXDynamicCastExpr::CreateEmpty(const ASTContext &C,807unsigned PathSize) {808void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize));809return new (Buffer) CXXDynamicCastExpr(EmptyShell(), PathSize);810}811812/// isAlwaysNull - Return whether the result of the dynamic_cast is proven813/// to always be null. For example:814///815/// struct A { };816/// struct B final : A { };817/// struct C { };818///819/// C *f(B* b) { return dynamic_cast<C*>(b); }820bool CXXDynamicCastExpr::isAlwaysNull() const {821if (isValueDependent() || getCastKind() != CK_Dynamic)822return false;823824QualType SrcType = getSubExpr()->getType();825QualType DestType = getType();826827if (DestType->isVoidPointerType())828return false;829830if (DestType->isPointerType()) {831SrcType = SrcType->getPointeeType();832DestType = DestType->getPointeeType();833}834835const auto *SrcRD = SrcType->getAsCXXRecordDecl();836const auto *DestRD = DestType->getAsCXXRecordDecl();837assert(SrcRD && DestRD);838839if (SrcRD->isEffectivelyFinal()) {840assert(!SrcRD->isDerivedFrom(DestRD) &&841"upcasts should not use CK_Dynamic");842return true;843}844845if (DestRD->isEffectivelyFinal() && !DestRD->isDerivedFrom(SrcRD))846return true;847848return false;849}850851CXXReinterpretCastExpr *852CXXReinterpretCastExpr::Create(const ASTContext &C, QualType T,853ExprValueKind VK, CastKind K, Expr *Op,854const CXXCastPath *BasePath,855TypeSourceInfo *WrittenTy, SourceLocation L,856SourceLocation RParenLoc,857SourceRange AngleBrackets) {858unsigned PathSize = (BasePath ? BasePath->size() : 0);859void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize));860auto *E =861new (Buffer) CXXReinterpretCastExpr(T, VK, K, Op, PathSize, WrittenTy, L,862RParenLoc, AngleBrackets);863if (PathSize)864std::uninitialized_copy_n(BasePath->data(), BasePath->size(),865E->getTrailingObjects<CXXBaseSpecifier *>());866return E;867}868869CXXReinterpretCastExpr *870CXXReinterpretCastExpr::CreateEmpty(const ASTContext &C, unsigned PathSize) {871void *Buffer = C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *>(PathSize));872return new (Buffer) CXXReinterpretCastExpr(EmptyShell(), PathSize);873}874875CXXConstCastExpr *CXXConstCastExpr::Create(const ASTContext &C, QualType T,876ExprValueKind VK, Expr *Op,877TypeSourceInfo *WrittenTy,878SourceLocation L,879SourceLocation RParenLoc,880SourceRange AngleBrackets) {881return new (C) CXXConstCastExpr(T, VK, Op, WrittenTy, L, RParenLoc, AngleBrackets);882}883884CXXConstCastExpr *CXXConstCastExpr::CreateEmpty(const ASTContext &C) {885return new (C) CXXConstCastExpr(EmptyShell());886}887888CXXAddrspaceCastExpr *889CXXAddrspaceCastExpr::Create(const ASTContext &C, QualType T, ExprValueKind VK,890CastKind K, Expr *Op, TypeSourceInfo *WrittenTy,891SourceLocation L, SourceLocation RParenLoc,892SourceRange AngleBrackets) {893return new (C) CXXAddrspaceCastExpr(T, VK, K, Op, WrittenTy, L, RParenLoc,894AngleBrackets);895}896897CXXAddrspaceCastExpr *CXXAddrspaceCastExpr::CreateEmpty(const ASTContext &C) {898return new (C) CXXAddrspaceCastExpr(EmptyShell());899}900901CXXFunctionalCastExpr *CXXFunctionalCastExpr::Create(902const ASTContext &C, QualType T, ExprValueKind VK, TypeSourceInfo *Written,903CastKind K, Expr *Op, const CXXCastPath *BasePath, FPOptionsOverride FPO,904SourceLocation L, SourceLocation R) {905unsigned PathSize = (BasePath ? BasePath->size() : 0);906void *Buffer =907C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *, FPOptionsOverride>(908PathSize, FPO.requiresTrailingStorage()));909auto *E = new (Buffer)910CXXFunctionalCastExpr(T, VK, Written, K, Op, PathSize, FPO, L, R);911if (PathSize)912std::uninitialized_copy_n(BasePath->data(), BasePath->size(),913E->getTrailingObjects<CXXBaseSpecifier *>());914return E;915}916917CXXFunctionalCastExpr *CXXFunctionalCastExpr::CreateEmpty(const ASTContext &C,918unsigned PathSize,919bool HasFPFeatures) {920void *Buffer =921C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *, FPOptionsOverride>(922PathSize, HasFPFeatures));923return new (Buffer)924CXXFunctionalCastExpr(EmptyShell(), PathSize, HasFPFeatures);925}926927SourceLocation CXXFunctionalCastExpr::getBeginLoc() const {928return getTypeInfoAsWritten()->getTypeLoc().getBeginLoc();929}930931SourceLocation CXXFunctionalCastExpr::getEndLoc() const {932return RParenLoc.isValid() ? RParenLoc : getSubExpr()->getEndLoc();933}934935UserDefinedLiteral::UserDefinedLiteral(Expr *Fn, ArrayRef<Expr *> Args,936QualType Ty, ExprValueKind VK,937SourceLocation LitEndLoc,938SourceLocation SuffixLoc,939FPOptionsOverride FPFeatures)940: CallExpr(UserDefinedLiteralClass, Fn, /*PreArgs=*/{}, Args, Ty, VK,941LitEndLoc, FPFeatures, /*MinNumArgs=*/0, NotADL),942UDSuffixLoc(SuffixLoc) {}943944UserDefinedLiteral::UserDefinedLiteral(unsigned NumArgs, bool HasFPFeatures,945EmptyShell Empty)946: CallExpr(UserDefinedLiteralClass, /*NumPreArgs=*/0, NumArgs,947HasFPFeatures, Empty) {}948949UserDefinedLiteral *UserDefinedLiteral::Create(const ASTContext &Ctx, Expr *Fn,950ArrayRef<Expr *> Args,951QualType Ty, ExprValueKind VK,952SourceLocation LitEndLoc,953SourceLocation SuffixLoc,954FPOptionsOverride FPFeatures) {955// Allocate storage for the trailing objects of CallExpr.956unsigned NumArgs = Args.size();957unsigned SizeOfTrailingObjects = CallExpr::sizeOfTrailingObjects(958/*NumPreArgs=*/0, NumArgs, FPFeatures.requiresTrailingStorage());959void *Mem = Ctx.Allocate(sizeof(UserDefinedLiteral) + SizeOfTrailingObjects,960alignof(UserDefinedLiteral));961return new (Mem)962UserDefinedLiteral(Fn, Args, Ty, VK, LitEndLoc, SuffixLoc, FPFeatures);963}964965UserDefinedLiteral *UserDefinedLiteral::CreateEmpty(const ASTContext &Ctx,966unsigned NumArgs,967bool HasFPOptions,968EmptyShell Empty) {969// Allocate storage for the trailing objects of CallExpr.970unsigned SizeOfTrailingObjects =971CallExpr::sizeOfTrailingObjects(/*NumPreArgs=*/0, NumArgs, HasFPOptions);972void *Mem = Ctx.Allocate(sizeof(UserDefinedLiteral) + SizeOfTrailingObjects,973alignof(UserDefinedLiteral));974return new (Mem) UserDefinedLiteral(NumArgs, HasFPOptions, Empty);975}976977UserDefinedLiteral::LiteralOperatorKind978UserDefinedLiteral::getLiteralOperatorKind() const {979if (getNumArgs() == 0)980return LOK_Template;981if (getNumArgs() == 2)982return LOK_String;983984assert(getNumArgs() == 1 && "unexpected #args in literal operator call");985QualType ParamTy =986cast<FunctionDecl>(getCalleeDecl())->getParamDecl(0)->getType();987if (ParamTy->isPointerType())988return LOK_Raw;989if (ParamTy->isAnyCharacterType())990return LOK_Character;991if (ParamTy->isIntegerType())992return LOK_Integer;993if (ParamTy->isFloatingType())994return LOK_Floating;995996llvm_unreachable("unknown kind of literal operator");997}998999Expr *UserDefinedLiteral::getCookedLiteral() {1000#ifndef NDEBUG1001LiteralOperatorKind LOK = getLiteralOperatorKind();1002assert(LOK != LOK_Template && LOK != LOK_Raw && "not a cooked literal");1003#endif1004return getArg(0);1005}10061007const IdentifierInfo *UserDefinedLiteral::getUDSuffix() const {1008return cast<FunctionDecl>(getCalleeDecl())->getLiteralIdentifier();1009}10101011CXXDefaultArgExpr *CXXDefaultArgExpr::CreateEmpty(const ASTContext &C,1012bool HasRewrittenInit) {1013size_t Size = totalSizeToAlloc<Expr *>(HasRewrittenInit);1014auto *Mem = C.Allocate(Size, alignof(CXXDefaultArgExpr));1015return new (Mem) CXXDefaultArgExpr(EmptyShell(), HasRewrittenInit);1016}10171018CXXDefaultArgExpr *CXXDefaultArgExpr::Create(const ASTContext &C,1019SourceLocation Loc,1020ParmVarDecl *Param,1021Expr *RewrittenExpr,1022DeclContext *UsedContext) {1023size_t Size = totalSizeToAlloc<Expr *>(RewrittenExpr != nullptr);1024auto *Mem = C.Allocate(Size, alignof(CXXDefaultArgExpr));1025return new (Mem) CXXDefaultArgExpr(CXXDefaultArgExprClass, Loc, Param,1026RewrittenExpr, UsedContext);1027}10281029Expr *CXXDefaultArgExpr::getExpr() {1030return CXXDefaultArgExprBits.HasRewrittenInit ? getAdjustedRewrittenExpr()1031: getParam()->getDefaultArg();1032}10331034Expr *CXXDefaultArgExpr::getAdjustedRewrittenExpr() {1035assert(hasRewrittenInit() &&1036"expected this CXXDefaultArgExpr to have a rewritten init.");1037Expr *Init = getRewrittenExpr();1038if (auto *E = dyn_cast_if_present<FullExpr>(Init))1039if (!isa<ConstantExpr>(E))1040return E->getSubExpr();1041return Init;1042}10431044CXXDefaultInitExpr::CXXDefaultInitExpr(const ASTContext &Ctx,1045SourceLocation Loc, FieldDecl *Field,1046QualType Ty, DeclContext *UsedContext,1047Expr *RewrittenInitExpr)1048: Expr(CXXDefaultInitExprClass, Ty.getNonLValueExprType(Ctx),1049Ty->isLValueReferenceType() ? VK_LValue1050: Ty->isRValueReferenceType() ? VK_XValue1051: VK_PRValue,1052/*FIXME*/ OK_Ordinary),1053Field(Field), UsedContext(UsedContext) {1054CXXDefaultInitExprBits.Loc = Loc;1055CXXDefaultInitExprBits.HasRewrittenInit = RewrittenInitExpr != nullptr;10561057if (CXXDefaultInitExprBits.HasRewrittenInit)1058*getTrailingObjects<Expr *>() = RewrittenInitExpr;10591060assert(Field->hasInClassInitializer());10611062setDependence(computeDependence(this));1063}10641065CXXDefaultInitExpr *CXXDefaultInitExpr::CreateEmpty(const ASTContext &C,1066bool HasRewrittenInit) {1067size_t Size = totalSizeToAlloc<Expr *>(HasRewrittenInit);1068auto *Mem = C.Allocate(Size, alignof(CXXDefaultInitExpr));1069return new (Mem) CXXDefaultInitExpr(EmptyShell(), HasRewrittenInit);1070}10711072CXXDefaultInitExpr *CXXDefaultInitExpr::Create(const ASTContext &Ctx,1073SourceLocation Loc,1074FieldDecl *Field,1075DeclContext *UsedContext,1076Expr *RewrittenInitExpr) {10771078size_t Size = totalSizeToAlloc<Expr *>(RewrittenInitExpr != nullptr);1079auto *Mem = Ctx.Allocate(Size, alignof(CXXDefaultInitExpr));1080return new (Mem) CXXDefaultInitExpr(Ctx, Loc, Field, Field->getType(),1081UsedContext, RewrittenInitExpr);1082}10831084Expr *CXXDefaultInitExpr::getExpr() {1085assert(Field->getInClassInitializer() && "initializer hasn't been parsed");1086if (hasRewrittenInit())1087return getRewrittenExpr();10881089return Field->getInClassInitializer();1090}10911092CXXTemporary *CXXTemporary::Create(const ASTContext &C,1093const CXXDestructorDecl *Destructor) {1094return new (C) CXXTemporary(Destructor);1095}10961097CXXBindTemporaryExpr *CXXBindTemporaryExpr::Create(const ASTContext &C,1098CXXTemporary *Temp,1099Expr* SubExpr) {1100assert((SubExpr->getType()->isRecordType() ||1101SubExpr->getType()->isArrayType()) &&1102"Expression bound to a temporary must have record or array type!");11031104return new (C) CXXBindTemporaryExpr(Temp, SubExpr);1105}11061107CXXTemporaryObjectExpr::CXXTemporaryObjectExpr(1108CXXConstructorDecl *Cons, QualType Ty, TypeSourceInfo *TSI,1109ArrayRef<Expr *> Args, SourceRange ParenOrBraceRange,1110bool HadMultipleCandidates, bool ListInitialization,1111bool StdInitListInitialization, bool ZeroInitialization)1112: CXXConstructExpr(1113CXXTemporaryObjectExprClass, Ty, TSI->getTypeLoc().getBeginLoc(),1114Cons, /* Elidable=*/false, Args, HadMultipleCandidates,1115ListInitialization, StdInitListInitialization, ZeroInitialization,1116CXXConstructionKind::Complete, ParenOrBraceRange),1117TSI(TSI) {1118setDependence(computeDependence(this));1119}11201121CXXTemporaryObjectExpr::CXXTemporaryObjectExpr(EmptyShell Empty,1122unsigned NumArgs)1123: CXXConstructExpr(CXXTemporaryObjectExprClass, Empty, NumArgs) {}11241125CXXTemporaryObjectExpr *CXXTemporaryObjectExpr::Create(1126const ASTContext &Ctx, CXXConstructorDecl *Cons, QualType Ty,1127TypeSourceInfo *TSI, ArrayRef<Expr *> Args, SourceRange ParenOrBraceRange,1128bool HadMultipleCandidates, bool ListInitialization,1129bool StdInitListInitialization, bool ZeroInitialization) {1130unsigned SizeOfTrailingObjects = sizeOfTrailingObjects(Args.size());1131void *Mem =1132Ctx.Allocate(sizeof(CXXTemporaryObjectExpr) + SizeOfTrailingObjects,1133alignof(CXXTemporaryObjectExpr));1134return new (Mem) CXXTemporaryObjectExpr(1135Cons, Ty, TSI, Args, ParenOrBraceRange, HadMultipleCandidates,1136ListInitialization, StdInitListInitialization, ZeroInitialization);1137}11381139CXXTemporaryObjectExpr *1140CXXTemporaryObjectExpr::CreateEmpty(const ASTContext &Ctx, unsigned NumArgs) {1141unsigned SizeOfTrailingObjects = sizeOfTrailingObjects(NumArgs);1142void *Mem =1143Ctx.Allocate(sizeof(CXXTemporaryObjectExpr) + SizeOfTrailingObjects,1144alignof(CXXTemporaryObjectExpr));1145return new (Mem) CXXTemporaryObjectExpr(EmptyShell(), NumArgs);1146}11471148SourceLocation CXXTemporaryObjectExpr::getBeginLoc() const {1149return getTypeSourceInfo()->getTypeLoc().getBeginLoc();1150}11511152SourceLocation CXXTemporaryObjectExpr::getEndLoc() const {1153SourceLocation Loc = getParenOrBraceRange().getEnd();1154if (Loc.isInvalid() && getNumArgs())1155Loc = getArg(getNumArgs() - 1)->getEndLoc();1156return Loc;1157}11581159CXXConstructExpr *CXXConstructExpr::Create(1160const ASTContext &Ctx, QualType Ty, SourceLocation Loc,1161CXXConstructorDecl *Ctor, bool Elidable, ArrayRef<Expr *> Args,1162bool HadMultipleCandidates, bool ListInitialization,1163bool StdInitListInitialization, bool ZeroInitialization,1164CXXConstructionKind ConstructKind, SourceRange ParenOrBraceRange) {1165unsigned SizeOfTrailingObjects = sizeOfTrailingObjects(Args.size());1166void *Mem = Ctx.Allocate(sizeof(CXXConstructExpr) + SizeOfTrailingObjects,1167alignof(CXXConstructExpr));1168return new (Mem) CXXConstructExpr(1169CXXConstructExprClass, Ty, Loc, Ctor, Elidable, Args,1170HadMultipleCandidates, ListInitialization, StdInitListInitialization,1171ZeroInitialization, ConstructKind, ParenOrBraceRange);1172}11731174CXXConstructExpr *CXXConstructExpr::CreateEmpty(const ASTContext &Ctx,1175unsigned NumArgs) {1176unsigned SizeOfTrailingObjects = sizeOfTrailingObjects(NumArgs);1177void *Mem = Ctx.Allocate(sizeof(CXXConstructExpr) + SizeOfTrailingObjects,1178alignof(CXXConstructExpr));1179return new (Mem)1180CXXConstructExpr(CXXConstructExprClass, EmptyShell(), NumArgs);1181}11821183CXXConstructExpr::CXXConstructExpr(1184StmtClass SC, QualType Ty, SourceLocation Loc, CXXConstructorDecl *Ctor,1185bool Elidable, ArrayRef<Expr *> Args, bool HadMultipleCandidates,1186bool ListInitialization, bool StdInitListInitialization,1187bool ZeroInitialization, CXXConstructionKind ConstructKind,1188SourceRange ParenOrBraceRange)1189: Expr(SC, Ty, VK_PRValue, OK_Ordinary), Constructor(Ctor),1190ParenOrBraceRange(ParenOrBraceRange), NumArgs(Args.size()) {1191CXXConstructExprBits.Elidable = Elidable;1192CXXConstructExprBits.HadMultipleCandidates = HadMultipleCandidates;1193CXXConstructExprBits.ListInitialization = ListInitialization;1194CXXConstructExprBits.StdInitListInitialization = StdInitListInitialization;1195CXXConstructExprBits.ZeroInitialization = ZeroInitialization;1196CXXConstructExprBits.ConstructionKind = llvm::to_underlying(ConstructKind);1197CXXConstructExprBits.IsImmediateEscalating = false;1198CXXConstructExprBits.Loc = Loc;11991200Stmt **TrailingArgs = getTrailingArgs();1201for (unsigned I = 0, N = Args.size(); I != N; ++I) {1202assert(Args[I] && "NULL argument in CXXConstructExpr!");1203TrailingArgs[I] = Args[I];1204}12051206// CXXTemporaryObjectExpr does this itself after setting its TypeSourceInfo.1207if (SC == CXXConstructExprClass)1208setDependence(computeDependence(this));1209}12101211CXXConstructExpr::CXXConstructExpr(StmtClass SC, EmptyShell Empty,1212unsigned NumArgs)1213: Expr(SC, Empty), NumArgs(NumArgs) {}12141215LambdaCapture::LambdaCapture(SourceLocation Loc, bool Implicit,1216LambdaCaptureKind Kind, ValueDecl *Var,1217SourceLocation EllipsisLoc)1218: DeclAndBits(Var, 0), Loc(Loc), EllipsisLoc(EllipsisLoc) {1219unsigned Bits = 0;1220if (Implicit)1221Bits |= Capture_Implicit;12221223switch (Kind) {1224case LCK_StarThis:1225Bits |= Capture_ByCopy;1226[[fallthrough]];1227case LCK_This:1228assert(!Var && "'this' capture cannot have a variable!");1229Bits |= Capture_This;1230break;12311232case LCK_ByCopy:1233Bits |= Capture_ByCopy;1234[[fallthrough]];1235case LCK_ByRef:1236assert(Var && "capture must have a variable!");1237break;1238case LCK_VLAType:1239assert(!Var && "VLA type capture cannot have a variable!");1240break;1241}1242DeclAndBits.setInt(Bits);1243}12441245LambdaCaptureKind LambdaCapture::getCaptureKind() const {1246if (capturesVLAType())1247return LCK_VLAType;1248bool CapByCopy = DeclAndBits.getInt() & Capture_ByCopy;1249if (capturesThis())1250return CapByCopy ? LCK_StarThis : LCK_This;1251return CapByCopy ? LCK_ByCopy : LCK_ByRef;1252}12531254LambdaExpr::LambdaExpr(QualType T, SourceRange IntroducerRange,1255LambdaCaptureDefault CaptureDefault,1256SourceLocation CaptureDefaultLoc, bool ExplicitParams,1257bool ExplicitResultType, ArrayRef<Expr *> CaptureInits,1258SourceLocation ClosingBrace,1259bool ContainsUnexpandedParameterPack)1260: Expr(LambdaExprClass, T, VK_PRValue, OK_Ordinary),1261IntroducerRange(IntroducerRange), CaptureDefaultLoc(CaptureDefaultLoc),1262ClosingBrace(ClosingBrace) {1263LambdaExprBits.NumCaptures = CaptureInits.size();1264LambdaExprBits.CaptureDefault = CaptureDefault;1265LambdaExprBits.ExplicitParams = ExplicitParams;1266LambdaExprBits.ExplicitResultType = ExplicitResultType;12671268CXXRecordDecl *Class = getLambdaClass();1269(void)Class;1270assert(capture_size() == Class->capture_size() && "Wrong number of captures");1271assert(getCaptureDefault() == Class->getLambdaCaptureDefault());12721273// Copy initialization expressions for the non-static data members.1274Stmt **Stored = getStoredStmts();1275for (unsigned I = 0, N = CaptureInits.size(); I != N; ++I)1276*Stored++ = CaptureInits[I];12771278// Copy the body of the lambda.1279*Stored++ = getCallOperator()->getBody();12801281setDependence(computeDependence(this, ContainsUnexpandedParameterPack));1282}12831284LambdaExpr::LambdaExpr(EmptyShell Empty, unsigned NumCaptures)1285: Expr(LambdaExprClass, Empty) {1286LambdaExprBits.NumCaptures = NumCaptures;12871288// Initially don't initialize the body of the LambdaExpr. The body will1289// be lazily deserialized when needed.1290getStoredStmts()[NumCaptures] = nullptr; // Not one past the end.1291}12921293LambdaExpr *LambdaExpr::Create(const ASTContext &Context, CXXRecordDecl *Class,1294SourceRange IntroducerRange,1295LambdaCaptureDefault CaptureDefault,1296SourceLocation CaptureDefaultLoc,1297bool ExplicitParams, bool ExplicitResultType,1298ArrayRef<Expr *> CaptureInits,1299SourceLocation ClosingBrace,1300bool ContainsUnexpandedParameterPack) {1301// Determine the type of the expression (i.e., the type of the1302// function object we're creating).1303QualType T = Context.getTypeDeclType(Class);13041305unsigned Size = totalSizeToAlloc<Stmt *>(CaptureInits.size() + 1);1306void *Mem = Context.Allocate(Size);1307return new (Mem)1308LambdaExpr(T, IntroducerRange, CaptureDefault, CaptureDefaultLoc,1309ExplicitParams, ExplicitResultType, CaptureInits, ClosingBrace,1310ContainsUnexpandedParameterPack);1311}13121313LambdaExpr *LambdaExpr::CreateDeserialized(const ASTContext &C,1314unsigned NumCaptures) {1315unsigned Size = totalSizeToAlloc<Stmt *>(NumCaptures + 1);1316void *Mem = C.Allocate(Size);1317return new (Mem) LambdaExpr(EmptyShell(), NumCaptures);1318}13191320void LambdaExpr::initBodyIfNeeded() const {1321if (!getStoredStmts()[capture_size()]) {1322auto *This = const_cast<LambdaExpr *>(this);1323This->getStoredStmts()[capture_size()] = getCallOperator()->getBody();1324}1325}13261327Stmt *LambdaExpr::getBody() const {1328initBodyIfNeeded();1329return getStoredStmts()[capture_size()];1330}13311332const CompoundStmt *LambdaExpr::getCompoundStmtBody() const {1333Stmt *Body = getBody();1334if (const auto *CoroBody = dyn_cast<CoroutineBodyStmt>(Body))1335return cast<CompoundStmt>(CoroBody->getBody());1336return cast<CompoundStmt>(Body);1337}13381339bool LambdaExpr::isInitCapture(const LambdaCapture *C) const {1340return C->capturesVariable() && C->getCapturedVar()->isInitCapture() &&1341getCallOperator() == C->getCapturedVar()->getDeclContext();1342}13431344LambdaExpr::capture_iterator LambdaExpr::capture_begin() const {1345return getLambdaClass()->captures_begin();1346}13471348LambdaExpr::capture_iterator LambdaExpr::capture_end() const {1349return getLambdaClass()->captures_end();1350}13511352LambdaExpr::capture_range LambdaExpr::captures() const {1353return capture_range(capture_begin(), capture_end());1354}13551356LambdaExpr::capture_iterator LambdaExpr::explicit_capture_begin() const {1357return capture_begin();1358}13591360LambdaExpr::capture_iterator LambdaExpr::explicit_capture_end() const {1361return capture_begin() +1362getLambdaClass()->getLambdaData().NumExplicitCaptures;1363}13641365LambdaExpr::capture_range LambdaExpr::explicit_captures() const {1366return capture_range(explicit_capture_begin(), explicit_capture_end());1367}13681369LambdaExpr::capture_iterator LambdaExpr::implicit_capture_begin() const {1370return explicit_capture_end();1371}13721373LambdaExpr::capture_iterator LambdaExpr::implicit_capture_end() const {1374return capture_end();1375}13761377LambdaExpr::capture_range LambdaExpr::implicit_captures() const {1378return capture_range(implicit_capture_begin(), implicit_capture_end());1379}13801381CXXRecordDecl *LambdaExpr::getLambdaClass() const {1382return getType()->getAsCXXRecordDecl();1383}13841385CXXMethodDecl *LambdaExpr::getCallOperator() const {1386CXXRecordDecl *Record = getLambdaClass();1387return Record->getLambdaCallOperator();1388}13891390FunctionTemplateDecl *LambdaExpr::getDependentCallOperator() const {1391CXXRecordDecl *Record = getLambdaClass();1392return Record->getDependentLambdaCallOperator();1393}13941395TemplateParameterList *LambdaExpr::getTemplateParameterList() const {1396CXXRecordDecl *Record = getLambdaClass();1397return Record->getGenericLambdaTemplateParameterList();1398}13991400ArrayRef<NamedDecl *> LambdaExpr::getExplicitTemplateParameters() const {1401const CXXRecordDecl *Record = getLambdaClass();1402return Record->getLambdaExplicitTemplateParameters();1403}14041405Expr *LambdaExpr::getTrailingRequiresClause() const {1406return getCallOperator()->getTrailingRequiresClause();1407}14081409bool LambdaExpr::isMutable() const { return !getCallOperator()->isConst(); }14101411LambdaExpr::child_range LambdaExpr::children() {1412initBodyIfNeeded();1413return child_range(getStoredStmts(), getStoredStmts() + capture_size() + 1);1414}14151416LambdaExpr::const_child_range LambdaExpr::children() const {1417initBodyIfNeeded();1418return const_child_range(getStoredStmts(),1419getStoredStmts() + capture_size() + 1);1420}14211422ExprWithCleanups::ExprWithCleanups(Expr *subexpr,1423bool CleanupsHaveSideEffects,1424ArrayRef<CleanupObject> objects)1425: FullExpr(ExprWithCleanupsClass, subexpr) {1426ExprWithCleanupsBits.CleanupsHaveSideEffects = CleanupsHaveSideEffects;1427ExprWithCleanupsBits.NumObjects = objects.size();1428for (unsigned i = 0, e = objects.size(); i != e; ++i)1429getTrailingObjects<CleanupObject>()[i] = objects[i];1430}14311432ExprWithCleanups *ExprWithCleanups::Create(const ASTContext &C, Expr *subexpr,1433bool CleanupsHaveSideEffects,1434ArrayRef<CleanupObject> objects) {1435void *buffer = C.Allocate(totalSizeToAlloc<CleanupObject>(objects.size()),1436alignof(ExprWithCleanups));1437return new (buffer)1438ExprWithCleanups(subexpr, CleanupsHaveSideEffects, objects);1439}14401441ExprWithCleanups::ExprWithCleanups(EmptyShell empty, unsigned numObjects)1442: FullExpr(ExprWithCleanupsClass, empty) {1443ExprWithCleanupsBits.NumObjects = numObjects;1444}14451446ExprWithCleanups *ExprWithCleanups::Create(const ASTContext &C,1447EmptyShell empty,1448unsigned numObjects) {1449void *buffer = C.Allocate(totalSizeToAlloc<CleanupObject>(numObjects),1450alignof(ExprWithCleanups));1451return new (buffer) ExprWithCleanups(empty, numObjects);1452}14531454CXXUnresolvedConstructExpr::CXXUnresolvedConstructExpr(1455QualType T, TypeSourceInfo *TSI, SourceLocation LParenLoc,1456ArrayRef<Expr *> Args, SourceLocation RParenLoc, bool IsListInit)1457: Expr(CXXUnresolvedConstructExprClass, T,1458(TSI->getType()->isLValueReferenceType() ? VK_LValue1459: TSI->getType()->isRValueReferenceType() ? VK_XValue1460: VK_PRValue),1461OK_Ordinary),1462TypeAndInitForm(TSI, IsListInit), LParenLoc(LParenLoc),1463RParenLoc(RParenLoc) {1464CXXUnresolvedConstructExprBits.NumArgs = Args.size();1465auto **StoredArgs = getTrailingObjects<Expr *>();1466for (unsigned I = 0; I != Args.size(); ++I)1467StoredArgs[I] = Args[I];1468setDependence(computeDependence(this));1469}14701471CXXUnresolvedConstructExpr *CXXUnresolvedConstructExpr::Create(1472const ASTContext &Context, QualType T, TypeSourceInfo *TSI,1473SourceLocation LParenLoc, ArrayRef<Expr *> Args, SourceLocation RParenLoc,1474bool IsListInit) {1475void *Mem = Context.Allocate(totalSizeToAlloc<Expr *>(Args.size()));1476return new (Mem) CXXUnresolvedConstructExpr(T, TSI, LParenLoc, Args,1477RParenLoc, IsListInit);1478}14791480CXXUnresolvedConstructExpr *1481CXXUnresolvedConstructExpr::CreateEmpty(const ASTContext &Context,1482unsigned NumArgs) {1483void *Mem = Context.Allocate(totalSizeToAlloc<Expr *>(NumArgs));1484return new (Mem) CXXUnresolvedConstructExpr(EmptyShell(), NumArgs);1485}14861487SourceLocation CXXUnresolvedConstructExpr::getBeginLoc() const {1488return TypeAndInitForm.getPointer()->getTypeLoc().getBeginLoc();1489}14901491CXXDependentScopeMemberExpr::CXXDependentScopeMemberExpr(1492const ASTContext &Ctx, Expr *Base, QualType BaseType, bool IsArrow,1493SourceLocation OperatorLoc, NestedNameSpecifierLoc QualifierLoc,1494SourceLocation TemplateKWLoc, NamedDecl *FirstQualifierFoundInScope,1495DeclarationNameInfo MemberNameInfo,1496const TemplateArgumentListInfo *TemplateArgs)1497: Expr(CXXDependentScopeMemberExprClass, Ctx.DependentTy, VK_LValue,1498OK_Ordinary),1499Base(Base), BaseType(BaseType), QualifierLoc(QualifierLoc),1500MemberNameInfo(MemberNameInfo) {1501CXXDependentScopeMemberExprBits.IsArrow = IsArrow;1502CXXDependentScopeMemberExprBits.HasTemplateKWAndArgsInfo =1503(TemplateArgs != nullptr) || TemplateKWLoc.isValid();1504CXXDependentScopeMemberExprBits.HasFirstQualifierFoundInScope =1505FirstQualifierFoundInScope != nullptr;1506CXXDependentScopeMemberExprBits.OperatorLoc = OperatorLoc;15071508if (TemplateArgs) {1509auto Deps = TemplateArgumentDependence::None;1510getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(1511TemplateKWLoc, *TemplateArgs, getTrailingObjects<TemplateArgumentLoc>(),1512Deps);1513} else if (TemplateKWLoc.isValid()) {1514getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(1515TemplateKWLoc);1516}15171518if (hasFirstQualifierFoundInScope())1519*getTrailingObjects<NamedDecl *>() = FirstQualifierFoundInScope;1520setDependence(computeDependence(this));1521}15221523CXXDependentScopeMemberExpr::CXXDependentScopeMemberExpr(1524EmptyShell Empty, bool HasTemplateKWAndArgsInfo,1525bool HasFirstQualifierFoundInScope)1526: Expr(CXXDependentScopeMemberExprClass, Empty) {1527CXXDependentScopeMemberExprBits.HasTemplateKWAndArgsInfo =1528HasTemplateKWAndArgsInfo;1529CXXDependentScopeMemberExprBits.HasFirstQualifierFoundInScope =1530HasFirstQualifierFoundInScope;1531}15321533CXXDependentScopeMemberExpr *CXXDependentScopeMemberExpr::Create(1534const ASTContext &Ctx, Expr *Base, QualType BaseType, bool IsArrow,1535SourceLocation OperatorLoc, NestedNameSpecifierLoc QualifierLoc,1536SourceLocation TemplateKWLoc, NamedDecl *FirstQualifierFoundInScope,1537DeclarationNameInfo MemberNameInfo,1538const TemplateArgumentListInfo *TemplateArgs) {1539bool HasTemplateKWAndArgsInfo =1540(TemplateArgs != nullptr) || TemplateKWLoc.isValid();1541unsigned NumTemplateArgs = TemplateArgs ? TemplateArgs->size() : 0;1542bool HasFirstQualifierFoundInScope = FirstQualifierFoundInScope != nullptr;15431544unsigned Size = totalSizeToAlloc<ASTTemplateKWAndArgsInfo,1545TemplateArgumentLoc, NamedDecl *>(1546HasTemplateKWAndArgsInfo, NumTemplateArgs, HasFirstQualifierFoundInScope);15471548void *Mem = Ctx.Allocate(Size, alignof(CXXDependentScopeMemberExpr));1549return new (Mem) CXXDependentScopeMemberExpr(1550Ctx, Base, BaseType, IsArrow, OperatorLoc, QualifierLoc, TemplateKWLoc,1551FirstQualifierFoundInScope, MemberNameInfo, TemplateArgs);1552}15531554CXXDependentScopeMemberExpr *CXXDependentScopeMemberExpr::CreateEmpty(1555const ASTContext &Ctx, bool HasTemplateKWAndArgsInfo,1556unsigned NumTemplateArgs, bool HasFirstQualifierFoundInScope) {1557assert(NumTemplateArgs == 0 || HasTemplateKWAndArgsInfo);15581559unsigned Size = totalSizeToAlloc<ASTTemplateKWAndArgsInfo,1560TemplateArgumentLoc, NamedDecl *>(1561HasTemplateKWAndArgsInfo, NumTemplateArgs, HasFirstQualifierFoundInScope);15621563void *Mem = Ctx.Allocate(Size, alignof(CXXDependentScopeMemberExpr));1564return new (Mem) CXXDependentScopeMemberExpr(1565EmptyShell(), HasTemplateKWAndArgsInfo, HasFirstQualifierFoundInScope);1566}15671568CXXThisExpr *CXXThisExpr::Create(const ASTContext &Ctx, SourceLocation L,1569QualType Ty, bool IsImplicit) {1570return new (Ctx) CXXThisExpr(L, Ty, IsImplicit,1571Ctx.getLangOpts().HLSL ? VK_LValue : VK_PRValue);1572}15731574CXXThisExpr *CXXThisExpr::CreateEmpty(const ASTContext &Ctx) {1575return new (Ctx) CXXThisExpr(EmptyShell());1576}15771578static bool hasOnlyNonStaticMemberFunctions(UnresolvedSetIterator begin,1579UnresolvedSetIterator end) {1580do {1581NamedDecl *decl = *begin;1582if (isa<UnresolvedUsingValueDecl>(decl))1583return false;15841585// Unresolved member expressions should only contain methods and1586// method templates.1587if (cast<CXXMethodDecl>(decl->getUnderlyingDecl()->getAsFunction())1588->isStatic())1589return false;1590} while (++begin != end);15911592return true;1593}15941595UnresolvedMemberExpr::UnresolvedMemberExpr(1596const ASTContext &Context, bool HasUnresolvedUsing, Expr *Base,1597QualType BaseType, bool IsArrow, SourceLocation OperatorLoc,1598NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc,1599const DeclarationNameInfo &MemberNameInfo,1600const TemplateArgumentListInfo *TemplateArgs, UnresolvedSetIterator Begin,1601UnresolvedSetIterator End)1602: OverloadExpr(1603UnresolvedMemberExprClass, Context, QualifierLoc, TemplateKWLoc,1604MemberNameInfo, TemplateArgs, Begin, End,1605// Dependent1606((Base && Base->isTypeDependent()) || BaseType->isDependentType()),1607((Base && Base->isInstantiationDependent()) ||1608BaseType->isInstantiationDependentType()),1609// Contains unexpanded parameter pack1610((Base && Base->containsUnexpandedParameterPack()) ||1611BaseType->containsUnexpandedParameterPack())),1612Base(Base), BaseType(BaseType), OperatorLoc(OperatorLoc) {1613UnresolvedMemberExprBits.IsArrow = IsArrow;1614UnresolvedMemberExprBits.HasUnresolvedUsing = HasUnresolvedUsing;16151616// Check whether all of the members are non-static member functions,1617// and if so, mark give this bound-member type instead of overload type.1618if (hasOnlyNonStaticMemberFunctions(Begin, End))1619setType(Context.BoundMemberTy);1620}16211622UnresolvedMemberExpr::UnresolvedMemberExpr(EmptyShell Empty,1623unsigned NumResults,1624bool HasTemplateKWAndArgsInfo)1625: OverloadExpr(UnresolvedMemberExprClass, Empty, NumResults,1626HasTemplateKWAndArgsInfo) {}16271628bool UnresolvedMemberExpr::isImplicitAccess() const {1629if (!Base)1630return true;16311632return cast<Expr>(Base)->isImplicitCXXThis();1633}16341635UnresolvedMemberExpr *UnresolvedMemberExpr::Create(1636const ASTContext &Context, bool HasUnresolvedUsing, Expr *Base,1637QualType BaseType, bool IsArrow, SourceLocation OperatorLoc,1638NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc,1639const DeclarationNameInfo &MemberNameInfo,1640const TemplateArgumentListInfo *TemplateArgs, UnresolvedSetIterator Begin,1641UnresolvedSetIterator End) {1642unsigned NumResults = End - Begin;1643bool HasTemplateKWAndArgsInfo = TemplateArgs || TemplateKWLoc.isValid();1644unsigned NumTemplateArgs = TemplateArgs ? TemplateArgs->size() : 0;1645unsigned Size = totalSizeToAlloc<DeclAccessPair, ASTTemplateKWAndArgsInfo,1646TemplateArgumentLoc>(1647NumResults, HasTemplateKWAndArgsInfo, NumTemplateArgs);1648void *Mem = Context.Allocate(Size, alignof(UnresolvedMemberExpr));1649return new (Mem) UnresolvedMemberExpr(1650Context, HasUnresolvedUsing, Base, BaseType, IsArrow, OperatorLoc,1651QualifierLoc, TemplateKWLoc, MemberNameInfo, TemplateArgs, Begin, End);1652}16531654UnresolvedMemberExpr *UnresolvedMemberExpr::CreateEmpty(1655const ASTContext &Context, unsigned NumResults,1656bool HasTemplateKWAndArgsInfo, unsigned NumTemplateArgs) {1657assert(NumTemplateArgs == 0 || HasTemplateKWAndArgsInfo);1658unsigned Size = totalSizeToAlloc<DeclAccessPair, ASTTemplateKWAndArgsInfo,1659TemplateArgumentLoc>(1660NumResults, HasTemplateKWAndArgsInfo, NumTemplateArgs);1661void *Mem = Context.Allocate(Size, alignof(UnresolvedMemberExpr));1662return new (Mem)1663UnresolvedMemberExpr(EmptyShell(), NumResults, HasTemplateKWAndArgsInfo);1664}16651666CXXRecordDecl *UnresolvedMemberExpr::getNamingClass() {1667// Unlike for UnresolvedLookupExpr, it is very easy to re-derive this.16681669// If there was a nested name specifier, it names the naming class.1670// It can't be dependent: after all, we were actually able to do the1671// lookup.1672CXXRecordDecl *Record = nullptr;1673auto *NNS = getQualifier();1674if (NNS && NNS->getKind() != NestedNameSpecifier::Super) {1675const Type *T = getQualifier()->getAsType();1676assert(T && "qualifier in member expression does not name type");1677Record = T->getAsCXXRecordDecl();1678assert(Record && "qualifier in member expression does not name record");1679}1680// Otherwise the naming class must have been the base class.1681else {1682QualType BaseType = getBaseType().getNonReferenceType();1683if (isArrow())1684BaseType = BaseType->castAs<PointerType>()->getPointeeType();16851686Record = BaseType->getAsCXXRecordDecl();1687assert(Record && "base of member expression does not name record");1688}16891690return Record;1691}16921693SizeOfPackExpr *SizeOfPackExpr::Create(ASTContext &Context,1694SourceLocation OperatorLoc,1695NamedDecl *Pack, SourceLocation PackLoc,1696SourceLocation RParenLoc,1697std::optional<unsigned> Length,1698ArrayRef<TemplateArgument> PartialArgs) {1699void *Storage =1700Context.Allocate(totalSizeToAlloc<TemplateArgument>(PartialArgs.size()));1701return new (Storage) SizeOfPackExpr(Context.getSizeType(), OperatorLoc, Pack,1702PackLoc, RParenLoc, Length, PartialArgs);1703}17041705SizeOfPackExpr *SizeOfPackExpr::CreateDeserialized(ASTContext &Context,1706unsigned NumPartialArgs) {1707void *Storage =1708Context.Allocate(totalSizeToAlloc<TemplateArgument>(NumPartialArgs));1709return new (Storage) SizeOfPackExpr(EmptyShell(), NumPartialArgs);1710}17111712NonTypeTemplateParmDecl *SubstNonTypeTemplateParmExpr::getParameter() const {1713return cast<NonTypeTemplateParmDecl>(1714getReplacedTemplateParameterList(getAssociatedDecl())->asArray()[Index]);1715}17161717PackIndexingExpr *PackIndexingExpr::Create(1718ASTContext &Context, SourceLocation EllipsisLoc, SourceLocation RSquareLoc,1719Expr *PackIdExpr, Expr *IndexExpr, std::optional<int64_t> Index,1720ArrayRef<Expr *> SubstitutedExprs, bool ExpandedToEmptyPack) {1721QualType Type;1722if (Index && !SubstitutedExprs.empty())1723Type = SubstitutedExprs[*Index]->getType();1724else1725Type = Context.DependentTy;17261727void *Storage =1728Context.Allocate(totalSizeToAlloc<Expr *>(SubstitutedExprs.size()));1729return new (Storage)1730PackIndexingExpr(Type, EllipsisLoc, RSquareLoc, PackIdExpr, IndexExpr,1731SubstitutedExprs, ExpandedToEmptyPack);1732}17331734NamedDecl *PackIndexingExpr::getPackDecl() const {1735if (auto *D = dyn_cast<DeclRefExpr>(getPackIdExpression()); D) {1736NamedDecl *ND = dyn_cast<NamedDecl>(D->getDecl());1737assert(ND && "exected a named decl");1738return ND;1739}1740assert(false && "invalid declaration kind in pack indexing expression");1741return nullptr;1742}17431744PackIndexingExpr *1745PackIndexingExpr::CreateDeserialized(ASTContext &Context,1746unsigned NumTransformedExprs) {1747void *Storage =1748Context.Allocate(totalSizeToAlloc<Expr *>(NumTransformedExprs));1749return new (Storage) PackIndexingExpr(EmptyShell{});1750}17511752QualType SubstNonTypeTemplateParmExpr::getParameterType(1753const ASTContext &Context) const {1754// Note that, for a class type NTTP, we will have an lvalue of type 'const1755// T', so we can't just compute this from the type and value category.1756if (isReferenceParameter())1757return Context.getLValueReferenceType(getType());1758return getType().getUnqualifiedType();1759}17601761SubstNonTypeTemplateParmPackExpr::SubstNonTypeTemplateParmPackExpr(1762QualType T, ExprValueKind ValueKind, SourceLocation NameLoc,1763const TemplateArgument &ArgPack, Decl *AssociatedDecl, unsigned Index)1764: Expr(SubstNonTypeTemplateParmPackExprClass, T, ValueKind, OK_Ordinary),1765AssociatedDecl(AssociatedDecl), Arguments(ArgPack.pack_begin()),1766NumArguments(ArgPack.pack_size()), Index(Index), NameLoc(NameLoc) {1767assert(AssociatedDecl != nullptr);1768setDependence(ExprDependence::TypeValueInstantiation |1769ExprDependence::UnexpandedPack);1770}17711772NonTypeTemplateParmDecl *1773SubstNonTypeTemplateParmPackExpr::getParameterPack() const {1774return cast<NonTypeTemplateParmDecl>(1775getReplacedTemplateParameterList(getAssociatedDecl())->asArray()[Index]);1776}17771778TemplateArgument SubstNonTypeTemplateParmPackExpr::getArgumentPack() const {1779return TemplateArgument(llvm::ArrayRef(Arguments, NumArguments));1780}17811782FunctionParmPackExpr::FunctionParmPackExpr(QualType T, VarDecl *ParamPack,1783SourceLocation NameLoc,1784unsigned NumParams,1785VarDecl *const *Params)1786: Expr(FunctionParmPackExprClass, T, VK_LValue, OK_Ordinary),1787ParamPack(ParamPack), NameLoc(NameLoc), NumParameters(NumParams) {1788if (Params)1789std::uninitialized_copy(Params, Params + NumParams,1790getTrailingObjects<VarDecl *>());1791setDependence(ExprDependence::TypeValueInstantiation |1792ExprDependence::UnexpandedPack);1793}17941795FunctionParmPackExpr *1796FunctionParmPackExpr::Create(const ASTContext &Context, QualType T,1797VarDecl *ParamPack, SourceLocation NameLoc,1798ArrayRef<VarDecl *> Params) {1799return new (Context.Allocate(totalSizeToAlloc<VarDecl *>(Params.size())))1800FunctionParmPackExpr(T, ParamPack, NameLoc, Params.size(), Params.data());1801}18021803FunctionParmPackExpr *1804FunctionParmPackExpr::CreateEmpty(const ASTContext &Context,1805unsigned NumParams) {1806return new (Context.Allocate(totalSizeToAlloc<VarDecl *>(NumParams)))1807FunctionParmPackExpr(QualType(), nullptr, SourceLocation(), 0, nullptr);1808}18091810MaterializeTemporaryExpr::MaterializeTemporaryExpr(1811QualType T, Expr *Temporary, bool BoundToLvalueReference,1812LifetimeExtendedTemporaryDecl *MTD)1813: Expr(MaterializeTemporaryExprClass, T,1814BoundToLvalueReference ? VK_LValue : VK_XValue, OK_Ordinary) {1815if (MTD) {1816State = MTD;1817MTD->ExprWithTemporary = Temporary;1818return;1819}1820State = Temporary;1821setDependence(computeDependence(this));1822}18231824void MaterializeTemporaryExpr::setExtendingDecl(ValueDecl *ExtendedBy,1825unsigned ManglingNumber) {1826// We only need extra state if we have to remember more than just the Stmt.1827if (!ExtendedBy)1828return;18291830// We may need to allocate extra storage for the mangling number and the1831// extended-by ValueDecl.1832if (!State.is<LifetimeExtendedTemporaryDecl *>())1833State = LifetimeExtendedTemporaryDecl::Create(1834cast<Expr>(State.get<Stmt *>()), ExtendedBy, ManglingNumber);18351836auto ES = State.get<LifetimeExtendedTemporaryDecl *>();1837ES->ExtendingDecl = ExtendedBy;1838ES->ManglingNumber = ManglingNumber;1839}18401841bool MaterializeTemporaryExpr::isUsableInConstantExpressions(1842const ASTContext &Context) const {1843// C++20 [expr.const]p4:1844// An object or reference is usable in constant expressions if it is [...]1845// a temporary object of non-volatile const-qualified literal type1846// whose lifetime is extended to that of a variable that is usable1847// in constant expressions1848auto *VD = dyn_cast_or_null<VarDecl>(getExtendingDecl());1849return VD && getType().isConstant(Context) &&1850!getType().isVolatileQualified() &&1851getType()->isLiteralType(Context) &&1852VD->isUsableInConstantExpressions(Context);1853}18541855TypeTraitExpr::TypeTraitExpr(QualType T, SourceLocation Loc, TypeTrait Kind,1856ArrayRef<TypeSourceInfo *> Args,1857SourceLocation RParenLoc, bool Value)1858: Expr(TypeTraitExprClass, T, VK_PRValue, OK_Ordinary), Loc(Loc),1859RParenLoc(RParenLoc) {1860assert(Kind <= TT_Last && "invalid enum value!");1861TypeTraitExprBits.Kind = Kind;1862assert(static_cast<unsigned>(Kind) == TypeTraitExprBits.Kind &&1863"TypeTraitExprBits.Kind overflow!");1864TypeTraitExprBits.Value = Value;1865TypeTraitExprBits.NumArgs = Args.size();1866assert(Args.size() == TypeTraitExprBits.NumArgs &&1867"TypeTraitExprBits.NumArgs overflow!");18681869auto **ToArgs = getTrailingObjects<TypeSourceInfo *>();1870for (unsigned I = 0, N = Args.size(); I != N; ++I)1871ToArgs[I] = Args[I];18721873setDependence(computeDependence(this));1874}18751876TypeTraitExpr *TypeTraitExpr::Create(const ASTContext &C, QualType T,1877SourceLocation Loc,1878TypeTrait Kind,1879ArrayRef<TypeSourceInfo *> Args,1880SourceLocation RParenLoc,1881bool Value) {1882void *Mem = C.Allocate(totalSizeToAlloc<TypeSourceInfo *>(Args.size()));1883return new (Mem) TypeTraitExpr(T, Loc, Kind, Args, RParenLoc, Value);1884}18851886TypeTraitExpr *TypeTraitExpr::CreateDeserialized(const ASTContext &C,1887unsigned NumArgs) {1888void *Mem = C.Allocate(totalSizeToAlloc<TypeSourceInfo *>(NumArgs));1889return new (Mem) TypeTraitExpr(EmptyShell());1890}18911892CUDAKernelCallExpr::CUDAKernelCallExpr(Expr *Fn, CallExpr *Config,1893ArrayRef<Expr *> Args, QualType Ty,1894ExprValueKind VK, SourceLocation RP,1895FPOptionsOverride FPFeatures,1896unsigned MinNumArgs)1897: CallExpr(CUDAKernelCallExprClass, Fn, /*PreArgs=*/Config, Args, Ty, VK,1898RP, FPFeatures, MinNumArgs, NotADL) {}18991900CUDAKernelCallExpr::CUDAKernelCallExpr(unsigned NumArgs, bool HasFPFeatures,1901EmptyShell Empty)1902: CallExpr(CUDAKernelCallExprClass, /*NumPreArgs=*/END_PREARG, NumArgs,1903HasFPFeatures, Empty) {}19041905CUDAKernelCallExpr *1906CUDAKernelCallExpr::Create(const ASTContext &Ctx, Expr *Fn, CallExpr *Config,1907ArrayRef<Expr *> Args, QualType Ty, ExprValueKind VK,1908SourceLocation RP, FPOptionsOverride FPFeatures,1909unsigned MinNumArgs) {1910// Allocate storage for the trailing objects of CallExpr.1911unsigned NumArgs = std::max<unsigned>(Args.size(), MinNumArgs);1912unsigned SizeOfTrailingObjects = CallExpr::sizeOfTrailingObjects(1913/*NumPreArgs=*/END_PREARG, NumArgs, FPFeatures.requiresTrailingStorage());1914void *Mem = Ctx.Allocate(sizeof(CUDAKernelCallExpr) + SizeOfTrailingObjects,1915alignof(CUDAKernelCallExpr));1916return new (Mem)1917CUDAKernelCallExpr(Fn, Config, Args, Ty, VK, RP, FPFeatures, MinNumArgs);1918}19191920CUDAKernelCallExpr *CUDAKernelCallExpr::CreateEmpty(const ASTContext &Ctx,1921unsigned NumArgs,1922bool HasFPFeatures,1923EmptyShell Empty) {1924// Allocate storage for the trailing objects of CallExpr.1925unsigned SizeOfTrailingObjects = CallExpr::sizeOfTrailingObjects(1926/*NumPreArgs=*/END_PREARG, NumArgs, HasFPFeatures);1927void *Mem = Ctx.Allocate(sizeof(CUDAKernelCallExpr) + SizeOfTrailingObjects,1928alignof(CUDAKernelCallExpr));1929return new (Mem) CUDAKernelCallExpr(NumArgs, HasFPFeatures, Empty);1930}19311932CXXParenListInitExpr *1933CXXParenListInitExpr::Create(ASTContext &C, ArrayRef<Expr *> Args, QualType T,1934unsigned NumUserSpecifiedExprs,1935SourceLocation InitLoc, SourceLocation LParenLoc,1936SourceLocation RParenLoc) {1937void *Mem = C.Allocate(totalSizeToAlloc<Expr *>(Args.size()));1938return new (Mem) CXXParenListInitExpr(Args, T, NumUserSpecifiedExprs, InitLoc,1939LParenLoc, RParenLoc);1940}19411942CXXParenListInitExpr *CXXParenListInitExpr::CreateEmpty(ASTContext &C,1943unsigned NumExprs,1944EmptyShell Empty) {1945void *Mem = C.Allocate(totalSizeToAlloc<Expr *>(NumExprs),1946alignof(CXXParenListInitExpr));1947return new (Mem) CXXParenListInitExpr(Empty, NumExprs);1948}194919501951