Local.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605
  1. //===-- Local.cpp - Functions to perform local transformations ------------===//
  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 family of functions perform various local transformations to the
  11. // program.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "llvm/Transforms/Utils/Local.h"
  15. #include "llvm/Constants.h"
  16. #include "llvm/GlobalAlias.h"
  17. #include "llvm/GlobalVariable.h"
  18. #include "llvm/DerivedTypes.h"
  19. #include "llvm/Instructions.h"
  20. #include "llvm/Intrinsics.h"
  21. #include "llvm/IntrinsicInst.h"
  22. #include "llvm/LLVMContext.h"
  23. #include "llvm/ADT/SmallPtrSet.h"
  24. #include "llvm/Analysis/ConstantFolding.h"
  25. #include "llvm/Analysis/DebugInfo.h"
  26. #include "llvm/Analysis/InstructionSimplify.h"
  27. #include "llvm/Analysis/ProfileInfo.h"
  28. #include "llvm/Target/TargetData.h"
  29. #include "llvm/Support/CFG.h"
  30. #include "llvm/Support/Debug.h"
  31. #include "llvm/Support/GetElementPtrTypeIterator.h"
  32. #include "llvm/Support/MathExtras.h"
  33. #include "llvm/Support/raw_ostream.h"
  34. using namespace llvm;
  35. //===----------------------------------------------------------------------===//
  36. // Local analysis.
  37. //
  38. /// isSafeToLoadUnconditionally - Return true if we know that executing a load
  39. /// from this value cannot trap. If it is not obviously safe to load from the
  40. /// specified pointer, we do a quick local scan of the basic block containing
  41. /// ScanFrom, to determine if the address is already accessed.
  42. bool llvm::isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
  43. // If it is an alloca it is always safe to load from.
  44. if (isa<AllocaInst>(V)) return true;
  45. // If it is a global variable it is mostly safe to load from.
  46. if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
  47. // Don't try to evaluate aliases. External weak GV can be null.
  48. return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
  49. // Otherwise, be a little bit agressive by scanning the local block where we
  50. // want to check to see if the pointer is already being loaded or stored
  51. // from/to. If so, the previous load or store would have already trapped,
  52. // so there is no harm doing an extra load (also, CSE will later eliminate
  53. // the load entirely).
  54. BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
  55. while (BBI != E) {
  56. --BBI;
  57. // If we see a free or a call which may write to memory (i.e. which might do
  58. // a free) the pointer could be marked invalid.
  59. if (isa<CallInst>(BBI) && BBI->mayWriteToMemory() &&
  60. !isa<DbgInfoIntrinsic>(BBI))
  61. return false;
  62. if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
  63. if (LI->getOperand(0) == V) return true;
  64. } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
  65. if (SI->getOperand(1) == V) return true;
  66. }
  67. }
  68. return false;
  69. }
  70. //===----------------------------------------------------------------------===//
  71. // Local constant propagation.
  72. //
  73. // ConstantFoldTerminator - If a terminator instruction is predicated on a
  74. // constant value, convert it into an unconditional branch to the constant
  75. // destination.
  76. //
  77. bool llvm::ConstantFoldTerminator(BasicBlock *BB) {
  78. TerminatorInst *T = BB->getTerminator();
  79. // Branch - See if we are conditional jumping on constant
  80. if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
  81. if (BI->isUnconditional()) return false; // Can't optimize uncond branch
  82. BasicBlock *Dest1 = BI->getSuccessor(0);
  83. BasicBlock *Dest2 = BI->getSuccessor(1);
  84. if (ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition())) {
  85. // Are we branching on constant?
  86. // YES. Change to unconditional branch...
  87. BasicBlock *Destination = Cond->getZExtValue() ? Dest1 : Dest2;
  88. BasicBlock *OldDest = Cond->getZExtValue() ? Dest2 : Dest1;
  89. //cerr << "Function: " << T->getParent()->getParent()
  90. // << "\nRemoving branch from " << T->getParent()
  91. // << "\n\nTo: " << OldDest << endl;
  92. // Let the basic block know that we are letting go of it. Based on this,
  93. // it will adjust it's PHI nodes.
  94. assert(BI->getParent() && "Terminator not inserted in block!");
  95. OldDest->removePredecessor(BI->getParent());
  96. // Set the unconditional destination, and change the insn to be an
  97. // unconditional branch.
  98. BI->setUnconditionalDest(Destination);
  99. return true;
  100. }
  101. if (Dest2 == Dest1) { // Conditional branch to same location?
  102. // This branch matches something like this:
  103. // br bool %cond, label %Dest, label %Dest
  104. // and changes it into: br label %Dest
  105. // Let the basic block know that we are letting go of one copy of it.
  106. assert(BI->getParent() && "Terminator not inserted in block!");
  107. Dest1->removePredecessor(BI->getParent());
  108. // Change a conditional branch to unconditional.
  109. BI->setUnconditionalDest(Dest1);
  110. return true;
  111. }
  112. return false;
  113. }
  114. if (SwitchInst *SI = dyn_cast<SwitchInst>(T)) {
  115. // If we are switching on a constant, we can convert the switch into a
  116. // single branch instruction!
  117. ConstantInt *CI = dyn_cast<ConstantInt>(SI->getCondition());
  118. BasicBlock *TheOnlyDest = SI->getSuccessor(0); // The default dest
  119. BasicBlock *DefaultDest = TheOnlyDest;
  120. assert(TheOnlyDest == SI->getDefaultDest() &&
  121. "Default destination is not successor #0?");
  122. // Figure out which case it goes to.
  123. for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i) {
  124. // Found case matching a constant operand?
  125. if (SI->getSuccessorValue(i) == CI) {
  126. TheOnlyDest = SI->getSuccessor(i);
  127. break;
  128. }
  129. // Check to see if this branch is going to the same place as the default
  130. // dest. If so, eliminate it as an explicit compare.
  131. if (SI->getSuccessor(i) == DefaultDest) {
  132. // Remove this entry.
  133. DefaultDest->removePredecessor(SI->getParent());
  134. SI->removeCase(i);
  135. --i; --e; // Don't skip an entry...
  136. continue;
  137. }
  138. // Otherwise, check to see if the switch only branches to one destination.
  139. // We do this by reseting "TheOnlyDest" to null when we find two non-equal
  140. // destinations.
  141. if (SI->getSuccessor(i) != TheOnlyDest) TheOnlyDest = 0;
  142. }
  143. if (CI && !TheOnlyDest) {
  144. // Branching on a constant, but not any of the cases, go to the default
  145. // successor.
  146. TheOnlyDest = SI->getDefaultDest();
  147. }
  148. // If we found a single destination that we can fold the switch into, do so
  149. // now.
  150. if (TheOnlyDest) {
  151. // Insert the new branch.
  152. BranchInst::Create(TheOnlyDest, SI);
  153. BasicBlock *BB = SI->getParent();
  154. // Remove entries from PHI nodes which we no longer branch to...
  155. for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) {
  156. // Found case matching a constant operand?
  157. BasicBlock *Succ = SI->getSuccessor(i);
  158. if (Succ == TheOnlyDest)
  159. TheOnlyDest = 0; // Don't modify the first branch to TheOnlyDest
  160. else
  161. Succ->removePredecessor(BB);
  162. }
  163. // Delete the old switch.
  164. BB->getInstList().erase(SI);
  165. return true;
  166. }
  167. if (SI->getNumSuccessors() == 2) {
  168. // Otherwise, we can fold this switch into a conditional branch
  169. // instruction if it has only one non-default destination.
  170. Value *Cond = new ICmpInst(SI, ICmpInst::ICMP_EQ, SI->getCondition(),
  171. SI->getSuccessorValue(1), "cond");
  172. // Insert the new branch.
  173. BranchInst::Create(SI->getSuccessor(1), SI->getSuccessor(0), Cond, SI);
  174. // Delete the old switch.
  175. SI->eraseFromParent();
  176. return true;
  177. }
  178. return false;
  179. }
  180. if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(T)) {
  181. // indirectbr blockaddress(@F, @BB) -> br label @BB
  182. if (BlockAddress *BA =
  183. dyn_cast<BlockAddress>(IBI->getAddress()->stripPointerCasts())) {
  184. BasicBlock *TheOnlyDest = BA->getBasicBlock();
  185. // Insert the new branch.
  186. BranchInst::Create(TheOnlyDest, IBI);
  187. for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
  188. if (IBI->getDestination(i) == TheOnlyDest)
  189. TheOnlyDest = 0;
  190. else
  191. IBI->getDestination(i)->removePredecessor(IBI->getParent());
  192. }
  193. IBI->eraseFromParent();
  194. // If we didn't find our destination in the IBI successor list, then we
  195. // have undefined behavior. Replace the unconditional branch with an
  196. // 'unreachable' instruction.
  197. if (TheOnlyDest) {
  198. BB->getTerminator()->eraseFromParent();
  199. new UnreachableInst(BB->getContext(), BB);
  200. }
  201. return true;
  202. }
  203. }
  204. return false;
  205. }
  206. //===----------------------------------------------------------------------===//
  207. // Local dead code elimination.
  208. //
  209. /// isInstructionTriviallyDead - Return true if the result produced by the
  210. /// instruction is not used, and the instruction has no side effects.
  211. ///
  212. bool llvm::isInstructionTriviallyDead(Instruction *I) {
  213. if (!I->use_empty() || isa<TerminatorInst>(I)) return false;
  214. // We don't want debug info removed by anything this general.
  215. if (isa<DbgInfoIntrinsic>(I)) return false;
  216. // Likewise for memory use markers.
  217. if (isa<MemoryUseIntrinsic>(I)) return false;
  218. if (!I->mayHaveSideEffects()) return true;
  219. // Special case intrinsics that "may have side effects" but can be deleted
  220. // when dead.
  221. if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
  222. // Safe to delete llvm.stacksave if dead.
  223. if (II->getIntrinsicID() == Intrinsic::stacksave)
  224. return true;
  225. return false;
  226. }
  227. /// RecursivelyDeleteTriviallyDeadInstructions - If the specified value is a
  228. /// trivially dead instruction, delete it. If that makes any of its operands
  229. /// trivially dead, delete them too, recursively.
  230. void llvm::RecursivelyDeleteTriviallyDeadInstructions(Value *V) {
  231. Instruction *I = dyn_cast<Instruction>(V);
  232. if (!I || !I->use_empty() || !isInstructionTriviallyDead(I))
  233. return;
  234. SmallVector<Instruction*, 16> DeadInsts;
  235. DeadInsts.push_back(I);
  236. while (!DeadInsts.empty()) {
  237. I = DeadInsts.pop_back_val();
  238. // Null out all of the instruction's operands to see if any operand becomes
  239. // dead as we go.
  240. for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
  241. Value *OpV = I->getOperand(i);
  242. I->setOperand(i, 0);
  243. if (!OpV->use_empty()) continue;
  244. // If the operand is an instruction that became dead as we nulled out the
  245. // operand, and if it is 'trivially' dead, delete it in a future loop
  246. // iteration.
  247. if (Instruction *OpI = dyn_cast<Instruction>(OpV))
  248. if (isInstructionTriviallyDead(OpI))
  249. DeadInsts.push_back(OpI);
  250. }
  251. I->eraseFromParent();
  252. }
  253. }
  254. /// RecursivelyDeleteDeadPHINode - If the specified value is an effectively
  255. /// dead PHI node, due to being a def-use chain of single-use nodes that
  256. /// either forms a cycle or is terminated by a trivially dead instruction,
  257. /// delete it. If that makes any of its operands trivially dead, delete them
  258. /// too, recursively.
  259. void
  260. llvm::RecursivelyDeleteDeadPHINode(PHINode *PN) {
  261. // We can remove a PHI if it is on a cycle in the def-use graph
  262. // where each node in the cycle has degree one, i.e. only one use,
  263. // and is an instruction with no side effects.
  264. if (!PN->hasOneUse())
  265. return;
  266. SmallPtrSet<PHINode *, 4> PHIs;
  267. PHIs.insert(PN);
  268. for (Instruction *J = cast<Instruction>(*PN->use_begin());
  269. J->hasOneUse() && !J->mayHaveSideEffects();
  270. J = cast<Instruction>(*J->use_begin()))
  271. // If we find a PHI more than once, we're on a cycle that
  272. // won't prove fruitful.
  273. if (PHINode *JP = dyn_cast<PHINode>(J))
  274. if (!PHIs.insert(cast<PHINode>(JP))) {
  275. // Break the cycle and delete the PHI and its operands.
  276. JP->replaceAllUsesWith(UndefValue::get(JP->getType()));
  277. RecursivelyDeleteTriviallyDeadInstructions(JP);
  278. break;
  279. }
  280. }
  281. //===----------------------------------------------------------------------===//
  282. // Control Flow Graph Restructuring.
  283. //
  284. /// RemovePredecessorAndSimplify - Like BasicBlock::removePredecessor, this
  285. /// method is called when we're about to delete Pred as a predecessor of BB. If
  286. /// BB contains any PHI nodes, this drops the entries in the PHI nodes for Pred.
  287. ///
  288. /// Unlike the removePredecessor method, this attempts to simplify uses of PHI
  289. /// nodes that collapse into identity values. For example, if we have:
  290. /// x = phi(1, 0, 0, 0)
  291. /// y = and x, z
  292. ///
  293. /// .. and delete the predecessor corresponding to the '1', this will attempt to
  294. /// recursively fold the and to 0.
  295. void llvm::RemovePredecessorAndSimplify(BasicBlock *BB, BasicBlock *Pred,
  296. TargetData *TD) {
  297. // This only adjusts blocks with PHI nodes.
  298. if (!isa<PHINode>(BB->begin()))
  299. return;
  300. // Remove the entries for Pred from the PHI nodes in BB, but do not simplify
  301. // them down. This will leave us with single entry phi nodes and other phis
  302. // that can be removed.
  303. BB->removePredecessor(Pred, true);
  304. WeakVH PhiIt = &BB->front();
  305. while (PHINode *PN = dyn_cast<PHINode>(PhiIt)) {
  306. PhiIt = &*++BasicBlock::iterator(cast<Instruction>(PhiIt));
  307. Value *PNV = PN->hasConstantValue();
  308. if (PNV == 0) continue;
  309. // If we're able to simplify the phi to a single value, substitute the new
  310. // value into all of its uses.
  311. assert(PNV != PN && "hasConstantValue broken");
  312. ReplaceAndSimplifyAllUses(PN, PNV, TD);
  313. // If recursive simplification ended up deleting the next PHI node we would
  314. // iterate to, then our iterator is invalid, restart scanning from the top
  315. // of the block.
  316. if (PhiIt == 0) PhiIt = &BB->front();
  317. }
  318. }
  319. /// MergeBasicBlockIntoOnlyPred - DestBB is a block with one predecessor and its
  320. /// predecessor is known to have one successor (DestBB!). Eliminate the edge
  321. /// between them, moving the instructions in the predecessor into DestBB and
  322. /// deleting the predecessor block.
  323. ///
  324. void llvm::MergeBasicBlockIntoOnlyPred(BasicBlock *DestBB, Pass *P) {
  325. // If BB has single-entry PHI nodes, fold them.
  326. while (PHINode *PN = dyn_cast<PHINode>(DestBB->begin())) {
  327. Value *NewVal = PN->getIncomingValue(0);
  328. // Replace self referencing PHI with undef, it must be dead.
  329. if (NewVal == PN) NewVal = UndefValue::get(PN->getType());
  330. PN->replaceAllUsesWith(NewVal);
  331. PN->eraseFromParent();
  332. }
  333. BasicBlock *PredBB = DestBB->getSinglePredecessor();
  334. assert(PredBB && "Block doesn't have a single predecessor!");
  335. // Splice all the instructions from PredBB to DestBB.
  336. PredBB->getTerminator()->eraseFromParent();
  337. DestBB->getInstList().splice(DestBB->begin(), PredBB->getInstList());
  338. // Anything that branched to PredBB now branches to DestBB.
  339. PredBB->replaceAllUsesWith(DestBB);
  340. if (P) {
  341. ProfileInfo *PI = P->getAnalysisIfAvailable<ProfileInfo>();
  342. if (PI) {
  343. PI->replaceAllUses(PredBB, DestBB);
  344. PI->removeEdge(ProfileInfo::getEdge(PredBB, DestBB));
  345. }
  346. }
  347. // Nuke BB.
  348. PredBB->eraseFromParent();
  349. }
  350. /// CanPropagatePredecessorsForPHIs - Return true if we can fold BB, an
  351. /// almost-empty BB ending in an unconditional branch to Succ, into succ.
  352. ///
  353. /// Assumption: Succ is the single successor for BB.
  354. ///
  355. static bool CanPropagatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) {
  356. assert(*succ_begin(BB) == Succ && "Succ is not successor of BB!");
  357. DEBUG(errs() << "Looking to fold " << BB->getName() << " into "
  358. << Succ->getName() << "\n");
  359. // Shortcut, if there is only a single predecessor it must be BB and merging
  360. // is always safe
  361. if (Succ->getSinglePredecessor()) return true;
  362. // Make a list of the predecessors of BB
  363. typedef SmallPtrSet<BasicBlock*, 16> BlockSet;
  364. BlockSet BBPreds(pred_begin(BB), pred_end(BB));
  365. // Use that list to make another list of common predecessors of BB and Succ
  366. BlockSet CommonPreds;
  367. for (pred_iterator PI = pred_begin(Succ), PE = pred_end(Succ);
  368. PI != PE; ++PI)
  369. if (BBPreds.count(*PI))
  370. CommonPreds.insert(*PI);
  371. // Shortcut, if there are no common predecessors, merging is always safe
  372. if (CommonPreds.empty())
  373. return true;
  374. // Look at all the phi nodes in Succ, to see if they present a conflict when
  375. // merging these blocks
  376. for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
  377. PHINode *PN = cast<PHINode>(I);
  378. // If the incoming value from BB is again a PHINode in
  379. // BB which has the same incoming value for *PI as PN does, we can
  380. // merge the phi nodes and then the blocks can still be merged
  381. PHINode *BBPN = dyn_cast<PHINode>(PN->getIncomingValueForBlock(BB));
  382. if (BBPN && BBPN->getParent() == BB) {
  383. for (BlockSet::iterator PI = CommonPreds.begin(), PE = CommonPreds.end();
  384. PI != PE; PI++) {
  385. if (BBPN->getIncomingValueForBlock(*PI)
  386. != PN->getIncomingValueForBlock(*PI)) {
  387. DEBUG(errs() << "Can't fold, phi node " << PN->getName() << " in "
  388. << Succ->getName() << " is conflicting with "
  389. << BBPN->getName() << " with regard to common predecessor "
  390. << (*PI)->getName() << "\n");
  391. return false;
  392. }
  393. }
  394. } else {
  395. Value* Val = PN->getIncomingValueForBlock(BB);
  396. for (BlockSet::iterator PI = CommonPreds.begin(), PE = CommonPreds.end();
  397. PI != PE; PI++) {
  398. // See if the incoming value for the common predecessor is equal to the
  399. // one for BB, in which case this phi node will not prevent the merging
  400. // of the block.
  401. if (Val != PN->getIncomingValueForBlock(*PI)) {
  402. DEBUG(errs() << "Can't fold, phi node " << PN->getName() << " in "
  403. << Succ->getName() << " is conflicting with regard to common "
  404. << "predecessor " << (*PI)->getName() << "\n");
  405. return false;
  406. }
  407. }
  408. }
  409. }
  410. return true;
  411. }
  412. /// TryToSimplifyUncondBranchFromEmptyBlock - BB is known to contain an
  413. /// unconditional branch, and contains no instructions other than PHI nodes,
  414. /// potential debug intrinsics and the branch. If possible, eliminate BB by
  415. /// rewriting all the predecessors to branch to the successor block and return
  416. /// true. If we can't transform, return false.
  417. bool llvm::TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock *BB) {
  418. // We can't eliminate infinite loops.
  419. BasicBlock *Succ = cast<BranchInst>(BB->getTerminator())->getSuccessor(0);
  420. if (BB == Succ) return false;
  421. // Check to see if merging these blocks would cause conflicts for any of the
  422. // phi nodes in BB or Succ. If not, we can safely merge.
  423. if (!CanPropagatePredecessorsForPHIs(BB, Succ)) return false;
  424. // Check for cases where Succ has multiple predecessors and a PHI node in BB
  425. // has uses which will not disappear when the PHI nodes are merged. It is
  426. // possible to handle such cases, but difficult: it requires checking whether
  427. // BB dominates Succ, which is non-trivial to calculate in the case where
  428. // Succ has multiple predecessors. Also, it requires checking whether
  429. // constructing the necessary self-referential PHI node doesn't intoduce any
  430. // conflicts; this isn't too difficult, but the previous code for doing this
  431. // was incorrect.
  432. //
  433. // Note that if this check finds a live use, BB dominates Succ, so BB is
  434. // something like a loop pre-header (or rarely, a part of an irreducible CFG);
  435. // folding the branch isn't profitable in that case anyway.
  436. if (!Succ->getSinglePredecessor()) {
  437. BasicBlock::iterator BBI = BB->begin();
  438. while (isa<PHINode>(*BBI)) {
  439. for (Value::use_iterator UI = BBI->use_begin(), E = BBI->use_end();
  440. UI != E; ++UI) {
  441. if (PHINode* PN = dyn_cast<PHINode>(*UI)) {
  442. if (PN->getIncomingBlock(UI) != BB)
  443. return false;
  444. } else {
  445. return false;
  446. }
  447. }
  448. ++BBI;
  449. }
  450. }
  451. DEBUG(errs() << "Killing Trivial BB: \n" << *BB);
  452. if (isa<PHINode>(Succ->begin())) {
  453. // If there is more than one pred of succ, and there are PHI nodes in
  454. // the successor, then we need to add incoming edges for the PHI nodes
  455. //
  456. const SmallVector<BasicBlock*, 16> BBPreds(pred_begin(BB), pred_end(BB));
  457. // Loop over all of the PHI nodes in the successor of BB.
  458. for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
  459. PHINode *PN = cast<PHINode>(I);
  460. Value *OldVal = PN->removeIncomingValue(BB, false);
  461. assert(OldVal && "No entry in PHI for Pred BB!");
  462. // If this incoming value is one of the PHI nodes in BB, the new entries
  463. // in the PHI node are the entries from the old PHI.
  464. if (isa<PHINode>(OldVal) && cast<PHINode>(OldVal)->getParent() == BB) {
  465. PHINode *OldValPN = cast<PHINode>(OldVal);
  466. for (unsigned i = 0, e = OldValPN->getNumIncomingValues(); i != e; ++i)
  467. // Note that, since we are merging phi nodes and BB and Succ might
  468. // have common predecessors, we could end up with a phi node with
  469. // identical incoming branches. This will be cleaned up later (and
  470. // will trigger asserts if we try to clean it up now, without also
  471. // simplifying the corresponding conditional branch).
  472. PN->addIncoming(OldValPN->getIncomingValue(i),
  473. OldValPN->getIncomingBlock(i));
  474. } else {
  475. // Add an incoming value for each of the new incoming values.
  476. for (unsigned i = 0, e = BBPreds.size(); i != e; ++i)
  477. PN->addIncoming(OldVal, BBPreds[i]);
  478. }
  479. }
  480. }
  481. while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
  482. if (Succ->getSinglePredecessor()) {
  483. // BB is the only predecessor of Succ, so Succ will end up with exactly
  484. // the same predecessors BB had.
  485. Succ->getInstList().splice(Succ->begin(),
  486. BB->getInstList(), BB->begin());
  487. } else {
  488. // We explicitly check for such uses in CanPropagatePredecessorsForPHIs.
  489. assert(PN->use_empty() && "There shouldn't be any uses here!");
  490. PN->eraseFromParent();
  491. }
  492. }
  493. // Everything that jumped to BB now goes to Succ.
  494. BB->replaceAllUsesWith(Succ);
  495. if (!Succ->hasName()) Succ->takeName(BB);
  496. BB->eraseFromParent(); // Delete the old basic block.
  497. return true;
  498. }
  499. /// OnlyUsedByDbgIntrinsics - Return true if the instruction I is only used
  500. /// by DbgIntrinsics. If DbgInUses is specified then the vector is filled
  501. /// with the DbgInfoIntrinsic that use the instruction I.
  502. bool llvm::OnlyUsedByDbgInfoIntrinsics(Instruction *I,
  503. SmallVectorImpl<DbgInfoIntrinsic *> *DbgInUses) {
  504. if (DbgInUses)
  505. DbgInUses->clear();
  506. for (Value::use_iterator UI = I->use_begin(), UE = I->use_end(); UI != UE;
  507. ++UI) {
  508. if (DbgInfoIntrinsic *DI = dyn_cast<DbgInfoIntrinsic>(*UI)) {
  509. if (DbgInUses)
  510. DbgInUses->push_back(DI);
  511. } else {
  512. if (DbgInUses)
  513. DbgInUses->clear();
  514. return false;
  515. }
  516. }
  517. return true;
  518. }