JumpThreading.cpp 67 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726
  1. //===- JumpThreading.cpp - Thread control through conditional blocks ------===//
  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 file implements the Jump Threading pass.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/Transforms/Scalar.h"
  14. #include "llvm/ADT/DenseMap.h"
  15. #include "llvm/ADT/DenseSet.h"
  16. #include "llvm/ADT/STLExtras.h"
  17. #include "llvm/ADT/SmallPtrSet.h"
  18. #include "llvm/ADT/SmallSet.h"
  19. #include "llvm/ADT/Statistic.h"
  20. #include "llvm/Analysis/CFG.h"
  21. #include "llvm/Analysis/ConstantFolding.h"
  22. #include "llvm/Analysis/InstructionSimplify.h"
  23. #include "llvm/Analysis/LazyValueInfo.h"
  24. #include "llvm/Analysis/Loads.h"
  25. #include "llvm/Analysis/TargetLibraryInfo.h"
  26. #include "llvm/IR/DataLayout.h"
  27. #include "llvm/IR/IntrinsicInst.h"
  28. #include "llvm/IR/LLVMContext.h"
  29. #include "llvm/IR/Metadata.h"
  30. #include "llvm/IR/ValueHandle.h"
  31. #include "llvm/Pass.h"
  32. #include "llvm/Support/CommandLine.h"
  33. #include "llvm/Support/Debug.h"
  34. #include "llvm/Support/raw_ostream.h"
  35. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  36. #include "llvm/Transforms/Utils/Local.h"
  37. #include "llvm/Transforms/Utils/SSAUpdater.h"
  38. using namespace llvm;
  39. #define DEBUG_TYPE "jump-threading"
  40. STATISTIC(NumThreads, "Number of jumps threaded");
  41. STATISTIC(NumFolds, "Number of terminators folded");
  42. STATISTIC(NumDupes, "Number of branch blocks duplicated to eliminate phi");
  43. static cl::opt<unsigned>
  44. BBDuplicateThreshold("jump-threading-threshold",
  45. cl::desc("Max block size to duplicate for jump threading"),
  46. cl::init(6), cl::Hidden);
  47. namespace {
  48. // These are at global scope so static functions can use them too.
  49. typedef SmallVectorImpl<std::pair<Constant*, BasicBlock*> > PredValueInfo;
  50. typedef SmallVector<std::pair<Constant*, BasicBlock*>, 8> PredValueInfoTy;
  51. // This is used to keep track of what kind of constant we're currently hoping
  52. // to find.
  53. enum ConstantPreference {
  54. WantInteger,
  55. WantBlockAddress
  56. };
  57. /// This pass performs 'jump threading', which looks at blocks that have
  58. /// multiple predecessors and multiple successors. If one or more of the
  59. /// predecessors of the block can be proven to always jump to one of the
  60. /// successors, we forward the edge from the predecessor to the successor by
  61. /// duplicating the contents of this block.
  62. ///
  63. /// An example of when this can occur is code like this:
  64. ///
  65. /// if () { ...
  66. /// X = 4;
  67. /// }
  68. /// if (X < 3) {
  69. ///
  70. /// In this case, the unconditional branch at the end of the first if can be
  71. /// revectored to the false side of the second if.
  72. ///
  73. class JumpThreading : public FunctionPass {
  74. TargetLibraryInfo *TLI;
  75. LazyValueInfo *LVI;
  76. #ifdef NDEBUG
  77. SmallPtrSet<BasicBlock*, 16> LoopHeaders;
  78. #else
  79. SmallSet<AssertingVH<BasicBlock>, 16> LoopHeaders;
  80. #endif
  81. DenseSet<std::pair<Value*, BasicBlock*> > RecursionSet;
  82. unsigned BBDupThreshold;
  83. // RAII helper for updating the recursion stack.
  84. struct RecursionSetRemover {
  85. DenseSet<std::pair<Value*, BasicBlock*> > &TheSet;
  86. std::pair<Value*, BasicBlock*> ThePair;
  87. RecursionSetRemover(DenseSet<std::pair<Value*, BasicBlock*> > &S,
  88. std::pair<Value*, BasicBlock*> P)
  89. : TheSet(S), ThePair(P) { }
  90. ~RecursionSetRemover() {
  91. TheSet.erase(ThePair);
  92. }
  93. };
  94. public:
  95. static char ID; // Pass identification
  96. JumpThreading(int T = -1) : FunctionPass(ID) {
  97. BBDupThreshold = (T == -1) ? BBDuplicateThreshold : unsigned(T);
  98. initializeJumpThreadingPass(*PassRegistry::getPassRegistry());
  99. }
  100. bool runOnFunction(Function &F) override;
  101. void getAnalysisUsage(AnalysisUsage &AU) const override {
  102. AU.addRequired<LazyValueInfo>();
  103. AU.addPreserved<LazyValueInfo>();
  104. AU.addRequired<TargetLibraryInfoWrapperPass>();
  105. }
  106. void FindLoopHeaders(Function &F);
  107. bool ProcessBlock(BasicBlock *BB);
  108. bool ThreadEdge(BasicBlock *BB, const SmallVectorImpl<BasicBlock*> &PredBBs,
  109. BasicBlock *SuccBB);
  110. bool DuplicateCondBranchOnPHIIntoPred(BasicBlock *BB,
  111. const SmallVectorImpl<BasicBlock *> &PredBBs);
  112. bool ComputeValueKnownInPredecessors(Value *V, BasicBlock *BB,
  113. PredValueInfo &Result,
  114. ConstantPreference Preference,
  115. Instruction *CxtI = nullptr);
  116. bool ProcessThreadableEdges(Value *Cond, BasicBlock *BB,
  117. ConstantPreference Preference,
  118. Instruction *CxtI = nullptr);
  119. bool ProcessBranchOnPHI(PHINode *PN);
  120. bool ProcessBranchOnXOR(BinaryOperator *BO);
  121. bool SimplifyPartiallyRedundantLoad(LoadInst *LI);
  122. bool TryToUnfoldSelect(CmpInst *CondCmp, BasicBlock *BB);
  123. };
  124. }
  125. char JumpThreading::ID = 0;
  126. INITIALIZE_PASS_BEGIN(JumpThreading, "jump-threading",
  127. "Jump Threading", false, false)
  128. INITIALIZE_PASS_DEPENDENCY(LazyValueInfo)
  129. INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
  130. INITIALIZE_PASS_END(JumpThreading, "jump-threading",
  131. "Jump Threading", false, false)
  132. // Public interface to the Jump Threading pass
  133. FunctionPass *llvm::createJumpThreadingPass(int Threshold) { return new JumpThreading(Threshold); }
  134. /// runOnFunction - Top level algorithm.
  135. ///
  136. bool JumpThreading::runOnFunction(Function &F) {
  137. if (skipOptnoneFunction(F))
  138. return false;
  139. DEBUG(dbgs() << "Jump threading on function '" << F.getName() << "'\n");
  140. TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
  141. LVI = &getAnalysis<LazyValueInfo>();
  142. // Remove unreachable blocks from function as they may result in infinite
  143. // loop. We do threading if we found something profitable. Jump threading a
  144. // branch can create other opportunities. If these opportunities form a cycle
  145. // i.e. if any jump treading is undoing previous threading in the path, then
  146. // we will loop forever. We take care of this issue by not jump threading for
  147. // back edges. This works for normal cases but not for unreachable blocks as
  148. // they may have cycle with no back edge.
  149. removeUnreachableBlocks(F);
  150. FindLoopHeaders(F);
  151. bool Changed, EverChanged = false;
  152. do {
  153. Changed = false;
  154. for (Function::iterator I = F.begin(), E = F.end(); I != E;) {
  155. BasicBlock *BB = I;
  156. // Thread all of the branches we can over this block.
  157. while (ProcessBlock(BB))
  158. Changed = true;
  159. ++I;
  160. // If the block is trivially dead, zap it. This eliminates the successor
  161. // edges which simplifies the CFG.
  162. if (pred_empty(BB) &&
  163. BB != &BB->getParent()->getEntryBlock()) {
  164. DEBUG(dbgs() << " JT: Deleting dead block '" << BB->getName()
  165. << "' with terminator: " << *BB->getTerminator() << '\n');
  166. LoopHeaders.erase(BB);
  167. LVI->eraseBlock(BB);
  168. DeleteDeadBlock(BB);
  169. Changed = true;
  170. continue;
  171. }
  172. BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
  173. // Can't thread an unconditional jump, but if the block is "almost
  174. // empty", we can replace uses of it with uses of the successor and make
  175. // this dead.
  176. if (BI && BI->isUnconditional() &&
  177. BB != &BB->getParent()->getEntryBlock() &&
  178. // If the terminator is the only non-phi instruction, try to nuke it.
  179. BB->getFirstNonPHIOrDbg()->isTerminator()) {
  180. // Since TryToSimplifyUncondBranchFromEmptyBlock may delete the
  181. // block, we have to make sure it isn't in the LoopHeaders set. We
  182. // reinsert afterward if needed.
  183. bool ErasedFromLoopHeaders = LoopHeaders.erase(BB);
  184. BasicBlock *Succ = BI->getSuccessor(0);
  185. // FIXME: It is always conservatively correct to drop the info
  186. // for a block even if it doesn't get erased. This isn't totally
  187. // awesome, but it allows us to use AssertingVH to prevent nasty
  188. // dangling pointer issues within LazyValueInfo.
  189. LVI->eraseBlock(BB);
  190. if (TryToSimplifyUncondBranchFromEmptyBlock(BB)) {
  191. Changed = true;
  192. // If we deleted BB and BB was the header of a loop, then the
  193. // successor is now the header of the loop.
  194. BB = Succ;
  195. }
  196. if (ErasedFromLoopHeaders)
  197. LoopHeaders.insert(BB);
  198. }
  199. }
  200. EverChanged |= Changed;
  201. } while (Changed);
  202. LoopHeaders.clear();
  203. return EverChanged;
  204. }
  205. /// getJumpThreadDuplicationCost - Return the cost of duplicating this block to
  206. /// thread across it. Stop scanning the block when passing the threshold.
  207. static unsigned getJumpThreadDuplicationCost(const BasicBlock *BB,
  208. unsigned Threshold) {
  209. /// Ignore PHI nodes, these will be flattened when duplication happens.
  210. BasicBlock::const_iterator I = BB->getFirstNonPHI();
  211. // FIXME: THREADING will delete values that are just used to compute the
  212. // branch, so they shouldn't count against the duplication cost.
  213. // Sum up the cost of each instruction until we get to the terminator. Don't
  214. // include the terminator because the copy won't include it.
  215. unsigned Size = 0;
  216. for (; !isa<TerminatorInst>(I); ++I) {
  217. // Stop scanning the block if we've reached the threshold.
  218. if (Size > Threshold)
  219. return Size;
  220. // Debugger intrinsics don't incur code size.
  221. if (isa<DbgInfoIntrinsic>(I)) continue;
  222. // If this is a pointer->pointer bitcast, it is free.
  223. if (isa<BitCastInst>(I) && I->getType()->isPointerTy())
  224. continue;
  225. // All other instructions count for at least one unit.
  226. ++Size;
  227. // Calls are more expensive. If they are non-intrinsic calls, we model them
  228. // as having cost of 4. If they are a non-vector intrinsic, we model them
  229. // as having cost of 2 total, and if they are a vector intrinsic, we model
  230. // them as having cost 1.
  231. if (const CallInst *CI = dyn_cast<CallInst>(I)) {
  232. if (CI->cannotDuplicate())
  233. // Blocks with NoDuplicate are modelled as having infinite cost, so they
  234. // are never duplicated.
  235. return ~0U;
  236. else if (!isa<IntrinsicInst>(CI))
  237. Size += 3;
  238. else if (!CI->getType()->isVectorTy())
  239. Size += 1;
  240. }
  241. }
  242. // Threading through a switch statement is particularly profitable. If this
  243. // block ends in a switch, decrease its cost to make it more likely to happen.
  244. if (isa<SwitchInst>(I))
  245. Size = Size > 6 ? Size-6 : 0;
  246. // The same holds for indirect branches, but slightly more so.
  247. if (isa<IndirectBrInst>(I))
  248. Size = Size > 8 ? Size-8 : 0;
  249. return Size;
  250. }
  251. /// FindLoopHeaders - We do not want jump threading to turn proper loop
  252. /// structures into irreducible loops. Doing this breaks up the loop nesting
  253. /// hierarchy and pessimizes later transformations. To prevent this from
  254. /// happening, we first have to find the loop headers. Here we approximate this
  255. /// by finding targets of backedges in the CFG.
  256. ///
  257. /// Note that there definitely are cases when we want to allow threading of
  258. /// edges across a loop header. For example, threading a jump from outside the
  259. /// loop (the preheader) to an exit block of the loop is definitely profitable.
  260. /// It is also almost always profitable to thread backedges from within the loop
  261. /// to exit blocks, and is often profitable to thread backedges to other blocks
  262. /// within the loop (forming a nested loop). This simple analysis is not rich
  263. /// enough to track all of these properties and keep it up-to-date as the CFG
  264. /// mutates, so we don't allow any of these transformations.
  265. ///
  266. void JumpThreading::FindLoopHeaders(Function &F) {
  267. SmallVector<std::pair<const BasicBlock*,const BasicBlock*>, 32> Edges;
  268. FindFunctionBackedges(F, Edges);
  269. for (unsigned i = 0, e = Edges.size(); i != e; ++i)
  270. LoopHeaders.insert(const_cast<BasicBlock*>(Edges[i].second));
  271. }
  272. /// getKnownConstant - Helper method to determine if we can thread over a
  273. /// terminator with the given value as its condition, and if so what value to
  274. /// use for that. What kind of value this is depends on whether we want an
  275. /// integer or a block address, but an undef is always accepted.
  276. /// Returns null if Val is null or not an appropriate constant.
  277. static Constant *getKnownConstant(Value *Val, ConstantPreference Preference) {
  278. if (!Val)
  279. return nullptr;
  280. // Undef is "known" enough.
  281. if (UndefValue *U = dyn_cast<UndefValue>(Val))
  282. return U;
  283. if (Preference == WantBlockAddress)
  284. return dyn_cast<BlockAddress>(Val->stripPointerCasts());
  285. return dyn_cast<ConstantInt>(Val);
  286. }
  287. /// ComputeValueKnownInPredecessors - Given a basic block BB and a value V, see
  288. /// if we can infer that the value is a known ConstantInt/BlockAddress or undef
  289. /// in any of our predecessors. If so, return the known list of value and pred
  290. /// BB in the result vector.
  291. ///
  292. /// This returns true if there were any known values.
  293. ///
  294. bool JumpThreading::
  295. ComputeValueKnownInPredecessors(Value *V, BasicBlock *BB, PredValueInfo &Result,
  296. ConstantPreference Preference,
  297. Instruction *CxtI) {
  298. // This method walks up use-def chains recursively. Because of this, we could
  299. // get into an infinite loop going around loops in the use-def chain. To
  300. // prevent this, keep track of what (value, block) pairs we've already visited
  301. // and terminate the search if we loop back to them
  302. if (!RecursionSet.insert(std::make_pair(V, BB)).second)
  303. return false;
  304. // An RAII help to remove this pair from the recursion set once the recursion
  305. // stack pops back out again.
  306. RecursionSetRemover remover(RecursionSet, std::make_pair(V, BB));
  307. // If V is a constant, then it is known in all predecessors.
  308. if (Constant *KC = getKnownConstant(V, Preference)) {
  309. for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
  310. Result.push_back(std::make_pair(KC, *PI));
  311. return true;
  312. }
  313. // If V is a non-instruction value, or an instruction in a different block,
  314. // then it can't be derived from a PHI.
  315. Instruction *I = dyn_cast<Instruction>(V);
  316. if (!I || I->getParent() != BB) {
  317. // Okay, if this is a live-in value, see if it has a known value at the end
  318. // of any of our predecessors.
  319. //
  320. // FIXME: This should be an edge property, not a block end property.
  321. /// TODO: Per PR2563, we could infer value range information about a
  322. /// predecessor based on its terminator.
  323. //
  324. // FIXME: change this to use the more-rich 'getPredicateOnEdge' method if
  325. // "I" is a non-local compare-with-a-constant instruction. This would be
  326. // able to handle value inequalities better, for example if the compare is
  327. // "X < 4" and "X < 3" is known true but "X < 4" itself is not available.
  328. // Perhaps getConstantOnEdge should be smart enough to do this?
  329. for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
  330. BasicBlock *P = *PI;
  331. // If the value is known by LazyValueInfo to be a constant in a
  332. // predecessor, use that information to try to thread this block.
  333. Constant *PredCst = LVI->getConstantOnEdge(V, P, BB, CxtI);
  334. if (Constant *KC = getKnownConstant(PredCst, Preference))
  335. Result.push_back(std::make_pair(KC, P));
  336. }
  337. return !Result.empty();
  338. }
  339. /// If I is a PHI node, then we know the incoming values for any constants.
  340. if (PHINode *PN = dyn_cast<PHINode>(I)) {
  341. for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
  342. Value *InVal = PN->getIncomingValue(i);
  343. if (Constant *KC = getKnownConstant(InVal, Preference)) {
  344. Result.push_back(std::make_pair(KC, PN->getIncomingBlock(i)));
  345. } else {
  346. Constant *CI = LVI->getConstantOnEdge(InVal,
  347. PN->getIncomingBlock(i),
  348. BB, CxtI);
  349. if (Constant *KC = getKnownConstant(CI, Preference))
  350. Result.push_back(std::make_pair(KC, PN->getIncomingBlock(i)));
  351. }
  352. }
  353. return !Result.empty();
  354. }
  355. PredValueInfoTy LHSVals, RHSVals;
  356. // Handle some boolean conditions.
  357. if (I->getType()->getPrimitiveSizeInBits() == 1) {
  358. assert(Preference == WantInteger && "One-bit non-integer type?");
  359. // X | true -> true
  360. // X & false -> false
  361. if (I->getOpcode() == Instruction::Or ||
  362. I->getOpcode() == Instruction::And) {
  363. ComputeValueKnownInPredecessors(I->getOperand(0), BB, LHSVals,
  364. WantInteger, CxtI);
  365. ComputeValueKnownInPredecessors(I->getOperand(1), BB, RHSVals,
  366. WantInteger, CxtI);
  367. if (LHSVals.empty() && RHSVals.empty())
  368. return false;
  369. ConstantInt *InterestingVal;
  370. if (I->getOpcode() == Instruction::Or)
  371. InterestingVal = ConstantInt::getTrue(I->getContext());
  372. else
  373. InterestingVal = ConstantInt::getFalse(I->getContext());
  374. SmallPtrSet<BasicBlock*, 4> LHSKnownBBs;
  375. // Scan for the sentinel. If we find an undef, force it to the
  376. // interesting value: x|undef -> true and x&undef -> false.
  377. for (unsigned i = 0, e = LHSVals.size(); i != e; ++i)
  378. if (LHSVals[i].first == InterestingVal ||
  379. isa<UndefValue>(LHSVals[i].first)) {
  380. Result.push_back(LHSVals[i]);
  381. Result.back().first = InterestingVal;
  382. LHSKnownBBs.insert(LHSVals[i].second);
  383. }
  384. for (unsigned i = 0, e = RHSVals.size(); i != e; ++i)
  385. if (RHSVals[i].first == InterestingVal ||
  386. isa<UndefValue>(RHSVals[i].first)) {
  387. // If we already inferred a value for this block on the LHS, don't
  388. // re-add it.
  389. if (!LHSKnownBBs.count(RHSVals[i].second)) {
  390. Result.push_back(RHSVals[i]);
  391. Result.back().first = InterestingVal;
  392. }
  393. }
  394. return !Result.empty();
  395. }
  396. // Handle the NOT form of XOR.
  397. if (I->getOpcode() == Instruction::Xor &&
  398. isa<ConstantInt>(I->getOperand(1)) &&
  399. cast<ConstantInt>(I->getOperand(1))->isOne()) {
  400. ComputeValueKnownInPredecessors(I->getOperand(0), BB, Result,
  401. WantInteger, CxtI);
  402. if (Result.empty())
  403. return false;
  404. // Invert the known values.
  405. for (unsigned i = 0, e = Result.size(); i != e; ++i)
  406. Result[i].first = ConstantExpr::getNot(Result[i].first);
  407. return true;
  408. }
  409. // Try to simplify some other binary operator values.
  410. } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
  411. assert(Preference != WantBlockAddress
  412. && "A binary operator creating a block address?");
  413. if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1))) {
  414. PredValueInfoTy LHSVals;
  415. ComputeValueKnownInPredecessors(BO->getOperand(0), BB, LHSVals,
  416. WantInteger, CxtI);
  417. // Try to use constant folding to simplify the binary operator.
  418. for (unsigned i = 0, e = LHSVals.size(); i != e; ++i) {
  419. Constant *V = LHSVals[i].first;
  420. Constant *Folded = ConstantExpr::get(BO->getOpcode(), V, CI);
  421. if (Constant *KC = getKnownConstant(Folded, WantInteger))
  422. Result.push_back(std::make_pair(KC, LHSVals[i].second));
  423. }
  424. }
  425. return !Result.empty();
  426. }
  427. // Handle compare with phi operand, where the PHI is defined in this block.
  428. if (CmpInst *Cmp = dyn_cast<CmpInst>(I)) {
  429. assert(Preference == WantInteger && "Compares only produce integers");
  430. PHINode *PN = dyn_cast<PHINode>(Cmp->getOperand(0));
  431. if (PN && PN->getParent() == BB) {
  432. const DataLayout &DL = PN->getModule()->getDataLayout();
  433. // We can do this simplification if any comparisons fold to true or false.
  434. // See if any do.
  435. for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
  436. BasicBlock *PredBB = PN->getIncomingBlock(i);
  437. Value *LHS = PN->getIncomingValue(i);
  438. Value *RHS = Cmp->getOperand(1)->DoPHITranslation(BB, PredBB);
  439. Value *Res = SimplifyCmpInst(Cmp->getPredicate(), LHS, RHS, DL);
  440. if (!Res) {
  441. if (!isa<Constant>(RHS))
  442. continue;
  443. LazyValueInfo::Tristate
  444. ResT = LVI->getPredicateOnEdge(Cmp->getPredicate(), LHS,
  445. cast<Constant>(RHS), PredBB, BB,
  446. CxtI ? CxtI : Cmp);
  447. if (ResT == LazyValueInfo::Unknown)
  448. continue;
  449. Res = ConstantInt::get(Type::getInt1Ty(LHS->getContext()), ResT);
  450. }
  451. if (Constant *KC = getKnownConstant(Res, WantInteger))
  452. Result.push_back(std::make_pair(KC, PredBB));
  453. }
  454. return !Result.empty();
  455. }
  456. // If comparing a live-in value against a constant, see if we know the
  457. // live-in value on any predecessors.
  458. if (isa<Constant>(Cmp->getOperand(1)) && Cmp->getType()->isIntegerTy()) {
  459. if (!isa<Instruction>(Cmp->getOperand(0)) ||
  460. cast<Instruction>(Cmp->getOperand(0))->getParent() != BB) {
  461. Constant *RHSCst = cast<Constant>(Cmp->getOperand(1));
  462. for (pred_iterator PI = pred_begin(BB), E = pred_end(BB);PI != E; ++PI){
  463. BasicBlock *P = *PI;
  464. // If the value is known by LazyValueInfo to be a constant in a
  465. // predecessor, use that information to try to thread this block.
  466. LazyValueInfo::Tristate Res =
  467. LVI->getPredicateOnEdge(Cmp->getPredicate(), Cmp->getOperand(0),
  468. RHSCst, P, BB, CxtI ? CxtI : Cmp);
  469. if (Res == LazyValueInfo::Unknown)
  470. continue;
  471. Constant *ResC = ConstantInt::get(Cmp->getType(), Res);
  472. Result.push_back(std::make_pair(ResC, P));
  473. }
  474. return !Result.empty();
  475. }
  476. // Try to find a constant value for the LHS of a comparison,
  477. // and evaluate it statically if we can.
  478. if (Constant *CmpConst = dyn_cast<Constant>(Cmp->getOperand(1))) {
  479. PredValueInfoTy LHSVals;
  480. ComputeValueKnownInPredecessors(I->getOperand(0), BB, LHSVals,
  481. WantInteger, CxtI);
  482. for (unsigned i = 0, e = LHSVals.size(); i != e; ++i) {
  483. Constant *V = LHSVals[i].first;
  484. Constant *Folded = ConstantExpr::getCompare(Cmp->getPredicate(),
  485. V, CmpConst);
  486. if (Constant *KC = getKnownConstant(Folded, WantInteger))
  487. Result.push_back(std::make_pair(KC, LHSVals[i].second));
  488. }
  489. return !Result.empty();
  490. }
  491. }
  492. }
  493. if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
  494. // Handle select instructions where at least one operand is a known constant
  495. // and we can figure out the condition value for any predecessor block.
  496. Constant *TrueVal = getKnownConstant(SI->getTrueValue(), Preference);
  497. Constant *FalseVal = getKnownConstant(SI->getFalseValue(), Preference);
  498. PredValueInfoTy Conds;
  499. if ((TrueVal || FalseVal) &&
  500. ComputeValueKnownInPredecessors(SI->getCondition(), BB, Conds,
  501. WantInteger, CxtI)) {
  502. for (unsigned i = 0, e = Conds.size(); i != e; ++i) {
  503. Constant *Cond = Conds[i].first;
  504. // Figure out what value to use for the condition.
  505. bool KnownCond;
  506. if (ConstantInt *CI = dyn_cast<ConstantInt>(Cond)) {
  507. // A known boolean.
  508. KnownCond = CI->isOne();
  509. } else {
  510. assert(isa<UndefValue>(Cond) && "Unexpected condition value");
  511. // Either operand will do, so be sure to pick the one that's a known
  512. // constant.
  513. // FIXME: Do this more cleverly if both values are known constants?
  514. KnownCond = (TrueVal != nullptr);
  515. }
  516. // See if the select has a known constant value for this predecessor.
  517. if (Constant *Val = KnownCond ? TrueVal : FalseVal)
  518. Result.push_back(std::make_pair(Val, Conds[i].second));
  519. }
  520. return !Result.empty();
  521. }
  522. }
  523. // If all else fails, see if LVI can figure out a constant value for us.
  524. Constant *CI = LVI->getConstant(V, BB, CxtI);
  525. if (Constant *KC = getKnownConstant(CI, Preference)) {
  526. for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
  527. Result.push_back(std::make_pair(KC, *PI));
  528. }
  529. return !Result.empty();
  530. }
  531. /// GetBestDestForBranchOnUndef - If we determine that the specified block ends
  532. /// in an undefined jump, decide which block is best to revector to.
  533. ///
  534. /// Since we can pick an arbitrary destination, we pick the successor with the
  535. /// fewest predecessors. This should reduce the in-degree of the others.
  536. ///
  537. static unsigned GetBestDestForJumpOnUndef(BasicBlock *BB) {
  538. TerminatorInst *BBTerm = BB->getTerminator();
  539. unsigned MinSucc = 0;
  540. BasicBlock *TestBB = BBTerm->getSuccessor(MinSucc);
  541. // Compute the successor with the minimum number of predecessors.
  542. unsigned MinNumPreds = std::distance(pred_begin(TestBB), pred_end(TestBB));
  543. for (unsigned i = 1, e = BBTerm->getNumSuccessors(); i != e; ++i) {
  544. TestBB = BBTerm->getSuccessor(i);
  545. unsigned NumPreds = std::distance(pred_begin(TestBB), pred_end(TestBB));
  546. if (NumPreds < MinNumPreds) {
  547. MinSucc = i;
  548. MinNumPreds = NumPreds;
  549. }
  550. }
  551. return MinSucc;
  552. }
  553. static bool hasAddressTakenAndUsed(BasicBlock *BB) {
  554. if (!BB->hasAddressTaken()) return false;
  555. // If the block has its address taken, it may be a tree of dead constants
  556. // hanging off of it. These shouldn't keep the block alive.
  557. BlockAddress *BA = BlockAddress::get(BB);
  558. BA->removeDeadConstantUsers();
  559. return !BA->use_empty();
  560. }
  561. /// ProcessBlock - If there are any predecessors whose control can be threaded
  562. /// through to a successor, transform them now.
  563. bool JumpThreading::ProcessBlock(BasicBlock *BB) {
  564. // If the block is trivially dead, just return and let the caller nuke it.
  565. // This simplifies other transformations.
  566. if (pred_empty(BB) &&
  567. BB != &BB->getParent()->getEntryBlock())
  568. return false;
  569. // If this block has a single predecessor, and if that pred has a single
  570. // successor, merge the blocks. This encourages recursive jump threading
  571. // because now the condition in this block can be threaded through
  572. // predecessors of our predecessor block.
  573. if (BasicBlock *SinglePred = BB->getSinglePredecessor()) {
  574. if (SinglePred->getTerminator()->getNumSuccessors() == 1 &&
  575. SinglePred != BB && !hasAddressTakenAndUsed(BB)) {
  576. // If SinglePred was a loop header, BB becomes one.
  577. if (LoopHeaders.erase(SinglePred))
  578. LoopHeaders.insert(BB);
  579. LVI->eraseBlock(SinglePred);
  580. MergeBasicBlockIntoOnlyPred(BB);
  581. return true;
  582. }
  583. }
  584. // What kind of constant we're looking for.
  585. ConstantPreference Preference = WantInteger;
  586. // Look to see if the terminator is a conditional branch, switch or indirect
  587. // branch, if not we can't thread it.
  588. Value *Condition;
  589. Instruction *Terminator = BB->getTerminator();
  590. if (BranchInst *BI = dyn_cast<BranchInst>(Terminator)) {
  591. // Can't thread an unconditional jump.
  592. if (BI->isUnconditional()) return false;
  593. Condition = BI->getCondition();
  594. } else if (SwitchInst *SI = dyn_cast<SwitchInst>(Terminator)) {
  595. Condition = SI->getCondition();
  596. } else if (IndirectBrInst *IB = dyn_cast<IndirectBrInst>(Terminator)) {
  597. // Can't thread indirect branch with no successors.
  598. if (IB->getNumSuccessors() == 0) return false;
  599. Condition = IB->getAddress()->stripPointerCasts();
  600. Preference = WantBlockAddress;
  601. } else {
  602. return false; // Must be an invoke.
  603. }
  604. // Run constant folding to see if we can reduce the condition to a simple
  605. // constant.
  606. if (Instruction *I = dyn_cast<Instruction>(Condition)) {
  607. Value *SimpleVal =
  608. ConstantFoldInstruction(I, BB->getModule()->getDataLayout(), TLI);
  609. if (SimpleVal) {
  610. I->replaceAllUsesWith(SimpleVal);
  611. I->eraseFromParent();
  612. Condition = SimpleVal;
  613. }
  614. }
  615. // If the terminator is branching on an undef, we can pick any of the
  616. // successors to branch to. Let GetBestDestForJumpOnUndef decide.
  617. if (isa<UndefValue>(Condition)) {
  618. unsigned BestSucc = GetBestDestForJumpOnUndef(BB);
  619. // Fold the branch/switch.
  620. TerminatorInst *BBTerm = BB->getTerminator();
  621. for (unsigned i = 0, e = BBTerm->getNumSuccessors(); i != e; ++i) {
  622. if (i == BestSucc) continue;
  623. BBTerm->getSuccessor(i)->removePredecessor(BB, true);
  624. }
  625. DEBUG(dbgs() << " In block '" << BB->getName()
  626. << "' folding undef terminator: " << *BBTerm << '\n');
  627. BranchInst::Create(BBTerm->getSuccessor(BestSucc), BBTerm);
  628. BBTerm->eraseFromParent();
  629. return true;
  630. }
  631. // If the terminator of this block is branching on a constant, simplify the
  632. // terminator to an unconditional branch. This can occur due to threading in
  633. // other blocks.
  634. if (getKnownConstant(Condition, Preference)) {
  635. DEBUG(dbgs() << " In block '" << BB->getName()
  636. << "' folding terminator: " << *BB->getTerminator() << '\n');
  637. ++NumFolds;
  638. ConstantFoldTerminator(BB, true);
  639. return true;
  640. }
  641. Instruction *CondInst = dyn_cast<Instruction>(Condition);
  642. // All the rest of our checks depend on the condition being an instruction.
  643. if (!CondInst) {
  644. // FIXME: Unify this with code below.
  645. if (ProcessThreadableEdges(Condition, BB, Preference, Terminator))
  646. return true;
  647. return false;
  648. }
  649. if (CmpInst *CondCmp = dyn_cast<CmpInst>(CondInst)) {
  650. // If we're branching on a conditional, LVI might be able to determine
  651. // it's value at the branch instruction. We only handle comparisons
  652. // against a constant at this time.
  653. // TODO: This should be extended to handle switches as well.
  654. BranchInst *CondBr = dyn_cast<BranchInst>(BB->getTerminator());
  655. Constant *CondConst = dyn_cast<Constant>(CondCmp->getOperand(1));
  656. if (CondBr && CondConst && CondBr->isConditional()) {
  657. LazyValueInfo::Tristate Ret =
  658. LVI->getPredicateAt(CondCmp->getPredicate(), CondCmp->getOperand(0),
  659. CondConst, CondBr);
  660. if (Ret != LazyValueInfo::Unknown) {
  661. unsigned ToRemove = Ret == LazyValueInfo::True ? 1 : 0;
  662. unsigned ToKeep = Ret == LazyValueInfo::True ? 0 : 1;
  663. CondBr->getSuccessor(ToRemove)->removePredecessor(BB, true);
  664. BranchInst::Create(CondBr->getSuccessor(ToKeep), CondBr);
  665. CondBr->eraseFromParent();
  666. if (CondCmp->use_empty())
  667. CondCmp->eraseFromParent();
  668. else if (CondCmp->getParent() == BB) {
  669. // If the fact we just learned is true for all uses of the
  670. // condition, replace it with a constant value
  671. auto *CI = Ret == LazyValueInfo::True ?
  672. ConstantInt::getTrue(CondCmp->getType()) :
  673. ConstantInt::getFalse(CondCmp->getType());
  674. CondCmp->replaceAllUsesWith(CI);
  675. CondCmp->eraseFromParent();
  676. }
  677. return true;
  678. }
  679. }
  680. if (CondBr && CondConst && TryToUnfoldSelect(CondCmp, BB))
  681. return true;
  682. }
  683. // Check for some cases that are worth simplifying. Right now we want to look
  684. // for loads that are used by a switch or by the condition for the branch. If
  685. // we see one, check to see if it's partially redundant. If so, insert a PHI
  686. // which can then be used to thread the values.
  687. //
  688. Value *SimplifyValue = CondInst;
  689. if (CmpInst *CondCmp = dyn_cast<CmpInst>(SimplifyValue))
  690. if (isa<Constant>(CondCmp->getOperand(1)))
  691. SimplifyValue = CondCmp->getOperand(0);
  692. // TODO: There are other places where load PRE would be profitable, such as
  693. // more complex comparisons.
  694. if (LoadInst *LI = dyn_cast<LoadInst>(SimplifyValue))
  695. if (SimplifyPartiallyRedundantLoad(LI))
  696. return true;
  697. // Handle a variety of cases where we are branching on something derived from
  698. // a PHI node in the current block. If we can prove that any predecessors
  699. // compute a predictable value based on a PHI node, thread those predecessors.
  700. //
  701. if (ProcessThreadableEdges(CondInst, BB, Preference, Terminator))
  702. return true;
  703. // If this is an otherwise-unfoldable branch on a phi node in the current
  704. // block, see if we can simplify.
  705. if (PHINode *PN = dyn_cast<PHINode>(CondInst))
  706. if (PN->getParent() == BB && isa<BranchInst>(BB->getTerminator()))
  707. return ProcessBranchOnPHI(PN);
  708. // If this is an otherwise-unfoldable branch on a XOR, see if we can simplify.
  709. if (CondInst->getOpcode() == Instruction::Xor &&
  710. CondInst->getParent() == BB && isa<BranchInst>(BB->getTerminator()))
  711. return ProcessBranchOnXOR(cast<BinaryOperator>(CondInst));
  712. // TODO: If we have: "br (X > 0)" and we have a predecessor where we know
  713. // "(X == 4)", thread through this block.
  714. return false;
  715. }
  716. /// SimplifyPartiallyRedundantLoad - If LI is an obviously partially redundant
  717. /// load instruction, eliminate it by replacing it with a PHI node. This is an
  718. /// important optimization that encourages jump threading, and needs to be run
  719. /// interlaced with other jump threading tasks.
  720. bool JumpThreading::SimplifyPartiallyRedundantLoad(LoadInst *LI) {
  721. // Don't hack volatile/atomic loads.
  722. if (!LI->isSimple()) return false;
  723. // If the load is defined in a block with exactly one predecessor, it can't be
  724. // partially redundant.
  725. BasicBlock *LoadBB = LI->getParent();
  726. if (LoadBB->getSinglePredecessor())
  727. return false;
  728. // If the load is defined in a landing pad, it can't be partially redundant,
  729. // because the edges between the invoke and the landing pad cannot have other
  730. // instructions between them.
  731. if (LoadBB->isLandingPad())
  732. return false;
  733. Value *LoadedPtr = LI->getOperand(0);
  734. // If the loaded operand is defined in the LoadBB, it can't be available.
  735. // TODO: Could do simple PHI translation, that would be fun :)
  736. if (Instruction *PtrOp = dyn_cast<Instruction>(LoadedPtr))
  737. if (PtrOp->getParent() == LoadBB)
  738. return false;
  739. // Scan a few instructions up from the load, to see if it is obviously live at
  740. // the entry to its block.
  741. BasicBlock::iterator BBIt = LI;
  742. if (Value *AvailableVal =
  743. FindAvailableLoadedValue(LoadedPtr, LoadBB, BBIt, 6)) {
  744. // If the value if the load is locally available within the block, just use
  745. // it. This frequently occurs for reg2mem'd allocas.
  746. //cerr << "LOAD ELIMINATED:\n" << *BBIt << *LI << "\n";
  747. // If the returned value is the load itself, replace with an undef. This can
  748. // only happen in dead loops.
  749. if (AvailableVal == LI) AvailableVal = UndefValue::get(LI->getType());
  750. if (AvailableVal->getType() != LI->getType())
  751. AvailableVal =
  752. CastInst::CreateBitOrPointerCast(AvailableVal, LI->getType(), "", LI);
  753. LI->replaceAllUsesWith(AvailableVal);
  754. LI->eraseFromParent();
  755. return true;
  756. }
  757. // Otherwise, if we scanned the whole block and got to the top of the block,
  758. // we know the block is locally transparent to the load. If not, something
  759. // might clobber its value.
  760. if (BBIt != LoadBB->begin())
  761. return false;
  762. // If all of the loads and stores that feed the value have the same AA tags,
  763. // then we can propagate them onto any newly inserted loads.
  764. AAMDNodes AATags;
  765. LI->getAAMetadata(AATags);
  766. SmallPtrSet<BasicBlock*, 8> PredsScanned;
  767. typedef SmallVector<std::pair<BasicBlock*, Value*>, 8> AvailablePredsTy;
  768. AvailablePredsTy AvailablePreds;
  769. BasicBlock *OneUnavailablePred = nullptr;
  770. // If we got here, the loaded value is transparent through to the start of the
  771. // block. Check to see if it is available in any of the predecessor blocks.
  772. for (pred_iterator PI = pred_begin(LoadBB), PE = pred_end(LoadBB);
  773. PI != PE; ++PI) {
  774. BasicBlock *PredBB = *PI;
  775. // If we already scanned this predecessor, skip it.
  776. if (!PredsScanned.insert(PredBB).second)
  777. continue;
  778. // Scan the predecessor to see if the value is available in the pred.
  779. BBIt = PredBB->end();
  780. AAMDNodes ThisAATags;
  781. Value *PredAvailable = FindAvailableLoadedValue(LoadedPtr, PredBB, BBIt, 6,
  782. nullptr, &ThisAATags);
  783. if (!PredAvailable) {
  784. OneUnavailablePred = PredBB;
  785. continue;
  786. }
  787. // If AA tags disagree or are not present, forget about them.
  788. if (AATags != ThisAATags) AATags = AAMDNodes();
  789. // If so, this load is partially redundant. Remember this info so that we
  790. // can create a PHI node.
  791. AvailablePreds.push_back(std::make_pair(PredBB, PredAvailable));
  792. }
  793. // If the loaded value isn't available in any predecessor, it isn't partially
  794. // redundant.
  795. if (AvailablePreds.empty()) return false;
  796. // Okay, the loaded value is available in at least one (and maybe all!)
  797. // predecessors. If the value is unavailable in more than one unique
  798. // predecessor, we want to insert a merge block for those common predecessors.
  799. // This ensures that we only have to insert one reload, thus not increasing
  800. // code size.
  801. BasicBlock *UnavailablePred = nullptr;
  802. // If there is exactly one predecessor where the value is unavailable, the
  803. // already computed 'OneUnavailablePred' block is it. If it ends in an
  804. // unconditional branch, we know that it isn't a critical edge.
  805. if (PredsScanned.size() == AvailablePreds.size()+1 &&
  806. OneUnavailablePred->getTerminator()->getNumSuccessors() == 1) {
  807. UnavailablePred = OneUnavailablePred;
  808. } else if (PredsScanned.size() != AvailablePreds.size()) {
  809. // Otherwise, we had multiple unavailable predecessors or we had a critical
  810. // edge from the one.
  811. SmallVector<BasicBlock*, 8> PredsToSplit;
  812. SmallPtrSet<BasicBlock*, 8> AvailablePredSet;
  813. for (unsigned i = 0, e = AvailablePreds.size(); i != e; ++i)
  814. AvailablePredSet.insert(AvailablePreds[i].first);
  815. // Add all the unavailable predecessors to the PredsToSplit list.
  816. for (pred_iterator PI = pred_begin(LoadBB), PE = pred_end(LoadBB);
  817. PI != PE; ++PI) {
  818. BasicBlock *P = *PI;
  819. // If the predecessor is an indirect goto, we can't split the edge.
  820. if (isa<IndirectBrInst>(P->getTerminator()))
  821. return false;
  822. if (!AvailablePredSet.count(P))
  823. PredsToSplit.push_back(P);
  824. }
  825. // Split them out to their own block.
  826. UnavailablePred =
  827. SplitBlockPredecessors(LoadBB, PredsToSplit, "thread-pre-split");
  828. }
  829. // If the value isn't available in all predecessors, then there will be
  830. // exactly one where it isn't available. Insert a load on that edge and add
  831. // it to the AvailablePreds list.
  832. if (UnavailablePred) {
  833. assert(UnavailablePred->getTerminator()->getNumSuccessors() == 1 &&
  834. "Can't handle critical edge here!");
  835. LoadInst *NewVal = new LoadInst(LoadedPtr, LI->getName()+".pr", false,
  836. LI->getAlignment(),
  837. UnavailablePred->getTerminator());
  838. NewVal->setDebugLoc(LI->getDebugLoc());
  839. if (AATags)
  840. NewVal->setAAMetadata(AATags);
  841. AvailablePreds.push_back(std::make_pair(UnavailablePred, NewVal));
  842. }
  843. // Now we know that each predecessor of this block has a value in
  844. // AvailablePreds, sort them for efficient access as we're walking the preds.
  845. array_pod_sort(AvailablePreds.begin(), AvailablePreds.end());
  846. // Create a PHI node at the start of the block for the PRE'd load value.
  847. pred_iterator PB = pred_begin(LoadBB), PE = pred_end(LoadBB);
  848. PHINode *PN = PHINode::Create(LI->getType(), std::distance(PB, PE), "",
  849. LoadBB->begin());
  850. PN->takeName(LI);
  851. PN->setDebugLoc(LI->getDebugLoc());
  852. // Insert new entries into the PHI for each predecessor. A single block may
  853. // have multiple entries here.
  854. for (pred_iterator PI = PB; PI != PE; ++PI) {
  855. BasicBlock *P = *PI;
  856. AvailablePredsTy::iterator I =
  857. std::lower_bound(AvailablePreds.begin(), AvailablePreds.end(),
  858. std::make_pair(P, (Value*)nullptr));
  859. assert(I != AvailablePreds.end() && I->first == P &&
  860. "Didn't find entry for predecessor!");
  861. // If we have an available predecessor but it requires casting, insert the
  862. // cast in the predecessor and use the cast. Note that we have to update the
  863. // AvailablePreds vector as we go so that all of the PHI entries for this
  864. // predecessor use the same bitcast.
  865. Value *&PredV = I->second;
  866. if (PredV->getType() != LI->getType())
  867. PredV = CastInst::CreateBitOrPointerCast(PredV, LI->getType(), "",
  868. P->getTerminator());
  869. PN->addIncoming(PredV, I->first);
  870. }
  871. //cerr << "PRE: " << *LI << *PN << "\n";
  872. LI->replaceAllUsesWith(PN);
  873. LI->eraseFromParent();
  874. return true;
  875. }
  876. /// FindMostPopularDest - The specified list contains multiple possible
  877. /// threadable destinations. Pick the one that occurs the most frequently in
  878. /// the list.
  879. static BasicBlock *
  880. FindMostPopularDest(BasicBlock *BB,
  881. const SmallVectorImpl<std::pair<BasicBlock*,
  882. BasicBlock*> > &PredToDestList) {
  883. assert(!PredToDestList.empty());
  884. // Determine popularity. If there are multiple possible destinations, we
  885. // explicitly choose to ignore 'undef' destinations. We prefer to thread
  886. // blocks with known and real destinations to threading undef. We'll handle
  887. // them later if interesting.
  888. DenseMap<BasicBlock*, unsigned> DestPopularity;
  889. for (unsigned i = 0, e = PredToDestList.size(); i != e; ++i)
  890. if (PredToDestList[i].second)
  891. DestPopularity[PredToDestList[i].second]++;
  892. // Find the most popular dest.
  893. DenseMap<BasicBlock*, unsigned>::iterator DPI = DestPopularity.begin();
  894. BasicBlock *MostPopularDest = DPI->first;
  895. unsigned Popularity = DPI->second;
  896. SmallVector<BasicBlock*, 4> SamePopularity;
  897. for (++DPI; DPI != DestPopularity.end(); ++DPI) {
  898. // If the popularity of this entry isn't higher than the popularity we've
  899. // seen so far, ignore it.
  900. if (DPI->second < Popularity)
  901. ; // ignore.
  902. else if (DPI->second == Popularity) {
  903. // If it is the same as what we've seen so far, keep track of it.
  904. SamePopularity.push_back(DPI->first);
  905. } else {
  906. // If it is more popular, remember it.
  907. SamePopularity.clear();
  908. MostPopularDest = DPI->first;
  909. Popularity = DPI->second;
  910. }
  911. }
  912. // Okay, now we know the most popular destination. If there is more than one
  913. // destination, we need to determine one. This is arbitrary, but we need
  914. // to make a deterministic decision. Pick the first one that appears in the
  915. // successor list.
  916. if (!SamePopularity.empty()) {
  917. SamePopularity.push_back(MostPopularDest);
  918. TerminatorInst *TI = BB->getTerminator();
  919. for (unsigned i = 0; ; ++i) {
  920. assert(i != TI->getNumSuccessors() && "Didn't find any successor!");
  921. if (std::find(SamePopularity.begin(), SamePopularity.end(),
  922. TI->getSuccessor(i)) == SamePopularity.end())
  923. continue;
  924. MostPopularDest = TI->getSuccessor(i);
  925. break;
  926. }
  927. }
  928. // Okay, we have finally picked the most popular destination.
  929. return MostPopularDest;
  930. }
  931. bool JumpThreading::ProcessThreadableEdges(Value *Cond, BasicBlock *BB,
  932. ConstantPreference Preference,
  933. Instruction *CxtI) {
  934. // If threading this would thread across a loop header, don't even try to
  935. // thread the edge.
  936. if (LoopHeaders.count(BB))
  937. return false;
  938. PredValueInfoTy PredValues;
  939. if (!ComputeValueKnownInPredecessors(Cond, BB, PredValues, Preference, CxtI))
  940. return false;
  941. assert(!PredValues.empty() &&
  942. "ComputeValueKnownInPredecessors returned true with no values");
  943. DEBUG(dbgs() << "IN BB: " << *BB;
  944. for (unsigned i = 0, e = PredValues.size(); i != e; ++i) {
  945. dbgs() << " BB '" << BB->getName() << "': FOUND condition = "
  946. << *PredValues[i].first
  947. << " for pred '" << PredValues[i].second->getName() << "'.\n";
  948. });
  949. // Decide what we want to thread through. Convert our list of known values to
  950. // a list of known destinations for each pred. This also discards duplicate
  951. // predecessors and keeps track of the undefined inputs (which are represented
  952. // as a null dest in the PredToDestList).
  953. SmallPtrSet<BasicBlock*, 16> SeenPreds;
  954. SmallVector<std::pair<BasicBlock*, BasicBlock*>, 16> PredToDestList;
  955. BasicBlock *OnlyDest = nullptr;
  956. BasicBlock *MultipleDestSentinel = (BasicBlock*)(intptr_t)~0ULL;
  957. for (unsigned i = 0, e = PredValues.size(); i != e; ++i) {
  958. BasicBlock *Pred = PredValues[i].second;
  959. if (!SeenPreds.insert(Pred).second)
  960. continue; // Duplicate predecessor entry.
  961. // If the predecessor ends with an indirect goto, we can't change its
  962. // destination.
  963. if (isa<IndirectBrInst>(Pred->getTerminator()))
  964. continue;
  965. Constant *Val = PredValues[i].first;
  966. BasicBlock *DestBB;
  967. if (isa<UndefValue>(Val))
  968. DestBB = nullptr;
  969. else if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator()))
  970. DestBB = BI->getSuccessor(cast<ConstantInt>(Val)->isZero());
  971. else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
  972. DestBB = SI->findCaseValue(cast<ConstantInt>(Val)).getCaseSuccessor();
  973. } else {
  974. assert(isa<IndirectBrInst>(BB->getTerminator())
  975. && "Unexpected terminator");
  976. DestBB = cast<BlockAddress>(Val)->getBasicBlock();
  977. }
  978. // If we have exactly one destination, remember it for efficiency below.
  979. if (PredToDestList.empty())
  980. OnlyDest = DestBB;
  981. else if (OnlyDest != DestBB)
  982. OnlyDest = MultipleDestSentinel;
  983. PredToDestList.push_back(std::make_pair(Pred, DestBB));
  984. }
  985. // If all edges were unthreadable, we fail.
  986. if (PredToDestList.empty())
  987. return false;
  988. // Determine which is the most common successor. If we have many inputs and
  989. // this block is a switch, we want to start by threading the batch that goes
  990. // to the most popular destination first. If we only know about one
  991. // threadable destination (the common case) we can avoid this.
  992. BasicBlock *MostPopularDest = OnlyDest;
  993. if (MostPopularDest == MultipleDestSentinel)
  994. MostPopularDest = FindMostPopularDest(BB, PredToDestList);
  995. // Now that we know what the most popular destination is, factor all
  996. // predecessors that will jump to it into a single predecessor.
  997. SmallVector<BasicBlock*, 16> PredsToFactor;
  998. for (unsigned i = 0, e = PredToDestList.size(); i != e; ++i)
  999. if (PredToDestList[i].second == MostPopularDest) {
  1000. BasicBlock *Pred = PredToDestList[i].first;
  1001. // This predecessor may be a switch or something else that has multiple
  1002. // edges to the block. Factor each of these edges by listing them
  1003. // according to # occurrences in PredsToFactor.
  1004. TerminatorInst *PredTI = Pred->getTerminator();
  1005. for (unsigned i = 0, e = PredTI->getNumSuccessors(); i != e; ++i)
  1006. if (PredTI->getSuccessor(i) == BB)
  1007. PredsToFactor.push_back(Pred);
  1008. }
  1009. // If the threadable edges are branching on an undefined value, we get to pick
  1010. // the destination that these predecessors should get to.
  1011. if (!MostPopularDest)
  1012. MostPopularDest = BB->getTerminator()->
  1013. getSuccessor(GetBestDestForJumpOnUndef(BB));
  1014. // Ok, try to thread it!
  1015. return ThreadEdge(BB, PredsToFactor, MostPopularDest);
  1016. }
  1017. /// ProcessBranchOnPHI - We have an otherwise unthreadable conditional branch on
  1018. /// a PHI node in the current block. See if there are any simplifications we
  1019. /// can do based on inputs to the phi node.
  1020. ///
  1021. bool JumpThreading::ProcessBranchOnPHI(PHINode *PN) {
  1022. BasicBlock *BB = PN->getParent();
  1023. // TODO: We could make use of this to do it once for blocks with common PHI
  1024. // values.
  1025. SmallVector<BasicBlock*, 1> PredBBs;
  1026. PredBBs.resize(1);
  1027. // If any of the predecessor blocks end in an unconditional branch, we can
  1028. // *duplicate* the conditional branch into that block in order to further
  1029. // encourage jump threading and to eliminate cases where we have branch on a
  1030. // phi of an icmp (branch on icmp is much better).
  1031. for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
  1032. BasicBlock *PredBB = PN->getIncomingBlock(i);
  1033. if (BranchInst *PredBr = dyn_cast<BranchInst>(PredBB->getTerminator()))
  1034. if (PredBr->isUnconditional()) {
  1035. PredBBs[0] = PredBB;
  1036. // Try to duplicate BB into PredBB.
  1037. if (DuplicateCondBranchOnPHIIntoPred(BB, PredBBs))
  1038. return true;
  1039. }
  1040. }
  1041. return false;
  1042. }
  1043. /// ProcessBranchOnXOR - We have an otherwise unthreadable conditional branch on
  1044. /// a xor instruction in the current block. See if there are any
  1045. /// simplifications we can do based on inputs to the xor.
  1046. ///
  1047. bool JumpThreading::ProcessBranchOnXOR(BinaryOperator *BO) {
  1048. BasicBlock *BB = BO->getParent();
  1049. // If either the LHS or RHS of the xor is a constant, don't do this
  1050. // optimization.
  1051. if (isa<ConstantInt>(BO->getOperand(0)) ||
  1052. isa<ConstantInt>(BO->getOperand(1)))
  1053. return false;
  1054. // If the first instruction in BB isn't a phi, we won't be able to infer
  1055. // anything special about any particular predecessor.
  1056. if (!isa<PHINode>(BB->front()))
  1057. return false;
  1058. // If we have a xor as the branch input to this block, and we know that the
  1059. // LHS or RHS of the xor in any predecessor is true/false, then we can clone
  1060. // the condition into the predecessor and fix that value to true, saving some
  1061. // logical ops on that path and encouraging other paths to simplify.
  1062. //
  1063. // This copies something like this:
  1064. //
  1065. // BB:
  1066. // %X = phi i1 [1], [%X']
  1067. // %Y = icmp eq i32 %A, %B
  1068. // %Z = xor i1 %X, %Y
  1069. // br i1 %Z, ...
  1070. //
  1071. // Into:
  1072. // BB':
  1073. // %Y = icmp ne i32 %A, %B
  1074. // br i1 %Z, ...
  1075. PredValueInfoTy XorOpValues;
  1076. bool isLHS = true;
  1077. if (!ComputeValueKnownInPredecessors(BO->getOperand(0), BB, XorOpValues,
  1078. WantInteger, BO)) {
  1079. assert(XorOpValues.empty());
  1080. if (!ComputeValueKnownInPredecessors(BO->getOperand(1), BB, XorOpValues,
  1081. WantInteger, BO))
  1082. return false;
  1083. isLHS = false;
  1084. }
  1085. assert(!XorOpValues.empty() &&
  1086. "ComputeValueKnownInPredecessors returned true with no values");
  1087. // Scan the information to see which is most popular: true or false. The
  1088. // predecessors can be of the set true, false, or undef.
  1089. unsigned NumTrue = 0, NumFalse = 0;
  1090. for (unsigned i = 0, e = XorOpValues.size(); i != e; ++i) {
  1091. if (isa<UndefValue>(XorOpValues[i].first))
  1092. // Ignore undefs for the count.
  1093. continue;
  1094. if (cast<ConstantInt>(XorOpValues[i].first)->isZero())
  1095. ++NumFalse;
  1096. else
  1097. ++NumTrue;
  1098. }
  1099. // Determine which value to split on, true, false, or undef if neither.
  1100. ConstantInt *SplitVal = nullptr;
  1101. if (NumTrue > NumFalse)
  1102. SplitVal = ConstantInt::getTrue(BB->getContext());
  1103. else if (NumTrue != 0 || NumFalse != 0)
  1104. SplitVal = ConstantInt::getFalse(BB->getContext());
  1105. // Collect all of the blocks that this can be folded into so that we can
  1106. // factor this once and clone it once.
  1107. SmallVector<BasicBlock*, 8> BlocksToFoldInto;
  1108. for (unsigned i = 0, e = XorOpValues.size(); i != e; ++i) {
  1109. if (XorOpValues[i].first != SplitVal &&
  1110. !isa<UndefValue>(XorOpValues[i].first))
  1111. continue;
  1112. BlocksToFoldInto.push_back(XorOpValues[i].second);
  1113. }
  1114. // If we inferred a value for all of the predecessors, then duplication won't
  1115. // help us. However, we can just replace the LHS or RHS with the constant.
  1116. if (BlocksToFoldInto.size() ==
  1117. cast<PHINode>(BB->front()).getNumIncomingValues()) {
  1118. if (!SplitVal) {
  1119. // If all preds provide undef, just nuke the xor, because it is undef too.
  1120. BO->replaceAllUsesWith(UndefValue::get(BO->getType()));
  1121. BO->eraseFromParent();
  1122. } else if (SplitVal->isZero()) {
  1123. // If all preds provide 0, replace the xor with the other input.
  1124. BO->replaceAllUsesWith(BO->getOperand(isLHS));
  1125. BO->eraseFromParent();
  1126. } else {
  1127. // If all preds provide 1, set the computed value to 1.
  1128. BO->setOperand(!isLHS, SplitVal);
  1129. }
  1130. return true;
  1131. }
  1132. // Try to duplicate BB into PredBB.
  1133. return DuplicateCondBranchOnPHIIntoPred(BB, BlocksToFoldInto);
  1134. }
  1135. /// AddPHINodeEntriesForMappedBlock - We're adding 'NewPred' as a new
  1136. /// predecessor to the PHIBB block. If it has PHI nodes, add entries for
  1137. /// NewPred using the entries from OldPred (suitably mapped).
  1138. static void AddPHINodeEntriesForMappedBlock(BasicBlock *PHIBB,
  1139. BasicBlock *OldPred,
  1140. BasicBlock *NewPred,
  1141. DenseMap<Instruction*, Value*> &ValueMap) {
  1142. for (BasicBlock::iterator PNI = PHIBB->begin();
  1143. PHINode *PN = dyn_cast<PHINode>(PNI); ++PNI) {
  1144. // Ok, we have a PHI node. Figure out what the incoming value was for the
  1145. // DestBlock.
  1146. Value *IV = PN->getIncomingValueForBlock(OldPred);
  1147. // Remap the value if necessary.
  1148. if (Instruction *Inst = dyn_cast<Instruction>(IV)) {
  1149. DenseMap<Instruction*, Value*>::iterator I = ValueMap.find(Inst);
  1150. if (I != ValueMap.end())
  1151. IV = I->second;
  1152. }
  1153. PN->addIncoming(IV, NewPred);
  1154. }
  1155. }
  1156. /// ThreadEdge - We have decided that it is safe and profitable to factor the
  1157. /// blocks in PredBBs to one predecessor, then thread an edge from it to SuccBB
  1158. /// across BB. Transform the IR to reflect this change.
  1159. bool JumpThreading::ThreadEdge(BasicBlock *BB,
  1160. const SmallVectorImpl<BasicBlock*> &PredBBs,
  1161. BasicBlock *SuccBB) {
  1162. // If threading to the same block as we come from, we would infinite loop.
  1163. if (SuccBB == BB) {
  1164. DEBUG(dbgs() << " Not threading across BB '" << BB->getName()
  1165. << "' - would thread to self!\n");
  1166. return false;
  1167. }
  1168. // If threading this would thread across a loop header, don't thread the edge.
  1169. // See the comments above FindLoopHeaders for justifications and caveats.
  1170. if (LoopHeaders.count(BB)) {
  1171. DEBUG(dbgs() << " Not threading across loop header BB '" << BB->getName()
  1172. << "' to dest BB '" << SuccBB->getName()
  1173. << "' - it might create an irreducible loop!\n");
  1174. return false;
  1175. }
  1176. unsigned JumpThreadCost = getJumpThreadDuplicationCost(BB, BBDupThreshold);
  1177. if (JumpThreadCost > BBDupThreshold) {
  1178. DEBUG(dbgs() << " Not threading BB '" << BB->getName()
  1179. << "' - Cost is too high: " << JumpThreadCost << "\n");
  1180. return false;
  1181. }
  1182. // And finally, do it! Start by factoring the predecessors is needed.
  1183. BasicBlock *PredBB;
  1184. if (PredBBs.size() == 1)
  1185. PredBB = PredBBs[0];
  1186. else {
  1187. DEBUG(dbgs() << " Factoring out " << PredBBs.size()
  1188. << " common predecessors.\n");
  1189. PredBB = SplitBlockPredecessors(BB, PredBBs, ".thr_comm");
  1190. }
  1191. // And finally, do it!
  1192. DEBUG(dbgs() << " Threading edge from '" << PredBB->getName() << "' to '"
  1193. << SuccBB->getName() << "' with cost: " << JumpThreadCost
  1194. << ", across block:\n "
  1195. << *BB << "\n");
  1196. LVI->threadEdge(PredBB, BB, SuccBB);
  1197. // We are going to have to map operands from the original BB block to the new
  1198. // copy of the block 'NewBB'. If there are PHI nodes in BB, evaluate them to
  1199. // account for entry from PredBB.
  1200. DenseMap<Instruction*, Value*> ValueMapping;
  1201. BasicBlock *NewBB = BasicBlock::Create(BB->getContext(),
  1202. BB->getName()+".thread",
  1203. BB->getParent(), BB);
  1204. NewBB->moveAfter(PredBB);
  1205. BasicBlock::iterator BI = BB->begin();
  1206. for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
  1207. ValueMapping[PN] = PN->getIncomingValueForBlock(PredBB);
  1208. // Clone the non-phi instructions of BB into NewBB, keeping track of the
  1209. // mapping and using it to remap operands in the cloned instructions.
  1210. for (; !isa<TerminatorInst>(BI); ++BI) {
  1211. Instruction *New = BI->clone();
  1212. New->setName(BI->getName());
  1213. NewBB->getInstList().push_back(New);
  1214. ValueMapping[BI] = New;
  1215. // Remap operands to patch up intra-block references.
  1216. for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
  1217. if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i))) {
  1218. DenseMap<Instruction*, Value*>::iterator I = ValueMapping.find(Inst);
  1219. if (I != ValueMapping.end())
  1220. New->setOperand(i, I->second);
  1221. }
  1222. }
  1223. // We didn't copy the terminator from BB over to NewBB, because there is now
  1224. // an unconditional jump to SuccBB. Insert the unconditional jump.
  1225. BranchInst *NewBI =BranchInst::Create(SuccBB, NewBB);
  1226. NewBI->setDebugLoc(BB->getTerminator()->getDebugLoc());
  1227. // Check to see if SuccBB has PHI nodes. If so, we need to add entries to the
  1228. // PHI nodes for NewBB now.
  1229. AddPHINodeEntriesForMappedBlock(SuccBB, BB, NewBB, ValueMapping);
  1230. // If there were values defined in BB that are used outside the block, then we
  1231. // now have to update all uses of the value to use either the original value,
  1232. // the cloned value, or some PHI derived value. This can require arbitrary
  1233. // PHI insertion, of which we are prepared to do, clean these up now.
  1234. SSAUpdater SSAUpdate;
  1235. SmallVector<Use*, 16> UsesToRename;
  1236. for (BasicBlock::iterator I = BB->begin(); I != BB->end(); ++I) {
  1237. // Scan all uses of this instruction to see if it is used outside of its
  1238. // block, and if so, record them in UsesToRename.
  1239. for (Use &U : I->uses()) {
  1240. Instruction *User = cast<Instruction>(U.getUser());
  1241. if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
  1242. if (UserPN->getIncomingBlock(U) == BB)
  1243. continue;
  1244. } else if (User->getParent() == BB)
  1245. continue;
  1246. UsesToRename.push_back(&U);
  1247. }
  1248. // If there are no uses outside the block, we're done with this instruction.
  1249. if (UsesToRename.empty())
  1250. continue;
  1251. DEBUG(dbgs() << "JT: Renaming non-local uses of: " << *I << "\n");
  1252. // We found a use of I outside of BB. Rename all uses of I that are outside
  1253. // its block to be uses of the appropriate PHI node etc. See ValuesInBlocks
  1254. // with the two values we know.
  1255. SSAUpdate.Initialize(I->getType(), I->getName());
  1256. SSAUpdate.AddAvailableValue(BB, I);
  1257. SSAUpdate.AddAvailableValue(NewBB, ValueMapping[I]);
  1258. while (!UsesToRename.empty())
  1259. SSAUpdate.RewriteUse(*UsesToRename.pop_back_val());
  1260. DEBUG(dbgs() << "\n");
  1261. }
  1262. // Ok, NewBB is good to go. Update the terminator of PredBB to jump to
  1263. // NewBB instead of BB. This eliminates predecessors from BB, which requires
  1264. // us to simplify any PHI nodes in BB.
  1265. TerminatorInst *PredTerm = PredBB->getTerminator();
  1266. for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i)
  1267. if (PredTerm->getSuccessor(i) == BB) {
  1268. BB->removePredecessor(PredBB, true);
  1269. PredTerm->setSuccessor(i, NewBB);
  1270. }
  1271. // At this point, the IR is fully up to date and consistent. Do a quick scan
  1272. // over the new instructions and zap any that are constants or dead. This
  1273. // frequently happens because of phi translation.
  1274. SimplifyInstructionsInBlock(NewBB, TLI);
  1275. // Threaded an edge!
  1276. ++NumThreads;
  1277. return true;
  1278. }
  1279. /// DuplicateCondBranchOnPHIIntoPred - PredBB contains an unconditional branch
  1280. /// to BB which contains an i1 PHI node and a conditional branch on that PHI.
  1281. /// If we can duplicate the contents of BB up into PredBB do so now, this
  1282. /// improves the odds that the branch will be on an analyzable instruction like
  1283. /// a compare.
  1284. bool JumpThreading::DuplicateCondBranchOnPHIIntoPred(BasicBlock *BB,
  1285. const SmallVectorImpl<BasicBlock *> &PredBBs) {
  1286. assert(!PredBBs.empty() && "Can't handle an empty set");
  1287. // If BB is a loop header, then duplicating this block outside the loop would
  1288. // cause us to transform this into an irreducible loop, don't do this.
  1289. // See the comments above FindLoopHeaders for justifications and caveats.
  1290. if (LoopHeaders.count(BB)) {
  1291. DEBUG(dbgs() << " Not duplicating loop header '" << BB->getName()
  1292. << "' into predecessor block '" << PredBBs[0]->getName()
  1293. << "' - it might create an irreducible loop!\n");
  1294. return false;
  1295. }
  1296. unsigned DuplicationCost = getJumpThreadDuplicationCost(BB, BBDupThreshold);
  1297. if (DuplicationCost > BBDupThreshold) {
  1298. DEBUG(dbgs() << " Not duplicating BB '" << BB->getName()
  1299. << "' - Cost is too high: " << DuplicationCost << "\n");
  1300. return false;
  1301. }
  1302. // And finally, do it! Start by factoring the predecessors is needed.
  1303. BasicBlock *PredBB;
  1304. if (PredBBs.size() == 1)
  1305. PredBB = PredBBs[0];
  1306. else {
  1307. DEBUG(dbgs() << " Factoring out " << PredBBs.size()
  1308. << " common predecessors.\n");
  1309. PredBB = SplitBlockPredecessors(BB, PredBBs, ".thr_comm");
  1310. }
  1311. // Okay, we decided to do this! Clone all the instructions in BB onto the end
  1312. // of PredBB.
  1313. DEBUG(dbgs() << " Duplicating block '" << BB->getName() << "' into end of '"
  1314. << PredBB->getName() << "' to eliminate branch on phi. Cost: "
  1315. << DuplicationCost << " block is:" << *BB << "\n");
  1316. // Unless PredBB ends with an unconditional branch, split the edge so that we
  1317. // can just clone the bits from BB into the end of the new PredBB.
  1318. BranchInst *OldPredBranch = dyn_cast<BranchInst>(PredBB->getTerminator());
  1319. if (!OldPredBranch || !OldPredBranch->isUnconditional()) {
  1320. PredBB = SplitEdge(PredBB, BB);
  1321. OldPredBranch = cast<BranchInst>(PredBB->getTerminator());
  1322. }
  1323. // We are going to have to map operands from the original BB block into the
  1324. // PredBB block. Evaluate PHI nodes in BB.
  1325. DenseMap<Instruction*, Value*> ValueMapping;
  1326. BasicBlock::iterator BI = BB->begin();
  1327. for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
  1328. ValueMapping[PN] = PN->getIncomingValueForBlock(PredBB);
  1329. // Clone the non-phi instructions of BB into PredBB, keeping track of the
  1330. // mapping and using it to remap operands in the cloned instructions.
  1331. for (; BI != BB->end(); ++BI) {
  1332. Instruction *New = BI->clone();
  1333. // Remap operands to patch up intra-block references.
  1334. for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
  1335. if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i))) {
  1336. DenseMap<Instruction*, Value*>::iterator I = ValueMapping.find(Inst);
  1337. if (I != ValueMapping.end())
  1338. New->setOperand(i, I->second);
  1339. }
  1340. // If this instruction can be simplified after the operands are updated,
  1341. // just use the simplified value instead. This frequently happens due to
  1342. // phi translation.
  1343. if (Value *IV =
  1344. SimplifyInstruction(New, BB->getModule()->getDataLayout())) {
  1345. delete New;
  1346. ValueMapping[BI] = IV;
  1347. } else {
  1348. // Otherwise, insert the new instruction into the block.
  1349. New->setName(BI->getName());
  1350. PredBB->getInstList().insert(OldPredBranch, New);
  1351. ValueMapping[BI] = New;
  1352. }
  1353. }
  1354. // Check to see if the targets of the branch had PHI nodes. If so, we need to
  1355. // add entries to the PHI nodes for branch from PredBB now.
  1356. BranchInst *BBBranch = cast<BranchInst>(BB->getTerminator());
  1357. AddPHINodeEntriesForMappedBlock(BBBranch->getSuccessor(0), BB, PredBB,
  1358. ValueMapping);
  1359. AddPHINodeEntriesForMappedBlock(BBBranch->getSuccessor(1), BB, PredBB,
  1360. ValueMapping);
  1361. // If there were values defined in BB that are used outside the block, then we
  1362. // now have to update all uses of the value to use either the original value,
  1363. // the cloned value, or some PHI derived value. This can require arbitrary
  1364. // PHI insertion, of which we are prepared to do, clean these up now.
  1365. SSAUpdater SSAUpdate;
  1366. SmallVector<Use*, 16> UsesToRename;
  1367. for (BasicBlock::iterator I = BB->begin(); I != BB->end(); ++I) {
  1368. // Scan all uses of this instruction to see if it is used outside of its
  1369. // block, and if so, record them in UsesToRename.
  1370. for (Use &U : I->uses()) {
  1371. Instruction *User = cast<Instruction>(U.getUser());
  1372. if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
  1373. if (UserPN->getIncomingBlock(U) == BB)
  1374. continue;
  1375. } else if (User->getParent() == BB)
  1376. continue;
  1377. UsesToRename.push_back(&U);
  1378. }
  1379. // If there are no uses outside the block, we're done with this instruction.
  1380. if (UsesToRename.empty())
  1381. continue;
  1382. DEBUG(dbgs() << "JT: Renaming non-local uses of: " << *I << "\n");
  1383. // We found a use of I outside of BB. Rename all uses of I that are outside
  1384. // its block to be uses of the appropriate PHI node etc. See ValuesInBlocks
  1385. // with the two values we know.
  1386. SSAUpdate.Initialize(I->getType(), I->getName());
  1387. SSAUpdate.AddAvailableValue(BB, I);
  1388. SSAUpdate.AddAvailableValue(PredBB, ValueMapping[I]);
  1389. while (!UsesToRename.empty())
  1390. SSAUpdate.RewriteUse(*UsesToRename.pop_back_val());
  1391. DEBUG(dbgs() << "\n");
  1392. }
  1393. // PredBB no longer jumps to BB, remove entries in the PHI node for the edge
  1394. // that we nuked.
  1395. BB->removePredecessor(PredBB, true);
  1396. // Remove the unconditional branch at the end of the PredBB block.
  1397. OldPredBranch->eraseFromParent();
  1398. ++NumDupes;
  1399. return true;
  1400. }
  1401. /// TryToUnfoldSelect - Look for blocks of the form
  1402. /// bb1:
  1403. /// %a = select
  1404. /// br bb
  1405. ///
  1406. /// bb2:
  1407. /// %p = phi [%a, %bb] ...
  1408. /// %c = icmp %p
  1409. /// br i1 %c
  1410. ///
  1411. /// And expand the select into a branch structure if one of its arms allows %c
  1412. /// to be folded. This later enables threading from bb1 over bb2.
  1413. bool JumpThreading::TryToUnfoldSelect(CmpInst *CondCmp, BasicBlock *BB) {
  1414. BranchInst *CondBr = dyn_cast<BranchInst>(BB->getTerminator());
  1415. PHINode *CondLHS = dyn_cast<PHINode>(CondCmp->getOperand(0));
  1416. Constant *CondRHS = cast<Constant>(CondCmp->getOperand(1));
  1417. if (!CondBr || !CondBr->isConditional() || !CondLHS ||
  1418. CondLHS->getParent() != BB)
  1419. return false;
  1420. for (unsigned I = 0, E = CondLHS->getNumIncomingValues(); I != E; ++I) {
  1421. BasicBlock *Pred = CondLHS->getIncomingBlock(I);
  1422. SelectInst *SI = dyn_cast<SelectInst>(CondLHS->getIncomingValue(I));
  1423. // Look if one of the incoming values is a select in the corresponding
  1424. // predecessor.
  1425. if (!SI || SI->getParent() != Pred || !SI->hasOneUse())
  1426. continue;
  1427. BranchInst *PredTerm = dyn_cast<BranchInst>(Pred->getTerminator());
  1428. if (!PredTerm || !PredTerm->isUnconditional())
  1429. continue;
  1430. // Now check if one of the select values would allow us to constant fold the
  1431. // terminator in BB. We don't do the transform if both sides fold, those
  1432. // cases will be threaded in any case.
  1433. LazyValueInfo::Tristate LHSFolds =
  1434. LVI->getPredicateOnEdge(CondCmp->getPredicate(), SI->getOperand(1),
  1435. CondRHS, Pred, BB, CondCmp);
  1436. LazyValueInfo::Tristate RHSFolds =
  1437. LVI->getPredicateOnEdge(CondCmp->getPredicate(), SI->getOperand(2),
  1438. CondRHS, Pred, BB, CondCmp);
  1439. if ((LHSFolds != LazyValueInfo::Unknown ||
  1440. RHSFolds != LazyValueInfo::Unknown) &&
  1441. LHSFolds != RHSFolds) {
  1442. // Expand the select.
  1443. //
  1444. // Pred --
  1445. // | v
  1446. // | NewBB
  1447. // | |
  1448. // |-----
  1449. // v
  1450. // BB
  1451. BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), "select.unfold",
  1452. BB->getParent(), BB);
  1453. // Move the unconditional branch to NewBB.
  1454. PredTerm->removeFromParent();
  1455. NewBB->getInstList().insert(NewBB->end(), PredTerm);
  1456. // Create a conditional branch and update PHI nodes.
  1457. BranchInst::Create(NewBB, BB, SI->getCondition(), Pred);
  1458. CondLHS->setIncomingValue(I, SI->getFalseValue());
  1459. CondLHS->addIncoming(SI->getTrueValue(), NewBB);
  1460. // The select is now dead.
  1461. SI->eraseFromParent();
  1462. // Update any other PHI nodes in BB.
  1463. for (BasicBlock::iterator BI = BB->begin();
  1464. PHINode *Phi = dyn_cast<PHINode>(BI); ++BI)
  1465. if (Phi != CondLHS)
  1466. Phi->addIncoming(Phi->getIncomingValueForBlock(Pred), NewBB);
  1467. return true;
  1468. }
  1469. }
  1470. return false;
  1471. }