Stmt.cpp 48 KB

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