Local.cpp 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269
  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/ADT/DenseMap.h"
  16. #include "llvm/ADT/STLExtras.h"
  17. #include "llvm/ADT/SmallPtrSet.h"
  18. #include "llvm/ADT/Statistic.h"
  19. #include "llvm/Analysis/Dominators.h"
  20. #include "llvm/Analysis/InstructionSimplify.h"
  21. #include "llvm/Analysis/MemoryBuiltins.h"
  22. #include "llvm/Analysis/ValueTracking.h"
  23. #include "llvm/DIBuilder.h"
  24. #include "llvm/DebugInfo.h"
  25. #include "llvm/IR/Constants.h"
  26. #include "llvm/IR/DataLayout.h"
  27. #include "llvm/IR/DerivedTypes.h"
  28. #include "llvm/IR/GlobalAlias.h"
  29. #include "llvm/IR/GlobalVariable.h"
  30. #include "llvm/IR/IRBuilder.h"
  31. #include "llvm/IR/Instructions.h"
  32. #include "llvm/IR/IntrinsicInst.h"
  33. #include "llvm/IR/Intrinsics.h"
  34. #include "llvm/IR/MDBuilder.h"
  35. #include "llvm/IR/Metadata.h"
  36. #include "llvm/IR/Operator.h"
  37. #include "llvm/Support/CFG.h"
  38. #include "llvm/Support/Debug.h"
  39. #include "llvm/Support/GetElementPtrTypeIterator.h"
  40. #include "llvm/Support/MathExtras.h"
  41. #include "llvm/Support/ValueHandle.h"
  42. #include "llvm/Support/raw_ostream.h"
  43. using namespace llvm;
  44. STATISTIC(NumRemoved, "Number of unreachable basic blocks removed");
  45. //===----------------------------------------------------------------------===//
  46. // Local constant propagation.
  47. //
  48. /// ConstantFoldTerminator - If a terminator instruction is predicated on a
  49. /// constant value, convert it into an unconditional branch to the constant
  50. /// destination. This is a nontrivial operation because the successors of this
  51. /// basic block must have their PHI nodes updated.
  52. /// Also calls RecursivelyDeleteTriviallyDeadInstructions() on any branch/switch
  53. /// conditions and indirectbr addresses this might make dead if
  54. /// DeleteDeadConditions is true.
  55. bool llvm::ConstantFoldTerminator(BasicBlock *BB, bool DeleteDeadConditions,
  56. const TargetLibraryInfo *TLI) {
  57. TerminatorInst *T = BB->getTerminator();
  58. IRBuilder<> Builder(T);
  59. // Branch - See if we are conditional jumping on constant
  60. if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
  61. if (BI->isUnconditional()) return false; // Can't optimize uncond branch
  62. BasicBlock *Dest1 = BI->getSuccessor(0);
  63. BasicBlock *Dest2 = BI->getSuccessor(1);
  64. if (ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition())) {
  65. // Are we branching on constant?
  66. // YES. Change to unconditional branch...
  67. BasicBlock *Destination = Cond->getZExtValue() ? Dest1 : Dest2;
  68. BasicBlock *OldDest = Cond->getZExtValue() ? Dest2 : Dest1;
  69. //cerr << "Function: " << T->getParent()->getParent()
  70. // << "\nRemoving branch from " << T->getParent()
  71. // << "\n\nTo: " << OldDest << endl;
  72. // Let the basic block know that we are letting go of it. Based on this,
  73. // it will adjust it's PHI nodes.
  74. OldDest->removePredecessor(BB);
  75. // Replace the conditional branch with an unconditional one.
  76. Builder.CreateBr(Destination);
  77. BI->eraseFromParent();
  78. return true;
  79. }
  80. if (Dest2 == Dest1) { // Conditional branch to same location?
  81. // This branch matches something like this:
  82. // br bool %cond, label %Dest, label %Dest
  83. // and changes it into: br label %Dest
  84. // Let the basic block know that we are letting go of one copy of it.
  85. assert(BI->getParent() && "Terminator not inserted in block!");
  86. Dest1->removePredecessor(BI->getParent());
  87. // Replace the conditional branch with an unconditional one.
  88. Builder.CreateBr(Dest1);
  89. Value *Cond = BI->getCondition();
  90. BI->eraseFromParent();
  91. if (DeleteDeadConditions)
  92. RecursivelyDeleteTriviallyDeadInstructions(Cond, TLI);
  93. return true;
  94. }
  95. return false;
  96. }
  97. if (SwitchInst *SI = dyn_cast<SwitchInst>(T)) {
  98. // If we are switching on a constant, we can convert the switch into a
  99. // single branch instruction!
  100. ConstantInt *CI = dyn_cast<ConstantInt>(SI->getCondition());
  101. BasicBlock *TheOnlyDest = SI->getDefaultDest();
  102. BasicBlock *DefaultDest = TheOnlyDest;
  103. // Figure out which case it goes to.
  104. for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
  105. i != e; ++i) {
  106. // Found case matching a constant operand?
  107. if (i.getCaseValue() == CI) {
  108. TheOnlyDest = i.getCaseSuccessor();
  109. break;
  110. }
  111. // Check to see if this branch is going to the same place as the default
  112. // dest. If so, eliminate it as an explicit compare.
  113. if (i.getCaseSuccessor() == DefaultDest) {
  114. MDNode* MD = SI->getMetadata(LLVMContext::MD_prof);
  115. // MD should have 2 + NumCases operands.
  116. if (MD && MD->getNumOperands() == 2 + SI->getNumCases()) {
  117. // Collect branch weights into a vector.
  118. SmallVector<uint32_t, 8> Weights;
  119. for (unsigned MD_i = 1, MD_e = MD->getNumOperands(); MD_i < MD_e;
  120. ++MD_i) {
  121. ConstantInt* CI = dyn_cast<ConstantInt>(MD->getOperand(MD_i));
  122. assert(CI);
  123. Weights.push_back(CI->getValue().getZExtValue());
  124. }
  125. // Merge weight of this case to the default weight.
  126. unsigned idx = i.getCaseIndex();
  127. Weights[0] += Weights[idx+1];
  128. // Remove weight for this case.
  129. std::swap(Weights[idx+1], Weights.back());
  130. Weights.pop_back();
  131. SI->setMetadata(LLVMContext::MD_prof,
  132. MDBuilder(BB->getContext()).
  133. createBranchWeights(Weights));
  134. }
  135. // Remove this entry.
  136. DefaultDest->removePredecessor(SI->getParent());
  137. SI->removeCase(i);
  138. --i; --e;
  139. continue;
  140. }
  141. // Otherwise, check to see if the switch only branches to one destination.
  142. // We do this by reseting "TheOnlyDest" to null when we find two non-equal
  143. // destinations.
  144. if (i.getCaseSuccessor() != TheOnlyDest) TheOnlyDest = 0;
  145. }
  146. if (CI && !TheOnlyDest) {
  147. // Branching on a constant, but not any of the cases, go to the default
  148. // successor.
  149. TheOnlyDest = SI->getDefaultDest();
  150. }
  151. // If we found a single destination that we can fold the switch into, do so
  152. // now.
  153. if (TheOnlyDest) {
  154. // Insert the new branch.
  155. Builder.CreateBr(TheOnlyDest);
  156. BasicBlock *BB = SI->getParent();
  157. // Remove entries from PHI nodes which we no longer branch to...
  158. for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) {
  159. // Found case matching a constant operand?
  160. BasicBlock *Succ = SI->getSuccessor(i);
  161. if (Succ == TheOnlyDest)
  162. TheOnlyDest = 0; // Don't modify the first branch to TheOnlyDest
  163. else
  164. Succ->removePredecessor(BB);
  165. }
  166. // Delete the old switch.
  167. Value *Cond = SI->getCondition();
  168. SI->eraseFromParent();
  169. if (DeleteDeadConditions)
  170. RecursivelyDeleteTriviallyDeadInstructions(Cond, TLI);
  171. return true;
  172. }
  173. if (SI->getNumCases() == 1) {
  174. // Otherwise, we can fold this switch into a conditional branch
  175. // instruction if it has only one non-default destination.
  176. SwitchInst::CaseIt FirstCase = SI->case_begin();
  177. Value *Cond = Builder.CreateICmpEQ(SI->getCondition(),
  178. FirstCase.getCaseValue(), "cond");
  179. // Insert the new branch.
  180. BranchInst *NewBr = Builder.CreateCondBr(Cond,
  181. FirstCase.getCaseSuccessor(),
  182. SI->getDefaultDest());
  183. MDNode* MD = SI->getMetadata(LLVMContext::MD_prof);
  184. if (MD && MD->getNumOperands() == 3) {
  185. ConstantInt *SICase = dyn_cast<ConstantInt>(MD->getOperand(2));
  186. ConstantInt *SIDef = dyn_cast<ConstantInt>(MD->getOperand(1));
  187. assert(SICase && SIDef);
  188. // The TrueWeight should be the weight for the single case of SI.
  189. NewBr->setMetadata(LLVMContext::MD_prof,
  190. MDBuilder(BB->getContext()).
  191. createBranchWeights(SICase->getValue().getZExtValue(),
  192. SIDef->getValue().getZExtValue()));
  193. }
  194. // Delete the old switch.
  195. SI->eraseFromParent();
  196. return true;
  197. }
  198. return false;
  199. }
  200. if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(T)) {
  201. // indirectbr blockaddress(@F, @BB) -> br label @BB
  202. if (BlockAddress *BA =
  203. dyn_cast<BlockAddress>(IBI->getAddress()->stripPointerCasts())) {
  204. BasicBlock *TheOnlyDest = BA->getBasicBlock();
  205. // Insert the new branch.
  206. Builder.CreateBr(TheOnlyDest);
  207. for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
  208. if (IBI->getDestination(i) == TheOnlyDest)
  209. TheOnlyDest = 0;
  210. else
  211. IBI->getDestination(i)->removePredecessor(IBI->getParent());
  212. }
  213. Value *Address = IBI->getAddress();
  214. IBI->eraseFromParent();
  215. if (DeleteDeadConditions)
  216. RecursivelyDeleteTriviallyDeadInstructions(Address, TLI);
  217. // If we didn't find our destination in the IBI successor list, then we
  218. // have undefined behavior. Replace the unconditional branch with an
  219. // 'unreachable' instruction.
  220. if (TheOnlyDest) {
  221. BB->getTerminator()->eraseFromParent();
  222. new UnreachableInst(BB->getContext(), BB);
  223. }
  224. return true;
  225. }
  226. }
  227. return false;
  228. }
  229. //===----------------------------------------------------------------------===//
  230. // Local dead code elimination.
  231. //
  232. /// isInstructionTriviallyDead - Return true if the result produced by the
  233. /// instruction is not used, and the instruction has no side effects.
  234. ///
  235. bool llvm::isInstructionTriviallyDead(Instruction *I,
  236. const TargetLibraryInfo *TLI) {
  237. if (!I->use_empty() || isa<TerminatorInst>(I)) return false;
  238. // We don't want the landingpad instruction removed by anything this general.
  239. if (isa<LandingPadInst>(I))
  240. return false;
  241. // We don't want debug info removed by anything this general, unless
  242. // debug info is empty.
  243. if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(I)) {
  244. if (DDI->getAddress())
  245. return false;
  246. return true;
  247. }
  248. if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(I)) {
  249. if (DVI->getValue())
  250. return false;
  251. return true;
  252. }
  253. if (!I->mayHaveSideEffects()) return true;
  254. // Special case intrinsics that "may have side effects" but can be deleted
  255. // when dead.
  256. if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
  257. // Safe to delete llvm.stacksave if dead.
  258. if (II->getIntrinsicID() == Intrinsic::stacksave)
  259. return true;
  260. // Lifetime intrinsics are dead when their right-hand is undef.
  261. if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
  262. II->getIntrinsicID() == Intrinsic::lifetime_end)
  263. return isa<UndefValue>(II->getArgOperand(1));
  264. }
  265. if (isAllocLikeFn(I, TLI)) return true;
  266. if (CallInst *CI = isFreeCall(I, TLI))
  267. if (Constant *C = dyn_cast<Constant>(CI->getArgOperand(0)))
  268. return C->isNullValue() || isa<UndefValue>(C);
  269. return false;
  270. }
  271. /// RecursivelyDeleteTriviallyDeadInstructions - If the specified value is a
  272. /// trivially dead instruction, delete it. If that makes any of its operands
  273. /// trivially dead, delete them too, recursively. Return true if any
  274. /// instructions were deleted.
  275. bool
  276. llvm::RecursivelyDeleteTriviallyDeadInstructions(Value *V,
  277. const TargetLibraryInfo *TLI) {
  278. Instruction *I = dyn_cast<Instruction>(V);
  279. if (!I || !I->use_empty() || !isInstructionTriviallyDead(I, TLI))
  280. return false;
  281. SmallVector<Instruction*, 16> DeadInsts;
  282. DeadInsts.push_back(I);
  283. do {
  284. I = DeadInsts.pop_back_val();
  285. // Null out all of the instruction's operands to see if any operand becomes
  286. // dead as we go.
  287. for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
  288. Value *OpV = I->getOperand(i);
  289. I->setOperand(i, 0);
  290. if (!OpV->use_empty()) continue;
  291. // If the operand is an instruction that became dead as we nulled out the
  292. // operand, and if it is 'trivially' dead, delete it in a future loop
  293. // iteration.
  294. if (Instruction *OpI = dyn_cast<Instruction>(OpV))
  295. if (isInstructionTriviallyDead(OpI, TLI))
  296. DeadInsts.push_back(OpI);
  297. }
  298. I->eraseFromParent();
  299. } while (!DeadInsts.empty());
  300. return true;
  301. }
  302. /// areAllUsesEqual - Check whether the uses of a value are all the same.
  303. /// This is similar to Instruction::hasOneUse() except this will also return
  304. /// true when there are no uses or multiple uses that all refer to the same
  305. /// value.
  306. static bool areAllUsesEqual(Instruction *I) {
  307. Value::use_iterator UI = I->use_begin();
  308. Value::use_iterator UE = I->use_end();
  309. if (UI == UE)
  310. return true;
  311. User *TheUse = *UI;
  312. for (++UI; UI != UE; ++UI) {
  313. if (*UI != TheUse)
  314. return false;
  315. }
  316. return true;
  317. }
  318. /// RecursivelyDeleteDeadPHINode - If the specified value is an effectively
  319. /// dead PHI node, due to being a def-use chain of single-use nodes that
  320. /// either forms a cycle or is terminated by a trivially dead instruction,
  321. /// delete it. If that makes any of its operands trivially dead, delete them
  322. /// too, recursively. Return true if a change was made.
  323. bool llvm::RecursivelyDeleteDeadPHINode(PHINode *PN,
  324. const TargetLibraryInfo *TLI) {
  325. SmallPtrSet<Instruction*, 4> Visited;
  326. for (Instruction *I = PN; areAllUsesEqual(I) && !I->mayHaveSideEffects();
  327. I = cast<Instruction>(*I->use_begin())) {
  328. if (I->use_empty())
  329. return RecursivelyDeleteTriviallyDeadInstructions(I, TLI);
  330. // If we find an instruction more than once, we're on a cycle that
  331. // won't prove fruitful.
  332. if (!Visited.insert(I)) {
  333. // Break the cycle and delete the instruction and its operands.
  334. I->replaceAllUsesWith(UndefValue::get(I->getType()));
  335. (void)RecursivelyDeleteTriviallyDeadInstructions(I, TLI);
  336. return true;
  337. }
  338. }
  339. return false;
  340. }
  341. /// SimplifyInstructionsInBlock - Scan the specified basic block and try to
  342. /// simplify any instructions in it and recursively delete dead instructions.
  343. ///
  344. /// This returns true if it changed the code, note that it can delete
  345. /// instructions in other blocks as well in this block.
  346. bool llvm::SimplifyInstructionsInBlock(BasicBlock *BB, const DataLayout *TD,
  347. const TargetLibraryInfo *TLI) {
  348. bool MadeChange = false;
  349. #ifndef NDEBUG
  350. // In debug builds, ensure that the terminator of the block is never replaced
  351. // or deleted by these simplifications. The idea of simplification is that it
  352. // cannot introduce new instructions, and there is no way to replace the
  353. // terminator of a block without introducing a new instruction.
  354. AssertingVH<Instruction> TerminatorVH(--BB->end());
  355. #endif
  356. for (BasicBlock::iterator BI = BB->begin(), E = --BB->end(); BI != E; ) {
  357. assert(!BI->isTerminator());
  358. Instruction *Inst = BI++;
  359. WeakVH BIHandle(BI);
  360. if (recursivelySimplifyInstruction(Inst, TD, TLI)) {
  361. MadeChange = true;
  362. if (BIHandle != BI)
  363. BI = BB->begin();
  364. continue;
  365. }
  366. MadeChange |= RecursivelyDeleteTriviallyDeadInstructions(Inst, TLI);
  367. if (BIHandle != BI)
  368. BI = BB->begin();
  369. }
  370. return MadeChange;
  371. }
  372. //===----------------------------------------------------------------------===//
  373. // Control Flow Graph Restructuring.
  374. //
  375. /// RemovePredecessorAndSimplify - Like BasicBlock::removePredecessor, this
  376. /// method is called when we're about to delete Pred as a predecessor of BB. If
  377. /// BB contains any PHI nodes, this drops the entries in the PHI nodes for Pred.
  378. ///
  379. /// Unlike the removePredecessor method, this attempts to simplify uses of PHI
  380. /// nodes that collapse into identity values. For example, if we have:
  381. /// x = phi(1, 0, 0, 0)
  382. /// y = and x, z
  383. ///
  384. /// .. and delete the predecessor corresponding to the '1', this will attempt to
  385. /// recursively fold the and to 0.
  386. void llvm::RemovePredecessorAndSimplify(BasicBlock *BB, BasicBlock *Pred,
  387. DataLayout *TD) {
  388. // This only adjusts blocks with PHI nodes.
  389. if (!isa<PHINode>(BB->begin()))
  390. return;
  391. // Remove the entries for Pred from the PHI nodes in BB, but do not simplify
  392. // them down. This will leave us with single entry phi nodes and other phis
  393. // that can be removed.
  394. BB->removePredecessor(Pred, true);
  395. WeakVH PhiIt = &BB->front();
  396. while (PHINode *PN = dyn_cast<PHINode>(PhiIt)) {
  397. PhiIt = &*++BasicBlock::iterator(cast<Instruction>(PhiIt));
  398. Value *OldPhiIt = PhiIt;
  399. if (!recursivelySimplifyInstruction(PN, TD))
  400. continue;
  401. // If recursive simplification ended up deleting the next PHI node we would
  402. // iterate to, then our iterator is invalid, restart scanning from the top
  403. // of the block.
  404. if (PhiIt != OldPhiIt) PhiIt = &BB->front();
  405. }
  406. }
  407. /// MergeBasicBlockIntoOnlyPred - DestBB is a block with one predecessor and its
  408. /// predecessor is known to have one successor (DestBB!). Eliminate the edge
  409. /// between them, moving the instructions in the predecessor into DestBB and
  410. /// deleting the predecessor block.
  411. ///
  412. void llvm::MergeBasicBlockIntoOnlyPred(BasicBlock *DestBB, Pass *P) {
  413. // If BB has single-entry PHI nodes, fold them.
  414. while (PHINode *PN = dyn_cast<PHINode>(DestBB->begin())) {
  415. Value *NewVal = PN->getIncomingValue(0);
  416. // Replace self referencing PHI with undef, it must be dead.
  417. if (NewVal == PN) NewVal = UndefValue::get(PN->getType());
  418. PN->replaceAllUsesWith(NewVal);
  419. PN->eraseFromParent();
  420. }
  421. BasicBlock *PredBB = DestBB->getSinglePredecessor();
  422. assert(PredBB && "Block doesn't have a single predecessor!");
  423. // Zap anything that took the address of DestBB. Not doing this will give the
  424. // address an invalid value.
  425. if (DestBB->hasAddressTaken()) {
  426. BlockAddress *BA = BlockAddress::get(DestBB);
  427. Constant *Replacement =
  428. ConstantInt::get(llvm::Type::getInt32Ty(BA->getContext()), 1);
  429. BA->replaceAllUsesWith(ConstantExpr::getIntToPtr(Replacement,
  430. BA->getType()));
  431. BA->destroyConstant();
  432. }
  433. // Anything that branched to PredBB now branches to DestBB.
  434. PredBB->replaceAllUsesWith(DestBB);
  435. // Splice all the instructions from PredBB to DestBB.
  436. PredBB->getTerminator()->eraseFromParent();
  437. DestBB->getInstList().splice(DestBB->begin(), PredBB->getInstList());
  438. if (P) {
  439. DominatorTree *DT = P->getAnalysisIfAvailable<DominatorTree>();
  440. if (DT) {
  441. BasicBlock *PredBBIDom = DT->getNode(PredBB)->getIDom()->getBlock();
  442. DT->changeImmediateDominator(DestBB, PredBBIDom);
  443. DT->eraseNode(PredBB);
  444. }
  445. }
  446. // Nuke BB.
  447. PredBB->eraseFromParent();
  448. }
  449. /// CanMergeValues - Return true if we can choose one of these values to use
  450. /// in place of the other. Note that we will always choose the non-undef
  451. /// value to keep.
  452. static bool CanMergeValues(Value *First, Value *Second) {
  453. return First == Second || isa<UndefValue>(First) || isa<UndefValue>(Second);
  454. }
  455. /// CanPropagatePredecessorsForPHIs - Return true if we can fold BB, an
  456. /// almost-empty BB ending in an unconditional branch to Succ, into Succ.
  457. ///
  458. /// Assumption: Succ is the single successor for BB.
  459. ///
  460. static bool CanPropagatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) {
  461. assert(*succ_begin(BB) == Succ && "Succ is not successor of BB!");
  462. DEBUG(dbgs() << "Looking to fold " << BB->getName() << " into "
  463. << Succ->getName() << "\n");
  464. // Shortcut, if there is only a single predecessor it must be BB and merging
  465. // is always safe
  466. if (Succ->getSinglePredecessor()) return true;
  467. // Make a list of the predecessors of BB
  468. SmallPtrSet<BasicBlock*, 16> BBPreds(pred_begin(BB), pred_end(BB));
  469. // Look at all the phi nodes in Succ, to see if they present a conflict when
  470. // merging these blocks
  471. for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
  472. PHINode *PN = cast<PHINode>(I);
  473. // If the incoming value from BB is again a PHINode in
  474. // BB which has the same incoming value for *PI as PN does, we can
  475. // merge the phi nodes and then the blocks can still be merged
  476. PHINode *BBPN = dyn_cast<PHINode>(PN->getIncomingValueForBlock(BB));
  477. if (BBPN && BBPN->getParent() == BB) {
  478. for (unsigned PI = 0, PE = PN->getNumIncomingValues(); PI != PE; ++PI) {
  479. BasicBlock *IBB = PN->getIncomingBlock(PI);
  480. if (BBPreds.count(IBB) &&
  481. !CanMergeValues(BBPN->getIncomingValueForBlock(IBB),
  482. PN->getIncomingValue(PI))) {
  483. DEBUG(dbgs() << "Can't fold, phi node " << PN->getName() << " in "
  484. << Succ->getName() << " is conflicting with "
  485. << BBPN->getName() << " with regard to common predecessor "
  486. << IBB->getName() << "\n");
  487. return false;
  488. }
  489. }
  490. } else {
  491. Value* Val = PN->getIncomingValueForBlock(BB);
  492. for (unsigned PI = 0, PE = PN->getNumIncomingValues(); PI != PE; ++PI) {
  493. // See if the incoming value for the common predecessor is equal to the
  494. // one for BB, in which case this phi node will not prevent the merging
  495. // of the block.
  496. BasicBlock *IBB = PN->getIncomingBlock(PI);
  497. if (BBPreds.count(IBB) &&
  498. !CanMergeValues(Val, PN->getIncomingValue(PI))) {
  499. DEBUG(dbgs() << "Can't fold, phi node " << PN->getName() << " in "
  500. << Succ->getName() << " is conflicting with regard to common "
  501. << "predecessor " << IBB->getName() << "\n");
  502. return false;
  503. }
  504. }
  505. }
  506. }
  507. return true;
  508. }
  509. typedef SmallVector<BasicBlock *, 16> PredBlockVector;
  510. typedef DenseMap<BasicBlock *, Value *> IncomingValueMap;
  511. /// \brief Determines the value to use as the phi node input for a block.
  512. ///
  513. /// Select between \p OldVal any value that we know flows from \p BB
  514. /// to a particular phi on the basis of which one (if either) is not
  515. /// undef. Update IncomingValues based on the selected value.
  516. ///
  517. /// \param OldVal The value we are considering selecting.
  518. /// \param BB The block that the value flows in from.
  519. /// \param IncomingValues A map from block-to-value for other phi inputs
  520. /// that we have examined.
  521. ///
  522. /// \returns the selected value.
  523. static Value *selectIncomingValueForBlock(Value *OldVal, BasicBlock *BB,
  524. IncomingValueMap &IncomingValues) {
  525. if (!isa<UndefValue>(OldVal)) {
  526. assert((!IncomingValues.count(BB) ||
  527. IncomingValues.find(BB)->second == OldVal) &&
  528. "Expected OldVal to match incoming value from BB!");
  529. IncomingValues.insert(std::make_pair(BB, OldVal));
  530. return OldVal;
  531. }
  532. IncomingValueMap::const_iterator It = IncomingValues.find(BB);
  533. if (It != IncomingValues.end()) return It->second;
  534. return OldVal;
  535. }
  536. /// \brief Create a map from block to value for the operands of a
  537. /// given phi.
  538. ///
  539. /// Create a map from block to value for each non-undef value flowing
  540. /// into \p PN.
  541. ///
  542. /// \param PN The phi we are collecting the map for.
  543. /// \param IncomingValues [out] The map from block to value for this phi.
  544. static void gatherIncomingValuesToPhi(PHINode *PN,
  545. IncomingValueMap &IncomingValues) {
  546. for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
  547. BasicBlock *BB = PN->getIncomingBlock(i);
  548. Value *V = PN->getIncomingValue(i);
  549. if (!isa<UndefValue>(V))
  550. IncomingValues.insert(std::make_pair(BB, V));
  551. }
  552. }
  553. /// \brief Replace the incoming undef values to a phi with the values
  554. /// from a block-to-value map.
  555. ///
  556. /// \param PN The phi we are replacing the undefs in.
  557. /// \param IncomingValues A map from block to value.
  558. static void replaceUndefValuesInPhi(PHINode *PN,
  559. const IncomingValueMap &IncomingValues) {
  560. for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
  561. Value *V = PN->getIncomingValue(i);
  562. if (!isa<UndefValue>(V)) continue;
  563. BasicBlock *BB = PN->getIncomingBlock(i);
  564. IncomingValueMap::const_iterator It = IncomingValues.find(BB);
  565. if (It == IncomingValues.end()) continue;
  566. PN->setIncomingValue(i, It->second);
  567. }
  568. }
  569. /// \brief Replace a value flowing from a block to a phi with
  570. /// potentially multiple instances of that value flowing from the
  571. /// block's predecessors to the phi.
  572. ///
  573. /// \param BB The block with the value flowing into the phi.
  574. /// \param BBPreds The predecessors of BB.
  575. /// \param PN The phi that we are updating.
  576. static void redirectValuesFromPredecessorsToPhi(BasicBlock *BB,
  577. const PredBlockVector &BBPreds,
  578. PHINode *PN) {
  579. Value *OldVal = PN->removeIncomingValue(BB, false);
  580. assert(OldVal && "No entry in PHI for Pred BB!");
  581. IncomingValueMap IncomingValues;
  582. // We are merging two blocks - BB, and the block containing PN - and
  583. // as a result we need to redirect edges from the predecessors of BB
  584. // to go to the block containing PN, and update PN
  585. // accordingly. Since we allow merging blocks in the case where the
  586. // predecessor and successor blocks both share some predecessors,
  587. // and where some of those common predecessors might have undef
  588. // values flowing into PN, we want to rewrite those values to be
  589. // consistent with the non-undef values.
  590. gatherIncomingValuesToPhi(PN, IncomingValues);
  591. // If this incoming value is one of the PHI nodes in BB, the new entries
  592. // in the PHI node are the entries from the old PHI.
  593. if (isa<PHINode>(OldVal) && cast<PHINode>(OldVal)->getParent() == BB) {
  594. PHINode *OldValPN = cast<PHINode>(OldVal);
  595. for (unsigned i = 0, e = OldValPN->getNumIncomingValues(); i != e; ++i) {
  596. // Note that, since we are merging phi nodes and BB and Succ might
  597. // have common predecessors, we could end up with a phi node with
  598. // identical incoming branches. This will be cleaned up later (and
  599. // will trigger asserts if we try to clean it up now, without also
  600. // simplifying the corresponding conditional branch).
  601. BasicBlock *PredBB = OldValPN->getIncomingBlock(i);
  602. Value *PredVal = OldValPN->getIncomingValue(i);
  603. Value *Selected = selectIncomingValueForBlock(PredVal, PredBB,
  604. IncomingValues);
  605. // And add a new incoming value for this predecessor for the
  606. // newly retargeted branch.
  607. PN->addIncoming(Selected, PredBB);
  608. }
  609. } else {
  610. for (unsigned i = 0, e = BBPreds.size(); i != e; ++i) {
  611. // Update existing incoming values in PN for this
  612. // predecessor of BB.
  613. BasicBlock *PredBB = BBPreds[i];
  614. Value *Selected = selectIncomingValueForBlock(OldVal, PredBB,
  615. IncomingValues);
  616. // And add a new incoming value for this predecessor for the
  617. // newly retargeted branch.
  618. PN->addIncoming(Selected, PredBB);
  619. }
  620. }
  621. replaceUndefValuesInPhi(PN, IncomingValues);
  622. }
  623. /// TryToSimplifyUncondBranchFromEmptyBlock - BB is known to contain an
  624. /// unconditional branch, and contains no instructions other than PHI nodes,
  625. /// potential side-effect free intrinsics and the branch. If possible,
  626. /// eliminate BB by rewriting all the predecessors to branch to the successor
  627. /// block and return true. If we can't transform, return false.
  628. bool llvm::TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock *BB) {
  629. assert(BB != &BB->getParent()->getEntryBlock() &&
  630. "TryToSimplifyUncondBranchFromEmptyBlock called on entry block!");
  631. // We can't eliminate infinite loops.
  632. BasicBlock *Succ = cast<BranchInst>(BB->getTerminator())->getSuccessor(0);
  633. if (BB == Succ) return false;
  634. // Check to see if merging these blocks would cause conflicts for any of the
  635. // phi nodes in BB or Succ. If not, we can safely merge.
  636. if (!CanPropagatePredecessorsForPHIs(BB, Succ)) return false;
  637. // Check for cases where Succ has multiple predecessors and a PHI node in BB
  638. // has uses which will not disappear when the PHI nodes are merged. It is
  639. // possible to handle such cases, but difficult: it requires checking whether
  640. // BB dominates Succ, which is non-trivial to calculate in the case where
  641. // Succ has multiple predecessors. Also, it requires checking whether
  642. // constructing the necessary self-referential PHI node doesn't introduce any
  643. // conflicts; this isn't too difficult, but the previous code for doing this
  644. // was incorrect.
  645. //
  646. // Note that if this check finds a live use, BB dominates Succ, so BB is
  647. // something like a loop pre-header (or rarely, a part of an irreducible CFG);
  648. // folding the branch isn't profitable in that case anyway.
  649. if (!Succ->getSinglePredecessor()) {
  650. BasicBlock::iterator BBI = BB->begin();
  651. while (isa<PHINode>(*BBI)) {
  652. for (Value::use_iterator UI = BBI->use_begin(), E = BBI->use_end();
  653. UI != E; ++UI) {
  654. if (PHINode* PN = dyn_cast<PHINode>(*UI)) {
  655. if (PN->getIncomingBlock(UI) != BB)
  656. return false;
  657. } else {
  658. return false;
  659. }
  660. }
  661. ++BBI;
  662. }
  663. }
  664. DEBUG(dbgs() << "Killing Trivial BB: \n" << *BB);
  665. if (isa<PHINode>(Succ->begin())) {
  666. // If there is more than one pred of succ, and there are PHI nodes in
  667. // the successor, then we need to add incoming edges for the PHI nodes
  668. //
  669. const PredBlockVector BBPreds(pred_begin(BB), pred_end(BB));
  670. // Loop over all of the PHI nodes in the successor of BB.
  671. for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
  672. PHINode *PN = cast<PHINode>(I);
  673. redirectValuesFromPredecessorsToPhi(BB, BBPreds, PN);
  674. }
  675. }
  676. if (Succ->getSinglePredecessor()) {
  677. // BB is the only predecessor of Succ, so Succ will end up with exactly
  678. // the same predecessors BB had.
  679. // Copy over any phi, debug or lifetime instruction.
  680. BB->getTerminator()->eraseFromParent();
  681. Succ->getInstList().splice(Succ->getFirstNonPHI(), BB->getInstList());
  682. } else {
  683. while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
  684. // We explicitly check for such uses in CanPropagatePredecessorsForPHIs.
  685. assert(PN->use_empty() && "There shouldn't be any uses here!");
  686. PN->eraseFromParent();
  687. }
  688. }
  689. // Everything that jumped to BB now goes to Succ.
  690. BB->replaceAllUsesWith(Succ);
  691. if (!Succ->hasName()) Succ->takeName(BB);
  692. BB->eraseFromParent(); // Delete the old basic block.
  693. return true;
  694. }
  695. /// EliminateDuplicatePHINodes - Check for and eliminate duplicate PHI
  696. /// nodes in this block. This doesn't try to be clever about PHI nodes
  697. /// which differ only in the order of the incoming values, but instcombine
  698. /// orders them so it usually won't matter.
  699. ///
  700. bool llvm::EliminateDuplicatePHINodes(BasicBlock *BB) {
  701. bool Changed = false;
  702. // This implementation doesn't currently consider undef operands
  703. // specially. Theoretically, two phis which are identical except for
  704. // one having an undef where the other doesn't could be collapsed.
  705. // Map from PHI hash values to PHI nodes. If multiple PHIs have
  706. // the same hash value, the element is the first PHI in the
  707. // linked list in CollisionMap.
  708. DenseMap<uintptr_t, PHINode *> HashMap;
  709. // Maintain linked lists of PHI nodes with common hash values.
  710. DenseMap<PHINode *, PHINode *> CollisionMap;
  711. // Examine each PHI.
  712. for (BasicBlock::iterator I = BB->begin();
  713. PHINode *PN = dyn_cast<PHINode>(I++); ) {
  714. // Compute a hash value on the operands. Instcombine will likely have sorted
  715. // them, which helps expose duplicates, but we have to check all the
  716. // operands to be safe in case instcombine hasn't run.
  717. uintptr_t Hash = 0;
  718. // This hash algorithm is quite weak as hash functions go, but it seems
  719. // to do a good enough job for this particular purpose, and is very quick.
  720. for (User::op_iterator I = PN->op_begin(), E = PN->op_end(); I != E; ++I) {
  721. Hash ^= reinterpret_cast<uintptr_t>(static_cast<Value *>(*I));
  722. Hash = (Hash << 7) | (Hash >> (sizeof(uintptr_t) * CHAR_BIT - 7));
  723. }
  724. for (PHINode::block_iterator I = PN->block_begin(), E = PN->block_end();
  725. I != E; ++I) {
  726. Hash ^= reinterpret_cast<uintptr_t>(static_cast<BasicBlock *>(*I));
  727. Hash = (Hash << 7) | (Hash >> (sizeof(uintptr_t) * CHAR_BIT - 7));
  728. }
  729. // Avoid colliding with the DenseMap sentinels ~0 and ~0-1.
  730. Hash >>= 1;
  731. // If we've never seen this hash value before, it's a unique PHI.
  732. std::pair<DenseMap<uintptr_t, PHINode *>::iterator, bool> Pair =
  733. HashMap.insert(std::make_pair(Hash, PN));
  734. if (Pair.second) continue;
  735. // Otherwise it's either a duplicate or a hash collision.
  736. for (PHINode *OtherPN = Pair.first->second; ; ) {
  737. if (OtherPN->isIdenticalTo(PN)) {
  738. // A duplicate. Replace this PHI with its duplicate.
  739. PN->replaceAllUsesWith(OtherPN);
  740. PN->eraseFromParent();
  741. Changed = true;
  742. break;
  743. }
  744. // A non-duplicate hash collision.
  745. DenseMap<PHINode *, PHINode *>::iterator I = CollisionMap.find(OtherPN);
  746. if (I == CollisionMap.end()) {
  747. // Set this PHI to be the head of the linked list of colliding PHIs.
  748. PHINode *Old = Pair.first->second;
  749. Pair.first->second = PN;
  750. CollisionMap[PN] = Old;
  751. break;
  752. }
  753. // Proceed to the next PHI in the list.
  754. OtherPN = I->second;
  755. }
  756. }
  757. return Changed;
  758. }
  759. /// enforceKnownAlignment - If the specified pointer points to an object that
  760. /// we control, modify the object's alignment to PrefAlign. This isn't
  761. /// often possible though. If alignment is important, a more reliable approach
  762. /// is to simply align all global variables and allocation instructions to
  763. /// their preferred alignment from the beginning.
  764. ///
  765. static unsigned enforceKnownAlignment(Value *V, unsigned Align,
  766. unsigned PrefAlign, const DataLayout *TD) {
  767. V = V->stripPointerCasts();
  768. if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
  769. // If the preferred alignment is greater than the natural stack alignment
  770. // then don't round up. This avoids dynamic stack realignment.
  771. if (TD && TD->exceedsNaturalStackAlignment(PrefAlign))
  772. return Align;
  773. // If there is a requested alignment and if this is an alloca, round up.
  774. if (AI->getAlignment() >= PrefAlign)
  775. return AI->getAlignment();
  776. AI->setAlignment(PrefAlign);
  777. return PrefAlign;
  778. }
  779. if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
  780. // If there is a large requested alignment and we can, bump up the alignment
  781. // of the global.
  782. if (GV->isDeclaration()) return Align;
  783. // If the memory we set aside for the global may not be the memory used by
  784. // the final program then it is impossible for us to reliably enforce the
  785. // preferred alignment.
  786. if (GV->isWeakForLinker()) return Align;
  787. if (GV->getAlignment() >= PrefAlign)
  788. return GV->getAlignment();
  789. // We can only increase the alignment of the global if it has no alignment
  790. // specified or if it is not assigned a section. If it is assigned a
  791. // section, the global could be densely packed with other objects in the
  792. // section, increasing the alignment could cause padding issues.
  793. if (!GV->hasSection() || GV->getAlignment() == 0)
  794. GV->setAlignment(PrefAlign);
  795. return GV->getAlignment();
  796. }
  797. return Align;
  798. }
  799. /// getOrEnforceKnownAlignment - If the specified pointer has an alignment that
  800. /// we can determine, return it, otherwise return 0. If PrefAlign is specified,
  801. /// and it is more than the alignment of the ultimate object, see if we can
  802. /// increase the alignment of the ultimate object, making this check succeed.
  803. unsigned llvm::getOrEnforceKnownAlignment(Value *V, unsigned PrefAlign,
  804. const DataLayout *DL) {
  805. assert(V->getType()->isPointerTy() &&
  806. "getOrEnforceKnownAlignment expects a pointer!");
  807. unsigned BitWidth = DL ? DL->getPointerTypeSizeInBits(V->getType()) : 64;
  808. APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
  809. ComputeMaskedBits(V, KnownZero, KnownOne, DL);
  810. unsigned TrailZ = KnownZero.countTrailingOnes();
  811. // Avoid trouble with ridiculously large TrailZ values, such as
  812. // those computed from a null pointer.
  813. TrailZ = std::min(TrailZ, unsigned(sizeof(unsigned) * CHAR_BIT - 1));
  814. unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
  815. // LLVM doesn't support alignments larger than this currently.
  816. Align = std::min(Align, +Value::MaximumAlignment);
  817. if (PrefAlign > Align)
  818. Align = enforceKnownAlignment(V, Align, PrefAlign, DL);
  819. // We don't need to make any adjustment.
  820. return Align;
  821. }
  822. ///===---------------------------------------------------------------------===//
  823. /// Dbg Intrinsic utilities
  824. ///
  825. /// See if there is a dbg.value intrinsic for DIVar before I.
  826. static bool LdStHasDebugValue(DIVariable &DIVar, Instruction *I) {
  827. // Since we can't guarantee that the original dbg.declare instrinsic
  828. // is removed by LowerDbgDeclare(), we need to make sure that we are
  829. // not inserting the same dbg.value intrinsic over and over.
  830. llvm::BasicBlock::InstListType::iterator PrevI(I);
  831. if (PrevI != I->getParent()->getInstList().begin()) {
  832. --PrevI;
  833. if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(PrevI))
  834. if (DVI->getValue() == I->getOperand(0) &&
  835. DVI->getOffset() == 0 &&
  836. DVI->getVariable() == DIVar)
  837. return true;
  838. }
  839. return false;
  840. }
  841. /// Inserts a llvm.dbg.value intrinsic before a store to an alloca'd value
  842. /// that has an associated llvm.dbg.decl intrinsic.
  843. bool llvm::ConvertDebugDeclareToDebugValue(DbgDeclareInst *DDI,
  844. StoreInst *SI, DIBuilder &Builder) {
  845. DIVariable DIVar(DDI->getVariable());
  846. assert((!DIVar || DIVar.isVariable()) &&
  847. "Variable in DbgDeclareInst should be either null or a DIVariable.");
  848. if (!DIVar)
  849. return false;
  850. if (LdStHasDebugValue(DIVar, SI))
  851. return true;
  852. Instruction *DbgVal = NULL;
  853. // If an argument is zero extended then use argument directly. The ZExt
  854. // may be zapped by an optimization pass in future.
  855. Argument *ExtendedArg = NULL;
  856. if (ZExtInst *ZExt = dyn_cast<ZExtInst>(SI->getOperand(0)))
  857. ExtendedArg = dyn_cast<Argument>(ZExt->getOperand(0));
  858. if (SExtInst *SExt = dyn_cast<SExtInst>(SI->getOperand(0)))
  859. ExtendedArg = dyn_cast<Argument>(SExt->getOperand(0));
  860. if (ExtendedArg)
  861. DbgVal = Builder.insertDbgValueIntrinsic(ExtendedArg, 0, DIVar, SI);
  862. else
  863. DbgVal = Builder.insertDbgValueIntrinsic(SI->getOperand(0), 0, DIVar, SI);
  864. // Propagate any debug metadata from the store onto the dbg.value.
  865. DebugLoc SIDL = SI->getDebugLoc();
  866. if (!SIDL.isUnknown())
  867. DbgVal->setDebugLoc(SIDL);
  868. // Otherwise propagate debug metadata from dbg.declare.
  869. else
  870. DbgVal->setDebugLoc(DDI->getDebugLoc());
  871. return true;
  872. }
  873. /// Inserts a llvm.dbg.value intrinsic before a load of an alloca'd value
  874. /// that has an associated llvm.dbg.decl intrinsic.
  875. bool llvm::ConvertDebugDeclareToDebugValue(DbgDeclareInst *DDI,
  876. LoadInst *LI, DIBuilder &Builder) {
  877. DIVariable DIVar(DDI->getVariable());
  878. assert((!DIVar || DIVar.isVariable()) &&
  879. "Variable in DbgDeclareInst should be either null or a DIVariable.");
  880. if (!DIVar)
  881. return false;
  882. if (LdStHasDebugValue(DIVar, LI))
  883. return true;
  884. Instruction *DbgVal =
  885. Builder.insertDbgValueIntrinsic(LI->getOperand(0), 0,
  886. DIVar, LI);
  887. // Propagate any debug metadata from the store onto the dbg.value.
  888. DebugLoc LIDL = LI->getDebugLoc();
  889. if (!LIDL.isUnknown())
  890. DbgVal->setDebugLoc(LIDL);
  891. // Otherwise propagate debug metadata from dbg.declare.
  892. else
  893. DbgVal->setDebugLoc(DDI->getDebugLoc());
  894. return true;
  895. }
  896. /// LowerDbgDeclare - Lowers llvm.dbg.declare intrinsics into appropriate set
  897. /// of llvm.dbg.value intrinsics.
  898. bool llvm::LowerDbgDeclare(Function &F) {
  899. DIBuilder DIB(*F.getParent());
  900. SmallVector<DbgDeclareInst *, 4> Dbgs;
  901. for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI)
  902. for (BasicBlock::iterator BI = FI->begin(), BE = FI->end(); BI != BE; ++BI) {
  903. if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(BI))
  904. Dbgs.push_back(DDI);
  905. }
  906. if (Dbgs.empty())
  907. return false;
  908. for (SmallVectorImpl<DbgDeclareInst *>::iterator I = Dbgs.begin(),
  909. E = Dbgs.end(); I != E; ++I) {
  910. DbgDeclareInst *DDI = *I;
  911. if (AllocaInst *AI = dyn_cast_or_null<AllocaInst>(DDI->getAddress())) {
  912. // We only remove the dbg.declare intrinsic if all uses are
  913. // converted to dbg.value intrinsics.
  914. bool RemoveDDI = true;
  915. for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
  916. UI != E; ++UI)
  917. if (StoreInst *SI = dyn_cast<StoreInst>(*UI))
  918. ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
  919. else if (LoadInst *LI = dyn_cast<LoadInst>(*UI))
  920. ConvertDebugDeclareToDebugValue(DDI, LI, DIB);
  921. else
  922. RemoveDDI = false;
  923. if (RemoveDDI)
  924. DDI->eraseFromParent();
  925. }
  926. }
  927. return true;
  928. }
  929. /// FindAllocaDbgDeclare - Finds the llvm.dbg.declare intrinsic describing the
  930. /// alloca 'V', if any.
  931. DbgDeclareInst *llvm::FindAllocaDbgDeclare(Value *V) {
  932. if (MDNode *DebugNode = MDNode::getIfExists(V->getContext(), V))
  933. for (Value::use_iterator UI = DebugNode->use_begin(),
  934. E = DebugNode->use_end(); UI != E; ++UI)
  935. if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(*UI))
  936. return DDI;
  937. return 0;
  938. }
  939. bool llvm::replaceDbgDeclareForAlloca(AllocaInst *AI, Value *NewAllocaAddress,
  940. DIBuilder &Builder) {
  941. DbgDeclareInst *DDI = FindAllocaDbgDeclare(AI);
  942. if (!DDI)
  943. return false;
  944. DIVariable DIVar(DDI->getVariable());
  945. assert((!DIVar || DIVar.isVariable()) &&
  946. "Variable in DbgDeclareInst should be either null or a DIVariable.");
  947. if (!DIVar)
  948. return false;
  949. // Create a copy of the original DIDescriptor for user variable, appending
  950. // "deref" operation to a list of address elements, as new llvm.dbg.declare
  951. // will take a value storing address of the memory for variable, not
  952. // alloca itself.
  953. Type *Int64Ty = Type::getInt64Ty(AI->getContext());
  954. SmallVector<Value*, 4> NewDIVarAddress;
  955. if (DIVar.hasComplexAddress()) {
  956. for (unsigned i = 0, n = DIVar.getNumAddrElements(); i < n; ++i) {
  957. NewDIVarAddress.push_back(
  958. ConstantInt::get(Int64Ty, DIVar.getAddrElement(i)));
  959. }
  960. }
  961. NewDIVarAddress.push_back(ConstantInt::get(Int64Ty, DIBuilder::OpDeref));
  962. DIVariable NewDIVar = Builder.createComplexVariable(
  963. DIVar.getTag(), DIVar.getContext(), DIVar.getName(),
  964. DIVar.getFile(), DIVar.getLineNumber(), DIVar.getType(),
  965. NewDIVarAddress, DIVar.getArgNumber());
  966. // Insert llvm.dbg.declare in the same basic block as the original alloca,
  967. // and remove old llvm.dbg.declare.
  968. BasicBlock *BB = AI->getParent();
  969. Builder.insertDeclare(NewAllocaAddress, NewDIVar, BB);
  970. DDI->eraseFromParent();
  971. return true;
  972. }
  973. /// changeToUnreachable - Insert an unreachable instruction before the specified
  974. /// instruction, making it and the rest of the code in the block dead.
  975. static void changeToUnreachable(Instruction *I, bool UseLLVMTrap) {
  976. BasicBlock *BB = I->getParent();
  977. // Loop over all of the successors, removing BB's entry from any PHI
  978. // nodes.
  979. for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI)
  980. (*SI)->removePredecessor(BB);
  981. // Insert a call to llvm.trap right before this. This turns the undefined
  982. // behavior into a hard fail instead of falling through into random code.
  983. if (UseLLVMTrap) {
  984. Function *TrapFn =
  985. Intrinsic::getDeclaration(BB->getParent()->getParent(), Intrinsic::trap);
  986. CallInst *CallTrap = CallInst::Create(TrapFn, "", I);
  987. CallTrap->setDebugLoc(I->getDebugLoc());
  988. }
  989. new UnreachableInst(I->getContext(), I);
  990. // All instructions after this are dead.
  991. BasicBlock::iterator BBI = I, BBE = BB->end();
  992. while (BBI != BBE) {
  993. if (!BBI->use_empty())
  994. BBI->replaceAllUsesWith(UndefValue::get(BBI->getType()));
  995. BB->getInstList().erase(BBI++);
  996. }
  997. }
  998. /// changeToCall - Convert the specified invoke into a normal call.
  999. static void changeToCall(InvokeInst *II) {
  1000. SmallVector<Value*, 8> Args(II->op_begin(), II->op_end() - 3);
  1001. CallInst *NewCall = CallInst::Create(II->getCalledValue(), Args, "", II);
  1002. NewCall->takeName(II);
  1003. NewCall->setCallingConv(II->getCallingConv());
  1004. NewCall->setAttributes(II->getAttributes());
  1005. NewCall->setDebugLoc(II->getDebugLoc());
  1006. II->replaceAllUsesWith(NewCall);
  1007. // Follow the call by a branch to the normal destination.
  1008. BranchInst::Create(II->getNormalDest(), II);
  1009. // Update PHI nodes in the unwind destination
  1010. II->getUnwindDest()->removePredecessor(II->getParent());
  1011. II->eraseFromParent();
  1012. }
  1013. static bool markAliveBlocks(BasicBlock *BB,
  1014. SmallPtrSet<BasicBlock*, 128> &Reachable) {
  1015. SmallVector<BasicBlock*, 128> Worklist;
  1016. Worklist.push_back(BB);
  1017. Reachable.insert(BB);
  1018. bool Changed = false;
  1019. do {
  1020. BB = Worklist.pop_back_val();
  1021. // Do a quick scan of the basic block, turning any obviously unreachable
  1022. // instructions into LLVM unreachable insts. The instruction combining pass
  1023. // canonicalizes unreachable insts into stores to null or undef.
  1024. for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E;++BBI){
  1025. if (CallInst *CI = dyn_cast<CallInst>(BBI)) {
  1026. if (CI->doesNotReturn()) {
  1027. // If we found a call to a no-return function, insert an unreachable
  1028. // instruction after it. Make sure there isn't *already* one there
  1029. // though.
  1030. ++BBI;
  1031. if (!isa<UnreachableInst>(BBI)) {
  1032. // Don't insert a call to llvm.trap right before the unreachable.
  1033. changeToUnreachable(BBI, false);
  1034. Changed = true;
  1035. }
  1036. break;
  1037. }
  1038. }
  1039. // Store to undef and store to null are undefined and used to signal that
  1040. // they should be changed to unreachable by passes that can't modify the
  1041. // CFG.
  1042. if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
  1043. // Don't touch volatile stores.
  1044. if (SI->isVolatile()) continue;
  1045. Value *Ptr = SI->getOperand(1);
  1046. if (isa<UndefValue>(Ptr) ||
  1047. (isa<ConstantPointerNull>(Ptr) &&
  1048. SI->getPointerAddressSpace() == 0)) {
  1049. changeToUnreachable(SI, true);
  1050. Changed = true;
  1051. break;
  1052. }
  1053. }
  1054. }
  1055. // Turn invokes that call 'nounwind' functions into ordinary calls.
  1056. if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
  1057. Value *Callee = II->getCalledValue();
  1058. if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
  1059. changeToUnreachable(II, true);
  1060. Changed = true;
  1061. } else if (II->doesNotThrow()) {
  1062. if (II->use_empty() && II->onlyReadsMemory()) {
  1063. // jump to the normal destination branch.
  1064. BranchInst::Create(II->getNormalDest(), II);
  1065. II->getUnwindDest()->removePredecessor(II->getParent());
  1066. II->eraseFromParent();
  1067. } else
  1068. changeToCall(II);
  1069. Changed = true;
  1070. }
  1071. }
  1072. Changed |= ConstantFoldTerminator(BB, true);
  1073. for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI)
  1074. if (Reachable.insert(*SI))
  1075. Worklist.push_back(*SI);
  1076. } while (!Worklist.empty());
  1077. return Changed;
  1078. }
  1079. /// removeUnreachableBlocksFromFn - Remove blocks that are not reachable, even
  1080. /// if they are in a dead cycle. Return true if a change was made, false
  1081. /// otherwise.
  1082. bool llvm::removeUnreachableBlocks(Function &F) {
  1083. SmallPtrSet<BasicBlock*, 128> Reachable;
  1084. bool Changed = markAliveBlocks(F.begin(), Reachable);
  1085. // If there are unreachable blocks in the CFG...
  1086. if (Reachable.size() == F.size())
  1087. return Changed;
  1088. assert(Reachable.size() < F.size());
  1089. NumRemoved += F.size()-Reachable.size();
  1090. // Loop over all of the basic blocks that are not reachable, dropping all of
  1091. // their internal references...
  1092. for (Function::iterator BB = ++F.begin(), E = F.end(); BB != E; ++BB) {
  1093. if (Reachable.count(BB))
  1094. continue;
  1095. for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI)
  1096. if (Reachable.count(*SI))
  1097. (*SI)->removePredecessor(BB);
  1098. BB->dropAllReferences();
  1099. }
  1100. for (Function::iterator I = ++F.begin(); I != F.end();)
  1101. if (!Reachable.count(I))
  1102. I = F.getBasicBlockList().erase(I);
  1103. else
  1104. ++I;
  1105. return true;
  1106. }