LiveVariables.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636
  1. //=- LiveVariables.cpp - Live Variable Analysis for Source CFGs ----------*-==//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements Live Variables analysis for source-level CFGs.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "clang/Analysis/Analyses/LiveVariables.h"
  14. #include "clang/AST/Stmt.h"
  15. #include "clang/AST/StmtVisitor.h"
  16. #include "clang/Analysis/Analyses/PostOrderCFGView.h"
  17. #include "clang/Analysis/AnalysisDeclContext.h"
  18. #include "clang/Analysis/CFG.h"
  19. #include "llvm/ADT/DenseMap.h"
  20. #include "llvm/ADT/PostOrderIterator.h"
  21. #include "llvm/ADT/PriorityQueue.h"
  22. #include "llvm/Support/raw_ostream.h"
  23. #include <algorithm>
  24. #include <vector>
  25. using namespace clang;
  26. namespace {
  27. class DataflowWorklist {
  28. llvm::BitVector enqueuedBlocks;
  29. PostOrderCFGView *POV;
  30. llvm::PriorityQueue<const CFGBlock *, SmallVector<const CFGBlock *, 20>,
  31. PostOrderCFGView::BlockOrderCompare> worklist;
  32. public:
  33. DataflowWorklist(const CFG &cfg, AnalysisDeclContext &Ctx)
  34. : enqueuedBlocks(cfg.getNumBlockIDs()),
  35. POV(Ctx.getAnalysis<PostOrderCFGView>()),
  36. worklist(POV->getComparator()) {}
  37. void enqueueBlock(const CFGBlock *block);
  38. void enqueuePredecessors(const CFGBlock *block);
  39. const CFGBlock *dequeue();
  40. };
  41. }
  42. void DataflowWorklist::enqueueBlock(const clang::CFGBlock *block) {
  43. if (block && !enqueuedBlocks[block->getBlockID()]) {
  44. enqueuedBlocks[block->getBlockID()] = true;
  45. worklist.push(block);
  46. }
  47. }
  48. void DataflowWorklist::enqueuePredecessors(const clang::CFGBlock *block) {
  49. for (CFGBlock::const_pred_iterator I = block->pred_begin(),
  50. E = block->pred_end(); I != E; ++I) {
  51. enqueueBlock(*I);
  52. }
  53. }
  54. const CFGBlock *DataflowWorklist::dequeue() {
  55. if (worklist.empty())
  56. return nullptr;
  57. const CFGBlock *b = worklist.top();
  58. worklist.pop();
  59. enqueuedBlocks[b->getBlockID()] = false;
  60. return b;
  61. }
  62. namespace {
  63. class LiveVariablesImpl {
  64. public:
  65. AnalysisDeclContext &analysisContext;
  66. llvm::ImmutableSet<const Stmt *>::Factory SSetFact;
  67. llvm::ImmutableSet<const VarDecl *>::Factory DSetFact;
  68. llvm::ImmutableSet<const BindingDecl *>::Factory BSetFact;
  69. llvm::DenseMap<const CFGBlock *, LiveVariables::LivenessValues> blocksEndToLiveness;
  70. llvm::DenseMap<const CFGBlock *, LiveVariables::LivenessValues> blocksBeginToLiveness;
  71. llvm::DenseMap<const Stmt *, LiveVariables::LivenessValues> stmtsToLiveness;
  72. llvm::DenseMap<const DeclRefExpr *, unsigned> inAssignment;
  73. const bool killAtAssign;
  74. LiveVariables::LivenessValues
  75. merge(LiveVariables::LivenessValues valsA,
  76. LiveVariables::LivenessValues valsB);
  77. LiveVariables::LivenessValues
  78. runOnBlock(const CFGBlock *block, LiveVariables::LivenessValues val,
  79. LiveVariables::Observer *obs = nullptr);
  80. void dumpBlockLiveness(const SourceManager& M);
  81. LiveVariablesImpl(AnalysisDeclContext &ac, bool KillAtAssign)
  82. : analysisContext(ac),
  83. SSetFact(false), // Do not canonicalize ImmutableSets by default.
  84. DSetFact(false), // This is a *major* performance win.
  85. BSetFact(false),
  86. killAtAssign(KillAtAssign) {}
  87. };
  88. }
  89. static LiveVariablesImpl &getImpl(void *x) {
  90. return *((LiveVariablesImpl *) x);
  91. }
  92. //===----------------------------------------------------------------------===//
  93. // Operations and queries on LivenessValues.
  94. //===----------------------------------------------------------------------===//
  95. bool LiveVariables::LivenessValues::isLive(const Stmt *S) const {
  96. return liveStmts.contains(S);
  97. }
  98. bool LiveVariables::LivenessValues::isLive(const VarDecl *D) const {
  99. if (const auto *DD = dyn_cast<DecompositionDecl>(D)) {
  100. bool alive = false;
  101. for (const BindingDecl *BD : DD->bindings())
  102. alive |= liveBindings.contains(BD);
  103. return alive;
  104. }
  105. return liveDecls.contains(D);
  106. }
  107. namespace {
  108. template <typename SET>
  109. SET mergeSets(SET A, SET B) {
  110. if (A.isEmpty())
  111. return B;
  112. for (typename SET::iterator it = B.begin(), ei = B.end(); it != ei; ++it) {
  113. A = A.add(*it);
  114. }
  115. return A;
  116. }
  117. }
  118. void LiveVariables::Observer::anchor() { }
  119. LiveVariables::LivenessValues
  120. LiveVariablesImpl::merge(LiveVariables::LivenessValues valsA,
  121. LiveVariables::LivenessValues valsB) {
  122. llvm::ImmutableSetRef<const Stmt *>
  123. SSetRefA(valsA.liveStmts.getRootWithoutRetain(), SSetFact.getTreeFactory()),
  124. SSetRefB(valsB.liveStmts.getRootWithoutRetain(), SSetFact.getTreeFactory());
  125. llvm::ImmutableSetRef<const VarDecl *>
  126. DSetRefA(valsA.liveDecls.getRootWithoutRetain(), DSetFact.getTreeFactory()),
  127. DSetRefB(valsB.liveDecls.getRootWithoutRetain(), DSetFact.getTreeFactory());
  128. llvm::ImmutableSetRef<const BindingDecl *>
  129. BSetRefA(valsA.liveBindings.getRootWithoutRetain(), BSetFact.getTreeFactory()),
  130. BSetRefB(valsB.liveBindings.getRootWithoutRetain(), BSetFact.getTreeFactory());
  131. SSetRefA = mergeSets(SSetRefA, SSetRefB);
  132. DSetRefA = mergeSets(DSetRefA, DSetRefB);
  133. BSetRefA = mergeSets(BSetRefA, BSetRefB);
  134. // asImmutableSet() canonicalizes the tree, allowing us to do an easy
  135. // comparison afterwards.
  136. return LiveVariables::LivenessValues(SSetRefA.asImmutableSet(),
  137. DSetRefA.asImmutableSet(),
  138. BSetRefA.asImmutableSet());
  139. }
  140. bool LiveVariables::LivenessValues::equals(const LivenessValues &V) const {
  141. return liveStmts == V.liveStmts && liveDecls == V.liveDecls;
  142. }
  143. //===----------------------------------------------------------------------===//
  144. // Query methods.
  145. //===----------------------------------------------------------------------===//
  146. static bool isAlwaysAlive(const VarDecl *D) {
  147. return D->hasGlobalStorage();
  148. }
  149. bool LiveVariables::isLive(const CFGBlock *B, const VarDecl *D) {
  150. return isAlwaysAlive(D) || getImpl(impl).blocksEndToLiveness[B].isLive(D);
  151. }
  152. bool LiveVariables::isLive(const Stmt *S, const VarDecl *D) {
  153. return isAlwaysAlive(D) || getImpl(impl).stmtsToLiveness[S].isLive(D);
  154. }
  155. bool LiveVariables::isLive(const Stmt *Loc, const Stmt *S) {
  156. return getImpl(impl).stmtsToLiveness[Loc].isLive(S);
  157. }
  158. //===----------------------------------------------------------------------===//
  159. // Dataflow computation.
  160. //===----------------------------------------------------------------------===//
  161. namespace {
  162. class TransferFunctions : public StmtVisitor<TransferFunctions> {
  163. LiveVariablesImpl &LV;
  164. LiveVariables::LivenessValues &val;
  165. LiveVariables::Observer *observer;
  166. const CFGBlock *currentBlock;
  167. public:
  168. TransferFunctions(LiveVariablesImpl &im,
  169. LiveVariables::LivenessValues &Val,
  170. LiveVariables::Observer *Observer,
  171. const CFGBlock *CurrentBlock)
  172. : LV(im), val(Val), observer(Observer), currentBlock(CurrentBlock) {}
  173. void VisitBinaryOperator(BinaryOperator *BO);
  174. void VisitBlockExpr(BlockExpr *BE);
  175. void VisitDeclRefExpr(DeclRefExpr *DR);
  176. void VisitDeclStmt(DeclStmt *DS);
  177. void VisitObjCForCollectionStmt(ObjCForCollectionStmt *OS);
  178. void VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *UE);
  179. void VisitUnaryOperator(UnaryOperator *UO);
  180. void Visit(Stmt *S);
  181. };
  182. }
  183. static const VariableArrayType *FindVA(QualType Ty) {
  184. const Type *ty = Ty.getTypePtr();
  185. while (const ArrayType *VT = dyn_cast<ArrayType>(ty)) {
  186. if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(VT))
  187. if (VAT->getSizeExpr())
  188. return VAT;
  189. ty = VT->getElementType().getTypePtr();
  190. }
  191. return nullptr;
  192. }
  193. static const Stmt *LookThroughStmt(const Stmt *S) {
  194. while (S) {
  195. if (const Expr *Ex = dyn_cast<Expr>(S))
  196. S = Ex->IgnoreParens();
  197. if (const FullExpr *FE = dyn_cast<FullExpr>(S)) {
  198. S = FE->getSubExpr();
  199. continue;
  200. }
  201. if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(S)) {
  202. S = OVE->getSourceExpr();
  203. continue;
  204. }
  205. break;
  206. }
  207. return S;
  208. }
  209. static void AddLiveStmt(llvm::ImmutableSet<const Stmt *> &Set,
  210. llvm::ImmutableSet<const Stmt *>::Factory &F,
  211. const Stmt *S) {
  212. Set = F.add(Set, LookThroughStmt(S));
  213. }
  214. void TransferFunctions::Visit(Stmt *S) {
  215. if (observer)
  216. observer->observeStmt(S, currentBlock, val);
  217. StmtVisitor<TransferFunctions>::Visit(S);
  218. if (isa<Expr>(S)) {
  219. val.liveStmts = LV.SSetFact.remove(val.liveStmts, S);
  220. }
  221. // Mark all children expressions live.
  222. switch (S->getStmtClass()) {
  223. default:
  224. break;
  225. case Stmt::StmtExprClass: {
  226. // For statement expressions, look through the compound statement.
  227. S = cast<StmtExpr>(S)->getSubStmt();
  228. break;
  229. }
  230. case Stmt::CXXMemberCallExprClass: {
  231. // Include the implicit "this" pointer as being live.
  232. CXXMemberCallExpr *CE = cast<CXXMemberCallExpr>(S);
  233. if (Expr *ImplicitObj = CE->getImplicitObjectArgument()) {
  234. AddLiveStmt(val.liveStmts, LV.SSetFact, ImplicitObj);
  235. }
  236. break;
  237. }
  238. case Stmt::ObjCMessageExprClass: {
  239. // In calls to super, include the implicit "self" pointer as being live.
  240. ObjCMessageExpr *CE = cast<ObjCMessageExpr>(S);
  241. if (CE->getReceiverKind() == ObjCMessageExpr::SuperInstance)
  242. val.liveDecls = LV.DSetFact.add(val.liveDecls,
  243. LV.analysisContext.getSelfDecl());
  244. break;
  245. }
  246. case Stmt::DeclStmtClass: {
  247. const DeclStmt *DS = cast<DeclStmt>(S);
  248. if (const VarDecl *VD = dyn_cast<VarDecl>(DS->getSingleDecl())) {
  249. for (const VariableArrayType* VA = FindVA(VD->getType());
  250. VA != nullptr; VA = FindVA(VA->getElementType())) {
  251. AddLiveStmt(val.liveStmts, LV.SSetFact, VA->getSizeExpr());
  252. }
  253. }
  254. break;
  255. }
  256. case Stmt::PseudoObjectExprClass: {
  257. // A pseudo-object operation only directly consumes its result
  258. // expression.
  259. Expr *child = cast<PseudoObjectExpr>(S)->getResultExpr();
  260. if (!child) return;
  261. if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(child))
  262. child = OV->getSourceExpr();
  263. child = child->IgnoreParens();
  264. val.liveStmts = LV.SSetFact.add(val.liveStmts, child);
  265. return;
  266. }
  267. // FIXME: These cases eventually shouldn't be needed.
  268. case Stmt::ExprWithCleanupsClass: {
  269. S = cast<ExprWithCleanups>(S)->getSubExpr();
  270. break;
  271. }
  272. case Stmt::CXXBindTemporaryExprClass: {
  273. S = cast<CXXBindTemporaryExpr>(S)->getSubExpr();
  274. break;
  275. }
  276. case Stmt::UnaryExprOrTypeTraitExprClass: {
  277. // No need to unconditionally visit subexpressions.
  278. return;
  279. }
  280. }
  281. for (Stmt *Child : S->children()) {
  282. if (Child)
  283. AddLiveStmt(val.liveStmts, LV.SSetFact, Child);
  284. }
  285. }
  286. static bool writeShouldKill(const VarDecl *VD) {
  287. return VD && !VD->getType()->isReferenceType() &&
  288. !isAlwaysAlive(VD);
  289. }
  290. void TransferFunctions::VisitBinaryOperator(BinaryOperator *B) {
  291. if (B->isAssignmentOp()) {
  292. if (!LV.killAtAssign)
  293. return;
  294. // Assigning to a variable?
  295. Expr *LHS = B->getLHS()->IgnoreParens();
  296. if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(LHS)) {
  297. const Decl* D = DR->getDecl();
  298. bool Killed = false;
  299. if (const BindingDecl* BD = dyn_cast<BindingDecl>(D)) {
  300. Killed = !BD->getType()->isReferenceType();
  301. if (Killed)
  302. val.liveBindings = LV.BSetFact.remove(val.liveBindings, BD);
  303. } else if (const auto *VD = dyn_cast<VarDecl>(D)) {
  304. Killed = writeShouldKill(VD);
  305. if (Killed)
  306. val.liveDecls = LV.DSetFact.remove(val.liveDecls, VD);
  307. }
  308. if (Killed && observer)
  309. observer->observerKill(DR);
  310. }
  311. }
  312. }
  313. void TransferFunctions::VisitBlockExpr(BlockExpr *BE) {
  314. for (const VarDecl *VD :
  315. LV.analysisContext.getReferencedBlockVars(BE->getBlockDecl())) {
  316. if (isAlwaysAlive(VD))
  317. continue;
  318. val.liveDecls = LV.DSetFact.add(val.liveDecls, VD);
  319. }
  320. }
  321. void TransferFunctions::VisitDeclRefExpr(DeclRefExpr *DR) {
  322. const Decl* D = DR->getDecl();
  323. bool InAssignment = LV.inAssignment[DR];
  324. if (const auto *BD = dyn_cast<BindingDecl>(D)) {
  325. if (!InAssignment)
  326. val.liveBindings = LV.BSetFact.add(val.liveBindings, BD);
  327. } else if (const auto *VD = dyn_cast<VarDecl>(D)) {
  328. if (!InAssignment && !isAlwaysAlive(VD))
  329. val.liveDecls = LV.DSetFact.add(val.liveDecls, VD);
  330. }
  331. }
  332. void TransferFunctions::VisitDeclStmt(DeclStmt *DS) {
  333. for (const auto *DI : DS->decls()) {
  334. if (const auto *DD = dyn_cast<DecompositionDecl>(DI)) {
  335. for (const auto *BD : DD->bindings())
  336. val.liveBindings = LV.BSetFact.remove(val.liveBindings, BD);
  337. } else if (const auto *VD = dyn_cast<VarDecl>(DI)) {
  338. if (!isAlwaysAlive(VD))
  339. val.liveDecls = LV.DSetFact.remove(val.liveDecls, VD);
  340. }
  341. }
  342. }
  343. void TransferFunctions::VisitObjCForCollectionStmt(ObjCForCollectionStmt *OS) {
  344. // Kill the iteration variable.
  345. DeclRefExpr *DR = nullptr;
  346. const VarDecl *VD = nullptr;
  347. Stmt *element = OS->getElement();
  348. if (DeclStmt *DS = dyn_cast<DeclStmt>(element)) {
  349. VD = cast<VarDecl>(DS->getSingleDecl());
  350. }
  351. else if ((DR = dyn_cast<DeclRefExpr>(cast<Expr>(element)->IgnoreParens()))) {
  352. VD = cast<VarDecl>(DR->getDecl());
  353. }
  354. if (VD) {
  355. val.liveDecls = LV.DSetFact.remove(val.liveDecls, VD);
  356. if (observer && DR)
  357. observer->observerKill(DR);
  358. }
  359. }
  360. void TransferFunctions::
  361. VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *UE)
  362. {
  363. // While sizeof(var) doesn't technically extend the liveness of 'var', it
  364. // does extent the liveness of metadata if 'var' is a VariableArrayType.
  365. // We handle that special case here.
  366. if (UE->getKind() != UETT_SizeOf || UE->isArgumentType())
  367. return;
  368. const Expr *subEx = UE->getArgumentExpr();
  369. if (subEx->getType()->isVariableArrayType()) {
  370. assert(subEx->isLValue());
  371. val.liveStmts = LV.SSetFact.add(val.liveStmts, subEx->IgnoreParens());
  372. }
  373. }
  374. void TransferFunctions::VisitUnaryOperator(UnaryOperator *UO) {
  375. // Treat ++/-- as a kill.
  376. // Note we don't actually have to do anything if we don't have an observer,
  377. // since a ++/-- acts as both a kill and a "use".
  378. if (!observer)
  379. return;
  380. switch (UO->getOpcode()) {
  381. default:
  382. return;
  383. case UO_PostInc:
  384. case UO_PostDec:
  385. case UO_PreInc:
  386. case UO_PreDec:
  387. break;
  388. }
  389. if (auto *DR = dyn_cast<DeclRefExpr>(UO->getSubExpr()->IgnoreParens())) {
  390. const Decl *D = DR->getDecl();
  391. if (isa<VarDecl>(D) || isa<BindingDecl>(D)) {
  392. // Treat ++/-- as a kill.
  393. observer->observerKill(DR);
  394. }
  395. }
  396. }
  397. LiveVariables::LivenessValues
  398. LiveVariablesImpl::runOnBlock(const CFGBlock *block,
  399. LiveVariables::LivenessValues val,
  400. LiveVariables::Observer *obs) {
  401. TransferFunctions TF(*this, val, obs, block);
  402. // Visit the terminator (if any).
  403. if (const Stmt *term = block->getTerminator())
  404. TF.Visit(const_cast<Stmt*>(term));
  405. // Apply the transfer function for all Stmts in the block.
  406. for (CFGBlock::const_reverse_iterator it = block->rbegin(),
  407. ei = block->rend(); it != ei; ++it) {
  408. const CFGElement &elem = *it;
  409. if (Optional<CFGAutomaticObjDtor> Dtor =
  410. elem.getAs<CFGAutomaticObjDtor>()) {
  411. val.liveDecls = DSetFact.add(val.liveDecls, Dtor->getVarDecl());
  412. continue;
  413. }
  414. if (!elem.getAs<CFGStmt>())
  415. continue;
  416. const Stmt *S = elem.castAs<CFGStmt>().getStmt();
  417. TF.Visit(const_cast<Stmt*>(S));
  418. stmtsToLiveness[S] = val;
  419. }
  420. return val;
  421. }
  422. void LiveVariables::runOnAllBlocks(LiveVariables::Observer &obs) {
  423. const CFG *cfg = getImpl(impl).analysisContext.getCFG();
  424. for (CFG::const_iterator it = cfg->begin(), ei = cfg->end(); it != ei; ++it)
  425. getImpl(impl).runOnBlock(*it, getImpl(impl).blocksEndToLiveness[*it], &obs);
  426. }
  427. LiveVariables::LiveVariables(void *im) : impl(im) {}
  428. LiveVariables::~LiveVariables() {
  429. delete (LiveVariablesImpl*) impl;
  430. }
  431. LiveVariables *
  432. LiveVariables::computeLiveness(AnalysisDeclContext &AC,
  433. bool killAtAssign) {
  434. // No CFG? Bail out.
  435. CFG *cfg = AC.getCFG();
  436. if (!cfg)
  437. return nullptr;
  438. // The analysis currently has scalability issues for very large CFGs.
  439. // Bail out if it looks too large.
  440. if (cfg->getNumBlockIDs() > 300000)
  441. return nullptr;
  442. LiveVariablesImpl *LV = new LiveVariablesImpl(AC, killAtAssign);
  443. // Construct the dataflow worklist. Enqueue the exit block as the
  444. // start of the analysis.
  445. DataflowWorklist worklist(*cfg, AC);
  446. llvm::BitVector everAnalyzedBlock(cfg->getNumBlockIDs());
  447. // FIXME: we should enqueue using post order.
  448. for (CFG::const_iterator it = cfg->begin(), ei = cfg->end(); it != ei; ++it) {
  449. const CFGBlock *block = *it;
  450. worklist.enqueueBlock(block);
  451. // FIXME: Scan for DeclRefExprs using in the LHS of an assignment.
  452. // We need to do this because we lack context in the reverse analysis
  453. // to determine if a DeclRefExpr appears in such a context, and thus
  454. // doesn't constitute a "use".
  455. if (killAtAssign)
  456. for (CFGBlock::const_iterator bi = block->begin(), be = block->end();
  457. bi != be; ++bi) {
  458. if (Optional<CFGStmt> cs = bi->getAs<CFGStmt>()) {
  459. const Stmt* stmt = cs->getStmt();
  460. if (const auto *BO = dyn_cast<BinaryOperator>(stmt)) {
  461. if (BO->getOpcode() == BO_Assign) {
  462. if (const auto *DR =
  463. dyn_cast<DeclRefExpr>(BO->getLHS()->IgnoreParens())) {
  464. LV->inAssignment[DR] = 1;
  465. }
  466. }
  467. }
  468. }
  469. }
  470. }
  471. while (const CFGBlock *block = worklist.dequeue()) {
  472. // Determine if the block's end value has changed. If not, we
  473. // have nothing left to do for this block.
  474. LivenessValues &prevVal = LV->blocksEndToLiveness[block];
  475. // Merge the values of all successor blocks.
  476. LivenessValues val;
  477. for (CFGBlock::const_succ_iterator it = block->succ_begin(),
  478. ei = block->succ_end(); it != ei; ++it) {
  479. if (const CFGBlock *succ = *it) {
  480. val = LV->merge(val, LV->blocksBeginToLiveness[succ]);
  481. }
  482. }
  483. if (!everAnalyzedBlock[block->getBlockID()])
  484. everAnalyzedBlock[block->getBlockID()] = true;
  485. else if (prevVal.equals(val))
  486. continue;
  487. prevVal = val;
  488. // Update the dataflow value for the start of this block.
  489. LV->blocksBeginToLiveness[block] = LV->runOnBlock(block, val);
  490. // Enqueue the value to the predecessors.
  491. worklist.enqueuePredecessors(block);
  492. }
  493. return new LiveVariables(LV);
  494. }
  495. void LiveVariables::dumpBlockLiveness(const SourceManager &M) {
  496. getImpl(impl).dumpBlockLiveness(M);
  497. }
  498. void LiveVariablesImpl::dumpBlockLiveness(const SourceManager &M) {
  499. std::vector<const CFGBlock *> vec;
  500. for (llvm::DenseMap<const CFGBlock *, LiveVariables::LivenessValues>::iterator
  501. it = blocksEndToLiveness.begin(), ei = blocksEndToLiveness.end();
  502. it != ei; ++it) {
  503. vec.push_back(it->first);
  504. }
  505. llvm::sort(vec, [](const CFGBlock *A, const CFGBlock *B) {
  506. return A->getBlockID() < B->getBlockID();
  507. });
  508. std::vector<const VarDecl*> declVec;
  509. for (std::vector<const CFGBlock *>::iterator
  510. it = vec.begin(), ei = vec.end(); it != ei; ++it) {
  511. llvm::errs() << "\n[ B" << (*it)->getBlockID()
  512. << " (live variables at block exit) ]\n";
  513. LiveVariables::LivenessValues vals = blocksEndToLiveness[*it];
  514. declVec.clear();
  515. for (llvm::ImmutableSet<const VarDecl *>::iterator si =
  516. vals.liveDecls.begin(),
  517. se = vals.liveDecls.end(); si != se; ++si) {
  518. declVec.push_back(*si);
  519. }
  520. llvm::sort(declVec, [](const Decl *A, const Decl *B) {
  521. return A->getBeginLoc() < B->getBeginLoc();
  522. });
  523. for (std::vector<const VarDecl*>::iterator di = declVec.begin(),
  524. de = declVec.end(); di != de; ++di) {
  525. llvm::errs() << " " << (*di)->getDeclName().getAsString()
  526. << " <";
  527. (*di)->getLocation().print(llvm::errs(), M);
  528. llvm::errs() << ">\n";
  529. }
  530. }
  531. llvm::errs() << "\n";
  532. }
  533. const void *LiveVariables::getTag() { static int x; return &x; }
  534. const void *RelaxedLiveVariables::getTag() { static int x; return &x; }