Local.cpp 52 KB

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