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