Local.cpp 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890
  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/DIBuilder.h"
  17. #include "llvm/DebugInfo.h"
  18. #include "llvm/DerivedTypes.h"
  19. #include "llvm/GlobalAlias.h"
  20. #include "llvm/GlobalVariable.h"
  21. #include "llvm/IRBuilder.h"
  22. #include "llvm/Instructions.h"
  23. #include "llvm/IntrinsicInst.h"
  24. #include "llvm/Intrinsics.h"
  25. #include "llvm/Metadata.h"
  26. #include "llvm/Operator.h"
  27. #include "llvm/ADT/DenseMap.h"
  28. #include "llvm/ADT/SmallPtrSet.h"
  29. #include "llvm/Analysis/Dominators.h"
  30. #include "llvm/Analysis/InstructionSimplify.h"
  31. #include "llvm/Analysis/MemoryBuiltins.h"
  32. #include "llvm/Analysis/ProfileInfo.h"
  33. #include "llvm/Analysis/ValueTracking.h"
  34. #include "llvm/Support/CFG.h"
  35. #include "llvm/Support/Debug.h"
  36. #include "llvm/Support/GetElementPtrTypeIterator.h"
  37. #include "llvm/Support/MathExtras.h"
  38. #include "llvm/Support/ValueHandle.h"
  39. #include "llvm/Support/raw_ostream.h"
  40. #include "llvm/Target/TargetData.h"
  41. using namespace llvm;
  42. //===----------------------------------------------------------------------===//
  43. // Local constant propagation.
  44. //
  45. /// ConstantFoldTerminator - If a terminator instruction is predicated on a
  46. /// constant value, convert it into an unconditional branch to the constant
  47. /// destination. This is a nontrivial operation because the successors of this
  48. /// basic block must have their PHI nodes updated.
  49. /// Also calls RecursivelyDeleteTriviallyDeadInstructions() on any branch/switch
  50. /// conditions and indirectbr addresses this might make dead if
  51. /// DeleteDeadConditions is true.
  52. bool llvm::ConstantFoldTerminator(BasicBlock *BB, bool DeleteDeadConditions) {
  53. TerminatorInst *T = BB->getTerminator();
  54. IRBuilder<> Builder(T);
  55. // Branch - See if we are conditional jumping on constant
  56. if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
  57. if (BI->isUnconditional()) return false; // Can't optimize uncond branch
  58. BasicBlock *Dest1 = BI->getSuccessor(0);
  59. BasicBlock *Dest2 = BI->getSuccessor(1);
  60. if (ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition())) {
  61. // Are we branching on constant?
  62. // YES. Change to unconditional branch...
  63. BasicBlock *Destination = Cond->getZExtValue() ? Dest1 : Dest2;
  64. BasicBlock *OldDest = Cond->getZExtValue() ? Dest2 : Dest1;
  65. //cerr << "Function: " << T->getParent()->getParent()
  66. // << "\nRemoving branch from " << T->getParent()
  67. // << "\n\nTo: " << OldDest << endl;
  68. // Let the basic block know that we are letting go of it. Based on this,
  69. // it will adjust it's PHI nodes.
  70. OldDest->removePredecessor(BB);
  71. // Replace the conditional branch with an unconditional one.
  72. Builder.CreateBr(Destination);
  73. BI->eraseFromParent();
  74. return true;
  75. }
  76. if (Dest2 == Dest1) { // Conditional branch to same location?
  77. // This branch matches something like this:
  78. // br bool %cond, label %Dest, label %Dest
  79. // and changes it into: br label %Dest
  80. // Let the basic block know that we are letting go of one copy of it.
  81. assert(BI->getParent() && "Terminator not inserted in block!");
  82. Dest1->removePredecessor(BI->getParent());
  83. // Replace the conditional branch with an unconditional one.
  84. Builder.CreateBr(Dest1);
  85. Value *Cond = BI->getCondition();
  86. BI->eraseFromParent();
  87. if (DeleteDeadConditions)
  88. RecursivelyDeleteTriviallyDeadInstructions(Cond);
  89. return true;
  90. }
  91. return false;
  92. }
  93. if (SwitchInst *SI = dyn_cast<SwitchInst>(T)) {
  94. // If we are switching on a constant, we can convert the switch into a
  95. // single branch instruction!
  96. ConstantInt *CI = dyn_cast<ConstantInt>(SI->getCondition());
  97. BasicBlock *TheOnlyDest = SI->getDefaultDest();
  98. BasicBlock *DefaultDest = TheOnlyDest;
  99. // Figure out which case it goes to.
  100. for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
  101. i != e; ++i) {
  102. // Found case matching a constant operand?
  103. if (i.getCaseValue() == CI) {
  104. TheOnlyDest = i.getCaseSuccessor();
  105. break;
  106. }
  107. // Check to see if this branch is going to the same place as the default
  108. // dest. If so, eliminate it as an explicit compare.
  109. if (i.getCaseSuccessor() == DefaultDest) {
  110. // Remove this entry.
  111. DefaultDest->removePredecessor(SI->getParent());
  112. SI->removeCase(i);
  113. --i; --e;
  114. continue;
  115. }
  116. // Otherwise, check to see if the switch only branches to one destination.
  117. // We do this by reseting "TheOnlyDest" to null when we find two non-equal
  118. // destinations.
  119. if (i.getCaseSuccessor() != TheOnlyDest) TheOnlyDest = 0;
  120. }
  121. if (CI && !TheOnlyDest) {
  122. // Branching on a constant, but not any of the cases, go to the default
  123. // successor.
  124. TheOnlyDest = SI->getDefaultDest();
  125. }
  126. // If we found a single destination that we can fold the switch into, do so
  127. // now.
  128. if (TheOnlyDest) {
  129. // Insert the new branch.
  130. Builder.CreateBr(TheOnlyDest);
  131. BasicBlock *BB = SI->getParent();
  132. // Remove entries from PHI nodes which we no longer branch to...
  133. for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) {
  134. // Found case matching a constant operand?
  135. BasicBlock *Succ = SI->getSuccessor(i);
  136. if (Succ == TheOnlyDest)
  137. TheOnlyDest = 0; // Don't modify the first branch to TheOnlyDest
  138. else
  139. Succ->removePredecessor(BB);
  140. }
  141. // Delete the old switch.
  142. Value *Cond = SI->getCondition();
  143. SI->eraseFromParent();
  144. if (DeleteDeadConditions)
  145. RecursivelyDeleteTriviallyDeadInstructions(Cond);
  146. return true;
  147. }
  148. if (SI->getNumCases() == 1) {
  149. // Otherwise, we can fold this switch into a conditional branch
  150. // instruction if it has only one non-default destination.
  151. SwitchInst::CaseIt FirstCase = SI->case_begin();
  152. IntegersSubset& Case = FirstCase.getCaseValueEx();
  153. if (Case.isSingleNumber()) {
  154. // FIXME: Currently work with ConstantInt based numbers.
  155. Value *Cond = Builder.CreateICmpEQ(SI->getCondition(),
  156. Case.getSingleNumber(0).toConstantInt(),
  157. "cond");
  158. // Insert the new branch.
  159. Builder.CreateCondBr(Cond, FirstCase.getCaseSuccessor(),
  160. SI->getDefaultDest());
  161. // Delete the old switch.
  162. SI->eraseFromParent();
  163. return true;
  164. }
  165. }
  166. return false;
  167. }
  168. if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(T)) {
  169. // indirectbr blockaddress(@F, @BB) -> br label @BB
  170. if (BlockAddress *BA =
  171. dyn_cast<BlockAddress>(IBI->getAddress()->stripPointerCasts())) {
  172. BasicBlock *TheOnlyDest = BA->getBasicBlock();
  173. // Insert the new branch.
  174. Builder.CreateBr(TheOnlyDest);
  175. for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
  176. if (IBI->getDestination(i) == TheOnlyDest)
  177. TheOnlyDest = 0;
  178. else
  179. IBI->getDestination(i)->removePredecessor(IBI->getParent());
  180. }
  181. Value *Address = IBI->getAddress();
  182. IBI->eraseFromParent();
  183. if (DeleteDeadConditions)
  184. RecursivelyDeleteTriviallyDeadInstructions(Address);
  185. // If we didn't find our destination in the IBI successor list, then we
  186. // have undefined behavior. Replace the unconditional branch with an
  187. // 'unreachable' instruction.
  188. if (TheOnlyDest) {
  189. BB->getTerminator()->eraseFromParent();
  190. new UnreachableInst(BB->getContext(), BB);
  191. }
  192. return true;
  193. }
  194. }
  195. return false;
  196. }
  197. //===----------------------------------------------------------------------===//
  198. // Local dead code elimination.
  199. //
  200. /// isInstructionTriviallyDead - Return true if the result produced by the
  201. /// instruction is not used, and the instruction has no side effects.
  202. ///
  203. bool llvm::isInstructionTriviallyDead(Instruction *I) {
  204. if (!I->use_empty() || isa<TerminatorInst>(I)) return false;
  205. // We don't want the landingpad instruction removed by anything this general.
  206. if (isa<LandingPadInst>(I))
  207. return false;
  208. // We don't want debug info removed by anything this general, unless
  209. // debug info is empty.
  210. if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(I)) {
  211. if (DDI->getAddress())
  212. return false;
  213. return true;
  214. }
  215. if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(I)) {
  216. if (DVI->getValue())
  217. return false;
  218. return true;
  219. }
  220. if (!I->mayHaveSideEffects()) return true;
  221. // Special case intrinsics that "may have side effects" but can be deleted
  222. // when dead.
  223. if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
  224. // Safe to delete llvm.stacksave if dead.
  225. if (II->getIntrinsicID() == Intrinsic::stacksave)
  226. return true;
  227. // Lifetime intrinsics are dead when their right-hand is undef.
  228. if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
  229. II->getIntrinsicID() == Intrinsic::lifetime_end)
  230. return isa<UndefValue>(II->getArgOperand(1));
  231. }
  232. if (isAllocLikeFn(I)) return true;
  233. if (CallInst *CI = isFreeCall(I))
  234. if (Constant *C = dyn_cast<Constant>(CI->getArgOperand(0)))
  235. return C->isNullValue() || isa<UndefValue>(C);
  236. return false;
  237. }
  238. /// RecursivelyDeleteTriviallyDeadInstructions - If the specified value is a
  239. /// trivially dead instruction, delete it. If that makes any of its operands
  240. /// trivially dead, delete them too, recursively. Return true if any
  241. /// instructions were deleted.
  242. bool llvm::RecursivelyDeleteTriviallyDeadInstructions(Value *V) {
  243. Instruction *I = dyn_cast<Instruction>(V);
  244. if (!I || !I->use_empty() || !isInstructionTriviallyDead(I))
  245. return false;
  246. SmallVector<Instruction*, 16> DeadInsts;
  247. DeadInsts.push_back(I);
  248. do {
  249. I = DeadInsts.pop_back_val();
  250. // Null out all of the instruction's operands to see if any operand becomes
  251. // dead as we go.
  252. for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
  253. Value *OpV = I->getOperand(i);
  254. I->setOperand(i, 0);
  255. if (!OpV->use_empty()) continue;
  256. // If the operand is an instruction that became dead as we nulled out the
  257. // operand, and if it is 'trivially' dead, delete it in a future loop
  258. // iteration.
  259. if (Instruction *OpI = dyn_cast<Instruction>(OpV))
  260. if (isInstructionTriviallyDead(OpI))
  261. DeadInsts.push_back(OpI);
  262. }
  263. I->eraseFromParent();
  264. } while (!DeadInsts.empty());
  265. return true;
  266. }
  267. /// areAllUsesEqual - Check whether the uses of a value are all the same.
  268. /// This is similar to Instruction::hasOneUse() except this will also return
  269. /// true when there are no uses or multiple uses that all refer to the same
  270. /// value.
  271. static bool areAllUsesEqual(Instruction *I) {
  272. Value::use_iterator UI = I->use_begin();
  273. Value::use_iterator UE = I->use_end();
  274. if (UI == UE)
  275. return true;
  276. User *TheUse = *UI;
  277. for (++UI; UI != UE; ++UI) {
  278. if (*UI != TheUse)
  279. return false;
  280. }
  281. return true;
  282. }
  283. /// RecursivelyDeleteDeadPHINode - If the specified value is an effectively
  284. /// dead PHI node, due to being a def-use chain of single-use nodes that
  285. /// either forms a cycle or is terminated by a trivially dead instruction,
  286. /// delete it. If that makes any of its operands trivially dead, delete them
  287. /// too, recursively. Return true if a change was made.
  288. bool llvm::RecursivelyDeleteDeadPHINode(PHINode *PN) {
  289. SmallPtrSet<Instruction*, 4> Visited;
  290. for (Instruction *I = PN; areAllUsesEqual(I) && !I->mayHaveSideEffects();
  291. I = cast<Instruction>(*I->use_begin())) {
  292. if (I->use_empty())
  293. return RecursivelyDeleteTriviallyDeadInstructions(I);
  294. // If we find an instruction more than once, we're on a cycle that
  295. // won't prove fruitful.
  296. if (!Visited.insert(I)) {
  297. // Break the cycle and delete the instruction and its operands.
  298. I->replaceAllUsesWith(UndefValue::get(I->getType()));
  299. (void)RecursivelyDeleteTriviallyDeadInstructions(I);
  300. return true;
  301. }
  302. }
  303. return false;
  304. }
  305. /// SimplifyInstructionsInBlock - Scan the specified basic block and try to
  306. /// simplify any instructions in it and recursively delete dead instructions.
  307. ///
  308. /// This returns true if it changed the code, note that it can delete
  309. /// instructions in other blocks as well in this block.
  310. bool llvm::SimplifyInstructionsInBlock(BasicBlock *BB, const TargetData *TD) {
  311. bool MadeChange = false;
  312. #ifndef NDEBUG
  313. // In debug builds, ensure that the terminator of the block is never replaced
  314. // or deleted by these simplifications. The idea of simplification is that it
  315. // cannot introduce new instructions, and there is no way to replace the
  316. // terminator of a block without introducing a new instruction.
  317. AssertingVH<Instruction> TerminatorVH(--BB->end());
  318. #endif
  319. for (BasicBlock::iterator BI = BB->begin(), E = --BB->end(); BI != E; ) {
  320. assert(!BI->isTerminator());
  321. Instruction *Inst = BI++;
  322. WeakVH BIHandle(BI);
  323. if (recursivelySimplifyInstruction(Inst, TD)) {
  324. MadeChange = true;
  325. if (BIHandle != BI)
  326. BI = BB->begin();
  327. continue;
  328. }
  329. MadeChange |= RecursivelyDeleteTriviallyDeadInstructions(Inst);
  330. if (BIHandle != BI)
  331. BI = BB->begin();
  332. }
  333. return MadeChange;
  334. }
  335. //===----------------------------------------------------------------------===//
  336. // Control Flow Graph Restructuring.
  337. //
  338. /// RemovePredecessorAndSimplify - Like BasicBlock::removePredecessor, this
  339. /// method is called when we're about to delete Pred as a predecessor of BB. If
  340. /// BB contains any PHI nodes, this drops the entries in the PHI nodes for Pred.
  341. ///
  342. /// Unlike the removePredecessor method, this attempts to simplify uses of PHI
  343. /// nodes that collapse into identity values. For example, if we have:
  344. /// x = phi(1, 0, 0, 0)
  345. /// y = and x, z
  346. ///
  347. /// .. and delete the predecessor corresponding to the '1', this will attempt to
  348. /// recursively fold the and to 0.
  349. void llvm::RemovePredecessorAndSimplify(BasicBlock *BB, BasicBlock *Pred,
  350. TargetData *TD) {
  351. // This only adjusts blocks with PHI nodes.
  352. if (!isa<PHINode>(BB->begin()))
  353. return;
  354. // Remove the entries for Pred from the PHI nodes in BB, but do not simplify
  355. // them down. This will leave us with single entry phi nodes and other phis
  356. // that can be removed.
  357. BB->removePredecessor(Pred, true);
  358. WeakVH PhiIt = &BB->front();
  359. while (PHINode *PN = dyn_cast<PHINode>(PhiIt)) {
  360. PhiIt = &*++BasicBlock::iterator(cast<Instruction>(PhiIt));
  361. Value *OldPhiIt = PhiIt;
  362. if (!recursivelySimplifyInstruction(PN, TD))
  363. continue;
  364. // If recursive simplification ended up deleting the next PHI node we would
  365. // iterate to, then our iterator is invalid, restart scanning from the top
  366. // of the block.
  367. if (PhiIt != OldPhiIt) PhiIt = &BB->front();
  368. }
  369. }
  370. /// MergeBasicBlockIntoOnlyPred - DestBB is a block with one predecessor and its
  371. /// predecessor is known to have one successor (DestBB!). Eliminate the edge
  372. /// between them, moving the instructions in the predecessor into DestBB and
  373. /// deleting the predecessor block.
  374. ///
  375. void llvm::MergeBasicBlockIntoOnlyPred(BasicBlock *DestBB, Pass *P) {
  376. // If BB has single-entry PHI nodes, fold them.
  377. while (PHINode *PN = dyn_cast<PHINode>(DestBB->begin())) {
  378. Value *NewVal = PN->getIncomingValue(0);
  379. // Replace self referencing PHI with undef, it must be dead.
  380. if (NewVal == PN) NewVal = UndefValue::get(PN->getType());
  381. PN->replaceAllUsesWith(NewVal);
  382. PN->eraseFromParent();
  383. }
  384. BasicBlock *PredBB = DestBB->getSinglePredecessor();
  385. assert(PredBB && "Block doesn't have a single predecessor!");
  386. // Zap anything that took the address of DestBB. Not doing this will give the
  387. // address an invalid value.
  388. if (DestBB->hasAddressTaken()) {
  389. BlockAddress *BA = BlockAddress::get(DestBB);
  390. Constant *Replacement =
  391. ConstantInt::get(llvm::Type::getInt32Ty(BA->getContext()), 1);
  392. BA->replaceAllUsesWith(ConstantExpr::getIntToPtr(Replacement,
  393. BA->getType()));
  394. BA->destroyConstant();
  395. }
  396. // Anything that branched to PredBB now branches to DestBB.
  397. PredBB->replaceAllUsesWith(DestBB);
  398. // Splice all the instructions from PredBB to DestBB.
  399. PredBB->getTerminator()->eraseFromParent();
  400. DestBB->getInstList().splice(DestBB->begin(), PredBB->getInstList());
  401. if (P) {
  402. DominatorTree *DT = P->getAnalysisIfAvailable<DominatorTree>();
  403. if (DT) {
  404. BasicBlock *PredBBIDom = DT->getNode(PredBB)->getIDom()->getBlock();
  405. DT->changeImmediateDominator(DestBB, PredBBIDom);
  406. DT->eraseNode(PredBB);
  407. }
  408. ProfileInfo *PI = P->getAnalysisIfAvailable<ProfileInfo>();
  409. if (PI) {
  410. PI->replaceAllUses(PredBB, DestBB);
  411. PI->removeEdge(ProfileInfo::getEdge(PredBB, DestBB));
  412. }
  413. }
  414. // Nuke BB.
  415. PredBB->eraseFromParent();
  416. }
  417. /// CanPropagatePredecessorsForPHIs - Return true if we can fold BB, an
  418. /// almost-empty BB ending in an unconditional branch to Succ, into succ.
  419. ///
  420. /// Assumption: Succ is the single successor for BB.
  421. ///
  422. static bool CanPropagatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) {
  423. assert(*succ_begin(BB) == Succ && "Succ is not successor of BB!");
  424. DEBUG(dbgs() << "Looking to fold " << BB->getName() << " into "
  425. << Succ->getName() << "\n");
  426. // Shortcut, if there is only a single predecessor it must be BB and merging
  427. // is always safe
  428. if (Succ->getSinglePredecessor()) return true;
  429. // Make a list of the predecessors of BB
  430. SmallPtrSet<BasicBlock*, 16> BBPreds(pred_begin(BB), pred_end(BB));
  431. // Look at all the phi nodes in Succ, to see if they present a conflict when
  432. // merging these blocks
  433. for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
  434. PHINode *PN = cast<PHINode>(I);
  435. // If the incoming value from BB is again a PHINode in
  436. // BB which has the same incoming value for *PI as PN does, we can
  437. // merge the phi nodes and then the blocks can still be merged
  438. PHINode *BBPN = dyn_cast<PHINode>(PN->getIncomingValueForBlock(BB));
  439. if (BBPN && BBPN->getParent() == BB) {
  440. for (unsigned PI = 0, PE = PN->getNumIncomingValues(); PI != PE; ++PI) {
  441. BasicBlock *IBB = PN->getIncomingBlock(PI);
  442. if (BBPreds.count(IBB) &&
  443. BBPN->getIncomingValueForBlock(IBB) != PN->getIncomingValue(PI)) {
  444. DEBUG(dbgs() << "Can't fold, phi node " << PN->getName() << " in "
  445. << Succ->getName() << " is conflicting with "
  446. << BBPN->getName() << " with regard to common predecessor "
  447. << IBB->getName() << "\n");
  448. return false;
  449. }
  450. }
  451. } else {
  452. Value* Val = PN->getIncomingValueForBlock(BB);
  453. for (unsigned PI = 0, PE = PN->getNumIncomingValues(); PI != PE; ++PI) {
  454. // See if the incoming value for the common predecessor is equal to the
  455. // one for BB, in which case this phi node will not prevent the merging
  456. // of the block.
  457. BasicBlock *IBB = PN->getIncomingBlock(PI);
  458. if (BBPreds.count(IBB) && Val != PN->getIncomingValue(PI)) {
  459. DEBUG(dbgs() << "Can't fold, phi node " << PN->getName() << " in "
  460. << Succ->getName() << " is conflicting with regard to common "
  461. << "predecessor " << IBB->getName() << "\n");
  462. return false;
  463. }
  464. }
  465. }
  466. }
  467. return true;
  468. }
  469. /// TryToSimplifyUncondBranchFromEmptyBlock - BB is known to contain an
  470. /// unconditional branch, and contains no instructions other than PHI nodes,
  471. /// potential side-effect free intrinsics and the branch. If possible,
  472. /// eliminate BB by rewriting all the predecessors to branch to the successor
  473. /// block and return true. If we can't transform, return false.
  474. bool llvm::TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock *BB) {
  475. assert(BB != &BB->getParent()->getEntryBlock() &&
  476. "TryToSimplifyUncondBranchFromEmptyBlock called on entry block!");
  477. // We can't eliminate infinite loops.
  478. BasicBlock *Succ = cast<BranchInst>(BB->getTerminator())->getSuccessor(0);
  479. if (BB == Succ) return false;
  480. // Check to see if merging these blocks would cause conflicts for any of the
  481. // phi nodes in BB or Succ. If not, we can safely merge.
  482. if (!CanPropagatePredecessorsForPHIs(BB, Succ)) return false;
  483. // Check for cases where Succ has multiple predecessors and a PHI node in BB
  484. // has uses which will not disappear when the PHI nodes are merged. It is
  485. // possible to handle such cases, but difficult: it requires checking whether
  486. // BB dominates Succ, which is non-trivial to calculate in the case where
  487. // Succ has multiple predecessors. Also, it requires checking whether
  488. // constructing the necessary self-referential PHI node doesn't intoduce any
  489. // conflicts; this isn't too difficult, but the previous code for doing this
  490. // was incorrect.
  491. //
  492. // Note that if this check finds a live use, BB dominates Succ, so BB is
  493. // something like a loop pre-header (or rarely, a part of an irreducible CFG);
  494. // folding the branch isn't profitable in that case anyway.
  495. if (!Succ->getSinglePredecessor()) {
  496. BasicBlock::iterator BBI = BB->begin();
  497. while (isa<PHINode>(*BBI)) {
  498. for (Value::use_iterator UI = BBI->use_begin(), E = BBI->use_end();
  499. UI != E; ++UI) {
  500. if (PHINode* PN = dyn_cast<PHINode>(*UI)) {
  501. if (PN->getIncomingBlock(UI) != BB)
  502. return false;
  503. } else {
  504. return false;
  505. }
  506. }
  507. ++BBI;
  508. }
  509. }
  510. DEBUG(dbgs() << "Killing Trivial BB: \n" << *BB);
  511. if (isa<PHINode>(Succ->begin())) {
  512. // If there is more than one pred of succ, and there are PHI nodes in
  513. // the successor, then we need to add incoming edges for the PHI nodes
  514. //
  515. const SmallVector<BasicBlock*, 16> BBPreds(pred_begin(BB), pred_end(BB));
  516. // Loop over all of the PHI nodes in the successor of BB.
  517. for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
  518. PHINode *PN = cast<PHINode>(I);
  519. Value *OldVal = PN->removeIncomingValue(BB, false);
  520. assert(OldVal && "No entry in PHI for Pred BB!");
  521. // If this incoming value is one of the PHI nodes in BB, the new entries
  522. // in the PHI node are the entries from the old PHI.
  523. if (isa<PHINode>(OldVal) && cast<PHINode>(OldVal)->getParent() == BB) {
  524. PHINode *OldValPN = cast<PHINode>(OldVal);
  525. for (unsigned i = 0, e = OldValPN->getNumIncomingValues(); i != e; ++i)
  526. // Note that, since we are merging phi nodes and BB and Succ might
  527. // have common predecessors, we could end up with a phi node with
  528. // identical incoming branches. This will be cleaned up later (and
  529. // will trigger asserts if we try to clean it up now, without also
  530. // simplifying the corresponding conditional branch).
  531. PN->addIncoming(OldValPN->getIncomingValue(i),
  532. OldValPN->getIncomingBlock(i));
  533. } else {
  534. // Add an incoming value for each of the new incoming values.
  535. for (unsigned i = 0, e = BBPreds.size(); i != e; ++i)
  536. PN->addIncoming(OldVal, BBPreds[i]);
  537. }
  538. }
  539. }
  540. if (Succ->getSinglePredecessor()) {
  541. // BB is the only predecessor of Succ, so Succ will end up with exactly
  542. // the same predecessors BB had.
  543. // Copy over any phi, debug or lifetime instruction.
  544. BB->getTerminator()->eraseFromParent();
  545. Succ->getInstList().splice(Succ->getFirstNonPHI(), BB->getInstList());
  546. } else {
  547. while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
  548. // We explicitly check for such uses in CanPropagatePredecessorsForPHIs.
  549. assert(PN->use_empty() && "There shouldn't be any uses here!");
  550. PN->eraseFromParent();
  551. }
  552. }
  553. // Everything that jumped to BB now goes to Succ.
  554. BB->replaceAllUsesWith(Succ);
  555. if (!Succ->hasName()) Succ->takeName(BB);
  556. BB->eraseFromParent(); // Delete the old basic block.
  557. return true;
  558. }
  559. /// EliminateDuplicatePHINodes - Check for and eliminate duplicate PHI
  560. /// nodes in this block. This doesn't try to be clever about PHI nodes
  561. /// which differ only in the order of the incoming values, but instcombine
  562. /// orders them so it usually won't matter.
  563. ///
  564. bool llvm::EliminateDuplicatePHINodes(BasicBlock *BB) {
  565. bool Changed = false;
  566. // This implementation doesn't currently consider undef operands
  567. // specially. Theoretically, two phis which are identical except for
  568. // one having an undef where the other doesn't could be collapsed.
  569. // Map from PHI hash values to PHI nodes. If multiple PHIs have
  570. // the same hash value, the element is the first PHI in the
  571. // linked list in CollisionMap.
  572. DenseMap<uintptr_t, PHINode *> HashMap;
  573. // Maintain linked lists of PHI nodes with common hash values.
  574. DenseMap<PHINode *, PHINode *> CollisionMap;
  575. // Examine each PHI.
  576. for (BasicBlock::iterator I = BB->begin();
  577. PHINode *PN = dyn_cast<PHINode>(I++); ) {
  578. // Compute a hash value on the operands. Instcombine will likely have sorted
  579. // them, which helps expose duplicates, but we have to check all the
  580. // operands to be safe in case instcombine hasn't run.
  581. uintptr_t Hash = 0;
  582. // This hash algorithm is quite weak as hash functions go, but it seems
  583. // to do a good enough job for this particular purpose, and is very quick.
  584. for (User::op_iterator I = PN->op_begin(), E = PN->op_end(); I != E; ++I) {
  585. Hash ^= reinterpret_cast<uintptr_t>(static_cast<Value *>(*I));
  586. Hash = (Hash << 7) | (Hash >> (sizeof(uintptr_t) * CHAR_BIT - 7));
  587. }
  588. for (PHINode::block_iterator I = PN->block_begin(), E = PN->block_end();
  589. I != E; ++I) {
  590. Hash ^= reinterpret_cast<uintptr_t>(static_cast<BasicBlock *>(*I));
  591. Hash = (Hash << 7) | (Hash >> (sizeof(uintptr_t) * CHAR_BIT - 7));
  592. }
  593. // Avoid colliding with the DenseMap sentinels ~0 and ~0-1.
  594. Hash >>= 1;
  595. // If we've never seen this hash value before, it's a unique PHI.
  596. std::pair<DenseMap<uintptr_t, PHINode *>::iterator, bool> Pair =
  597. HashMap.insert(std::make_pair(Hash, PN));
  598. if (Pair.second) continue;
  599. // Otherwise it's either a duplicate or a hash collision.
  600. for (PHINode *OtherPN = Pair.first->second; ; ) {
  601. if (OtherPN->isIdenticalTo(PN)) {
  602. // A duplicate. Replace this PHI with its duplicate.
  603. PN->replaceAllUsesWith(OtherPN);
  604. PN->eraseFromParent();
  605. Changed = true;
  606. break;
  607. }
  608. // A non-duplicate hash collision.
  609. DenseMap<PHINode *, PHINode *>::iterator I = CollisionMap.find(OtherPN);
  610. if (I == CollisionMap.end()) {
  611. // Set this PHI to be the head of the linked list of colliding PHIs.
  612. PHINode *Old = Pair.first->second;
  613. Pair.first->second = PN;
  614. CollisionMap[PN] = Old;
  615. break;
  616. }
  617. // Proceed to the next PHI in the list.
  618. OtherPN = I->second;
  619. }
  620. }
  621. return Changed;
  622. }
  623. /// enforceKnownAlignment - If the specified pointer points to an object that
  624. /// we control, modify the object's alignment to PrefAlign. This isn't
  625. /// often possible though. If alignment is important, a more reliable approach
  626. /// is to simply align all global variables and allocation instructions to
  627. /// their preferred alignment from the beginning.
  628. ///
  629. static unsigned enforceKnownAlignment(Value *V, unsigned Align,
  630. unsigned PrefAlign, const TargetData *TD) {
  631. V = V->stripPointerCasts();
  632. if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
  633. // If the preferred alignment is greater than the natural stack alignment
  634. // then don't round up. This avoids dynamic stack realignment.
  635. if (TD && TD->exceedsNaturalStackAlignment(PrefAlign))
  636. return Align;
  637. // If there is a requested alignment and if this is an alloca, round up.
  638. if (AI->getAlignment() >= PrefAlign)
  639. return AI->getAlignment();
  640. AI->setAlignment(PrefAlign);
  641. return PrefAlign;
  642. }
  643. if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
  644. // If there is a large requested alignment and we can, bump up the alignment
  645. // of the global.
  646. if (GV->isDeclaration()) return Align;
  647. // If the memory we set aside for the global may not be the memory used by
  648. // the final program then it is impossible for us to reliably enforce the
  649. // preferred alignment.
  650. if (GV->isWeakForLinker()) return Align;
  651. if (GV->getAlignment() >= PrefAlign)
  652. return GV->getAlignment();
  653. // We can only increase the alignment of the global if it has no alignment
  654. // specified or if it is not assigned a section. If it is assigned a
  655. // section, the global could be densely packed with other objects in the
  656. // section, increasing the alignment could cause padding issues.
  657. if (!GV->hasSection() || GV->getAlignment() == 0)
  658. GV->setAlignment(PrefAlign);
  659. return GV->getAlignment();
  660. }
  661. return Align;
  662. }
  663. /// getOrEnforceKnownAlignment - If the specified pointer has an alignment that
  664. /// we can determine, return it, otherwise return 0. If PrefAlign is specified,
  665. /// and it is more than the alignment of the ultimate object, see if we can
  666. /// increase the alignment of the ultimate object, making this check succeed.
  667. unsigned llvm::getOrEnforceKnownAlignment(Value *V, unsigned PrefAlign,
  668. const TargetData *TD) {
  669. assert(V->getType()->isPointerTy() &&
  670. "getOrEnforceKnownAlignment expects a pointer!");
  671. unsigned BitWidth = TD ? TD->getPointerSizeInBits() : 64;
  672. APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
  673. ComputeMaskedBits(V, KnownZero, KnownOne, TD);
  674. unsigned TrailZ = KnownZero.countTrailingOnes();
  675. // Avoid trouble with rediculously large TrailZ values, such as
  676. // those computed from a null pointer.
  677. TrailZ = std::min(TrailZ, unsigned(sizeof(unsigned) * CHAR_BIT - 1));
  678. unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
  679. // LLVM doesn't support alignments larger than this currently.
  680. Align = std::min(Align, +Value::MaximumAlignment);
  681. if (PrefAlign > Align)
  682. Align = enforceKnownAlignment(V, Align, PrefAlign, TD);
  683. // We don't need to make any adjustment.
  684. return Align;
  685. }
  686. ///===---------------------------------------------------------------------===//
  687. /// Dbg Intrinsic utilities
  688. ///
  689. /// Inserts a llvm.dbg.value instrinsic before the stores to an alloca'd value
  690. /// that has an associated llvm.dbg.decl intrinsic.
  691. bool llvm::ConvertDebugDeclareToDebugValue(DbgDeclareInst *DDI,
  692. StoreInst *SI, DIBuilder &Builder) {
  693. DIVariable DIVar(DDI->getVariable());
  694. if (!DIVar.Verify())
  695. return false;
  696. Instruction *DbgVal = NULL;
  697. // If an argument is zero extended then use argument directly. The ZExt
  698. // may be zapped by an optimization pass in future.
  699. Argument *ExtendedArg = NULL;
  700. if (ZExtInst *ZExt = dyn_cast<ZExtInst>(SI->getOperand(0)))
  701. ExtendedArg = dyn_cast<Argument>(ZExt->getOperand(0));
  702. if (SExtInst *SExt = dyn_cast<SExtInst>(SI->getOperand(0)))
  703. ExtendedArg = dyn_cast<Argument>(SExt->getOperand(0));
  704. if (ExtendedArg)
  705. DbgVal = Builder.insertDbgValueIntrinsic(ExtendedArg, 0, DIVar, SI);
  706. else
  707. DbgVal = Builder.insertDbgValueIntrinsic(SI->getOperand(0), 0, DIVar, SI);
  708. // Propagate any debug metadata from the store onto the dbg.value.
  709. DebugLoc SIDL = SI->getDebugLoc();
  710. if (!SIDL.isUnknown())
  711. DbgVal->setDebugLoc(SIDL);
  712. // Otherwise propagate debug metadata from dbg.declare.
  713. else
  714. DbgVal->setDebugLoc(DDI->getDebugLoc());
  715. return true;
  716. }
  717. /// Inserts a llvm.dbg.value instrinsic before the stores to an alloca'd value
  718. /// that has an associated llvm.dbg.decl intrinsic.
  719. bool llvm::ConvertDebugDeclareToDebugValue(DbgDeclareInst *DDI,
  720. LoadInst *LI, DIBuilder &Builder) {
  721. DIVariable DIVar(DDI->getVariable());
  722. if (!DIVar.Verify())
  723. return false;
  724. Instruction *DbgVal =
  725. Builder.insertDbgValueIntrinsic(LI->getOperand(0), 0,
  726. DIVar, LI);
  727. // Propagate any debug metadata from the store onto the dbg.value.
  728. DebugLoc LIDL = LI->getDebugLoc();
  729. if (!LIDL.isUnknown())
  730. DbgVal->setDebugLoc(LIDL);
  731. // Otherwise propagate debug metadata from dbg.declare.
  732. else
  733. DbgVal->setDebugLoc(DDI->getDebugLoc());
  734. return true;
  735. }
  736. /// LowerDbgDeclare - Lowers llvm.dbg.declare intrinsics into appropriate set
  737. /// of llvm.dbg.value intrinsics.
  738. bool llvm::LowerDbgDeclare(Function &F) {
  739. DIBuilder DIB(*F.getParent());
  740. SmallVector<DbgDeclareInst *, 4> Dbgs;
  741. for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI)
  742. for (BasicBlock::iterator BI = FI->begin(), BE = FI->end(); BI != BE; ++BI) {
  743. if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(BI))
  744. Dbgs.push_back(DDI);
  745. }
  746. if (Dbgs.empty())
  747. return false;
  748. for (SmallVector<DbgDeclareInst *, 4>::iterator I = Dbgs.begin(),
  749. E = Dbgs.end(); I != E; ++I) {
  750. DbgDeclareInst *DDI = *I;
  751. if (AllocaInst *AI = dyn_cast_or_null<AllocaInst>(DDI->getAddress())) {
  752. bool RemoveDDI = true;
  753. for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
  754. UI != E; ++UI)
  755. if (StoreInst *SI = dyn_cast<StoreInst>(*UI))
  756. ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
  757. else if (LoadInst *LI = dyn_cast<LoadInst>(*UI))
  758. ConvertDebugDeclareToDebugValue(DDI, LI, DIB);
  759. else
  760. RemoveDDI = false;
  761. if (RemoveDDI)
  762. DDI->eraseFromParent();
  763. }
  764. }
  765. return true;
  766. }
  767. /// FindAllocaDbgDeclare - Finds the llvm.dbg.declare intrinsic describing the
  768. /// alloca 'V', if any.
  769. DbgDeclareInst *llvm::FindAllocaDbgDeclare(Value *V) {
  770. if (MDNode *DebugNode = MDNode::getIfExists(V->getContext(), V))
  771. for (Value::use_iterator UI = DebugNode->use_begin(),
  772. E = DebugNode->use_end(); UI != E; ++UI)
  773. if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(*UI))
  774. return DDI;
  775. return 0;
  776. }