Stmt.cpp 48 KB

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