Local.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754
  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/ADT/DenseMap.h"
  23. #include "llvm/ADT/SmallPtrSet.h"
  24. #include "llvm/Analysis/Dominators.h"
  25. #include "llvm/Analysis/ConstantFolding.h"
  26. #include "llvm/Analysis/InstructionSimplify.h"
  27. #include "llvm/Analysis/ProfileInfo.h"
  28. #include "llvm/Analysis/ValueTracking.h"
  29. #include "llvm/Target/TargetData.h"
  30. #include "llvm/Support/CFG.h"
  31. #include "llvm/Support/Debug.h"
  32. #include "llvm/Support/GetElementPtrTypeIterator.h"
  33. #include "llvm/Support/MathExtras.h"
  34. #include "llvm/Support/ValueHandle.h"
  35. #include "llvm/Support/raw_ostream.h"
  36. using namespace llvm;
  37. //===----------------------------------------------------------------------===//
  38. // Local constant propagation.
  39. //
  40. // ConstantFoldTerminator - If a terminator instruction is predicated on a
  41. // constant value, convert it into an unconditional branch to the constant
  42. // destination.
  43. //
  44. bool llvm::ConstantFoldTerminator(BasicBlock *BB) {
  45. TerminatorInst *T = BB->getTerminator();
  46. // Branch - See if we are conditional jumping on constant
  47. if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
  48. if (BI->isUnconditional()) return false; // Can't optimize uncond branch
  49. BasicBlock *Dest1 = BI->getSuccessor(0);
  50. BasicBlock *Dest2 = BI->getSuccessor(1);
  51. if (ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition())) {
  52. // Are we branching on constant?
  53. // YES. Change to unconditional branch...
  54. BasicBlock *Destination = Cond->getZExtValue() ? Dest1 : Dest2;
  55. BasicBlock *OldDest = Cond->getZExtValue() ? Dest2 : Dest1;
  56. //cerr << "Function: " << T->getParent()->getParent()
  57. // << "\nRemoving branch from " << T->getParent()
  58. // << "\n\nTo: " << OldDest << endl;
  59. // Let the basic block know that we are letting go of it. Based on this,
  60. // it will adjust it's PHI nodes.
  61. assert(BI->getParent() && "Terminator not inserted in block!");
  62. OldDest->removePredecessor(BI->getParent());
  63. // Replace the conditional branch with an unconditional one.
  64. BranchInst::Create(Destination, BI);
  65. BI->eraseFromParent();
  66. return true;
  67. }
  68. if (Dest2 == Dest1) { // Conditional branch to same location?
  69. // This branch matches something like this:
  70. // br bool %cond, label %Dest, label %Dest
  71. // and changes it into: br label %Dest
  72. // Let the basic block know that we are letting go of one copy of it.
  73. assert(BI->getParent() && "Terminator not inserted in block!");
  74. Dest1->removePredecessor(BI->getParent());
  75. // Replace the conditional branch with an unconditional one.
  76. BranchInst::Create(Dest1, BI);
  77. BI->eraseFromParent();
  78. return true;
  79. }
  80. return false;
  81. }
  82. if (SwitchInst *SI = dyn_cast<SwitchInst>(T)) {
  83. // If we are switching on a constant, we can convert the switch into a
  84. // single branch instruction!
  85. ConstantInt *CI = dyn_cast<ConstantInt>(SI->getCondition());
  86. BasicBlock *TheOnlyDest = SI->getSuccessor(0); // The default dest
  87. BasicBlock *DefaultDest = TheOnlyDest;
  88. assert(TheOnlyDest == SI->getDefaultDest() &&
  89. "Default destination is not successor #0?");
  90. // Figure out which case it goes to.
  91. for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i) {
  92. // Found case matching a constant operand?
  93. if (SI->getSuccessorValue(i) == CI) {
  94. TheOnlyDest = SI->getSuccessor(i);
  95. break;
  96. }
  97. // Check to see if this branch is going to the same place as the default
  98. // dest. If so, eliminate it as an explicit compare.
  99. if (SI->getSuccessor(i) == DefaultDest) {
  100. // Remove this entry.
  101. DefaultDest->removePredecessor(SI->getParent());
  102. SI->removeCase(i);
  103. --i; --e; // Don't skip an entry...
  104. continue;
  105. }
  106. // Otherwise, check to see if the switch only branches to one destination.
  107. // We do this by reseting "TheOnlyDest" to null when we find two non-equal
  108. // destinations.
  109. if (SI->getSuccessor(i) != TheOnlyDest) TheOnlyDest = 0;
  110. }
  111. if (CI && !TheOnlyDest) {
  112. // Branching on a constant, but not any of the cases, go to the default
  113. // successor.
  114. TheOnlyDest = SI->getDefaultDest();
  115. }
  116. // If we found a single destination that we can fold the switch into, do so
  117. // now.
  118. if (TheOnlyDest) {
  119. // Insert the new branch.
  120. BranchInst::Create(TheOnlyDest, SI);
  121. BasicBlock *BB = SI->getParent();
  122. // Remove entries from PHI nodes which we no longer branch to...
  123. for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) {
  124. // Found case matching a constant operand?
  125. BasicBlock *Succ = SI->getSuccessor(i);
  126. if (Succ == TheOnlyDest)
  127. TheOnlyDest = 0; // Don't modify the first branch to TheOnlyDest
  128. else
  129. Succ->removePredecessor(BB);
  130. }
  131. // Delete the old switch.
  132. BB->getInstList().erase(SI);
  133. return true;
  134. }
  135. if (SI->getNumSuccessors() == 2) {
  136. // Otherwise, we can fold this switch into a conditional branch
  137. // instruction if it has only one non-default destination.
  138. Value *Cond = new ICmpInst(SI, ICmpInst::ICMP_EQ, SI->getCondition(),
  139. SI->getSuccessorValue(1), "cond");
  140. // Insert the new branch.
  141. BranchInst::Create(SI->getSuccessor(1), SI->getSuccessor(0), Cond, SI);
  142. // Delete the old switch.
  143. SI->eraseFromParent();
  144. return true;
  145. }
  146. return false;
  147. }
  148. if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(T)) {
  149. // indirectbr blockaddress(@F, @BB) -> br label @BB
  150. if (BlockAddress *BA =
  151. dyn_cast<BlockAddress>(IBI->getAddress()->stripPointerCasts())) {
  152. BasicBlock *TheOnlyDest = BA->getBasicBlock();
  153. // Insert the new branch.
  154. BranchInst::Create(TheOnlyDest, IBI);
  155. for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
  156. if (IBI->getDestination(i) == TheOnlyDest)
  157. TheOnlyDest = 0;
  158. else
  159. IBI->getDestination(i)->removePredecessor(IBI->getParent());
  160. }
  161. IBI->eraseFromParent();
  162. // If we didn't find our destination in the IBI successor list, then we
  163. // have undefined behavior. Replace the unconditional branch with an
  164. // 'unreachable' instruction.
  165. if (TheOnlyDest) {
  166. BB->getTerminator()->eraseFromParent();
  167. new UnreachableInst(BB->getContext(), BB);
  168. }
  169. return true;
  170. }
  171. }
  172. return false;
  173. }
  174. //===----------------------------------------------------------------------===//
  175. // Local dead code elimination.
  176. //
  177. /// isInstructionTriviallyDead - Return true if the result produced by the
  178. /// instruction is not used, and the instruction has no side effects.
  179. ///
  180. bool llvm::isInstructionTriviallyDead(Instruction *I) {
  181. if (!I->use_empty() || isa<TerminatorInst>(I)) return false;
  182. // We don't want debug info removed by anything this general.
  183. if (isa<DbgInfoIntrinsic>(I)) return false;
  184. if (!I->mayHaveSideEffects()) return true;
  185. // Special case intrinsics that "may have side effects" but can be deleted
  186. // when dead.
  187. if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
  188. // Safe to delete llvm.stacksave if dead.
  189. if (II->getIntrinsicID() == Intrinsic::stacksave)
  190. return true;
  191. return false;
  192. }
  193. /// RecursivelyDeleteTriviallyDeadInstructions - If the specified value is a
  194. /// trivially dead instruction, delete it. If that makes any of its operands
  195. /// trivially dead, delete them too, recursively. Return true if any
  196. /// instructions were deleted.
  197. bool llvm::RecursivelyDeleteTriviallyDeadInstructions(Value *V) {
  198. Instruction *I = dyn_cast<Instruction>(V);
  199. if (!I || !I->use_empty() || !isInstructionTriviallyDead(I))
  200. return false;
  201. SmallVector<Instruction*, 16> DeadInsts;
  202. DeadInsts.push_back(I);
  203. do {
  204. I = DeadInsts.pop_back_val();
  205. // Null out all of the instruction's operands to see if any operand becomes
  206. // dead as we go.
  207. for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
  208. Value *OpV = I->getOperand(i);
  209. I->setOperand(i, 0);
  210. if (!OpV->use_empty()) continue;
  211. // If the operand is an instruction that became dead as we nulled out the
  212. // operand, and if it is 'trivially' dead, delete it in a future loop
  213. // iteration.
  214. if (Instruction *OpI = dyn_cast<Instruction>(OpV))
  215. if (isInstructionTriviallyDead(OpI))
  216. DeadInsts.push_back(OpI);
  217. }
  218. I->eraseFromParent();
  219. } while (!DeadInsts.empty());
  220. return true;
  221. }
  222. /// areAllUsesEqual - Check whether the uses of a value are all the same.
  223. /// This is similar to Instruction::hasOneUse() except this will also return
  224. /// true when there are no uses or multiple uses that all refer to the same
  225. /// value.
  226. static bool areAllUsesEqual(Instruction *I) {
  227. Value::use_iterator UI = I->use_begin();
  228. Value::use_iterator UE = I->use_end();
  229. if (UI == UE)
  230. return true;
  231. User *TheUse = *UI;
  232. for (++UI; UI != UE; ++UI) {
  233. if (*UI != TheUse)
  234. return false;
  235. }
  236. return true;
  237. }
  238. /// RecursivelyDeleteDeadPHINode - If the specified value is an effectively
  239. /// dead PHI node, due to being a def-use chain of single-use nodes that
  240. /// either forms a cycle or is terminated by a trivially dead instruction,
  241. /// delete it. If that makes any of its operands trivially dead, delete them
  242. /// too, recursively. Return true if the PHI node is actually deleted.
  243. bool llvm::RecursivelyDeleteDeadPHINode(PHINode *PN) {
  244. SmallPtrSet<Instruction*, 4> Visited;
  245. for (Instruction *I = PN; areAllUsesEqual(I) && !I->mayHaveSideEffects();
  246. I = cast<Instruction>(*I->use_begin())) {
  247. if (I->use_empty())
  248. return RecursivelyDeleteTriviallyDeadInstructions(I);
  249. // If we find an instruction more than once, we're on a cycle that
  250. // won't prove fruitful.
  251. if (!Visited.insert(I)) {
  252. // Break the cycle and delete the instruction and its operands.
  253. I->replaceAllUsesWith(UndefValue::get(I->getType()));
  254. return RecursivelyDeleteTriviallyDeadInstructions(I);
  255. }
  256. }
  257. return false;
  258. }
  259. /// SimplifyInstructionsInBlock - Scan the specified basic block and try to
  260. /// simplify any instructions in it and recursively delete dead instructions.
  261. ///
  262. /// This returns true if it changed the code, note that it can delete
  263. /// instructions in other blocks as well in this block.
  264. bool llvm::SimplifyInstructionsInBlock(BasicBlock *BB, const TargetData *TD) {
  265. bool MadeChange = false;
  266. for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
  267. Instruction *Inst = BI++;
  268. if (Value *V = SimplifyInstruction(Inst, TD)) {
  269. WeakVH BIHandle(BI);
  270. ReplaceAndSimplifyAllUses(Inst, V, TD);
  271. MadeChange = true;
  272. if (BIHandle != BI)
  273. BI = BB->begin();
  274. continue;
  275. }
  276. MadeChange |= RecursivelyDeleteTriviallyDeadInstructions(Inst);
  277. }
  278. return MadeChange;
  279. }
  280. //===----------------------------------------------------------------------===//
  281. // Control Flow Graph Restructuring.
  282. //
  283. /// RemovePredecessorAndSimplify - Like BasicBlock::removePredecessor, this
  284. /// method is called when we're about to delete Pred as a predecessor of BB. If
  285. /// BB contains any PHI nodes, this drops the entries in the PHI nodes for Pred.
  286. ///
  287. /// Unlike the removePredecessor method, this attempts to simplify uses of PHI
  288. /// nodes that collapse into identity values. For example, if we have:
  289. /// x = phi(1, 0, 0, 0)
  290. /// y = and x, z
  291. ///
  292. /// .. and delete the predecessor corresponding to the '1', this will attempt to
  293. /// recursively fold the and to 0.
  294. void llvm::RemovePredecessorAndSimplify(BasicBlock *BB, BasicBlock *Pred,
  295. TargetData *TD) {
  296. // This only adjusts blocks with PHI nodes.
  297. if (!isa<PHINode>(BB->begin()))
  298. return;
  299. // Remove the entries for Pred from the PHI nodes in BB, but do not simplify
  300. // them down. This will leave us with single entry phi nodes and other phis
  301. // that can be removed.
  302. BB->removePredecessor(Pred, true);
  303. WeakVH PhiIt = &BB->front();
  304. while (PHINode *PN = dyn_cast<PHINode>(PhiIt)) {
  305. PhiIt = &*++BasicBlock::iterator(cast<Instruction>(PhiIt));
  306. Value *PNV = SimplifyInstruction(PN, TD);
  307. if (PNV == 0) continue;
  308. // If we're able to simplify the phi to a single value, substitute the new
  309. // value into all of its uses.
  310. assert(PNV != PN && "SimplifyInstruction broken!");
  311. Value *OldPhiIt = PhiIt;
  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 != OldPhiIt) 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. // Zap anything that took the address of DestBB. Not doing this will give the
  339. // address an invalid value.
  340. if (DestBB->hasAddressTaken()) {
  341. BlockAddress *BA = BlockAddress::get(DestBB);
  342. Constant *Replacement =
  343. ConstantInt::get(llvm::Type::getInt32Ty(BA->getContext()), 1);
  344. BA->replaceAllUsesWith(ConstantExpr::getIntToPtr(Replacement,
  345. BA->getType()));
  346. BA->destroyConstant();
  347. }
  348. // Anything that branched to PredBB now branches to DestBB.
  349. PredBB->replaceAllUsesWith(DestBB);
  350. if (P) {
  351. DominatorTree *DT = P->getAnalysisIfAvailable<DominatorTree>();
  352. if (DT) {
  353. BasicBlock *PredBBIDom = DT->getNode(PredBB)->getIDom()->getBlock();
  354. DT->changeImmediateDominator(DestBB, PredBBIDom);
  355. DT->eraseNode(PredBB);
  356. }
  357. ProfileInfo *PI = P->getAnalysisIfAvailable<ProfileInfo>();
  358. if (PI) {
  359. PI->replaceAllUses(PredBB, DestBB);
  360. PI->removeEdge(ProfileInfo::getEdge(PredBB, DestBB));
  361. }
  362. }
  363. // Nuke BB.
  364. PredBB->eraseFromParent();
  365. }
  366. /// CanPropagatePredecessorsForPHIs - Return true if we can fold BB, an
  367. /// almost-empty BB ending in an unconditional branch to Succ, into succ.
  368. ///
  369. /// Assumption: Succ is the single successor for BB.
  370. ///
  371. static bool CanPropagatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) {
  372. assert(*succ_begin(BB) == Succ && "Succ is not successor of BB!");
  373. DEBUG(dbgs() << "Looking to fold " << BB->getName() << " into "
  374. << Succ->getName() << "\n");
  375. // Shortcut, if there is only a single predecessor it must be BB and merging
  376. // is always safe
  377. if (Succ->getSinglePredecessor()) return true;
  378. // Make a list of the predecessors of BB
  379. typedef SmallPtrSet<BasicBlock*, 16> BlockSet;
  380. BlockSet BBPreds(pred_begin(BB), pred_end(BB));
  381. // Use that list to make another list of common predecessors of BB and Succ
  382. BlockSet CommonPreds;
  383. for (pred_iterator PI = pred_begin(Succ), PE = pred_end(Succ);
  384. PI != PE; ++PI) {
  385. BasicBlock *P = *PI;
  386. if (BBPreds.count(P))
  387. CommonPreds.insert(P);
  388. }
  389. // Shortcut, if there are no common predecessors, merging is always safe
  390. if (CommonPreds.empty())
  391. return true;
  392. // Look at all the phi nodes in Succ, to see if they present a conflict when
  393. // merging these blocks
  394. for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
  395. PHINode *PN = cast<PHINode>(I);
  396. // If the incoming value from BB is again a PHINode in
  397. // BB which has the same incoming value for *PI as PN does, we can
  398. // merge the phi nodes and then the blocks can still be merged
  399. PHINode *BBPN = dyn_cast<PHINode>(PN->getIncomingValueForBlock(BB));
  400. if (BBPN && BBPN->getParent() == BB) {
  401. for (BlockSet::iterator PI = CommonPreds.begin(), PE = CommonPreds.end();
  402. PI != PE; PI++) {
  403. if (BBPN->getIncomingValueForBlock(*PI)
  404. != PN->getIncomingValueForBlock(*PI)) {
  405. DEBUG(dbgs() << "Can't fold, phi node " << PN->getName() << " in "
  406. << Succ->getName() << " is conflicting with "
  407. << BBPN->getName() << " with regard to common predecessor "
  408. << (*PI)->getName() << "\n");
  409. return false;
  410. }
  411. }
  412. } else {
  413. Value* Val = PN->getIncomingValueForBlock(BB);
  414. for (BlockSet::iterator PI = CommonPreds.begin(), PE = CommonPreds.end();
  415. PI != PE; PI++) {
  416. // See if the incoming value for the common predecessor is equal to the
  417. // one for BB, in which case this phi node will not prevent the merging
  418. // of the block.
  419. if (Val != PN->getIncomingValueForBlock(*PI)) {
  420. DEBUG(dbgs() << "Can't fold, phi node " << PN->getName() << " in "
  421. << Succ->getName() << " is conflicting with regard to common "
  422. << "predecessor " << (*PI)->getName() << "\n");
  423. return false;
  424. }
  425. }
  426. }
  427. }
  428. return true;
  429. }
  430. /// TryToSimplifyUncondBranchFromEmptyBlock - BB is known to contain an
  431. /// unconditional branch, and contains no instructions other than PHI nodes,
  432. /// potential debug intrinsics and the branch. If possible, eliminate BB by
  433. /// rewriting all the predecessors to branch to the successor block and return
  434. /// true. If we can't transform, return false.
  435. bool llvm::TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock *BB) {
  436. assert(BB != &BB->getParent()->getEntryBlock() &&
  437. "TryToSimplifyUncondBranchFromEmptyBlock called on entry block!");
  438. // We can't eliminate infinite loops.
  439. BasicBlock *Succ = cast<BranchInst>(BB->getTerminator())->getSuccessor(0);
  440. if (BB == Succ) return false;
  441. // Check to see if merging these blocks would cause conflicts for any of the
  442. // phi nodes in BB or Succ. If not, we can safely merge.
  443. if (!CanPropagatePredecessorsForPHIs(BB, Succ)) return false;
  444. // Check for cases where Succ has multiple predecessors and a PHI node in BB
  445. // has uses which will not disappear when the PHI nodes are merged. It is
  446. // possible to handle such cases, but difficult: it requires checking whether
  447. // BB dominates Succ, which is non-trivial to calculate in the case where
  448. // Succ has multiple predecessors. Also, it requires checking whether
  449. // constructing the necessary self-referential PHI node doesn't intoduce any
  450. // conflicts; this isn't too difficult, but the previous code for doing this
  451. // was incorrect.
  452. //
  453. // Note that if this check finds a live use, BB dominates Succ, so BB is
  454. // something like a loop pre-header (or rarely, a part of an irreducible CFG);
  455. // folding the branch isn't profitable in that case anyway.
  456. if (!Succ->getSinglePredecessor()) {
  457. BasicBlock::iterator BBI = BB->begin();
  458. while (isa<PHINode>(*BBI)) {
  459. for (Value::use_iterator UI = BBI->use_begin(), E = BBI->use_end();
  460. UI != E; ++UI) {
  461. if (PHINode* PN = dyn_cast<PHINode>(*UI)) {
  462. if (PN->getIncomingBlock(UI) != BB)
  463. return false;
  464. } else {
  465. return false;
  466. }
  467. }
  468. ++BBI;
  469. }
  470. }
  471. DEBUG(dbgs() << "Killing Trivial BB: \n" << *BB);
  472. if (isa<PHINode>(Succ->begin())) {
  473. // If there is more than one pred of succ, and there are PHI nodes in
  474. // the successor, then we need to add incoming edges for the PHI nodes
  475. //
  476. const SmallVector<BasicBlock*, 16> BBPreds(pred_begin(BB), pred_end(BB));
  477. // Loop over all of the PHI nodes in the successor of BB.
  478. for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
  479. PHINode *PN = cast<PHINode>(I);
  480. Value *OldVal = PN->removeIncomingValue(BB, false);
  481. assert(OldVal && "No entry in PHI for Pred BB!");
  482. // If this incoming value is one of the PHI nodes in BB, the new entries
  483. // in the PHI node are the entries from the old PHI.
  484. if (isa<PHINode>(OldVal) && cast<PHINode>(OldVal)->getParent() == BB) {
  485. PHINode *OldValPN = cast<PHINode>(OldVal);
  486. for (unsigned i = 0, e = OldValPN->getNumIncomingValues(); i != e; ++i)
  487. // Note that, since we are merging phi nodes and BB and Succ might
  488. // have common predecessors, we could end up with a phi node with
  489. // identical incoming branches. This will be cleaned up later (and
  490. // will trigger asserts if we try to clean it up now, without also
  491. // simplifying the corresponding conditional branch).
  492. PN->addIncoming(OldValPN->getIncomingValue(i),
  493. OldValPN->getIncomingBlock(i));
  494. } else {
  495. // Add an incoming value for each of the new incoming values.
  496. for (unsigned i = 0, e = BBPreds.size(); i != e; ++i)
  497. PN->addIncoming(OldVal, BBPreds[i]);
  498. }
  499. }
  500. }
  501. while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
  502. if (Succ->getSinglePredecessor()) {
  503. // BB is the only predecessor of Succ, so Succ will end up with exactly
  504. // the same predecessors BB had.
  505. Succ->getInstList().splice(Succ->begin(),
  506. BB->getInstList(), BB->begin());
  507. } else {
  508. // We explicitly check for such uses in CanPropagatePredecessorsForPHIs.
  509. assert(PN->use_empty() && "There shouldn't be any uses here!");
  510. PN->eraseFromParent();
  511. }
  512. }
  513. // Everything that jumped to BB now goes to Succ.
  514. BB->replaceAllUsesWith(Succ);
  515. if (!Succ->hasName()) Succ->takeName(BB);
  516. BB->eraseFromParent(); // Delete the old basic block.
  517. return true;
  518. }
  519. /// EliminateDuplicatePHINodes - Check for and eliminate duplicate PHI
  520. /// nodes in this block. This doesn't try to be clever about PHI nodes
  521. /// which differ only in the order of the incoming values, but instcombine
  522. /// orders them so it usually won't matter.
  523. ///
  524. bool llvm::EliminateDuplicatePHINodes(BasicBlock *BB) {
  525. bool Changed = false;
  526. // This implementation doesn't currently consider undef operands
  527. // specially. Theroetically, two phis which are identical except for
  528. // one having an undef where the other doesn't could be collapsed.
  529. // Map from PHI hash values to PHI nodes. If multiple PHIs have
  530. // the same hash value, the element is the first PHI in the
  531. // linked list in CollisionMap.
  532. DenseMap<uintptr_t, PHINode *> HashMap;
  533. // Maintain linked lists of PHI nodes with common hash values.
  534. DenseMap<PHINode *, PHINode *> CollisionMap;
  535. // Examine each PHI.
  536. for (BasicBlock::iterator I = BB->begin();
  537. PHINode *PN = dyn_cast<PHINode>(I++); ) {
  538. // Compute a hash value on the operands. Instcombine will likely have sorted
  539. // them, which helps expose duplicates, but we have to check all the
  540. // operands to be safe in case instcombine hasn't run.
  541. uintptr_t Hash = 0;
  542. for (User::op_iterator I = PN->op_begin(), E = PN->op_end(); I != E; ++I) {
  543. // This hash algorithm is quite weak as hash functions go, but it seems
  544. // to do a good enough job for this particular purpose, and is very quick.
  545. Hash ^= reinterpret_cast<uintptr_t>(static_cast<Value *>(*I));
  546. Hash = (Hash << 7) | (Hash >> (sizeof(uintptr_t) * CHAR_BIT - 7));
  547. }
  548. // If we've never seen this hash value before, it's a unique PHI.
  549. std::pair<DenseMap<uintptr_t, PHINode *>::iterator, bool> Pair =
  550. HashMap.insert(std::make_pair(Hash, PN));
  551. if (Pair.second) continue;
  552. // Otherwise it's either a duplicate or a hash collision.
  553. for (PHINode *OtherPN = Pair.first->second; ; ) {
  554. if (OtherPN->isIdenticalTo(PN)) {
  555. // A duplicate. Replace this PHI with its duplicate.
  556. PN->replaceAllUsesWith(OtherPN);
  557. PN->eraseFromParent();
  558. Changed = true;
  559. break;
  560. }
  561. // A non-duplicate hash collision.
  562. DenseMap<PHINode *, PHINode *>::iterator I = CollisionMap.find(OtherPN);
  563. if (I == CollisionMap.end()) {
  564. // Set this PHI to be the head of the linked list of colliding PHIs.
  565. PHINode *Old = Pair.first->second;
  566. Pair.first->second = PN;
  567. CollisionMap[PN] = Old;
  568. break;
  569. }
  570. // Procede to the next PHI in the list.
  571. OtherPN = I->second;
  572. }
  573. }
  574. return Changed;
  575. }
  576. /// enforceKnownAlignment - If the specified pointer points to an object that
  577. /// we control, modify the object's alignment to PrefAlign. This isn't
  578. /// often possible though. If alignment is important, a more reliable approach
  579. /// is to simply align all global variables and allocation instructions to
  580. /// their preferred alignment from the beginning.
  581. ///
  582. static unsigned enforceKnownAlignment(Value *V, unsigned Align,
  583. unsigned PrefAlign) {
  584. User *U = dyn_cast<User>(V);
  585. if (!U) return Align;
  586. switch (Operator::getOpcode(U)) {
  587. default: break;
  588. case Instruction::BitCast:
  589. return enforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
  590. case Instruction::GetElementPtr: {
  591. // If all indexes are zero, it is just the alignment of the base pointer.
  592. bool AllZeroOperands = true;
  593. for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
  594. if (!isa<Constant>(*i) ||
  595. !cast<Constant>(*i)->isNullValue()) {
  596. AllZeroOperands = false;
  597. break;
  598. }
  599. if (AllZeroOperands) {
  600. // Treat this like a bitcast.
  601. return enforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
  602. }
  603. return Align;
  604. }
  605. case Instruction::Alloca: {
  606. AllocaInst *AI = cast<AllocaInst>(V);
  607. // If there is a requested alignment and if this is an alloca, round up.
  608. if (AI->getAlignment() >= PrefAlign)
  609. return AI->getAlignment();
  610. AI->setAlignment(PrefAlign);
  611. return PrefAlign;
  612. }
  613. }
  614. if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
  615. // If there is a large requested alignment and we can, bump up the alignment
  616. // of the global.
  617. if (GV->isDeclaration()) return Align;
  618. if (GV->getAlignment() >= PrefAlign)
  619. return GV->getAlignment();
  620. // We can only increase the alignment of the global if it has no alignment
  621. // specified or if it is not assigned a section. If it is assigned a
  622. // section, the global could be densely packed with other objects in the
  623. // section, increasing the alignment could cause padding issues.
  624. if (!GV->hasSection() || GV->getAlignment() == 0)
  625. GV->setAlignment(PrefAlign);
  626. return GV->getAlignment();
  627. }
  628. return Align;
  629. }
  630. /// getOrEnforceKnownAlignment - If the specified pointer has an alignment that
  631. /// we can determine, return it, otherwise return 0. If PrefAlign is specified,
  632. /// and it is more than the alignment of the ultimate object, see if we can
  633. /// increase the alignment of the ultimate object, making this check succeed.
  634. unsigned llvm::getOrEnforceKnownAlignment(Value *V, unsigned PrefAlign,
  635. const TargetData *TD) {
  636. assert(V->getType()->isPointerTy() &&
  637. "getOrEnforceKnownAlignment expects a pointer!");
  638. unsigned BitWidth = TD ? TD->getPointerSizeInBits() : 64;
  639. APInt Mask = APInt::getAllOnesValue(BitWidth);
  640. APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
  641. ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD);
  642. unsigned TrailZ = KnownZero.countTrailingOnes();
  643. // Avoid trouble with rediculously large TrailZ values, such as
  644. // those computed from a null pointer.
  645. TrailZ = std::min(TrailZ, unsigned(sizeof(unsigned) * CHAR_BIT - 1));
  646. unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
  647. // LLVM doesn't support alignments larger than this currently.
  648. Align = std::min(Align, +Value::MaximumAlignment);
  649. if (PrefAlign > Align)
  650. Align = enforceKnownAlignment(V, Align, PrefAlign);
  651. // We don't need to make any adjustment.
  652. return Align;
  653. }