Local.cpp 51 KB

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