Local.cpp 51 KB

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