CFG.h 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- CFG.h - Classes for representing and building CFGs -------*- C++ -*-===//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. //
  14. // This file defines the CFG and CFGBuilder classes for representing and
  15. // building Control-Flow Graphs (CFGs) from ASTs.
  16. //
  17. //===----------------------------------------------------------------------===//
  18. #ifndef LLVM_CLANG_ANALYSIS_CFG_H
  19. #define LLVM_CLANG_ANALYSIS_CFG_H
  20. #include "clang/Analysis/Support/BumpVector.h"
  21. #include "clang/Analysis/ConstructionContext.h"
  22. #include "clang/AST/ExprCXX.h"
  23. #include "clang/AST/ExprObjC.h"
  24. #include "clang/Basic/LLVM.h"
  25. #include "llvm/ADT/DenseMap.h"
  26. #include "llvm/ADT/GraphTraits.h"
  27. #include "llvm/ADT/PointerIntPair.h"
  28. #include "llvm/ADT/iterator_range.h"
  29. #include "llvm/Support/Allocator.h"
  30. #include "llvm/Support/raw_ostream.h"
  31. #include <bitset>
  32. #include <cassert>
  33. #include <cstddef>
  34. #include <iterator>
  35. #include <memory>
  36. #include <optional>
  37. #include <vector>
  38. namespace clang {
  39. class ASTContext;
  40. class BinaryOperator;
  41. class CFG;
  42. class CXXBaseSpecifier;
  43. class CXXBindTemporaryExpr;
  44. class CXXCtorInitializer;
  45. class CXXDeleteExpr;
  46. class CXXDestructorDecl;
  47. class CXXNewExpr;
  48. class CXXRecordDecl;
  49. class Decl;
  50. class FieldDecl;
  51. class LangOptions;
  52. class VarDecl;
  53. /// Represents a top-level expression in a basic block.
  54. class CFGElement {
  55. public:
  56. enum Kind {
  57. // main kind
  58. Initializer,
  59. ScopeBegin,
  60. ScopeEnd,
  61. NewAllocator,
  62. LifetimeEnds,
  63. LoopExit,
  64. // stmt kind
  65. Statement,
  66. Constructor,
  67. CXXRecordTypedCall,
  68. STMT_BEGIN = Statement,
  69. STMT_END = CXXRecordTypedCall,
  70. // dtor kind
  71. AutomaticObjectDtor,
  72. DeleteDtor,
  73. BaseDtor,
  74. MemberDtor,
  75. TemporaryDtor,
  76. DTOR_BEGIN = AutomaticObjectDtor,
  77. DTOR_END = TemporaryDtor
  78. };
  79. protected:
  80. // The int bits are used to mark the kind.
  81. llvm::PointerIntPair<void *, 2> Data1;
  82. llvm::PointerIntPair<void *, 2> Data2;
  83. CFGElement(Kind kind, const void *Ptr1, const void *Ptr2 = nullptr)
  84. : Data1(const_cast<void*>(Ptr1), ((unsigned) kind) & 0x3),
  85. Data2(const_cast<void*>(Ptr2), (((unsigned) kind) >> 2) & 0x3) {
  86. assert(getKind() == kind);
  87. }
  88. CFGElement() = default;
  89. public:
  90. /// Convert to the specified CFGElement type, asserting that this
  91. /// CFGElement is of the desired type.
  92. template<typename T>
  93. T castAs() const {
  94. assert(T::isKind(*this));
  95. T t;
  96. CFGElement& e = t;
  97. e = *this;
  98. return t;
  99. }
  100. /// Convert to the specified CFGElement type, returning std::nullopt if this
  101. /// CFGElement is not of the desired type.
  102. template <typename T> std::optional<T> getAs() const {
  103. if (!T::isKind(*this))
  104. return std::nullopt;
  105. T t;
  106. CFGElement& e = t;
  107. e = *this;
  108. return t;
  109. }
  110. Kind getKind() const {
  111. unsigned x = Data2.getInt();
  112. x <<= 2;
  113. x |= Data1.getInt();
  114. return (Kind) x;
  115. }
  116. void dumpToStream(llvm::raw_ostream &OS) const;
  117. void dump() const {
  118. dumpToStream(llvm::errs());
  119. }
  120. };
  121. class CFGStmt : public CFGElement {
  122. public:
  123. explicit CFGStmt(const Stmt *S, Kind K = Statement) : CFGElement(K, S) {
  124. assert(isKind(*this));
  125. }
  126. const Stmt *getStmt() const {
  127. return static_cast<const Stmt *>(Data1.getPointer());
  128. }
  129. private:
  130. friend class CFGElement;
  131. static bool isKind(const CFGElement &E) {
  132. return E.getKind() >= STMT_BEGIN && E.getKind() <= STMT_END;
  133. }
  134. protected:
  135. CFGStmt() = default;
  136. };
  137. /// Represents C++ constructor call. Maintains information necessary to figure
  138. /// out what memory is being initialized by the constructor expression. For now
  139. /// this is only used by the analyzer's CFG.
  140. class CFGConstructor : public CFGStmt {
  141. public:
  142. explicit CFGConstructor(const CXXConstructExpr *CE,
  143. const ConstructionContext *C)
  144. : CFGStmt(CE, Constructor) {
  145. assert(C);
  146. Data2.setPointer(const_cast<ConstructionContext *>(C));
  147. }
  148. const ConstructionContext *getConstructionContext() const {
  149. return static_cast<ConstructionContext *>(Data2.getPointer());
  150. }
  151. private:
  152. friend class CFGElement;
  153. CFGConstructor() = default;
  154. static bool isKind(const CFGElement &E) {
  155. return E.getKind() == Constructor;
  156. }
  157. };
  158. /// Represents a function call that returns a C++ object by value. This, like
  159. /// constructor, requires a construction context in order to understand the
  160. /// storage of the returned object . In C such tracking is not necessary because
  161. /// no additional effort is required for destroying the object or modeling copy
  162. /// elision. Like CFGConstructor, this element is for now only used by the
  163. /// analyzer's CFG.
  164. class CFGCXXRecordTypedCall : public CFGStmt {
  165. public:
  166. /// Returns true when call expression \p CE needs to be represented
  167. /// by CFGCXXRecordTypedCall, as opposed to a regular CFGStmt.
  168. static bool isCXXRecordTypedCall(const Expr *E) {
  169. assert(isa<CallExpr>(E) || isa<ObjCMessageExpr>(E));
  170. // There is no such thing as reference-type expression. If the function
  171. // returns a reference, it'll return the respective lvalue or xvalue
  172. // instead, and we're only interested in objects.
  173. return !E->isGLValue() &&
  174. E->getType().getCanonicalType()->getAsCXXRecordDecl();
  175. }
  176. explicit CFGCXXRecordTypedCall(const Expr *E, const ConstructionContext *C)
  177. : CFGStmt(E, CXXRecordTypedCall) {
  178. assert(isCXXRecordTypedCall(E));
  179. assert(C && (isa<TemporaryObjectConstructionContext>(C) ||
  180. // These are possible in C++17 due to mandatory copy elision.
  181. isa<ReturnedValueConstructionContext>(C) ||
  182. isa<VariableConstructionContext>(C) ||
  183. isa<ConstructorInitializerConstructionContext>(C) ||
  184. isa<ArgumentConstructionContext>(C) ||
  185. isa<LambdaCaptureConstructionContext>(C)));
  186. Data2.setPointer(const_cast<ConstructionContext *>(C));
  187. }
  188. const ConstructionContext *getConstructionContext() const {
  189. return static_cast<ConstructionContext *>(Data2.getPointer());
  190. }
  191. private:
  192. friend class CFGElement;
  193. CFGCXXRecordTypedCall() = default;
  194. static bool isKind(const CFGElement &E) {
  195. return E.getKind() == CXXRecordTypedCall;
  196. }
  197. };
  198. /// Represents C++ base or member initializer from constructor's initialization
  199. /// list.
  200. class CFGInitializer : public CFGElement {
  201. public:
  202. explicit CFGInitializer(const CXXCtorInitializer *initializer)
  203. : CFGElement(Initializer, initializer) {}
  204. CXXCtorInitializer* getInitializer() const {
  205. return static_cast<CXXCtorInitializer*>(Data1.getPointer());
  206. }
  207. private:
  208. friend class CFGElement;
  209. CFGInitializer() = default;
  210. static bool isKind(const CFGElement &E) {
  211. return E.getKind() == Initializer;
  212. }
  213. };
  214. /// Represents C++ allocator call.
  215. class CFGNewAllocator : public CFGElement {
  216. public:
  217. explicit CFGNewAllocator(const CXXNewExpr *S)
  218. : CFGElement(NewAllocator, S) {}
  219. // Get the new expression.
  220. const CXXNewExpr *getAllocatorExpr() const {
  221. return static_cast<CXXNewExpr *>(Data1.getPointer());
  222. }
  223. private:
  224. friend class CFGElement;
  225. CFGNewAllocator() = default;
  226. static bool isKind(const CFGElement &elem) {
  227. return elem.getKind() == NewAllocator;
  228. }
  229. };
  230. /// Represents the point where a loop ends.
  231. /// This element is only produced when building the CFG for the static
  232. /// analyzer and hidden behind the 'cfg-loopexit' analyzer config flag.
  233. ///
  234. /// Note: a loop exit element can be reached even when the loop body was never
  235. /// entered.
  236. class CFGLoopExit : public CFGElement {
  237. public:
  238. explicit CFGLoopExit(const Stmt *stmt) : CFGElement(LoopExit, stmt) {}
  239. const Stmt *getLoopStmt() const {
  240. return static_cast<Stmt *>(Data1.getPointer());
  241. }
  242. private:
  243. friend class CFGElement;
  244. CFGLoopExit() = default;
  245. static bool isKind(const CFGElement &elem) {
  246. return elem.getKind() == LoopExit;
  247. }
  248. };
  249. /// Represents the point where the lifetime of an automatic object ends
  250. class CFGLifetimeEnds : public CFGElement {
  251. public:
  252. explicit CFGLifetimeEnds(const VarDecl *var, const Stmt *stmt)
  253. : CFGElement(LifetimeEnds, var, stmt) {}
  254. const VarDecl *getVarDecl() const {
  255. return static_cast<VarDecl *>(Data1.getPointer());
  256. }
  257. const Stmt *getTriggerStmt() const {
  258. return static_cast<Stmt *>(Data2.getPointer());
  259. }
  260. private:
  261. friend class CFGElement;
  262. CFGLifetimeEnds() = default;
  263. static bool isKind(const CFGElement &elem) {
  264. return elem.getKind() == LifetimeEnds;
  265. }
  266. };
  267. /// Represents beginning of a scope implicitly generated
  268. /// by the compiler on encountering a CompoundStmt
  269. class CFGScopeBegin : public CFGElement {
  270. public:
  271. CFGScopeBegin() {}
  272. CFGScopeBegin(const VarDecl *VD, const Stmt *S)
  273. : CFGElement(ScopeBegin, VD, S) {}
  274. // Get statement that triggered a new scope.
  275. const Stmt *getTriggerStmt() const {
  276. return static_cast<Stmt*>(Data2.getPointer());
  277. }
  278. // Get VD that triggered a new scope.
  279. const VarDecl *getVarDecl() const {
  280. return static_cast<VarDecl *>(Data1.getPointer());
  281. }
  282. private:
  283. friend class CFGElement;
  284. static bool isKind(const CFGElement &E) {
  285. Kind kind = E.getKind();
  286. return kind == ScopeBegin;
  287. }
  288. };
  289. /// Represents end of a scope implicitly generated by
  290. /// the compiler after the last Stmt in a CompoundStmt's body
  291. class CFGScopeEnd : public CFGElement {
  292. public:
  293. CFGScopeEnd() {}
  294. CFGScopeEnd(const VarDecl *VD, const Stmt *S) : CFGElement(ScopeEnd, VD, S) {}
  295. const VarDecl *getVarDecl() const {
  296. return static_cast<VarDecl *>(Data1.getPointer());
  297. }
  298. const Stmt *getTriggerStmt() const {
  299. return static_cast<Stmt *>(Data2.getPointer());
  300. }
  301. private:
  302. friend class CFGElement;
  303. static bool isKind(const CFGElement &E) {
  304. Kind kind = E.getKind();
  305. return kind == ScopeEnd;
  306. }
  307. };
  308. /// Represents C++ object destructor implicitly generated by compiler on various
  309. /// occasions.
  310. class CFGImplicitDtor : public CFGElement {
  311. protected:
  312. CFGImplicitDtor() = default;
  313. CFGImplicitDtor(Kind kind, const void *data1, const void *data2 = nullptr)
  314. : CFGElement(kind, data1, data2) {
  315. assert(kind >= DTOR_BEGIN && kind <= DTOR_END);
  316. }
  317. public:
  318. const CXXDestructorDecl *getDestructorDecl(ASTContext &astContext) const;
  319. bool isNoReturn(ASTContext &astContext) const;
  320. private:
  321. friend class CFGElement;
  322. static bool isKind(const CFGElement &E) {
  323. Kind kind = E.getKind();
  324. return kind >= DTOR_BEGIN && kind <= DTOR_END;
  325. }
  326. };
  327. /// Represents C++ object destructor implicitly generated for automatic object
  328. /// or temporary bound to const reference at the point of leaving its local
  329. /// scope.
  330. class CFGAutomaticObjDtor: public CFGImplicitDtor {
  331. public:
  332. CFGAutomaticObjDtor(const VarDecl *var, const Stmt *stmt)
  333. : CFGImplicitDtor(AutomaticObjectDtor, var, stmt) {}
  334. const VarDecl *getVarDecl() const {
  335. return static_cast<VarDecl*>(Data1.getPointer());
  336. }
  337. // Get statement end of which triggered the destructor call.
  338. const Stmt *getTriggerStmt() const {
  339. return static_cast<Stmt*>(Data2.getPointer());
  340. }
  341. private:
  342. friend class CFGElement;
  343. CFGAutomaticObjDtor() = default;
  344. static bool isKind(const CFGElement &elem) {
  345. return elem.getKind() == AutomaticObjectDtor;
  346. }
  347. };
  348. /// Represents C++ object destructor generated from a call to delete.
  349. class CFGDeleteDtor : public CFGImplicitDtor {
  350. public:
  351. CFGDeleteDtor(const CXXRecordDecl *RD, const CXXDeleteExpr *DE)
  352. : CFGImplicitDtor(DeleteDtor, RD, DE) {}
  353. const CXXRecordDecl *getCXXRecordDecl() const {
  354. return static_cast<CXXRecordDecl*>(Data1.getPointer());
  355. }
  356. // Get Delete expression which triggered the destructor call.
  357. const CXXDeleteExpr *getDeleteExpr() const {
  358. return static_cast<CXXDeleteExpr *>(Data2.getPointer());
  359. }
  360. private:
  361. friend class CFGElement;
  362. CFGDeleteDtor() = default;
  363. static bool isKind(const CFGElement &elem) {
  364. return elem.getKind() == DeleteDtor;
  365. }
  366. };
  367. /// Represents C++ object destructor implicitly generated for base object in
  368. /// destructor.
  369. class CFGBaseDtor : public CFGImplicitDtor {
  370. public:
  371. CFGBaseDtor(const CXXBaseSpecifier *base)
  372. : CFGImplicitDtor(BaseDtor, base) {}
  373. const CXXBaseSpecifier *getBaseSpecifier() const {
  374. return static_cast<const CXXBaseSpecifier*>(Data1.getPointer());
  375. }
  376. private:
  377. friend class CFGElement;
  378. CFGBaseDtor() = default;
  379. static bool isKind(const CFGElement &E) {
  380. return E.getKind() == BaseDtor;
  381. }
  382. };
  383. /// Represents C++ object destructor implicitly generated for member object in
  384. /// destructor.
  385. class CFGMemberDtor : public CFGImplicitDtor {
  386. public:
  387. CFGMemberDtor(const FieldDecl *field)
  388. : CFGImplicitDtor(MemberDtor, field, nullptr) {}
  389. const FieldDecl *getFieldDecl() const {
  390. return static_cast<const FieldDecl*>(Data1.getPointer());
  391. }
  392. private:
  393. friend class CFGElement;
  394. CFGMemberDtor() = default;
  395. static bool isKind(const CFGElement &E) {
  396. return E.getKind() == MemberDtor;
  397. }
  398. };
  399. /// Represents C++ object destructor implicitly generated at the end of full
  400. /// expression for temporary object.
  401. class CFGTemporaryDtor : public CFGImplicitDtor {
  402. public:
  403. CFGTemporaryDtor(const CXXBindTemporaryExpr *expr)
  404. : CFGImplicitDtor(TemporaryDtor, expr, nullptr) {}
  405. const CXXBindTemporaryExpr *getBindTemporaryExpr() const {
  406. return static_cast<const CXXBindTemporaryExpr *>(Data1.getPointer());
  407. }
  408. private:
  409. friend class CFGElement;
  410. CFGTemporaryDtor() = default;
  411. static bool isKind(const CFGElement &E) {
  412. return E.getKind() == TemporaryDtor;
  413. }
  414. };
  415. /// Represents CFGBlock terminator statement.
  416. ///
  417. class CFGTerminator {
  418. public:
  419. enum Kind {
  420. /// A branch that corresponds to a statement in the code,
  421. /// such as an if-statement.
  422. StmtBranch,
  423. /// A branch in control flow of destructors of temporaries. In this case
  424. /// terminator statement is the same statement that branches control flow
  425. /// in evaluation of matching full expression.
  426. TemporaryDtorsBranch,
  427. /// A shortcut around virtual base initializers. It gets taken when
  428. /// virtual base classes have already been initialized by the constructor
  429. /// of the most derived class while we're in the base class.
  430. VirtualBaseBranch,
  431. /// Number of different kinds, for assertions. We subtract 1 so that
  432. /// to keep receiving compiler warnings when we don't cover all enum values
  433. /// in a switch.
  434. NumKindsMinusOne = VirtualBaseBranch
  435. };
  436. private:
  437. static constexpr int KindBits = 2;
  438. static_assert((1 << KindBits) > NumKindsMinusOne,
  439. "Not enough room for kind!");
  440. llvm::PointerIntPair<Stmt *, KindBits> Data;
  441. public:
  442. CFGTerminator() { assert(!isValid()); }
  443. CFGTerminator(Stmt *S, Kind K = StmtBranch) : Data(S, K) {}
  444. bool isValid() const { return Data.getOpaqueValue() != nullptr; }
  445. Stmt *getStmt() { return Data.getPointer(); }
  446. const Stmt *getStmt() const { return Data.getPointer(); }
  447. Kind getKind() const { return static_cast<Kind>(Data.getInt()); }
  448. bool isStmtBranch() const {
  449. return getKind() == StmtBranch;
  450. }
  451. bool isTemporaryDtorsBranch() const {
  452. return getKind() == TemporaryDtorsBranch;
  453. }
  454. bool isVirtualBaseBranch() const {
  455. return getKind() == VirtualBaseBranch;
  456. }
  457. };
  458. /// Represents a single basic block in a source-level CFG.
  459. /// It consists of:
  460. ///
  461. /// (1) A set of statements/expressions (which may contain subexpressions).
  462. /// (2) A "terminator" statement (not in the set of statements).
  463. /// (3) A list of successors and predecessors.
  464. ///
  465. /// Terminator: The terminator represents the type of control-flow that occurs
  466. /// at the end of the basic block. The terminator is a Stmt* referring to an
  467. /// AST node that has control-flow: if-statements, breaks, loops, etc.
  468. /// If the control-flow is conditional, the condition expression will appear
  469. /// within the set of statements in the block (usually the last statement).
  470. ///
  471. /// Predecessors: the order in the set of predecessors is arbitrary.
  472. ///
  473. /// Successors: the order in the set of successors is NOT arbitrary. We
  474. /// currently have the following orderings based on the terminator:
  475. ///
  476. /// Terminator | Successor Ordering
  477. /// ------------------|------------------------------------
  478. /// if | Then Block; Else Block
  479. /// ? operator | LHS expression; RHS expression
  480. /// logical and/or | expression that consumes the op, RHS
  481. /// vbase inits | already handled by the most derived class; not yet
  482. ///
  483. /// But note that any of that may be NULL in case of optimized-out edges.
  484. class CFGBlock {
  485. class ElementList {
  486. using ImplTy = BumpVector<CFGElement>;
  487. ImplTy Impl;
  488. public:
  489. ElementList(BumpVectorContext &C) : Impl(C, 4) {}
  490. using iterator = std::reverse_iterator<ImplTy::iterator>;
  491. using const_iterator = std::reverse_iterator<ImplTy::const_iterator>;
  492. using reverse_iterator = ImplTy::iterator;
  493. using const_reverse_iterator = ImplTy::const_iterator;
  494. using const_reference = ImplTy::const_reference;
  495. void push_back(CFGElement e, BumpVectorContext &C) { Impl.push_back(e, C); }
  496. reverse_iterator insert(reverse_iterator I, size_t Cnt, CFGElement E,
  497. BumpVectorContext &C) {
  498. return Impl.insert(I, Cnt, E, C);
  499. }
  500. const_reference front() const { return Impl.back(); }
  501. const_reference back() const { return Impl.front(); }
  502. iterator begin() { return Impl.rbegin(); }
  503. iterator end() { return Impl.rend(); }
  504. const_iterator begin() const { return Impl.rbegin(); }
  505. const_iterator end() const { return Impl.rend(); }
  506. reverse_iterator rbegin() { return Impl.begin(); }
  507. reverse_iterator rend() { return Impl.end(); }
  508. const_reverse_iterator rbegin() const { return Impl.begin(); }
  509. const_reverse_iterator rend() const { return Impl.end(); }
  510. CFGElement operator[](size_t i) const {
  511. assert(i < Impl.size());
  512. return Impl[Impl.size() - 1 - i];
  513. }
  514. size_t size() const { return Impl.size(); }
  515. bool empty() const { return Impl.empty(); }
  516. };
  517. /// A convenience class for comparing CFGElements, since methods of CFGBlock
  518. /// like operator[] return CFGElements by value. This is practically a wrapper
  519. /// around a (CFGBlock, Index) pair.
  520. template <bool IsConst> class ElementRefImpl {
  521. template <bool IsOtherConst> friend class ElementRefImpl;
  522. using CFGBlockPtr =
  523. std::conditional_t<IsConst, const CFGBlock *, CFGBlock *>;
  524. using CFGElementPtr =
  525. std::conditional_t<IsConst, const CFGElement *, CFGElement *>;
  526. protected:
  527. CFGBlockPtr Parent;
  528. size_t Index;
  529. public:
  530. ElementRefImpl(CFGBlockPtr Parent, size_t Index)
  531. : Parent(Parent), Index(Index) {}
  532. template <bool IsOtherConst>
  533. ElementRefImpl(ElementRefImpl<IsOtherConst> Other)
  534. : ElementRefImpl(Other.Parent, Other.Index) {}
  535. size_t getIndexInBlock() const { return Index; }
  536. CFGBlockPtr getParent() { return Parent; }
  537. CFGBlockPtr getParent() const { return Parent; }
  538. bool operator<(ElementRefImpl Other) const {
  539. return std::make_pair(Parent, Index) <
  540. std::make_pair(Other.Parent, Other.Index);
  541. }
  542. bool operator==(ElementRefImpl Other) const {
  543. return Parent == Other.Parent && Index == Other.Index;
  544. }
  545. bool operator!=(ElementRefImpl Other) const { return !(*this == Other); }
  546. CFGElement operator*() const { return (*Parent)[Index]; }
  547. CFGElementPtr operator->() const { return &*(Parent->begin() + Index); }
  548. void dumpToStream(llvm::raw_ostream &OS) const {
  549. OS << getIndexInBlock() + 1 << ": ";
  550. (*this)->dumpToStream(OS);
  551. }
  552. void dump() const {
  553. dumpToStream(llvm::errs());
  554. }
  555. };
  556. template <bool IsReverse, bool IsConst> class ElementRefIterator {
  557. template <bool IsOtherReverse, bool IsOtherConst>
  558. friend class ElementRefIterator;
  559. using CFGBlockRef =
  560. std::conditional_t<IsConst, const CFGBlock *, CFGBlock *>;
  561. using UnderlayingIteratorTy = std::conditional_t<
  562. IsConst,
  563. std::conditional_t<IsReverse, ElementList::const_reverse_iterator,
  564. ElementList::const_iterator>,
  565. std::conditional_t<IsReverse, ElementList::reverse_iterator,
  566. ElementList::iterator>>;
  567. using IteratorTraits = typename std::iterator_traits<UnderlayingIteratorTy>;
  568. using ElementRef = typename CFGBlock::ElementRefImpl<IsConst>;
  569. public:
  570. using difference_type = typename IteratorTraits::difference_type;
  571. using value_type = ElementRef;
  572. using pointer = ElementRef *;
  573. using iterator_category = typename IteratorTraits::iterator_category;
  574. private:
  575. CFGBlockRef Parent;
  576. UnderlayingIteratorTy Pos;
  577. public:
  578. ElementRefIterator(CFGBlockRef Parent, UnderlayingIteratorTy Pos)
  579. : Parent(Parent), Pos(Pos) {}
  580. template <bool IsOtherConst>
  581. ElementRefIterator(ElementRefIterator<false, IsOtherConst> E)
  582. : ElementRefIterator(E.Parent, E.Pos.base()) {}
  583. template <bool IsOtherConst>
  584. ElementRefIterator(ElementRefIterator<true, IsOtherConst> E)
  585. : ElementRefIterator(E.Parent, std::make_reverse_iterator(E.Pos)) {}
  586. bool operator<(ElementRefIterator Other) const {
  587. assert(Parent == Other.Parent);
  588. return Pos < Other.Pos;
  589. }
  590. bool operator==(ElementRefIterator Other) const {
  591. return Parent == Other.Parent && Pos == Other.Pos;
  592. }
  593. bool operator!=(ElementRefIterator Other) const {
  594. return !(*this == Other);
  595. }
  596. private:
  597. template <bool IsOtherConst>
  598. static size_t
  599. getIndexInBlock(CFGBlock::ElementRefIterator<true, IsOtherConst> E) {
  600. return E.Parent->size() - (E.Pos - E.Parent->rbegin()) - 1;
  601. }
  602. template <bool IsOtherConst>
  603. static size_t
  604. getIndexInBlock(CFGBlock::ElementRefIterator<false, IsOtherConst> E) {
  605. return E.Pos - E.Parent->begin();
  606. }
  607. public:
  608. value_type operator*() { return {Parent, getIndexInBlock(*this)}; }
  609. difference_type operator-(ElementRefIterator Other) const {
  610. return Pos - Other.Pos;
  611. }
  612. ElementRefIterator operator++() {
  613. ++this->Pos;
  614. return *this;
  615. }
  616. ElementRefIterator operator++(int) {
  617. ElementRefIterator Ret = *this;
  618. ++*this;
  619. return Ret;
  620. }
  621. ElementRefIterator operator+(size_t count) {
  622. this->Pos += count;
  623. return *this;
  624. }
  625. ElementRefIterator operator-(size_t count) {
  626. this->Pos -= count;
  627. return *this;
  628. }
  629. };
  630. public:
  631. /// The set of statements in the basic block.
  632. ElementList Elements;
  633. /// An (optional) label that prefixes the executable statements in the block.
  634. /// When this variable is non-NULL, it is either an instance of LabelStmt,
  635. /// SwitchCase or CXXCatchStmt.
  636. Stmt *Label = nullptr;
  637. /// The terminator for a basic block that indicates the type of control-flow
  638. /// that occurs between a block and its successors.
  639. CFGTerminator Terminator;
  640. /// Some blocks are used to represent the "loop edge" to the start of a loop
  641. /// from within the loop body. This Stmt* will be refer to the loop statement
  642. /// for such blocks (and be null otherwise).
  643. const Stmt *LoopTarget = nullptr;
  644. /// A numerical ID assigned to a CFGBlock during construction of the CFG.
  645. unsigned BlockID;
  646. public:
  647. /// This class represents a potential adjacent block in the CFG. It encodes
  648. /// whether or not the block is actually reachable, or can be proved to be
  649. /// trivially unreachable. For some cases it allows one to encode scenarios
  650. /// where a block was substituted because the original (now alternate) block
  651. /// is unreachable.
  652. class AdjacentBlock {
  653. enum Kind {
  654. AB_Normal,
  655. AB_Unreachable,
  656. AB_Alternate
  657. };
  658. CFGBlock *ReachableBlock;
  659. llvm::PointerIntPair<CFGBlock *, 2> UnreachableBlock;
  660. public:
  661. /// Construct an AdjacentBlock with a possibly unreachable block.
  662. AdjacentBlock(CFGBlock *B, bool IsReachable);
  663. /// Construct an AdjacentBlock with a reachable block and an alternate
  664. /// unreachable block.
  665. AdjacentBlock(CFGBlock *B, CFGBlock *AlternateBlock);
  666. /// Get the reachable block, if one exists.
  667. CFGBlock *getReachableBlock() const {
  668. return ReachableBlock;
  669. }
  670. /// Get the potentially unreachable block.
  671. CFGBlock *getPossiblyUnreachableBlock() const {
  672. return UnreachableBlock.getPointer();
  673. }
  674. /// Provide an implicit conversion to CFGBlock* so that
  675. /// AdjacentBlock can be substituted for CFGBlock*.
  676. operator CFGBlock*() const {
  677. return getReachableBlock();
  678. }
  679. CFGBlock& operator *() const {
  680. return *getReachableBlock();
  681. }
  682. CFGBlock* operator ->() const {
  683. return getReachableBlock();
  684. }
  685. bool isReachable() const {
  686. Kind K = (Kind) UnreachableBlock.getInt();
  687. return K == AB_Normal || K == AB_Alternate;
  688. }
  689. };
  690. private:
  691. /// Keep track of the predecessor / successor CFG blocks.
  692. using AdjacentBlocks = BumpVector<AdjacentBlock>;
  693. AdjacentBlocks Preds;
  694. AdjacentBlocks Succs;
  695. /// This bit is set when the basic block contains a function call
  696. /// or implicit destructor that is attributed as 'noreturn'. In that case,
  697. /// control cannot technically ever proceed past this block. All such blocks
  698. /// will have a single immediate successor: the exit block. This allows them
  699. /// to be easily reached from the exit block and using this bit quickly
  700. /// recognized without scanning the contents of the block.
  701. ///
  702. /// Optimization Note: This bit could be profitably folded with Terminator's
  703. /// storage if the memory usage of CFGBlock becomes an issue.
  704. unsigned HasNoReturnElement : 1;
  705. /// The parent CFG that owns this CFGBlock.
  706. CFG *Parent;
  707. public:
  708. explicit CFGBlock(unsigned blockid, BumpVectorContext &C, CFG *parent)
  709. : Elements(C), Terminator(nullptr), BlockID(blockid), Preds(C, 1),
  710. Succs(C, 1), HasNoReturnElement(false), Parent(parent) {}
  711. // Statement iterators
  712. using iterator = ElementList::iterator;
  713. using const_iterator = ElementList::const_iterator;
  714. using reverse_iterator = ElementList::reverse_iterator;
  715. using const_reverse_iterator = ElementList::const_reverse_iterator;
  716. size_t getIndexInCFG() const;
  717. CFGElement front() const { return Elements.front(); }
  718. CFGElement back() const { return Elements.back(); }
  719. iterator begin() { return Elements.begin(); }
  720. iterator end() { return Elements.end(); }
  721. const_iterator begin() const { return Elements.begin(); }
  722. const_iterator end() const { return Elements.end(); }
  723. reverse_iterator rbegin() { return Elements.rbegin(); }
  724. reverse_iterator rend() { return Elements.rend(); }
  725. const_reverse_iterator rbegin() const { return Elements.rbegin(); }
  726. const_reverse_iterator rend() const { return Elements.rend(); }
  727. using CFGElementRef = ElementRefImpl<false>;
  728. using ConstCFGElementRef = ElementRefImpl<true>;
  729. using ref_iterator = ElementRefIterator<false, false>;
  730. using ref_iterator_range = llvm::iterator_range<ref_iterator>;
  731. using const_ref_iterator = ElementRefIterator<false, true>;
  732. using const_ref_iterator_range = llvm::iterator_range<const_ref_iterator>;
  733. using reverse_ref_iterator = ElementRefIterator<true, false>;
  734. using reverse_ref_iterator_range = llvm::iterator_range<reverse_ref_iterator>;
  735. using const_reverse_ref_iterator = ElementRefIterator<true, true>;
  736. using const_reverse_ref_iterator_range =
  737. llvm::iterator_range<const_reverse_ref_iterator>;
  738. ref_iterator ref_begin() { return {this, begin()}; }
  739. ref_iterator ref_end() { return {this, end()}; }
  740. const_ref_iterator ref_begin() const { return {this, begin()}; }
  741. const_ref_iterator ref_end() const { return {this, end()}; }
  742. reverse_ref_iterator rref_begin() { return {this, rbegin()}; }
  743. reverse_ref_iterator rref_end() { return {this, rend()}; }
  744. const_reverse_ref_iterator rref_begin() const { return {this, rbegin()}; }
  745. const_reverse_ref_iterator rref_end() const { return {this, rend()}; }
  746. ref_iterator_range refs() { return {ref_begin(), ref_end()}; }
  747. const_ref_iterator_range refs() const { return {ref_begin(), ref_end()}; }
  748. reverse_ref_iterator_range rrefs() { return {rref_begin(), rref_end()}; }
  749. const_reverse_ref_iterator_range rrefs() const {
  750. return {rref_begin(), rref_end()};
  751. }
  752. unsigned size() const { return Elements.size(); }
  753. bool empty() const { return Elements.empty(); }
  754. CFGElement operator[](size_t i) const { return Elements[i]; }
  755. // CFG iterators
  756. using pred_iterator = AdjacentBlocks::iterator;
  757. using const_pred_iterator = AdjacentBlocks::const_iterator;
  758. using pred_reverse_iterator = AdjacentBlocks::reverse_iterator;
  759. using const_pred_reverse_iterator = AdjacentBlocks::const_reverse_iterator;
  760. using pred_range = llvm::iterator_range<pred_iterator>;
  761. using pred_const_range = llvm::iterator_range<const_pred_iterator>;
  762. using succ_iterator = AdjacentBlocks::iterator;
  763. using const_succ_iterator = AdjacentBlocks::const_iterator;
  764. using succ_reverse_iterator = AdjacentBlocks::reverse_iterator;
  765. using const_succ_reverse_iterator = AdjacentBlocks::const_reverse_iterator;
  766. using succ_range = llvm::iterator_range<succ_iterator>;
  767. using succ_const_range = llvm::iterator_range<const_succ_iterator>;
  768. pred_iterator pred_begin() { return Preds.begin(); }
  769. pred_iterator pred_end() { return Preds.end(); }
  770. const_pred_iterator pred_begin() const { return Preds.begin(); }
  771. const_pred_iterator pred_end() const { return Preds.end(); }
  772. pred_reverse_iterator pred_rbegin() { return Preds.rbegin(); }
  773. pred_reverse_iterator pred_rend() { return Preds.rend(); }
  774. const_pred_reverse_iterator pred_rbegin() const { return Preds.rbegin(); }
  775. const_pred_reverse_iterator pred_rend() const { return Preds.rend(); }
  776. pred_range preds() {
  777. return pred_range(pred_begin(), pred_end());
  778. }
  779. pred_const_range preds() const {
  780. return pred_const_range(pred_begin(), pred_end());
  781. }
  782. succ_iterator succ_begin() { return Succs.begin(); }
  783. succ_iterator succ_end() { return Succs.end(); }
  784. const_succ_iterator succ_begin() const { return Succs.begin(); }
  785. const_succ_iterator succ_end() const { return Succs.end(); }
  786. succ_reverse_iterator succ_rbegin() { return Succs.rbegin(); }
  787. succ_reverse_iterator succ_rend() { return Succs.rend(); }
  788. const_succ_reverse_iterator succ_rbegin() const { return Succs.rbegin(); }
  789. const_succ_reverse_iterator succ_rend() const { return Succs.rend(); }
  790. succ_range succs() {
  791. return succ_range(succ_begin(), succ_end());
  792. }
  793. succ_const_range succs() const {
  794. return succ_const_range(succ_begin(), succ_end());
  795. }
  796. unsigned succ_size() const { return Succs.size(); }
  797. bool succ_empty() const { return Succs.empty(); }
  798. unsigned pred_size() const { return Preds.size(); }
  799. bool pred_empty() const { return Preds.empty(); }
  800. class FilterOptions {
  801. public:
  802. unsigned IgnoreNullPredecessors : 1;
  803. unsigned IgnoreDefaultsWithCoveredEnums : 1;
  804. FilterOptions()
  805. : IgnoreNullPredecessors(1), IgnoreDefaultsWithCoveredEnums(0) {}
  806. };
  807. static bool FilterEdge(const FilterOptions &F, const CFGBlock *Src,
  808. const CFGBlock *Dst);
  809. template <typename IMPL, bool IsPred>
  810. class FilteredCFGBlockIterator {
  811. private:
  812. IMPL I, E;
  813. const FilterOptions F;
  814. const CFGBlock *From;
  815. public:
  816. explicit FilteredCFGBlockIterator(const IMPL &i, const IMPL &e,
  817. const CFGBlock *from,
  818. const FilterOptions &f)
  819. : I(i), E(e), F(f), From(from) {
  820. while (hasMore() && Filter(*I))
  821. ++I;
  822. }
  823. bool hasMore() const { return I != E; }
  824. FilteredCFGBlockIterator &operator++() {
  825. do { ++I; } while (hasMore() && Filter(*I));
  826. return *this;
  827. }
  828. const CFGBlock *operator*() const { return *I; }
  829. private:
  830. bool Filter(const CFGBlock *To) {
  831. return IsPred ? FilterEdge(F, To, From) : FilterEdge(F, From, To);
  832. }
  833. };
  834. using filtered_pred_iterator =
  835. FilteredCFGBlockIterator<const_pred_iterator, true>;
  836. using filtered_succ_iterator =
  837. FilteredCFGBlockIterator<const_succ_iterator, false>;
  838. filtered_pred_iterator filtered_pred_start_end(const FilterOptions &f) const {
  839. return filtered_pred_iterator(pred_begin(), pred_end(), this, f);
  840. }
  841. filtered_succ_iterator filtered_succ_start_end(const FilterOptions &f) const {
  842. return filtered_succ_iterator(succ_begin(), succ_end(), this, f);
  843. }
  844. // Manipulation of block contents
  845. void setTerminator(CFGTerminator Term) { Terminator = Term; }
  846. void setLabel(Stmt *Statement) { Label = Statement; }
  847. void setLoopTarget(const Stmt *loopTarget) { LoopTarget = loopTarget; }
  848. void setHasNoReturnElement() { HasNoReturnElement = true; }
  849. /// Returns true if the block would eventually end with a sink (a noreturn
  850. /// node).
  851. bool isInevitablySinking() const;
  852. CFGTerminator getTerminator() const { return Terminator; }
  853. Stmt *getTerminatorStmt() { return Terminator.getStmt(); }
  854. const Stmt *getTerminatorStmt() const { return Terminator.getStmt(); }
  855. /// \returns the last (\c rbegin()) condition, e.g. observe the following code
  856. /// snippet:
  857. /// if (A && B && C)
  858. /// A block would be created for \c A, \c B, and \c C. For the latter,
  859. /// \c getTerminatorStmt() would retrieve the entire condition, rather than
  860. /// C itself, while this method would only return C.
  861. const Expr *getLastCondition() const;
  862. Stmt *getTerminatorCondition(bool StripParens = true);
  863. const Stmt *getTerminatorCondition(bool StripParens = true) const {
  864. return const_cast<CFGBlock*>(this)->getTerminatorCondition(StripParens);
  865. }
  866. const Stmt *getLoopTarget() const { return LoopTarget; }
  867. Stmt *getLabel() { return Label; }
  868. const Stmt *getLabel() const { return Label; }
  869. bool hasNoReturnElement() const { return HasNoReturnElement; }
  870. unsigned getBlockID() const { return BlockID; }
  871. CFG *getParent() const { return Parent; }
  872. void dump() const;
  873. void dump(const CFG *cfg, const LangOptions &LO, bool ShowColors = false) const;
  874. void print(raw_ostream &OS, const CFG* cfg, const LangOptions &LO,
  875. bool ShowColors) const;
  876. void printTerminator(raw_ostream &OS, const LangOptions &LO) const;
  877. void printTerminatorJson(raw_ostream &Out, const LangOptions &LO,
  878. bool AddQuotes) const;
  879. void printAsOperand(raw_ostream &OS, bool /*PrintType*/) {
  880. OS << "BB#" << getBlockID();
  881. }
  882. /// Adds a (potentially unreachable) successor block to the current block.
  883. void addSuccessor(AdjacentBlock Succ, BumpVectorContext &C);
  884. void appendStmt(Stmt *statement, BumpVectorContext &C) {
  885. Elements.push_back(CFGStmt(statement), C);
  886. }
  887. void appendConstructor(CXXConstructExpr *CE, const ConstructionContext *CC,
  888. BumpVectorContext &C) {
  889. Elements.push_back(CFGConstructor(CE, CC), C);
  890. }
  891. void appendCXXRecordTypedCall(Expr *E,
  892. const ConstructionContext *CC,
  893. BumpVectorContext &C) {
  894. Elements.push_back(CFGCXXRecordTypedCall(E, CC), C);
  895. }
  896. void appendInitializer(CXXCtorInitializer *initializer,
  897. BumpVectorContext &C) {
  898. Elements.push_back(CFGInitializer(initializer), C);
  899. }
  900. void appendNewAllocator(CXXNewExpr *NE,
  901. BumpVectorContext &C) {
  902. Elements.push_back(CFGNewAllocator(NE), C);
  903. }
  904. void appendScopeBegin(const VarDecl *VD, const Stmt *S,
  905. BumpVectorContext &C) {
  906. Elements.push_back(CFGScopeBegin(VD, S), C);
  907. }
  908. void prependScopeBegin(const VarDecl *VD, const Stmt *S,
  909. BumpVectorContext &C) {
  910. Elements.insert(Elements.rbegin(), 1, CFGScopeBegin(VD, S), C);
  911. }
  912. void appendScopeEnd(const VarDecl *VD, const Stmt *S, BumpVectorContext &C) {
  913. Elements.push_back(CFGScopeEnd(VD, S), C);
  914. }
  915. void prependScopeEnd(const VarDecl *VD, const Stmt *S, BumpVectorContext &C) {
  916. Elements.insert(Elements.rbegin(), 1, CFGScopeEnd(VD, S), C);
  917. }
  918. void appendBaseDtor(const CXXBaseSpecifier *BS, BumpVectorContext &C) {
  919. Elements.push_back(CFGBaseDtor(BS), C);
  920. }
  921. void appendMemberDtor(FieldDecl *FD, BumpVectorContext &C) {
  922. Elements.push_back(CFGMemberDtor(FD), C);
  923. }
  924. void appendTemporaryDtor(CXXBindTemporaryExpr *E, BumpVectorContext &C) {
  925. Elements.push_back(CFGTemporaryDtor(E), C);
  926. }
  927. void appendAutomaticObjDtor(VarDecl *VD, Stmt *S, BumpVectorContext &C) {
  928. Elements.push_back(CFGAutomaticObjDtor(VD, S), C);
  929. }
  930. void appendLifetimeEnds(VarDecl *VD, Stmt *S, BumpVectorContext &C) {
  931. Elements.push_back(CFGLifetimeEnds(VD, S), C);
  932. }
  933. void appendLoopExit(const Stmt *LoopStmt, BumpVectorContext &C) {
  934. Elements.push_back(CFGLoopExit(LoopStmt), C);
  935. }
  936. void appendDeleteDtor(CXXRecordDecl *RD, CXXDeleteExpr *DE, BumpVectorContext &C) {
  937. Elements.push_back(CFGDeleteDtor(RD, DE), C);
  938. }
  939. // Destructors must be inserted in reversed order. So insertion is in two
  940. // steps. First we prepare space for some number of elements, then we insert
  941. // the elements beginning at the last position in prepared space.
  942. iterator beginAutomaticObjDtorsInsert(iterator I, size_t Cnt,
  943. BumpVectorContext &C) {
  944. return iterator(Elements.insert(I.base(), Cnt,
  945. CFGAutomaticObjDtor(nullptr, nullptr), C));
  946. }
  947. iterator insertAutomaticObjDtor(iterator I, VarDecl *VD, Stmt *S) {
  948. *I = CFGAutomaticObjDtor(VD, S);
  949. return ++I;
  950. }
  951. // Scope leaving must be performed in reversed order. So insertion is in two
  952. // steps. First we prepare space for some number of elements, then we insert
  953. // the elements beginning at the last position in prepared space.
  954. iterator beginLifetimeEndsInsert(iterator I, size_t Cnt,
  955. BumpVectorContext &C) {
  956. return iterator(
  957. Elements.insert(I.base(), Cnt, CFGLifetimeEnds(nullptr, nullptr), C));
  958. }
  959. iterator insertLifetimeEnds(iterator I, VarDecl *VD, Stmt *S) {
  960. *I = CFGLifetimeEnds(VD, S);
  961. return ++I;
  962. }
  963. // Scope leaving must be performed in reversed order. So insertion is in two
  964. // steps. First we prepare space for some number of elements, then we insert
  965. // the elements beginning at the last position in prepared space.
  966. iterator beginScopeEndInsert(iterator I, size_t Cnt, BumpVectorContext &C) {
  967. return iterator(
  968. Elements.insert(I.base(), Cnt, CFGScopeEnd(nullptr, nullptr), C));
  969. }
  970. iterator insertScopeEnd(iterator I, VarDecl *VD, Stmt *S) {
  971. *I = CFGScopeEnd(VD, S);
  972. return ++I;
  973. }
  974. };
  975. /// CFGCallback defines methods that should be called when a logical
  976. /// operator error is found when building the CFG.
  977. class CFGCallback {
  978. public:
  979. CFGCallback() = default;
  980. virtual ~CFGCallback() = default;
  981. virtual void compareAlwaysTrue(const BinaryOperator *B, bool isAlwaysTrue) {}
  982. virtual void compareBitwiseEquality(const BinaryOperator *B,
  983. bool isAlwaysTrue) {}
  984. virtual void compareBitwiseOr(const BinaryOperator *B) {}
  985. };
  986. /// Represents a source-level, intra-procedural CFG that represents the
  987. /// control-flow of a Stmt. The Stmt can represent an entire function body,
  988. /// or a single expression. A CFG will always contain one empty block that
  989. /// represents the Exit point of the CFG. A CFG will also contain a designated
  990. /// Entry block. The CFG solely represents control-flow; it consists of
  991. /// CFGBlocks which are simply containers of Stmt*'s in the AST the CFG
  992. /// was constructed from.
  993. class CFG {
  994. public:
  995. //===--------------------------------------------------------------------===//
  996. // CFG Construction & Manipulation.
  997. //===--------------------------------------------------------------------===//
  998. class BuildOptions {
  999. std::bitset<Stmt::lastStmtConstant> alwaysAddMask;
  1000. public:
  1001. using ForcedBlkExprs = llvm::DenseMap<const Stmt *, const CFGBlock *>;
  1002. ForcedBlkExprs **forcedBlkExprs = nullptr;
  1003. CFGCallback *Observer = nullptr;
  1004. bool PruneTriviallyFalseEdges = true;
  1005. bool AddEHEdges = false;
  1006. bool AddInitializers = false;
  1007. bool AddImplicitDtors = false;
  1008. bool AddLifetime = false;
  1009. bool AddLoopExit = false;
  1010. bool AddTemporaryDtors = false;
  1011. bool AddScopes = false;
  1012. bool AddStaticInitBranches = false;
  1013. bool AddCXXNewAllocator = false;
  1014. bool AddCXXDefaultInitExprInCtors = false;
  1015. bool AddCXXDefaultInitExprInAggregates = false;
  1016. bool AddRichCXXConstructors = false;
  1017. bool MarkElidedCXXConstructors = false;
  1018. bool AddVirtualBaseBranches = false;
  1019. bool OmitImplicitValueInitializers = false;
  1020. BuildOptions() = default;
  1021. bool alwaysAdd(const Stmt *stmt) const {
  1022. return alwaysAddMask[stmt->getStmtClass()];
  1023. }
  1024. BuildOptions &setAlwaysAdd(Stmt::StmtClass stmtClass, bool val = true) {
  1025. alwaysAddMask[stmtClass] = val;
  1026. return *this;
  1027. }
  1028. BuildOptions &setAllAlwaysAdd() {
  1029. alwaysAddMask.set();
  1030. return *this;
  1031. }
  1032. };
  1033. /// Builds a CFG from an AST.
  1034. static std::unique_ptr<CFG> buildCFG(const Decl *D, Stmt *AST, ASTContext *C,
  1035. const BuildOptions &BO);
  1036. /// Create a new block in the CFG. The CFG owns the block; the caller should
  1037. /// not directly free it.
  1038. CFGBlock *createBlock();
  1039. /// Set the entry block of the CFG. This is typically used only during CFG
  1040. /// construction. Most CFG clients expect that the entry block has no
  1041. /// predecessors and contains no statements.
  1042. void setEntry(CFGBlock *B) { Entry = B; }
  1043. /// Set the block used for indirect goto jumps. This is typically used only
  1044. /// during CFG construction.
  1045. void setIndirectGotoBlock(CFGBlock *B) { IndirectGotoBlock = B; }
  1046. //===--------------------------------------------------------------------===//
  1047. // Block Iterators
  1048. //===--------------------------------------------------------------------===//
  1049. using CFGBlockListTy = BumpVector<CFGBlock *>;
  1050. using iterator = CFGBlockListTy::iterator;
  1051. using const_iterator = CFGBlockListTy::const_iterator;
  1052. using reverse_iterator = std::reverse_iterator<iterator>;
  1053. using const_reverse_iterator = std::reverse_iterator<const_iterator>;
  1054. CFGBlock & front() { return *Blocks.front(); }
  1055. CFGBlock & back() { return *Blocks.back(); }
  1056. iterator begin() { return Blocks.begin(); }
  1057. iterator end() { return Blocks.end(); }
  1058. const_iterator begin() const { return Blocks.begin(); }
  1059. const_iterator end() const { return Blocks.end(); }
  1060. iterator nodes_begin() { return iterator(Blocks.begin()); }
  1061. iterator nodes_end() { return iterator(Blocks.end()); }
  1062. llvm::iterator_range<iterator> nodes() { return {begin(), end()}; }
  1063. llvm::iterator_range<const_iterator> const_nodes() const {
  1064. return {begin(), end()};
  1065. }
  1066. const_iterator nodes_begin() const { return const_iterator(Blocks.begin()); }
  1067. const_iterator nodes_end() const { return const_iterator(Blocks.end()); }
  1068. reverse_iterator rbegin() { return Blocks.rbegin(); }
  1069. reverse_iterator rend() { return Blocks.rend(); }
  1070. const_reverse_iterator rbegin() const { return Blocks.rbegin(); }
  1071. const_reverse_iterator rend() const { return Blocks.rend(); }
  1072. llvm::iterator_range<reverse_iterator> reverse_nodes() {
  1073. return {rbegin(), rend()};
  1074. }
  1075. llvm::iterator_range<const_reverse_iterator> const_reverse_nodes() const {
  1076. return {rbegin(), rend()};
  1077. }
  1078. CFGBlock & getEntry() { return *Entry; }
  1079. const CFGBlock & getEntry() const { return *Entry; }
  1080. CFGBlock & getExit() { return *Exit; }
  1081. const CFGBlock & getExit() const { return *Exit; }
  1082. CFGBlock * getIndirectGotoBlock() { return IndirectGotoBlock; }
  1083. const CFGBlock * getIndirectGotoBlock() const { return IndirectGotoBlock; }
  1084. using try_block_iterator = std::vector<const CFGBlock *>::const_iterator;
  1085. using try_block_range = llvm::iterator_range<try_block_iterator>;
  1086. try_block_iterator try_blocks_begin() const {
  1087. return TryDispatchBlocks.begin();
  1088. }
  1089. try_block_iterator try_blocks_end() const {
  1090. return TryDispatchBlocks.end();
  1091. }
  1092. try_block_range try_blocks() const {
  1093. return try_block_range(try_blocks_begin(), try_blocks_end());
  1094. }
  1095. void addTryDispatchBlock(const CFGBlock *block) {
  1096. TryDispatchBlocks.push_back(block);
  1097. }
  1098. /// Records a synthetic DeclStmt and the DeclStmt it was constructed from.
  1099. ///
  1100. /// The CFG uses synthetic DeclStmts when a single AST DeclStmt contains
  1101. /// multiple decls.
  1102. void addSyntheticDeclStmt(const DeclStmt *Synthetic,
  1103. const DeclStmt *Source) {
  1104. assert(Synthetic->isSingleDecl() && "Can handle single declarations only");
  1105. assert(Synthetic != Source && "Don't include original DeclStmts in map");
  1106. assert(!SyntheticDeclStmts.count(Synthetic) && "Already in map");
  1107. SyntheticDeclStmts[Synthetic] = Source;
  1108. }
  1109. using synthetic_stmt_iterator =
  1110. llvm::DenseMap<const DeclStmt *, const DeclStmt *>::const_iterator;
  1111. using synthetic_stmt_range = llvm::iterator_range<synthetic_stmt_iterator>;
  1112. /// Iterates over synthetic DeclStmts in the CFG.
  1113. ///
  1114. /// Each element is a (synthetic statement, source statement) pair.
  1115. ///
  1116. /// \sa addSyntheticDeclStmt
  1117. synthetic_stmt_iterator synthetic_stmt_begin() const {
  1118. return SyntheticDeclStmts.begin();
  1119. }
  1120. /// \sa synthetic_stmt_begin
  1121. synthetic_stmt_iterator synthetic_stmt_end() const {
  1122. return SyntheticDeclStmts.end();
  1123. }
  1124. /// \sa synthetic_stmt_begin
  1125. synthetic_stmt_range synthetic_stmts() const {
  1126. return synthetic_stmt_range(synthetic_stmt_begin(), synthetic_stmt_end());
  1127. }
  1128. //===--------------------------------------------------------------------===//
  1129. // Member templates useful for various batch operations over CFGs.
  1130. //===--------------------------------------------------------------------===//
  1131. template <typename Callback> void VisitBlockStmts(Callback &O) const {
  1132. for (const_iterator I = begin(), E = end(); I != E; ++I)
  1133. for (CFGBlock::const_iterator BI = (*I)->begin(), BE = (*I)->end();
  1134. BI != BE; ++BI) {
  1135. if (std::optional<CFGStmt> stmt = BI->getAs<CFGStmt>())
  1136. O(const_cast<Stmt *>(stmt->getStmt()));
  1137. }
  1138. }
  1139. //===--------------------------------------------------------------------===//
  1140. // CFG Introspection.
  1141. //===--------------------------------------------------------------------===//
  1142. /// Returns the total number of BlockIDs allocated (which start at 0).
  1143. unsigned getNumBlockIDs() const { return NumBlockIDs; }
  1144. /// Return the total number of CFGBlocks within the CFG This is simply a
  1145. /// renaming of the getNumBlockIDs(). This is necessary because the dominator
  1146. /// implementation needs such an interface.
  1147. unsigned size() const { return NumBlockIDs; }
  1148. /// Returns true if the CFG has no branches. Usually it boils down to the CFG
  1149. /// having exactly three blocks (entry, the actual code, exit), but sometimes
  1150. /// more blocks appear due to having control flow that can be fully
  1151. /// resolved in compile time.
  1152. bool isLinear() const;
  1153. //===--------------------------------------------------------------------===//
  1154. // CFG Debugging: Pretty-Printing and Visualization.
  1155. //===--------------------------------------------------------------------===//
  1156. void viewCFG(const LangOptions &LO) const;
  1157. void print(raw_ostream &OS, const LangOptions &LO, bool ShowColors) const;
  1158. void dump(const LangOptions &LO, bool ShowColors) const;
  1159. //===--------------------------------------------------------------------===//
  1160. // Internal: constructors and data.
  1161. //===--------------------------------------------------------------------===//
  1162. CFG() : Blocks(BlkBVC, 10) {}
  1163. llvm::BumpPtrAllocator& getAllocator() {
  1164. return BlkBVC.getAllocator();
  1165. }
  1166. BumpVectorContext &getBumpVectorContext() {
  1167. return BlkBVC;
  1168. }
  1169. private:
  1170. CFGBlock *Entry = nullptr;
  1171. CFGBlock *Exit = nullptr;
  1172. // Special block to contain collective dispatch for indirect gotos
  1173. CFGBlock* IndirectGotoBlock = nullptr;
  1174. unsigned NumBlockIDs = 0;
  1175. BumpVectorContext BlkBVC;
  1176. CFGBlockListTy Blocks;
  1177. /// C++ 'try' statements are modeled with an indirect dispatch block.
  1178. /// This is the collection of such blocks present in the CFG.
  1179. std::vector<const CFGBlock *> TryDispatchBlocks;
  1180. /// Collects DeclStmts synthesized for this CFG and maps each one back to its
  1181. /// source DeclStmt.
  1182. llvm::DenseMap<const DeclStmt *, const DeclStmt *> SyntheticDeclStmts;
  1183. };
  1184. Expr *extractElementInitializerFromNestedAILE(const ArrayInitLoopExpr *AILE);
  1185. } // namespace clang
  1186. //===----------------------------------------------------------------------===//
  1187. // GraphTraits specializations for CFG basic block graphs (source-level CFGs)
  1188. //===----------------------------------------------------------------------===//
  1189. namespace llvm {
  1190. /// Implement simplify_type for CFGTerminator, so that we can dyn_cast from
  1191. /// CFGTerminator to a specific Stmt class.
  1192. template <> struct simplify_type< ::clang::CFGTerminator> {
  1193. using SimpleType = ::clang::Stmt *;
  1194. static SimpleType getSimplifiedValue(::clang::CFGTerminator Val) {
  1195. return Val.getStmt();
  1196. }
  1197. };
  1198. // Traits for: CFGBlock
  1199. template <> struct GraphTraits< ::clang::CFGBlock *> {
  1200. using NodeRef = ::clang::CFGBlock *;
  1201. using ChildIteratorType = ::clang::CFGBlock::succ_iterator;
  1202. static NodeRef getEntryNode(::clang::CFGBlock *BB) { return BB; }
  1203. static ChildIteratorType child_begin(NodeRef N) { return N->succ_begin(); }
  1204. static ChildIteratorType child_end(NodeRef N) { return N->succ_end(); }
  1205. };
  1206. template <> struct GraphTraits< const ::clang::CFGBlock *> {
  1207. using NodeRef = const ::clang::CFGBlock *;
  1208. using ChildIteratorType = ::clang::CFGBlock::const_succ_iterator;
  1209. static NodeRef getEntryNode(const clang::CFGBlock *BB) { return BB; }
  1210. static ChildIteratorType child_begin(NodeRef N) { return N->succ_begin(); }
  1211. static ChildIteratorType child_end(NodeRef N) { return N->succ_end(); }
  1212. };
  1213. template <> struct GraphTraits<Inverse< ::clang::CFGBlock *>> {
  1214. using NodeRef = ::clang::CFGBlock *;
  1215. using ChildIteratorType = ::clang::CFGBlock::const_pred_iterator;
  1216. static NodeRef getEntryNode(Inverse<::clang::CFGBlock *> G) {
  1217. return G.Graph;
  1218. }
  1219. static ChildIteratorType child_begin(NodeRef N) { return N->pred_begin(); }
  1220. static ChildIteratorType child_end(NodeRef N) { return N->pred_end(); }
  1221. };
  1222. template <> struct GraphTraits<Inverse<const ::clang::CFGBlock *>> {
  1223. using NodeRef = const ::clang::CFGBlock *;
  1224. using ChildIteratorType = ::clang::CFGBlock::const_pred_iterator;
  1225. static NodeRef getEntryNode(Inverse<const ::clang::CFGBlock *> G) {
  1226. return G.Graph;
  1227. }
  1228. static ChildIteratorType child_begin(NodeRef N) { return N->pred_begin(); }
  1229. static ChildIteratorType child_end(NodeRef N) { return N->pred_end(); }
  1230. };
  1231. // Traits for: CFG
  1232. template <> struct GraphTraits< ::clang::CFG* >
  1233. : public GraphTraits< ::clang::CFGBlock *> {
  1234. using nodes_iterator = ::clang::CFG::iterator;
  1235. static NodeRef getEntryNode(::clang::CFG *F) { return &F->getEntry(); }
  1236. static nodes_iterator nodes_begin(::clang::CFG* F) { return F->nodes_begin();}
  1237. static nodes_iterator nodes_end(::clang::CFG* F) { return F->nodes_end(); }
  1238. static unsigned size(::clang::CFG* F) { return F->size(); }
  1239. };
  1240. template <> struct GraphTraits<const ::clang::CFG* >
  1241. : public GraphTraits<const ::clang::CFGBlock *> {
  1242. using nodes_iterator = ::clang::CFG::const_iterator;
  1243. static NodeRef getEntryNode(const ::clang::CFG *F) { return &F->getEntry(); }
  1244. static nodes_iterator nodes_begin( const ::clang::CFG* F) {
  1245. return F->nodes_begin();
  1246. }
  1247. static nodes_iterator nodes_end( const ::clang::CFG* F) {
  1248. return F->nodes_end();
  1249. }
  1250. static unsigned size(const ::clang::CFG* F) {
  1251. return F->size();
  1252. }
  1253. };
  1254. template <> struct GraphTraits<Inverse< ::clang::CFG *>>
  1255. : public GraphTraits<Inverse< ::clang::CFGBlock *>> {
  1256. using nodes_iterator = ::clang::CFG::iterator;
  1257. static NodeRef getEntryNode(::clang::CFG *F) { return &F->getExit(); }
  1258. static nodes_iterator nodes_begin( ::clang::CFG* F) {return F->nodes_begin();}
  1259. static nodes_iterator nodes_end( ::clang::CFG* F) { return F->nodes_end(); }
  1260. };
  1261. template <> struct GraphTraits<Inverse<const ::clang::CFG *>>
  1262. : public GraphTraits<Inverse<const ::clang::CFGBlock *>> {
  1263. using nodes_iterator = ::clang::CFG::const_iterator;
  1264. static NodeRef getEntryNode(const ::clang::CFG *F) { return &F->getExit(); }
  1265. static nodes_iterator nodes_begin(const ::clang::CFG* F) {
  1266. return F->nodes_begin();
  1267. }
  1268. static nodes_iterator nodes_end(const ::clang::CFG* F) {
  1269. return F->nodes_end();
  1270. }
  1271. };
  1272. } // namespace llvm
  1273. #endif // LLVM_CLANG_ANALYSIS_CFG_H
  1274. #ifdef __GNUC__
  1275. #pragma GCC diagnostic pop
  1276. #endif