Stmt.cpp 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324
  1. //===- Stmt.cpp - Statement 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 Stmt class and statement subclasses.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "clang/AST/Stmt.h"
  13. #include "clang/AST/ASTContext.h"
  14. #include "clang/AST/ASTDiagnostic.h"
  15. #include "clang/AST/Decl.h"
  16. #include "clang/AST/DeclGroup.h"
  17. #include "clang/AST/Expr.h"
  18. #include "clang/AST/ExprCXX.h"
  19. #include "clang/AST/ExprObjC.h"
  20. #include "clang/AST/ExprOpenMP.h"
  21. #include "clang/AST/StmtCXX.h"
  22. #include "clang/AST/StmtObjC.h"
  23. #include "clang/AST/StmtOpenMP.h"
  24. #include "clang/AST/Type.h"
  25. #include "clang/Basic/CharInfo.h"
  26. #include "clang/Basic/LLVM.h"
  27. #include "clang/Basic/SourceLocation.h"
  28. #include "clang/Basic/TargetInfo.h"
  29. #include "clang/Lex/Token.h"
  30. #include "llvm/ADT/SmallVector.h"
  31. #include "llvm/ADT/StringExtras.h"
  32. #include "llvm/ADT/StringRef.h"
  33. #include "llvm/Support/Casting.h"
  34. #include "llvm/Support/Compiler.h"
  35. #include "llvm/Support/ErrorHandling.h"
  36. #include "llvm/Support/MathExtras.h"
  37. #include "llvm/Support/raw_ostream.h"
  38. #include <algorithm>
  39. #include <cassert>
  40. #include <cstring>
  41. #include <string>
  42. #include <utility>
  43. #include <type_traits>
  44. using namespace clang;
  45. static struct StmtClassNameTable {
  46. const char *Name;
  47. unsigned Counter;
  48. unsigned Size;
  49. } StmtClassInfo[Stmt::lastStmtConstant+1];
  50. static StmtClassNameTable &getStmtInfoTableEntry(Stmt::StmtClass E) {
  51. static bool Initialized = false;
  52. if (Initialized)
  53. return StmtClassInfo[E];
  54. // Initialize the table on the first use.
  55. Initialized = true;
  56. #define ABSTRACT_STMT(STMT)
  57. #define STMT(CLASS, PARENT) \
  58. StmtClassInfo[(unsigned)Stmt::CLASS##Class].Name = #CLASS; \
  59. StmtClassInfo[(unsigned)Stmt::CLASS##Class].Size = sizeof(CLASS);
  60. #include "clang/AST/StmtNodes.inc"
  61. return StmtClassInfo[E];
  62. }
  63. void *Stmt::operator new(size_t bytes, const ASTContext& C,
  64. unsigned alignment) {
  65. return ::operator new(bytes, C, alignment);
  66. }
  67. const char *Stmt::getStmtClassName() const {
  68. return getStmtInfoTableEntry((StmtClass) StmtBits.sClass).Name;
  69. }
  70. // Check that no statement / expression class is polymorphic. LLVM style RTTI
  71. // should be used instead. If absolutely needed an exception can still be added
  72. // here by defining the appropriate macro (but please don't do this).
  73. #define STMT(CLASS, PARENT) \
  74. static_assert(!std::is_polymorphic<CLASS>::value, \
  75. #CLASS " should not be polymorphic!");
  76. #include "clang/AST/StmtNodes.inc"
  77. // Check that no statement / expression class has a non-trival destructor.
  78. // Statements and expressions are allocated with the BumpPtrAllocator from
  79. // ASTContext and therefore their destructor is not executed.
  80. #define STMT(CLASS, PARENT) \
  81. static_assert(std::is_trivially_destructible<CLASS>::value, \
  82. #CLASS " should be trivially destructible!");
  83. // FIXME: InitListExpr is not trivially destructible due to its ASTVector.
  84. #define INITLISTEXPR(CLASS, PARENT)
  85. #include "clang/AST/StmtNodes.inc"
  86. void Stmt::PrintStats() {
  87. // Ensure the table is primed.
  88. getStmtInfoTableEntry(Stmt::NullStmtClass);
  89. unsigned sum = 0;
  90. llvm::errs() << "\n*** Stmt/Expr Stats:\n";
  91. for (int i = 0; i != Stmt::lastStmtConstant+1; i++) {
  92. if (StmtClassInfo[i].Name == nullptr) continue;
  93. sum += StmtClassInfo[i].Counter;
  94. }
  95. llvm::errs() << " " << sum << " stmts/exprs total.\n";
  96. sum = 0;
  97. for (int i = 0; i != Stmt::lastStmtConstant+1; i++) {
  98. if (StmtClassInfo[i].Name == nullptr) continue;
  99. if (StmtClassInfo[i].Counter == 0) continue;
  100. llvm::errs() << " " << StmtClassInfo[i].Counter << " "
  101. << StmtClassInfo[i].Name << ", " << StmtClassInfo[i].Size
  102. << " each (" << StmtClassInfo[i].Counter*StmtClassInfo[i].Size
  103. << " bytes)\n";
  104. sum += StmtClassInfo[i].Counter*StmtClassInfo[i].Size;
  105. }
  106. llvm::errs() << "Total bytes = " << sum << "\n";
  107. }
  108. void Stmt::addStmtClass(StmtClass s) {
  109. ++getStmtInfoTableEntry(s).Counter;
  110. }
  111. bool Stmt::StatisticsEnabled = false;
  112. void Stmt::EnableStatistics() {
  113. StatisticsEnabled = true;
  114. }
  115. /// Skip no-op (attributed, compound) container stmts and skip captured
  116. /// stmt at the top, if \a IgnoreCaptured is true.
  117. Stmt *Stmt::IgnoreContainers(bool IgnoreCaptured) {
  118. Stmt *S = this;
  119. if (IgnoreCaptured)
  120. if (auto CapS = dyn_cast_or_null<CapturedStmt>(S))
  121. S = CapS->getCapturedStmt();
  122. while (true) {
  123. if (auto AS = dyn_cast_or_null<AttributedStmt>(S))
  124. S = AS->getSubStmt();
  125. else if (auto CS = dyn_cast_or_null<CompoundStmt>(S)) {
  126. if (CS->size() != 1)
  127. break;
  128. S = CS->body_back();
  129. } else
  130. break;
  131. }
  132. return S;
  133. }
  134. /// Strip off all label-like statements.
  135. ///
  136. /// This will strip off label statements, case statements, attributed
  137. /// statements and default statements recursively.
  138. const Stmt *Stmt::stripLabelLikeStatements() const {
  139. const Stmt *S = this;
  140. while (true) {
  141. if (const auto *LS = dyn_cast<LabelStmt>(S))
  142. S = LS->getSubStmt();
  143. else if (const auto *SC = dyn_cast<SwitchCase>(S))
  144. S = SC->getSubStmt();
  145. else if (const auto *AS = dyn_cast<AttributedStmt>(S))
  146. S = AS->getSubStmt();
  147. else
  148. return S;
  149. }
  150. }
  151. namespace {
  152. struct good {};
  153. struct bad {};
  154. // These silly little functions have to be static inline to suppress
  155. // unused warnings, and they have to be defined to suppress other
  156. // warnings.
  157. static good is_good(good) { return good(); }
  158. typedef Stmt::child_range children_t();
  159. template <class T> good implements_children(children_t T::*) {
  160. return good();
  161. }
  162. LLVM_ATTRIBUTE_UNUSED
  163. static bad implements_children(children_t Stmt::*) {
  164. return bad();
  165. }
  166. typedef SourceLocation getBeginLoc_t() const;
  167. template <class T> good implements_getBeginLoc(getBeginLoc_t T::*) {
  168. return good();
  169. }
  170. LLVM_ATTRIBUTE_UNUSED
  171. static bad implements_getBeginLoc(getBeginLoc_t Stmt::*) { return bad(); }
  172. typedef SourceLocation getLocEnd_t() const;
  173. template <class T> good implements_getEndLoc(getLocEnd_t T::*) {
  174. return good();
  175. }
  176. LLVM_ATTRIBUTE_UNUSED
  177. static bad implements_getEndLoc(getLocEnd_t Stmt::*) { return bad(); }
  178. #define ASSERT_IMPLEMENTS_children(type) \
  179. (void) is_good(implements_children(&type::children))
  180. #define ASSERT_IMPLEMENTS_getBeginLoc(type) \
  181. (void)is_good(implements_getBeginLoc(&type::getBeginLoc))
  182. #define ASSERT_IMPLEMENTS_getEndLoc(type) \
  183. (void)is_good(implements_getEndLoc(&type::getEndLoc))
  184. } // namespace
  185. /// Check whether the various Stmt classes implement their member
  186. /// functions.
  187. LLVM_ATTRIBUTE_UNUSED
  188. static inline void check_implementations() {
  189. #define ABSTRACT_STMT(type)
  190. #define STMT(type, base) \
  191. ASSERT_IMPLEMENTS_children(type); \
  192. ASSERT_IMPLEMENTS_getBeginLoc(type); \
  193. ASSERT_IMPLEMENTS_getEndLoc(type);
  194. #include "clang/AST/StmtNodes.inc"
  195. }
  196. Stmt::child_range Stmt::children() {
  197. switch (getStmtClass()) {
  198. case Stmt::NoStmtClass: llvm_unreachable("statement without class");
  199. #define ABSTRACT_STMT(type)
  200. #define STMT(type, base) \
  201. case Stmt::type##Class: \
  202. return static_cast<type*>(this)->children();
  203. #include "clang/AST/StmtNodes.inc"
  204. }
  205. llvm_unreachable("unknown statement kind!");
  206. }
  207. // Amusing macro metaprogramming hack: check whether a class provides
  208. // a more specific implementation of getSourceRange.
  209. //
  210. // See also Expr.cpp:getExprLoc().
  211. namespace {
  212. /// This implementation is used when a class provides a custom
  213. /// implementation of getSourceRange.
  214. template <class S, class T>
  215. SourceRange getSourceRangeImpl(const Stmt *stmt,
  216. SourceRange (T::*v)() const) {
  217. return static_cast<const S*>(stmt)->getSourceRange();
  218. }
  219. /// This implementation is used when a class doesn't provide a custom
  220. /// implementation of getSourceRange. Overload resolution should pick it over
  221. /// the implementation above because it's more specialized according to
  222. /// function template partial ordering.
  223. template <class S>
  224. SourceRange getSourceRangeImpl(const Stmt *stmt,
  225. SourceRange (Stmt::*v)() const) {
  226. return SourceRange(static_cast<const S *>(stmt)->getBeginLoc(),
  227. static_cast<const S *>(stmt)->getEndLoc());
  228. }
  229. } // namespace
  230. SourceRange Stmt::getSourceRange() const {
  231. switch (getStmtClass()) {
  232. case Stmt::NoStmtClass: llvm_unreachable("statement without class");
  233. #define ABSTRACT_STMT(type)
  234. #define STMT(type, base) \
  235. case Stmt::type##Class: \
  236. return getSourceRangeImpl<type>(this, &type::getSourceRange);
  237. #include "clang/AST/StmtNodes.inc"
  238. }
  239. llvm_unreachable("unknown statement kind!");
  240. }
  241. SourceLocation Stmt::getBeginLoc() const {
  242. // llvm::errs() << "getBeginLoc() for " << getStmtClassName() << "\n";
  243. switch (getStmtClass()) {
  244. case Stmt::NoStmtClass: llvm_unreachable("statement without class");
  245. #define ABSTRACT_STMT(type)
  246. #define STMT(type, base) \
  247. case Stmt::type##Class: \
  248. return static_cast<const type *>(this)->getBeginLoc();
  249. #include "clang/AST/StmtNodes.inc"
  250. }
  251. llvm_unreachable("unknown statement kind");
  252. }
  253. SourceLocation Stmt::getEndLoc() const {
  254. switch (getStmtClass()) {
  255. case Stmt::NoStmtClass: llvm_unreachable("statement without class");
  256. #define ABSTRACT_STMT(type)
  257. #define STMT(type, base) \
  258. case Stmt::type##Class: \
  259. return static_cast<const type *>(this)->getEndLoc();
  260. #include "clang/AST/StmtNodes.inc"
  261. }
  262. llvm_unreachable("unknown statement kind");
  263. }
  264. int64_t Stmt::getID(const ASTContext &Context) const {
  265. return Context.getAllocator().identifyKnownAlignedObject<Stmt>(this);
  266. }
  267. CompoundStmt::CompoundStmt(ArrayRef<Stmt *> Stmts, SourceLocation LB,
  268. SourceLocation RB)
  269. : Stmt(CompoundStmtClass), RBraceLoc(RB) {
  270. CompoundStmtBits.NumStmts = Stmts.size();
  271. setStmts(Stmts);
  272. CompoundStmtBits.LBraceLoc = LB;
  273. }
  274. void CompoundStmt::setStmts(ArrayRef<Stmt *> Stmts) {
  275. assert(CompoundStmtBits.NumStmts == Stmts.size() &&
  276. "NumStmts doesn't fit in bits of CompoundStmtBits.NumStmts!");
  277. std::copy(Stmts.begin(), Stmts.end(), body_begin());
  278. }
  279. CompoundStmt *CompoundStmt::Create(const ASTContext &C, ArrayRef<Stmt *> Stmts,
  280. SourceLocation LB, SourceLocation RB) {
  281. void *Mem =
  282. C.Allocate(totalSizeToAlloc<Stmt *>(Stmts.size()), alignof(CompoundStmt));
  283. return new (Mem) CompoundStmt(Stmts, LB, RB);
  284. }
  285. CompoundStmt *CompoundStmt::CreateEmpty(const ASTContext &C,
  286. unsigned NumStmts) {
  287. void *Mem =
  288. C.Allocate(totalSizeToAlloc<Stmt *>(NumStmts), alignof(CompoundStmt));
  289. CompoundStmt *New = new (Mem) CompoundStmt(EmptyShell());
  290. New->CompoundStmtBits.NumStmts = NumStmts;
  291. return New;
  292. }
  293. const Expr *ValueStmt::getExprStmt() const {
  294. const Stmt *S = this;
  295. do {
  296. if (const auto *E = dyn_cast<Expr>(S))
  297. return E;
  298. if (const auto *LS = dyn_cast<LabelStmt>(S))
  299. S = LS->getSubStmt();
  300. else if (const auto *AS = dyn_cast<AttributedStmt>(S))
  301. S = AS->getSubStmt();
  302. else
  303. llvm_unreachable("unknown kind of ValueStmt");
  304. } while (isa<ValueStmt>(S));
  305. return nullptr;
  306. }
  307. const char *LabelStmt::getName() const {
  308. return getDecl()->getIdentifier()->getNameStart();
  309. }
  310. AttributedStmt *AttributedStmt::Create(const ASTContext &C, SourceLocation Loc,
  311. ArrayRef<const Attr*> Attrs,
  312. Stmt *SubStmt) {
  313. assert(!Attrs.empty() && "Attrs should not be empty");
  314. void *Mem = C.Allocate(totalSizeToAlloc<const Attr *>(Attrs.size()),
  315. alignof(AttributedStmt));
  316. return new (Mem) AttributedStmt(Loc, Attrs, SubStmt);
  317. }
  318. AttributedStmt *AttributedStmt::CreateEmpty(const ASTContext &C,
  319. unsigned NumAttrs) {
  320. assert(NumAttrs > 0 && "NumAttrs should be greater than zero");
  321. void *Mem = C.Allocate(totalSizeToAlloc<const Attr *>(NumAttrs),
  322. alignof(AttributedStmt));
  323. return new (Mem) AttributedStmt(EmptyShell(), NumAttrs);
  324. }
  325. std::string AsmStmt::generateAsmString(const ASTContext &C) const {
  326. if (const auto *gccAsmStmt = dyn_cast<GCCAsmStmt>(this))
  327. return gccAsmStmt->generateAsmString(C);
  328. if (const auto *msAsmStmt = dyn_cast<MSAsmStmt>(this))
  329. return msAsmStmt->generateAsmString(C);
  330. llvm_unreachable("unknown asm statement kind!");
  331. }
  332. StringRef AsmStmt::getOutputConstraint(unsigned i) const {
  333. if (const auto *gccAsmStmt = dyn_cast<GCCAsmStmt>(this))
  334. return gccAsmStmt->getOutputConstraint(i);
  335. if (const auto *msAsmStmt = dyn_cast<MSAsmStmt>(this))
  336. return msAsmStmt->getOutputConstraint(i);
  337. llvm_unreachable("unknown asm statement kind!");
  338. }
  339. const Expr *AsmStmt::getOutputExpr(unsigned i) const {
  340. if (const auto *gccAsmStmt = dyn_cast<GCCAsmStmt>(this))
  341. return gccAsmStmt->getOutputExpr(i);
  342. if (const auto *msAsmStmt = dyn_cast<MSAsmStmt>(this))
  343. return msAsmStmt->getOutputExpr(i);
  344. llvm_unreachable("unknown asm statement kind!");
  345. }
  346. StringRef AsmStmt::getInputConstraint(unsigned i) const {
  347. if (const auto *gccAsmStmt = dyn_cast<GCCAsmStmt>(this))
  348. return gccAsmStmt->getInputConstraint(i);
  349. if (const auto *msAsmStmt = dyn_cast<MSAsmStmt>(this))
  350. return msAsmStmt->getInputConstraint(i);
  351. llvm_unreachable("unknown asm statement kind!");
  352. }
  353. const Expr *AsmStmt::getInputExpr(unsigned i) const {
  354. if (const auto *gccAsmStmt = dyn_cast<GCCAsmStmt>(this))
  355. return gccAsmStmt->getInputExpr(i);
  356. if (const auto *msAsmStmt = dyn_cast<MSAsmStmt>(this))
  357. return msAsmStmt->getInputExpr(i);
  358. llvm_unreachable("unknown asm statement kind!");
  359. }
  360. StringRef AsmStmt::getClobber(unsigned i) const {
  361. if (const auto *gccAsmStmt = dyn_cast<GCCAsmStmt>(this))
  362. return gccAsmStmt->getClobber(i);
  363. if (const auto *msAsmStmt = dyn_cast<MSAsmStmt>(this))
  364. return msAsmStmt->getClobber(i);
  365. llvm_unreachable("unknown asm statement kind!");
  366. }
  367. /// getNumPlusOperands - Return the number of output operands that have a "+"
  368. /// constraint.
  369. unsigned AsmStmt::getNumPlusOperands() const {
  370. unsigned Res = 0;
  371. for (unsigned i = 0, e = getNumOutputs(); i != e; ++i)
  372. if (isOutputPlusConstraint(i))
  373. ++Res;
  374. return Res;
  375. }
  376. char GCCAsmStmt::AsmStringPiece::getModifier() const {
  377. assert(isOperand() && "Only Operands can have modifiers.");
  378. return isLetter(Str[0]) ? Str[0] : '\0';
  379. }
  380. StringRef GCCAsmStmt::getClobber(unsigned i) const {
  381. return getClobberStringLiteral(i)->getString();
  382. }
  383. Expr *GCCAsmStmt::getOutputExpr(unsigned i) {
  384. return cast<Expr>(Exprs[i]);
  385. }
  386. /// getOutputConstraint - Return the constraint string for the specified
  387. /// output operand. All output constraints are known to be non-empty (either
  388. /// '=' or '+').
  389. StringRef GCCAsmStmt::getOutputConstraint(unsigned i) const {
  390. return getOutputConstraintLiteral(i)->getString();
  391. }
  392. Expr *GCCAsmStmt::getInputExpr(unsigned i) {
  393. return cast<Expr>(Exprs[i + NumOutputs]);
  394. }
  395. void GCCAsmStmt::setInputExpr(unsigned i, Expr *E) {
  396. Exprs[i + NumOutputs] = E;
  397. }
  398. AddrLabelExpr *GCCAsmStmt::getLabelExpr(unsigned i) const {
  399. return cast<AddrLabelExpr>(Exprs[i + NumInputs]);
  400. }
  401. StringRef GCCAsmStmt::getLabelName(unsigned i) const {
  402. return getLabelExpr(i)->getLabel()->getName();
  403. }
  404. /// getInputConstraint - Return the specified input constraint. Unlike output
  405. /// constraints, these can be empty.
  406. StringRef GCCAsmStmt::getInputConstraint(unsigned i) const {
  407. return getInputConstraintLiteral(i)->getString();
  408. }
  409. void GCCAsmStmt::setOutputsAndInputsAndClobbers(const ASTContext &C,
  410. IdentifierInfo **Names,
  411. StringLiteral **Constraints,
  412. Stmt **Exprs,
  413. unsigned NumOutputs,
  414. unsigned NumInputs,
  415. unsigned NumLabels,
  416. StringLiteral **Clobbers,
  417. unsigned NumClobbers) {
  418. this->NumOutputs = NumOutputs;
  419. this->NumInputs = NumInputs;
  420. this->NumClobbers = NumClobbers;
  421. this->NumLabels = NumLabels;
  422. assert(!(NumOutputs && NumLabels) && "asm goto cannot have outputs");
  423. unsigned NumExprs = NumOutputs + NumInputs + NumLabels;
  424. C.Deallocate(this->Names);
  425. this->Names = new (C) IdentifierInfo*[NumExprs];
  426. std::copy(Names, Names + NumExprs, this->Names);
  427. C.Deallocate(this->Exprs);
  428. this->Exprs = new (C) Stmt*[NumExprs];
  429. std::copy(Exprs, Exprs + NumExprs, this->Exprs);
  430. unsigned NumConstraints = NumOutputs + NumInputs;
  431. C.Deallocate(this->Constraints);
  432. this->Constraints = new (C) StringLiteral*[NumConstraints];
  433. std::copy(Constraints, Constraints + NumConstraints, this->Constraints);
  434. C.Deallocate(this->Clobbers);
  435. this->Clobbers = new (C) StringLiteral*[NumClobbers];
  436. std::copy(Clobbers, Clobbers + NumClobbers, this->Clobbers);
  437. }
  438. /// getNamedOperand - Given a symbolic operand reference like %[foo],
  439. /// translate this into a numeric value needed to reference the same operand.
  440. /// This returns -1 if the operand name is invalid.
  441. int GCCAsmStmt::getNamedOperand(StringRef SymbolicName) const {
  442. unsigned NumPlusOperands = 0;
  443. // Check if this is an output operand.
  444. for (unsigned i = 0, e = getNumOutputs(); i != e; ++i) {
  445. if (getOutputName(i) == SymbolicName)
  446. return i;
  447. }
  448. for (unsigned i = 0, e = getNumInputs(); i != e; ++i)
  449. if (getInputName(i) == SymbolicName)
  450. return getNumOutputs() + NumPlusOperands + i;
  451. for (unsigned i = 0, e = getNumLabels(); i != e; ++i)
  452. if (getLabelName(i) == SymbolicName)
  453. return i + getNumInputs();
  454. // Not found.
  455. return -1;
  456. }
  457. /// AnalyzeAsmString - Analyze the asm string of the current asm, decomposing
  458. /// it into pieces. If the asm string is erroneous, emit errors and return
  459. /// true, otherwise return false.
  460. unsigned GCCAsmStmt::AnalyzeAsmString(SmallVectorImpl<AsmStringPiece>&Pieces,
  461. const ASTContext &C, unsigned &DiagOffs) const {
  462. StringRef Str = getAsmString()->getString();
  463. const char *StrStart = Str.begin();
  464. const char *StrEnd = Str.end();
  465. const char *CurPtr = StrStart;
  466. // "Simple" inline asms have no constraints or operands, just convert the asm
  467. // string to escape $'s.
  468. if (isSimple()) {
  469. std::string Result;
  470. for (; CurPtr != StrEnd; ++CurPtr) {
  471. switch (*CurPtr) {
  472. case '$':
  473. Result += "$$";
  474. break;
  475. default:
  476. Result += *CurPtr;
  477. break;
  478. }
  479. }
  480. Pieces.push_back(AsmStringPiece(Result));
  481. return 0;
  482. }
  483. // CurStringPiece - The current string that we are building up as we scan the
  484. // asm string.
  485. std::string CurStringPiece;
  486. bool HasVariants = !C.getTargetInfo().hasNoAsmVariants();
  487. unsigned LastAsmStringToken = 0;
  488. unsigned LastAsmStringOffset = 0;
  489. while (true) {
  490. // Done with the string?
  491. if (CurPtr == StrEnd) {
  492. if (!CurStringPiece.empty())
  493. Pieces.push_back(AsmStringPiece(CurStringPiece));
  494. return 0;
  495. }
  496. char CurChar = *CurPtr++;
  497. switch (CurChar) {
  498. case '$': CurStringPiece += "$$"; continue;
  499. case '{': CurStringPiece += (HasVariants ? "$(" : "{"); continue;
  500. case '|': CurStringPiece += (HasVariants ? "$|" : "|"); continue;
  501. case '}': CurStringPiece += (HasVariants ? "$)" : "}"); continue;
  502. case '%':
  503. break;
  504. default:
  505. CurStringPiece += CurChar;
  506. continue;
  507. }
  508. // Escaped "%" character in asm string.
  509. if (CurPtr == StrEnd) {
  510. // % at end of string is invalid (no escape).
  511. DiagOffs = CurPtr-StrStart-1;
  512. return diag::err_asm_invalid_escape;
  513. }
  514. // Handle escaped char and continue looping over the asm string.
  515. char EscapedChar = *CurPtr++;
  516. switch (EscapedChar) {
  517. default:
  518. break;
  519. case '%': // %% -> %
  520. case '{': // %{ -> {
  521. case '}': // %} -> }
  522. CurStringPiece += EscapedChar;
  523. continue;
  524. case '=': // %= -> Generate a unique ID.
  525. CurStringPiece += "${:uid}";
  526. continue;
  527. }
  528. // Otherwise, we have an operand. If we have accumulated a string so far,
  529. // add it to the Pieces list.
  530. if (!CurStringPiece.empty()) {
  531. Pieces.push_back(AsmStringPiece(CurStringPiece));
  532. CurStringPiece.clear();
  533. }
  534. // Handle operands that have asmSymbolicName (e.g., %x[foo]) and those that
  535. // don't (e.g., %x4). 'x' following the '%' is the constraint modifier.
  536. const char *Begin = CurPtr - 1; // Points to the character following '%'.
  537. const char *Percent = Begin - 1; // Points to '%'.
  538. if (isLetter(EscapedChar)) {
  539. if (CurPtr == StrEnd) { // Premature end.
  540. DiagOffs = CurPtr-StrStart-1;
  541. return diag::err_asm_invalid_escape;
  542. }
  543. EscapedChar = *CurPtr++;
  544. }
  545. const TargetInfo &TI = C.getTargetInfo();
  546. const SourceManager &SM = C.getSourceManager();
  547. const LangOptions &LO = C.getLangOpts();
  548. // Handle operands that don't have asmSymbolicName (e.g., %x4).
  549. if (isDigit(EscapedChar)) {
  550. // %n - Assembler operand n
  551. unsigned N = 0;
  552. --CurPtr;
  553. while (CurPtr != StrEnd && isDigit(*CurPtr))
  554. N = N*10 + ((*CurPtr++)-'0');
  555. unsigned NumOperands = getNumOutputs() + getNumPlusOperands() +
  556. getNumInputs() + getNumLabels();
  557. if (N >= NumOperands) {
  558. DiagOffs = CurPtr-StrStart-1;
  559. return diag::err_asm_invalid_operand_number;
  560. }
  561. // Str contains "x4" (Operand without the leading %).
  562. std::string Str(Begin, CurPtr - Begin);
  563. // (BeginLoc, EndLoc) represents the range of the operand we are currently
  564. // processing. Unlike Str, the range includes the leading '%'.
  565. SourceLocation BeginLoc = getAsmString()->getLocationOfByte(
  566. Percent - StrStart, SM, LO, TI, &LastAsmStringToken,
  567. &LastAsmStringOffset);
  568. SourceLocation EndLoc = getAsmString()->getLocationOfByte(
  569. CurPtr - StrStart, SM, LO, TI, &LastAsmStringToken,
  570. &LastAsmStringOffset);
  571. Pieces.emplace_back(N, std::move(Str), BeginLoc, EndLoc);
  572. continue;
  573. }
  574. // Handle operands that have asmSymbolicName (e.g., %x[foo]).
  575. if (EscapedChar == '[') {
  576. DiagOffs = CurPtr-StrStart-1;
  577. // Find the ']'.
  578. const char *NameEnd = (const char*)memchr(CurPtr, ']', StrEnd-CurPtr);
  579. if (NameEnd == nullptr)
  580. return diag::err_asm_unterminated_symbolic_operand_name;
  581. if (NameEnd == CurPtr)
  582. return diag::err_asm_empty_symbolic_operand_name;
  583. StringRef SymbolicName(CurPtr, NameEnd - CurPtr);
  584. int N = getNamedOperand(SymbolicName);
  585. if (N == -1) {
  586. // Verify that an operand with that name exists.
  587. DiagOffs = CurPtr-StrStart;
  588. return diag::err_asm_unknown_symbolic_operand_name;
  589. }
  590. // Str contains "x[foo]" (Operand without the leading %).
  591. std::string Str(Begin, NameEnd + 1 - Begin);
  592. // (BeginLoc, EndLoc) represents the range of the operand we are currently
  593. // processing. Unlike Str, the range includes the leading '%'.
  594. SourceLocation BeginLoc = getAsmString()->getLocationOfByte(
  595. Percent - StrStart, SM, LO, TI, &LastAsmStringToken,
  596. &LastAsmStringOffset);
  597. SourceLocation EndLoc = getAsmString()->getLocationOfByte(
  598. NameEnd + 1 - StrStart, SM, LO, TI, &LastAsmStringToken,
  599. &LastAsmStringOffset);
  600. Pieces.emplace_back(N, std::move(Str), BeginLoc, EndLoc);
  601. CurPtr = NameEnd+1;
  602. continue;
  603. }
  604. DiagOffs = CurPtr-StrStart-1;
  605. return diag::err_asm_invalid_escape;
  606. }
  607. }
  608. /// Assemble final IR asm string (GCC-style).
  609. std::string GCCAsmStmt::generateAsmString(const ASTContext &C) const {
  610. // Analyze the asm string to decompose it into its pieces. We know that Sema
  611. // has already done this, so it is guaranteed to be successful.
  612. SmallVector<GCCAsmStmt::AsmStringPiece, 4> Pieces;
  613. unsigned DiagOffs;
  614. AnalyzeAsmString(Pieces, C, DiagOffs);
  615. std::string AsmString;
  616. for (const auto &Piece : Pieces) {
  617. if (Piece.isString())
  618. AsmString += Piece.getString();
  619. else if (Piece.getModifier() == '\0')
  620. AsmString += '$' + llvm::utostr(Piece.getOperandNo());
  621. else
  622. AsmString += "${" + llvm::utostr(Piece.getOperandNo()) + ':' +
  623. Piece.getModifier() + '}';
  624. }
  625. return AsmString;
  626. }
  627. /// Assemble final IR asm string (MS-style).
  628. std::string MSAsmStmt::generateAsmString(const ASTContext &C) const {
  629. // FIXME: This needs to be translated into the IR string representation.
  630. return AsmStr;
  631. }
  632. Expr *MSAsmStmt::getOutputExpr(unsigned i) {
  633. return cast<Expr>(Exprs[i]);
  634. }
  635. Expr *MSAsmStmt::getInputExpr(unsigned i) {
  636. return cast<Expr>(Exprs[i + NumOutputs]);
  637. }
  638. void MSAsmStmt::setInputExpr(unsigned i, Expr *E) {
  639. Exprs[i + NumOutputs] = E;
  640. }
  641. //===----------------------------------------------------------------------===//
  642. // Constructors
  643. //===----------------------------------------------------------------------===//
  644. GCCAsmStmt::GCCAsmStmt(const ASTContext &C, SourceLocation asmloc,
  645. bool issimple, bool isvolatile, unsigned numoutputs,
  646. unsigned numinputs, IdentifierInfo **names,
  647. StringLiteral **constraints, Expr **exprs,
  648. StringLiteral *asmstr, unsigned numclobbers,
  649. StringLiteral **clobbers, unsigned numlabels,
  650. SourceLocation rparenloc)
  651. : AsmStmt(GCCAsmStmtClass, asmloc, issimple, isvolatile, numoutputs,
  652. numinputs, numclobbers),
  653. RParenLoc(rparenloc), AsmStr(asmstr), NumLabels(numlabels) {
  654. unsigned NumExprs = NumOutputs + NumInputs + NumLabels;
  655. Names = new (C) IdentifierInfo*[NumExprs];
  656. std::copy(names, names + NumExprs, Names);
  657. Exprs = new (C) Stmt*[NumExprs];
  658. std::copy(exprs, exprs + NumExprs, Exprs);
  659. unsigned NumConstraints = NumOutputs + NumInputs;
  660. Constraints = new (C) StringLiteral*[NumConstraints];
  661. std::copy(constraints, constraints + NumConstraints, Constraints);
  662. Clobbers = new (C) StringLiteral*[NumClobbers];
  663. std::copy(clobbers, clobbers + NumClobbers, Clobbers);
  664. }
  665. MSAsmStmt::MSAsmStmt(const ASTContext &C, SourceLocation asmloc,
  666. SourceLocation lbraceloc, bool issimple, bool isvolatile,
  667. ArrayRef<Token> asmtoks, unsigned numoutputs,
  668. unsigned numinputs,
  669. ArrayRef<StringRef> constraints, ArrayRef<Expr*> exprs,
  670. StringRef asmstr, ArrayRef<StringRef> clobbers,
  671. SourceLocation endloc)
  672. : AsmStmt(MSAsmStmtClass, asmloc, issimple, isvolatile, numoutputs,
  673. numinputs, clobbers.size()), LBraceLoc(lbraceloc),
  674. EndLoc(endloc), NumAsmToks(asmtoks.size()) {
  675. initialize(C, asmstr, asmtoks, constraints, exprs, clobbers);
  676. }
  677. static StringRef copyIntoContext(const ASTContext &C, StringRef str) {
  678. return str.copy(C);
  679. }
  680. void MSAsmStmt::initialize(const ASTContext &C, StringRef asmstr,
  681. ArrayRef<Token> asmtoks,
  682. ArrayRef<StringRef> constraints,
  683. ArrayRef<Expr*> exprs,
  684. ArrayRef<StringRef> clobbers) {
  685. assert(NumAsmToks == asmtoks.size());
  686. assert(NumClobbers == clobbers.size());
  687. assert(exprs.size() == NumOutputs + NumInputs);
  688. assert(exprs.size() == constraints.size());
  689. AsmStr = copyIntoContext(C, asmstr);
  690. Exprs = new (C) Stmt*[exprs.size()];
  691. std::copy(exprs.begin(), exprs.end(), Exprs);
  692. AsmToks = new (C) Token[asmtoks.size()];
  693. std::copy(asmtoks.begin(), asmtoks.end(), AsmToks);
  694. Constraints = new (C) StringRef[exprs.size()];
  695. std::transform(constraints.begin(), constraints.end(), Constraints,
  696. [&](StringRef Constraint) {
  697. return copyIntoContext(C, Constraint);
  698. });
  699. Clobbers = new (C) StringRef[NumClobbers];
  700. // FIXME: Avoid the allocation/copy if at all possible.
  701. std::transform(clobbers.begin(), clobbers.end(), Clobbers,
  702. [&](StringRef Clobber) {
  703. return copyIntoContext(C, Clobber);
  704. });
  705. }
  706. IfStmt::IfStmt(const ASTContext &Ctx, SourceLocation IL, bool IsConstexpr,
  707. Stmt *Init, VarDecl *Var, Expr *Cond, Stmt *Then,
  708. SourceLocation EL, Stmt *Else)
  709. : Stmt(IfStmtClass) {
  710. bool HasElse = Else != nullptr;
  711. bool HasVar = Var != nullptr;
  712. bool HasInit = Init != nullptr;
  713. IfStmtBits.HasElse = HasElse;
  714. IfStmtBits.HasVar = HasVar;
  715. IfStmtBits.HasInit = HasInit;
  716. setConstexpr(IsConstexpr);
  717. setCond(Cond);
  718. setThen(Then);
  719. if (HasElse)
  720. setElse(Else);
  721. if (HasVar)
  722. setConditionVariable(Ctx, Var);
  723. if (HasInit)
  724. setInit(Init);
  725. setIfLoc(IL);
  726. if (HasElse)
  727. setElseLoc(EL);
  728. }
  729. IfStmt::IfStmt(EmptyShell Empty, bool HasElse, bool HasVar, bool HasInit)
  730. : Stmt(IfStmtClass, Empty) {
  731. IfStmtBits.HasElse = HasElse;
  732. IfStmtBits.HasVar = HasVar;
  733. IfStmtBits.HasInit = HasInit;
  734. }
  735. IfStmt *IfStmt::Create(const ASTContext &Ctx, SourceLocation IL,
  736. bool IsConstexpr, Stmt *Init, VarDecl *Var, Expr *Cond,
  737. Stmt *Then, SourceLocation EL, Stmt *Else) {
  738. bool HasElse = Else != nullptr;
  739. bool HasVar = Var != nullptr;
  740. bool HasInit = Init != nullptr;
  741. void *Mem = Ctx.Allocate(
  742. totalSizeToAlloc<Stmt *, SourceLocation>(
  743. NumMandatoryStmtPtr + HasElse + HasVar + HasInit, HasElse),
  744. alignof(IfStmt));
  745. return new (Mem)
  746. IfStmt(Ctx, IL, IsConstexpr, Init, Var, Cond, Then, EL, Else);
  747. }
  748. IfStmt *IfStmt::CreateEmpty(const ASTContext &Ctx, bool HasElse, bool HasVar,
  749. bool HasInit) {
  750. void *Mem = Ctx.Allocate(
  751. totalSizeToAlloc<Stmt *, SourceLocation>(
  752. NumMandatoryStmtPtr + HasElse + HasVar + HasInit, HasElse),
  753. alignof(IfStmt));
  754. return new (Mem) IfStmt(EmptyShell(), HasElse, HasVar, HasInit);
  755. }
  756. VarDecl *IfStmt::getConditionVariable() {
  757. auto *DS = getConditionVariableDeclStmt();
  758. if (!DS)
  759. return nullptr;
  760. return cast<VarDecl>(DS->getSingleDecl());
  761. }
  762. void IfStmt::setConditionVariable(const ASTContext &Ctx, VarDecl *V) {
  763. assert(hasVarStorage() &&
  764. "This if statement has no storage for a condition variable!");
  765. if (!V) {
  766. getTrailingObjects<Stmt *>()[varOffset()] = nullptr;
  767. return;
  768. }
  769. SourceRange VarRange = V->getSourceRange();
  770. getTrailingObjects<Stmt *>()[varOffset()] = new (Ctx)
  771. DeclStmt(DeclGroupRef(V), VarRange.getBegin(), VarRange.getEnd());
  772. }
  773. bool IfStmt::isObjCAvailabilityCheck() const {
  774. return isa<ObjCAvailabilityCheckExpr>(getCond());
  775. }
  776. ForStmt::ForStmt(const ASTContext &C, Stmt *Init, Expr *Cond, VarDecl *condVar,
  777. Expr *Inc, Stmt *Body, SourceLocation FL, SourceLocation LP,
  778. SourceLocation RP)
  779. : Stmt(ForStmtClass), LParenLoc(LP), RParenLoc(RP)
  780. {
  781. SubExprs[INIT] = Init;
  782. setConditionVariable(C, condVar);
  783. SubExprs[COND] = Cond;
  784. SubExprs[INC] = Inc;
  785. SubExprs[BODY] = Body;
  786. ForStmtBits.ForLoc = FL;
  787. }
  788. VarDecl *ForStmt::getConditionVariable() const {
  789. if (!SubExprs[CONDVAR])
  790. return nullptr;
  791. auto *DS = cast<DeclStmt>(SubExprs[CONDVAR]);
  792. return cast<VarDecl>(DS->getSingleDecl());
  793. }
  794. void ForStmt::setConditionVariable(const ASTContext &C, VarDecl *V) {
  795. if (!V) {
  796. SubExprs[CONDVAR] = nullptr;
  797. return;
  798. }
  799. SourceRange VarRange = V->getSourceRange();
  800. SubExprs[CONDVAR] = new (C) DeclStmt(DeclGroupRef(V), VarRange.getBegin(),
  801. VarRange.getEnd());
  802. }
  803. SwitchStmt::SwitchStmt(const ASTContext &Ctx, Stmt *Init, VarDecl *Var,
  804. Expr *Cond)
  805. : Stmt(SwitchStmtClass), FirstCase(nullptr) {
  806. bool HasInit = Init != nullptr;
  807. bool HasVar = Var != nullptr;
  808. SwitchStmtBits.HasInit = HasInit;
  809. SwitchStmtBits.HasVar = HasVar;
  810. SwitchStmtBits.AllEnumCasesCovered = false;
  811. setCond(Cond);
  812. setBody(nullptr);
  813. if (HasInit)
  814. setInit(Init);
  815. if (HasVar)
  816. setConditionVariable(Ctx, Var);
  817. setSwitchLoc(SourceLocation{});
  818. }
  819. SwitchStmt::SwitchStmt(EmptyShell Empty, bool HasInit, bool HasVar)
  820. : Stmt(SwitchStmtClass, Empty) {
  821. SwitchStmtBits.HasInit = HasInit;
  822. SwitchStmtBits.HasVar = HasVar;
  823. SwitchStmtBits.AllEnumCasesCovered = false;
  824. }
  825. SwitchStmt *SwitchStmt::Create(const ASTContext &Ctx, Stmt *Init, VarDecl *Var,
  826. Expr *Cond) {
  827. bool HasInit = Init != nullptr;
  828. bool HasVar = Var != nullptr;
  829. void *Mem = Ctx.Allocate(
  830. totalSizeToAlloc<Stmt *>(NumMandatoryStmtPtr + HasInit + HasVar),
  831. alignof(SwitchStmt));
  832. return new (Mem) SwitchStmt(Ctx, Init, Var, Cond);
  833. }
  834. SwitchStmt *SwitchStmt::CreateEmpty(const ASTContext &Ctx, bool HasInit,
  835. bool HasVar) {
  836. void *Mem = Ctx.Allocate(
  837. totalSizeToAlloc<Stmt *>(NumMandatoryStmtPtr + HasInit + HasVar),
  838. alignof(SwitchStmt));
  839. return new (Mem) SwitchStmt(EmptyShell(), HasInit, HasVar);
  840. }
  841. VarDecl *SwitchStmt::getConditionVariable() {
  842. auto *DS = getConditionVariableDeclStmt();
  843. if (!DS)
  844. return nullptr;
  845. return cast<VarDecl>(DS->getSingleDecl());
  846. }
  847. void SwitchStmt::setConditionVariable(const ASTContext &Ctx, VarDecl *V) {
  848. assert(hasVarStorage() &&
  849. "This switch statement has no storage for a condition variable!");
  850. if (!V) {
  851. getTrailingObjects<Stmt *>()[varOffset()] = nullptr;
  852. return;
  853. }
  854. SourceRange VarRange = V->getSourceRange();
  855. getTrailingObjects<Stmt *>()[varOffset()] = new (Ctx)
  856. DeclStmt(DeclGroupRef(V), VarRange.getBegin(), VarRange.getEnd());
  857. }
  858. WhileStmt::WhileStmt(const ASTContext &Ctx, VarDecl *Var, Expr *Cond,
  859. Stmt *Body, SourceLocation WL)
  860. : Stmt(WhileStmtClass) {
  861. bool HasVar = Var != nullptr;
  862. WhileStmtBits.HasVar = HasVar;
  863. setCond(Cond);
  864. setBody(Body);
  865. if (HasVar)
  866. setConditionVariable(Ctx, Var);
  867. setWhileLoc(WL);
  868. }
  869. WhileStmt::WhileStmt(EmptyShell Empty, bool HasVar)
  870. : Stmt(WhileStmtClass, Empty) {
  871. WhileStmtBits.HasVar = HasVar;
  872. }
  873. WhileStmt *WhileStmt::Create(const ASTContext &Ctx, VarDecl *Var, Expr *Cond,
  874. Stmt *Body, SourceLocation WL) {
  875. bool HasVar = Var != nullptr;
  876. void *Mem =
  877. Ctx.Allocate(totalSizeToAlloc<Stmt *>(NumMandatoryStmtPtr + HasVar),
  878. alignof(WhileStmt));
  879. return new (Mem) WhileStmt(Ctx, Var, Cond, Body, WL);
  880. }
  881. WhileStmt *WhileStmt::CreateEmpty(const ASTContext &Ctx, bool HasVar) {
  882. void *Mem =
  883. Ctx.Allocate(totalSizeToAlloc<Stmt *>(NumMandatoryStmtPtr + HasVar),
  884. alignof(WhileStmt));
  885. return new (Mem) WhileStmt(EmptyShell(), HasVar);
  886. }
  887. VarDecl *WhileStmt::getConditionVariable() {
  888. auto *DS = getConditionVariableDeclStmt();
  889. if (!DS)
  890. return nullptr;
  891. return cast<VarDecl>(DS->getSingleDecl());
  892. }
  893. void WhileStmt::setConditionVariable(const ASTContext &Ctx, VarDecl *V) {
  894. assert(hasVarStorage() &&
  895. "This while statement has no storage for a condition variable!");
  896. if (!V) {
  897. getTrailingObjects<Stmt *>()[varOffset()] = nullptr;
  898. return;
  899. }
  900. SourceRange VarRange = V->getSourceRange();
  901. getTrailingObjects<Stmt *>()[varOffset()] = new (Ctx)
  902. DeclStmt(DeclGroupRef(V), VarRange.getBegin(), VarRange.getEnd());
  903. }
  904. // IndirectGotoStmt
  905. LabelDecl *IndirectGotoStmt::getConstantTarget() {
  906. if (auto *E = dyn_cast<AddrLabelExpr>(getTarget()->IgnoreParenImpCasts()))
  907. return E->getLabel();
  908. return nullptr;
  909. }
  910. // ReturnStmt
  911. ReturnStmt::ReturnStmt(SourceLocation RL, Expr *E, const VarDecl *NRVOCandidate)
  912. : Stmt(ReturnStmtClass), RetExpr(E) {
  913. bool HasNRVOCandidate = NRVOCandidate != nullptr;
  914. ReturnStmtBits.HasNRVOCandidate = HasNRVOCandidate;
  915. if (HasNRVOCandidate)
  916. setNRVOCandidate(NRVOCandidate);
  917. setReturnLoc(RL);
  918. }
  919. ReturnStmt::ReturnStmt(EmptyShell Empty, bool HasNRVOCandidate)
  920. : Stmt(ReturnStmtClass, Empty) {
  921. ReturnStmtBits.HasNRVOCandidate = HasNRVOCandidate;
  922. }
  923. ReturnStmt *ReturnStmt::Create(const ASTContext &Ctx, SourceLocation RL,
  924. Expr *E, const VarDecl *NRVOCandidate) {
  925. bool HasNRVOCandidate = NRVOCandidate != nullptr;
  926. void *Mem = Ctx.Allocate(totalSizeToAlloc<const VarDecl *>(HasNRVOCandidate),
  927. alignof(ReturnStmt));
  928. return new (Mem) ReturnStmt(RL, E, NRVOCandidate);
  929. }
  930. ReturnStmt *ReturnStmt::CreateEmpty(const ASTContext &Ctx,
  931. bool HasNRVOCandidate) {
  932. void *Mem = Ctx.Allocate(totalSizeToAlloc<const VarDecl *>(HasNRVOCandidate),
  933. alignof(ReturnStmt));
  934. return new (Mem) ReturnStmt(EmptyShell(), HasNRVOCandidate);
  935. }
  936. // CaseStmt
  937. CaseStmt *CaseStmt::Create(const ASTContext &Ctx, Expr *lhs, Expr *rhs,
  938. SourceLocation caseLoc, SourceLocation ellipsisLoc,
  939. SourceLocation colonLoc) {
  940. bool CaseStmtIsGNURange = rhs != nullptr;
  941. void *Mem = Ctx.Allocate(
  942. totalSizeToAlloc<Stmt *, SourceLocation>(
  943. NumMandatoryStmtPtr + CaseStmtIsGNURange, CaseStmtIsGNURange),
  944. alignof(CaseStmt));
  945. return new (Mem) CaseStmt(lhs, rhs, caseLoc, ellipsisLoc, colonLoc);
  946. }
  947. CaseStmt *CaseStmt::CreateEmpty(const ASTContext &Ctx,
  948. bool CaseStmtIsGNURange) {
  949. void *Mem = Ctx.Allocate(
  950. totalSizeToAlloc<Stmt *, SourceLocation>(
  951. NumMandatoryStmtPtr + CaseStmtIsGNURange, CaseStmtIsGNURange),
  952. alignof(CaseStmt));
  953. return new (Mem) CaseStmt(EmptyShell(), CaseStmtIsGNURange);
  954. }
  955. SEHTryStmt::SEHTryStmt(bool IsCXXTry, SourceLocation TryLoc, Stmt *TryBlock,
  956. Stmt *Handler)
  957. : Stmt(SEHTryStmtClass), IsCXXTry(IsCXXTry), TryLoc(TryLoc) {
  958. Children[TRY] = TryBlock;
  959. Children[HANDLER] = Handler;
  960. }
  961. SEHTryStmt* SEHTryStmt::Create(const ASTContext &C, bool IsCXXTry,
  962. SourceLocation TryLoc, Stmt *TryBlock,
  963. Stmt *Handler) {
  964. return new(C) SEHTryStmt(IsCXXTry,TryLoc,TryBlock,Handler);
  965. }
  966. SEHExceptStmt* SEHTryStmt::getExceptHandler() const {
  967. return dyn_cast<SEHExceptStmt>(getHandler());
  968. }
  969. SEHFinallyStmt* SEHTryStmt::getFinallyHandler() const {
  970. return dyn_cast<SEHFinallyStmt>(getHandler());
  971. }
  972. SEHExceptStmt::SEHExceptStmt(SourceLocation Loc, Expr *FilterExpr, Stmt *Block)
  973. : Stmt(SEHExceptStmtClass), Loc(Loc) {
  974. Children[FILTER_EXPR] = FilterExpr;
  975. Children[BLOCK] = Block;
  976. }
  977. SEHExceptStmt* SEHExceptStmt::Create(const ASTContext &C, SourceLocation Loc,
  978. Expr *FilterExpr, Stmt *Block) {
  979. return new(C) SEHExceptStmt(Loc,FilterExpr,Block);
  980. }
  981. SEHFinallyStmt::SEHFinallyStmt(SourceLocation Loc, Stmt *Block)
  982. : Stmt(SEHFinallyStmtClass), Loc(Loc), Block(Block) {}
  983. SEHFinallyStmt* SEHFinallyStmt::Create(const ASTContext &C, SourceLocation Loc,
  984. Stmt *Block) {
  985. return new(C)SEHFinallyStmt(Loc,Block);
  986. }
  987. CapturedStmt::Capture::Capture(SourceLocation Loc, VariableCaptureKind Kind,
  988. VarDecl *Var)
  989. : VarAndKind(Var, Kind), Loc(Loc) {
  990. switch (Kind) {
  991. case VCK_This:
  992. assert(!Var && "'this' capture cannot have a variable!");
  993. break;
  994. case VCK_ByRef:
  995. assert(Var && "capturing by reference must have a variable!");
  996. break;
  997. case VCK_ByCopy:
  998. assert(Var && "capturing by copy must have a variable!");
  999. assert(
  1000. (Var->getType()->isScalarType() || (Var->getType()->isReferenceType() &&
  1001. Var->getType()
  1002. ->castAs<ReferenceType>()
  1003. ->getPointeeType()
  1004. ->isScalarType())) &&
  1005. "captures by copy are expected to have a scalar type!");
  1006. break;
  1007. case VCK_VLAType:
  1008. assert(!Var &&
  1009. "Variable-length array type capture cannot have a variable!");
  1010. break;
  1011. }
  1012. }
  1013. CapturedStmt::VariableCaptureKind
  1014. CapturedStmt::Capture::getCaptureKind() const {
  1015. return VarAndKind.getInt();
  1016. }
  1017. VarDecl *CapturedStmt::Capture::getCapturedVar() const {
  1018. assert((capturesVariable() || capturesVariableByCopy()) &&
  1019. "No variable available for 'this' or VAT capture");
  1020. return VarAndKind.getPointer();
  1021. }
  1022. CapturedStmt::Capture *CapturedStmt::getStoredCaptures() const {
  1023. unsigned Size = sizeof(CapturedStmt) + sizeof(Stmt *) * (NumCaptures + 1);
  1024. // Offset of the first Capture object.
  1025. unsigned FirstCaptureOffset = llvm::alignTo(Size, alignof(Capture));
  1026. return reinterpret_cast<Capture *>(
  1027. reinterpret_cast<char *>(const_cast<CapturedStmt *>(this))
  1028. + FirstCaptureOffset);
  1029. }
  1030. CapturedStmt::CapturedStmt(Stmt *S, CapturedRegionKind Kind,
  1031. ArrayRef<Capture> Captures,
  1032. ArrayRef<Expr *> CaptureInits,
  1033. CapturedDecl *CD,
  1034. RecordDecl *RD)
  1035. : Stmt(CapturedStmtClass), NumCaptures(Captures.size()),
  1036. CapDeclAndKind(CD, Kind), TheRecordDecl(RD) {
  1037. assert( S && "null captured statement");
  1038. assert(CD && "null captured declaration for captured statement");
  1039. assert(RD && "null record declaration for captured statement");
  1040. // Copy initialization expressions.
  1041. Stmt **Stored = getStoredStmts();
  1042. for (unsigned I = 0, N = NumCaptures; I != N; ++I)
  1043. *Stored++ = CaptureInits[I];
  1044. // Copy the statement being captured.
  1045. *Stored = S;
  1046. // Copy all Capture objects.
  1047. Capture *Buffer = getStoredCaptures();
  1048. std::copy(Captures.begin(), Captures.end(), Buffer);
  1049. }
  1050. CapturedStmt::CapturedStmt(EmptyShell Empty, unsigned NumCaptures)
  1051. : Stmt(CapturedStmtClass, Empty), NumCaptures(NumCaptures),
  1052. CapDeclAndKind(nullptr, CR_Default) {
  1053. getStoredStmts()[NumCaptures] = nullptr;
  1054. }
  1055. CapturedStmt *CapturedStmt::Create(const ASTContext &Context, Stmt *S,
  1056. CapturedRegionKind Kind,
  1057. ArrayRef<Capture> Captures,
  1058. ArrayRef<Expr *> CaptureInits,
  1059. CapturedDecl *CD,
  1060. RecordDecl *RD) {
  1061. // The layout is
  1062. //
  1063. // -----------------------------------------------------------
  1064. // | CapturedStmt, Init, ..., Init, S, Capture, ..., Capture |
  1065. // ----------------^-------------------^----------------------
  1066. // getStoredStmts() getStoredCaptures()
  1067. //
  1068. // where S is the statement being captured.
  1069. //
  1070. assert(CaptureInits.size() == Captures.size() && "wrong number of arguments");
  1071. unsigned Size = sizeof(CapturedStmt) + sizeof(Stmt *) * (Captures.size() + 1);
  1072. if (!Captures.empty()) {
  1073. // Realign for the following Capture array.
  1074. Size = llvm::alignTo(Size, alignof(Capture));
  1075. Size += sizeof(Capture) * Captures.size();
  1076. }
  1077. void *Mem = Context.Allocate(Size);
  1078. return new (Mem) CapturedStmt(S, Kind, Captures, CaptureInits, CD, RD);
  1079. }
  1080. CapturedStmt *CapturedStmt::CreateDeserialized(const ASTContext &Context,
  1081. unsigned NumCaptures) {
  1082. unsigned Size = sizeof(CapturedStmt) + sizeof(Stmt *) * (NumCaptures + 1);
  1083. if (NumCaptures > 0) {
  1084. // Realign for the following Capture array.
  1085. Size = llvm::alignTo(Size, alignof(Capture));
  1086. Size += sizeof(Capture) * NumCaptures;
  1087. }
  1088. void *Mem = Context.Allocate(Size);
  1089. return new (Mem) CapturedStmt(EmptyShell(), NumCaptures);
  1090. }
  1091. Stmt::child_range CapturedStmt::children() {
  1092. // Children are captured field initializers.
  1093. return child_range(getStoredStmts(), getStoredStmts() + NumCaptures);
  1094. }
  1095. Stmt::const_child_range CapturedStmt::children() const {
  1096. return const_child_range(getStoredStmts(), getStoredStmts() + NumCaptures);
  1097. }
  1098. CapturedDecl *CapturedStmt::getCapturedDecl() {
  1099. return CapDeclAndKind.getPointer();
  1100. }
  1101. const CapturedDecl *CapturedStmt::getCapturedDecl() const {
  1102. return CapDeclAndKind.getPointer();
  1103. }
  1104. /// Set the outlined function declaration.
  1105. void CapturedStmt::setCapturedDecl(CapturedDecl *D) {
  1106. assert(D && "null CapturedDecl");
  1107. CapDeclAndKind.setPointer(D);
  1108. }
  1109. /// Retrieve the captured region kind.
  1110. CapturedRegionKind CapturedStmt::getCapturedRegionKind() const {
  1111. return CapDeclAndKind.getInt();
  1112. }
  1113. /// Set the captured region kind.
  1114. void CapturedStmt::setCapturedRegionKind(CapturedRegionKind Kind) {
  1115. CapDeclAndKind.setInt(Kind);
  1116. }
  1117. bool CapturedStmt::capturesVariable(const VarDecl *Var) const {
  1118. for (const auto &I : captures()) {
  1119. if (!I.capturesVariable() && !I.capturesVariableByCopy())
  1120. continue;
  1121. if (I.getCapturedVar()->getCanonicalDecl() == Var->getCanonicalDecl())
  1122. return true;
  1123. }
  1124. return false;
  1125. }