ExprCXX.cpp 72 KB

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