JumpThreading.cpp 84 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192
  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/JumpThreading.h"
  14. #include "llvm/Transforms/Scalar.h"
  15. #include "llvm/ADT/DenseMap.h"
  16. #include "llvm/ADT/DenseSet.h"
  17. #include "llvm/ADT/STLExtras.h"
  18. #include "llvm/ADT/Statistic.h"
  19. #include "llvm/Analysis/AliasAnalysis.h"
  20. #include "llvm/Analysis/GlobalsModRef.h"
  21. #include "llvm/Analysis/CFG.h"
  22. #include "llvm/Analysis/BlockFrequencyInfoImpl.h"
  23. #include "llvm/Analysis/ConstantFolding.h"
  24. #include "llvm/Analysis/InstructionSimplify.h"
  25. #include "llvm/Analysis/Loads.h"
  26. #include "llvm/Analysis/LoopInfo.h"
  27. #include "llvm/Analysis/ValueTracking.h"
  28. #include "llvm/IR/DataLayout.h"
  29. #include "llvm/IR/IntrinsicInst.h"
  30. #include "llvm/IR/LLVMContext.h"
  31. #include "llvm/IR/MDBuilder.h"
  32. #include "llvm/IR/Metadata.h"
  33. #include "llvm/IR/PatternMatch.h"
  34. #include "llvm/Pass.h"
  35. #include "llvm/Support/CommandLine.h"
  36. #include "llvm/Support/Debug.h"
  37. #include "llvm/Support/raw_ostream.h"
  38. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  39. #include "llvm/Transforms/Utils/Cloning.h"
  40. #include "llvm/Transforms/Utils/Local.h"
  41. #include "llvm/Transforms/Utils/SSAUpdater.h"
  42. #include <algorithm>
  43. #include <memory>
  44. using namespace llvm;
  45. using namespace jumpthreading;
  46. #define DEBUG_TYPE "jump-threading"
  47. STATISTIC(NumThreads, "Number of jumps threaded");
  48. STATISTIC(NumFolds, "Number of terminators folded");
  49. STATISTIC(NumDupes, "Number of branch blocks duplicated to eliminate phi");
  50. static cl::opt<unsigned>
  51. BBDuplicateThreshold("jump-threading-threshold",
  52. cl::desc("Max block size to duplicate for jump threading"),
  53. cl::init(6), cl::Hidden);
  54. static cl::opt<unsigned>
  55. ImplicationSearchThreshold(
  56. "jump-threading-implication-search-threshold",
  57. cl::desc("The number of predecessors to search for a stronger "
  58. "condition to use to thread over a weaker condition"),
  59. cl::init(3), cl::Hidden);
  60. namespace {
  61. /// This pass performs 'jump threading', which looks at blocks that have
  62. /// multiple predecessors and multiple successors. If one or more of the
  63. /// predecessors of the block can be proven to always jump to one of the
  64. /// successors, we forward the edge from the predecessor to the successor by
  65. /// duplicating the contents of this block.
  66. ///
  67. /// An example of when this can occur is code like this:
  68. ///
  69. /// if () { ...
  70. /// X = 4;
  71. /// }
  72. /// if (X < 3) {
  73. ///
  74. /// In this case, the unconditional branch at the end of the first if can be
  75. /// revectored to the false side of the second if.
  76. ///
  77. class JumpThreading : public FunctionPass {
  78. JumpThreadingPass Impl;
  79. public:
  80. static char ID; // Pass identification
  81. JumpThreading(int T = -1) : FunctionPass(ID), Impl(T) {
  82. initializeJumpThreadingPass(*PassRegistry::getPassRegistry());
  83. }
  84. bool runOnFunction(Function &F) override;
  85. void getAnalysisUsage(AnalysisUsage &AU) const override {
  86. AU.addRequired<AAResultsWrapperPass>();
  87. AU.addRequired<LazyValueInfoWrapperPass>();
  88. AU.addPreserved<LazyValueInfoWrapperPass>();
  89. AU.addPreserved<GlobalsAAWrapperPass>();
  90. AU.addRequired<TargetLibraryInfoWrapperPass>();
  91. }
  92. void releaseMemory() override { Impl.releaseMemory(); }
  93. };
  94. }
  95. char JumpThreading::ID = 0;
  96. INITIALIZE_PASS_BEGIN(JumpThreading, "jump-threading",
  97. "Jump Threading", false, false)
  98. INITIALIZE_PASS_DEPENDENCY(LazyValueInfoWrapperPass)
  99. INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
  100. INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
  101. INITIALIZE_PASS_END(JumpThreading, "jump-threading",
  102. "Jump Threading", false, false)
  103. // Public interface to the Jump Threading pass
  104. FunctionPass *llvm::createJumpThreadingPass(int Threshold) { return new JumpThreading(Threshold); }
  105. JumpThreadingPass::JumpThreadingPass(int T) {
  106. BBDupThreshold = (T == -1) ? BBDuplicateThreshold : unsigned(T);
  107. }
  108. /// runOnFunction - Top level algorithm.
  109. ///
  110. bool JumpThreading::runOnFunction(Function &F) {
  111. if (skipFunction(F))
  112. return false;
  113. auto TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
  114. auto LVI = &getAnalysis<LazyValueInfoWrapperPass>().getLVI();
  115. auto AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
  116. std::unique_ptr<BlockFrequencyInfo> BFI;
  117. std::unique_ptr<BranchProbabilityInfo> BPI;
  118. bool HasProfileData = F.getEntryCount().hasValue();
  119. if (HasProfileData) {
  120. LoopInfo LI{DominatorTree(F)};
  121. BPI.reset(new BranchProbabilityInfo(F, LI));
  122. BFI.reset(new BlockFrequencyInfo(F, *BPI, LI));
  123. }
  124. return Impl.runImpl(F, TLI, LVI, AA, HasProfileData, std::move(BFI),
  125. std::move(BPI));
  126. }
  127. PreservedAnalyses JumpThreadingPass::run(Function &F,
  128. FunctionAnalysisManager &AM) {
  129. auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
  130. auto &LVI = AM.getResult<LazyValueAnalysis>(F);
  131. auto &AA = AM.getResult<AAManager>(F);
  132. std::unique_ptr<BlockFrequencyInfo> BFI;
  133. std::unique_ptr<BranchProbabilityInfo> BPI;
  134. bool HasProfileData = F.getEntryCount().hasValue();
  135. if (HasProfileData) {
  136. LoopInfo LI{DominatorTree(F)};
  137. BPI.reset(new BranchProbabilityInfo(F, LI));
  138. BFI.reset(new BlockFrequencyInfo(F, *BPI, LI));
  139. }
  140. bool Changed = runImpl(F, &TLI, &LVI, &AA, HasProfileData, std::move(BFI),
  141. std::move(BPI));
  142. if (!Changed)
  143. return PreservedAnalyses::all();
  144. PreservedAnalyses PA;
  145. PA.preserve<GlobalsAA>();
  146. return PA;
  147. }
  148. bool JumpThreadingPass::runImpl(Function &F, TargetLibraryInfo *TLI_,
  149. LazyValueInfo *LVI_, AliasAnalysis *AA_,
  150. bool HasProfileData_,
  151. std::unique_ptr<BlockFrequencyInfo> BFI_,
  152. std::unique_ptr<BranchProbabilityInfo> BPI_) {
  153. DEBUG(dbgs() << "Jump threading on function '" << F.getName() << "'\n");
  154. TLI = TLI_;
  155. LVI = LVI_;
  156. AA = AA_;
  157. BFI.reset();
  158. BPI.reset();
  159. // When profile data is available, we need to update edge weights after
  160. // successful jump threading, which requires both BPI and BFI being available.
  161. HasProfileData = HasProfileData_;
  162. auto *GuardDecl = F.getParent()->getFunction(
  163. Intrinsic::getName(Intrinsic::experimental_guard));
  164. HasGuards = GuardDecl && !GuardDecl->use_empty();
  165. if (HasProfileData) {
  166. BPI = std::move(BPI_);
  167. BFI = std::move(BFI_);
  168. }
  169. // Remove unreachable blocks from function as they may result in infinite
  170. // loop. We do threading if we found something profitable. Jump threading a
  171. // branch can create other opportunities. If these opportunities form a cycle
  172. // i.e. if any jump threading is undoing previous threading in the path, then
  173. // we will loop forever. We take care of this issue by not jump threading for
  174. // back edges. This works for normal cases but not for unreachable blocks as
  175. // they may have cycle with no back edge.
  176. bool EverChanged = false;
  177. EverChanged |= removeUnreachableBlocks(F, LVI);
  178. FindLoopHeaders(F);
  179. bool Changed;
  180. do {
  181. Changed = false;
  182. for (Function::iterator I = F.begin(), E = F.end(); I != E;) {
  183. BasicBlock *BB = &*I;
  184. // Thread all of the branches we can over this block.
  185. while (ProcessBlock(BB))
  186. Changed = true;
  187. ++I;
  188. // If the block is trivially dead, zap it. This eliminates the successor
  189. // edges which simplifies the CFG.
  190. if (pred_empty(BB) &&
  191. BB != &BB->getParent()->getEntryBlock()) {
  192. DEBUG(dbgs() << " JT: Deleting dead block '" << BB->getName()
  193. << "' with terminator: " << *BB->getTerminator() << '\n');
  194. LoopHeaders.erase(BB);
  195. LVI->eraseBlock(BB);
  196. DeleteDeadBlock(BB);
  197. Changed = true;
  198. continue;
  199. }
  200. BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
  201. // Can't thread an unconditional jump, but if the block is "almost
  202. // empty", we can replace uses of it with uses of the successor and make
  203. // this dead.
  204. // We should not eliminate the loop header either, because eliminating
  205. // a loop header might later prevent LoopSimplify from transforming nested
  206. // loops into simplified form.
  207. if (BI && BI->isUnconditional() &&
  208. BB != &BB->getParent()->getEntryBlock() &&
  209. // If the terminator is the only non-phi instruction, try to nuke it.
  210. BB->getFirstNonPHIOrDbg()->isTerminator() && !LoopHeaders.count(BB)) {
  211. // FIXME: It is always conservatively correct to drop the info
  212. // for a block even if it doesn't get erased. This isn't totally
  213. // awesome, but it allows us to use AssertingVH to prevent nasty
  214. // dangling pointer issues within LazyValueInfo.
  215. LVI->eraseBlock(BB);
  216. if (TryToSimplifyUncondBranchFromEmptyBlock(BB))
  217. Changed = true;
  218. }
  219. }
  220. EverChanged |= Changed;
  221. } while (Changed);
  222. LoopHeaders.clear();
  223. return EverChanged;
  224. }
  225. /// Return the cost of duplicating a piece of this block from first non-phi
  226. /// and before StopAt instruction to thread across it. Stop scanning the block
  227. /// when exceeding the threshold. If duplication is impossible, returns ~0U.
  228. static unsigned getJumpThreadDuplicationCost(BasicBlock *BB,
  229. Instruction *StopAt,
  230. unsigned Threshold) {
  231. assert(StopAt->getParent() == BB && "Not an instruction from proper BB?");
  232. /// Ignore PHI nodes, these will be flattened when duplication happens.
  233. BasicBlock::const_iterator I(BB->getFirstNonPHI());
  234. // FIXME: THREADING will delete values that are just used to compute the
  235. // branch, so they shouldn't count against the duplication cost.
  236. unsigned Bonus = 0;
  237. if (BB->getTerminator() == StopAt) {
  238. // Threading through a switch statement is particularly profitable. If this
  239. // block ends in a switch, decrease its cost to make it more likely to
  240. // happen.
  241. if (isa<SwitchInst>(StopAt))
  242. Bonus = 6;
  243. // The same holds for indirect branches, but slightly more so.
  244. if (isa<IndirectBrInst>(StopAt))
  245. Bonus = 8;
  246. }
  247. // Bump the threshold up so the early exit from the loop doesn't skip the
  248. // terminator-based Size adjustment at the end.
  249. Threshold += Bonus;
  250. // Sum up the cost of each instruction until we get to the terminator. Don't
  251. // include the terminator because the copy won't include it.
  252. unsigned Size = 0;
  253. for (; &*I != StopAt; ++I) {
  254. // Stop scanning the block if we've reached the threshold.
  255. if (Size > Threshold)
  256. return Size;
  257. // Debugger intrinsics don't incur code size.
  258. if (isa<DbgInfoIntrinsic>(I)) continue;
  259. // If this is a pointer->pointer bitcast, it is free.
  260. if (isa<BitCastInst>(I) && I->getType()->isPointerTy())
  261. continue;
  262. // Bail out if this instruction gives back a token type, it is not possible
  263. // to duplicate it if it is used outside this BB.
  264. if (I->getType()->isTokenTy() && I->isUsedOutsideOfBlock(BB))
  265. return ~0U;
  266. // All other instructions count for at least one unit.
  267. ++Size;
  268. // Calls are more expensive. If they are non-intrinsic calls, we model them
  269. // as having cost of 4. If they are a non-vector intrinsic, we model them
  270. // as having cost of 2 total, and if they are a vector intrinsic, we model
  271. // them as having cost 1.
  272. if (const CallInst *CI = dyn_cast<CallInst>(I)) {
  273. if (CI->cannotDuplicate() || CI->isConvergent())
  274. // Blocks with NoDuplicate are modelled as having infinite cost, so they
  275. // are never duplicated.
  276. return ~0U;
  277. else if (!isa<IntrinsicInst>(CI))
  278. Size += 3;
  279. else if (!CI->getType()->isVectorTy())
  280. Size += 1;
  281. }
  282. }
  283. return Size > Bonus ? Size - Bonus : 0;
  284. }
  285. /// FindLoopHeaders - We do not want jump threading to turn proper loop
  286. /// structures into irreducible loops. Doing this breaks up the loop nesting
  287. /// hierarchy and pessimizes later transformations. To prevent this from
  288. /// happening, we first have to find the loop headers. Here we approximate this
  289. /// by finding targets of backedges in the CFG.
  290. ///
  291. /// Note that there definitely are cases when we want to allow threading of
  292. /// edges across a loop header. For example, threading a jump from outside the
  293. /// loop (the preheader) to an exit block of the loop is definitely profitable.
  294. /// It is also almost always profitable to thread backedges from within the loop
  295. /// to exit blocks, and is often profitable to thread backedges to other blocks
  296. /// within the loop (forming a nested loop). This simple analysis is not rich
  297. /// enough to track all of these properties and keep it up-to-date as the CFG
  298. /// mutates, so we don't allow any of these transformations.
  299. ///
  300. void JumpThreadingPass::FindLoopHeaders(Function &F) {
  301. SmallVector<std::pair<const BasicBlock*,const BasicBlock*>, 32> Edges;
  302. FindFunctionBackedges(F, Edges);
  303. for (const auto &Edge : Edges)
  304. LoopHeaders.insert(Edge.second);
  305. }
  306. /// getKnownConstant - Helper method to determine if we can thread over a
  307. /// terminator with the given value as its condition, and if so what value to
  308. /// use for that. What kind of value this is depends on whether we want an
  309. /// integer or a block address, but an undef is always accepted.
  310. /// Returns null if Val is null or not an appropriate constant.
  311. static Constant *getKnownConstant(Value *Val, ConstantPreference Preference) {
  312. if (!Val)
  313. return nullptr;
  314. // Undef is "known" enough.
  315. if (UndefValue *U = dyn_cast<UndefValue>(Val))
  316. return U;
  317. if (Preference == WantBlockAddress)
  318. return dyn_cast<BlockAddress>(Val->stripPointerCasts());
  319. return dyn_cast<ConstantInt>(Val);
  320. }
  321. /// ComputeValueKnownInPredecessors - Given a basic block BB and a value V, see
  322. /// if we can infer that the value is a known ConstantInt/BlockAddress or undef
  323. /// in any of our predecessors. If so, return the known list of value and pred
  324. /// BB in the result vector.
  325. ///
  326. /// This returns true if there were any known values.
  327. ///
  328. bool JumpThreadingPass::ComputeValueKnownInPredecessors(
  329. Value *V, BasicBlock *BB, PredValueInfo &Result,
  330. ConstantPreference Preference, Instruction *CxtI) {
  331. // This method walks up use-def chains recursively. Because of this, we could
  332. // get into an infinite loop going around loops in the use-def chain. To
  333. // prevent this, keep track of what (value, block) pairs we've already visited
  334. // and terminate the search if we loop back to them
  335. if (!RecursionSet.insert(std::make_pair(V, BB)).second)
  336. return false;
  337. // An RAII help to remove this pair from the recursion set once the recursion
  338. // stack pops back out again.
  339. RecursionSetRemover remover(RecursionSet, std::make_pair(V, BB));
  340. // If V is a constant, then it is known in all predecessors.
  341. if (Constant *KC = getKnownConstant(V, Preference)) {
  342. for (BasicBlock *Pred : predecessors(BB))
  343. Result.push_back(std::make_pair(KC, Pred));
  344. return !Result.empty();
  345. }
  346. // If V is a non-instruction value, or an instruction in a different block,
  347. // then it can't be derived from a PHI.
  348. Instruction *I = dyn_cast<Instruction>(V);
  349. if (!I || I->getParent() != BB) {
  350. // Okay, if this is a live-in value, see if it has a known value at the end
  351. // of any of our predecessors.
  352. //
  353. // FIXME: This should be an edge property, not a block end property.
  354. /// TODO: Per PR2563, we could infer value range information about a
  355. /// predecessor based on its terminator.
  356. //
  357. // FIXME: change this to use the more-rich 'getPredicateOnEdge' method if
  358. // "I" is a non-local compare-with-a-constant instruction. This would be
  359. // able to handle value inequalities better, for example if the compare is
  360. // "X < 4" and "X < 3" is known true but "X < 4" itself is not available.
  361. // Perhaps getConstantOnEdge should be smart enough to do this?
  362. for (BasicBlock *P : predecessors(BB)) {
  363. // If the value is known by LazyValueInfo to be a constant in a
  364. // predecessor, use that information to try to thread this block.
  365. Constant *PredCst = LVI->getConstantOnEdge(V, P, BB, CxtI);
  366. if (Constant *KC = getKnownConstant(PredCst, Preference))
  367. Result.push_back(std::make_pair(KC, P));
  368. }
  369. return !Result.empty();
  370. }
  371. /// If I is a PHI node, then we know the incoming values for any constants.
  372. if (PHINode *PN = dyn_cast<PHINode>(I)) {
  373. for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
  374. Value *InVal = PN->getIncomingValue(i);
  375. if (Constant *KC = getKnownConstant(InVal, Preference)) {
  376. Result.push_back(std::make_pair(KC, PN->getIncomingBlock(i)));
  377. } else {
  378. Constant *CI = LVI->getConstantOnEdge(InVal,
  379. PN->getIncomingBlock(i),
  380. BB, CxtI);
  381. if (Constant *KC = getKnownConstant(CI, Preference))
  382. Result.push_back(std::make_pair(KC, PN->getIncomingBlock(i)));
  383. }
  384. }
  385. return !Result.empty();
  386. }
  387. // Handle Cast instructions. Only see through Cast when the source operand is
  388. // PHI or Cmp and the source type is i1 to save the compilation time.
  389. if (CastInst *CI = dyn_cast<CastInst>(I)) {
  390. Value *Source = CI->getOperand(0);
  391. if (!Source->getType()->isIntegerTy(1))
  392. return false;
  393. if (!isa<PHINode>(Source) && !isa<CmpInst>(Source))
  394. return false;
  395. ComputeValueKnownInPredecessors(Source, BB, Result, Preference, CxtI);
  396. if (Result.empty())
  397. return false;
  398. // Convert the known values.
  399. for (auto &R : Result)
  400. R.first = ConstantExpr::getCast(CI->getOpcode(), R.first, CI->getType());
  401. return true;
  402. }
  403. PredValueInfoTy LHSVals, RHSVals;
  404. // Handle some boolean conditions.
  405. if (I->getType()->getPrimitiveSizeInBits() == 1) {
  406. assert(Preference == WantInteger && "One-bit non-integer type?");
  407. // X | true -> true
  408. // X & false -> false
  409. if (I->getOpcode() == Instruction::Or ||
  410. I->getOpcode() == Instruction::And) {
  411. ComputeValueKnownInPredecessors(I->getOperand(0), BB, LHSVals,
  412. WantInteger, CxtI);
  413. ComputeValueKnownInPredecessors(I->getOperand(1), BB, RHSVals,
  414. WantInteger, CxtI);
  415. if (LHSVals.empty() && RHSVals.empty())
  416. return false;
  417. ConstantInt *InterestingVal;
  418. if (I->getOpcode() == Instruction::Or)
  419. InterestingVal = ConstantInt::getTrue(I->getContext());
  420. else
  421. InterestingVal = ConstantInt::getFalse(I->getContext());
  422. SmallPtrSet<BasicBlock*, 4> LHSKnownBBs;
  423. // Scan for the sentinel. If we find an undef, force it to the
  424. // interesting value: x|undef -> true and x&undef -> false.
  425. for (const auto &LHSVal : LHSVals)
  426. if (LHSVal.first == InterestingVal || isa<UndefValue>(LHSVal.first)) {
  427. Result.emplace_back(InterestingVal, LHSVal.second);
  428. LHSKnownBBs.insert(LHSVal.second);
  429. }
  430. for (const auto &RHSVal : RHSVals)
  431. if (RHSVal.first == InterestingVal || isa<UndefValue>(RHSVal.first)) {
  432. // If we already inferred a value for this block on the LHS, don't
  433. // re-add it.
  434. if (!LHSKnownBBs.count(RHSVal.second))
  435. Result.emplace_back(InterestingVal, RHSVal.second);
  436. }
  437. return !Result.empty();
  438. }
  439. // Handle the NOT form of XOR.
  440. if (I->getOpcode() == Instruction::Xor &&
  441. isa<ConstantInt>(I->getOperand(1)) &&
  442. cast<ConstantInt>(I->getOperand(1))->isOne()) {
  443. ComputeValueKnownInPredecessors(I->getOperand(0), BB, Result,
  444. WantInteger, CxtI);
  445. if (Result.empty())
  446. return false;
  447. // Invert the known values.
  448. for (auto &R : Result)
  449. R.first = ConstantExpr::getNot(R.first);
  450. return true;
  451. }
  452. // Try to simplify some other binary operator values.
  453. } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
  454. assert(Preference != WantBlockAddress
  455. && "A binary operator creating a block address?");
  456. if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1))) {
  457. PredValueInfoTy LHSVals;
  458. ComputeValueKnownInPredecessors(BO->getOperand(0), BB, LHSVals,
  459. WantInteger, CxtI);
  460. // Try to use constant folding to simplify the binary operator.
  461. for (const auto &LHSVal : LHSVals) {
  462. Constant *V = LHSVal.first;
  463. Constant *Folded = ConstantExpr::get(BO->getOpcode(), V, CI);
  464. if (Constant *KC = getKnownConstant(Folded, WantInteger))
  465. Result.push_back(std::make_pair(KC, LHSVal.second));
  466. }
  467. }
  468. return !Result.empty();
  469. }
  470. // Handle compare with phi operand, where the PHI is defined in this block.
  471. if (CmpInst *Cmp = dyn_cast<CmpInst>(I)) {
  472. assert(Preference == WantInteger && "Compares only produce integers");
  473. PHINode *PN = dyn_cast<PHINode>(Cmp->getOperand(0));
  474. if (PN && PN->getParent() == BB) {
  475. const DataLayout &DL = PN->getModule()->getDataLayout();
  476. // We can do this simplification if any comparisons fold to true or false.
  477. // See if any do.
  478. for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
  479. BasicBlock *PredBB = PN->getIncomingBlock(i);
  480. Value *LHS = PN->getIncomingValue(i);
  481. Value *RHS = Cmp->getOperand(1)->DoPHITranslation(BB, PredBB);
  482. Value *Res = SimplifyCmpInst(Cmp->getPredicate(), LHS, RHS, DL);
  483. if (!Res) {
  484. if (!isa<Constant>(RHS))
  485. continue;
  486. LazyValueInfo::Tristate
  487. ResT = LVI->getPredicateOnEdge(Cmp->getPredicate(), LHS,
  488. cast<Constant>(RHS), PredBB, BB,
  489. CxtI ? CxtI : Cmp);
  490. if (ResT == LazyValueInfo::Unknown)
  491. continue;
  492. Res = ConstantInt::get(Type::getInt1Ty(LHS->getContext()), ResT);
  493. }
  494. if (Constant *KC = getKnownConstant(Res, WantInteger))
  495. Result.push_back(std::make_pair(KC, PredBB));
  496. }
  497. return !Result.empty();
  498. }
  499. // If comparing a live-in value against a constant, see if we know the
  500. // live-in value on any predecessors.
  501. if (isa<Constant>(Cmp->getOperand(1)) && Cmp->getType()->isIntegerTy()) {
  502. if (!isa<Instruction>(Cmp->getOperand(0)) ||
  503. cast<Instruction>(Cmp->getOperand(0))->getParent() != BB) {
  504. Constant *RHSCst = cast<Constant>(Cmp->getOperand(1));
  505. for (BasicBlock *P : predecessors(BB)) {
  506. // If the value is known by LazyValueInfo to be a constant in a
  507. // predecessor, use that information to try to thread this block.
  508. LazyValueInfo::Tristate Res =
  509. LVI->getPredicateOnEdge(Cmp->getPredicate(), Cmp->getOperand(0),
  510. RHSCst, P, BB, CxtI ? CxtI : Cmp);
  511. if (Res == LazyValueInfo::Unknown)
  512. continue;
  513. Constant *ResC = ConstantInt::get(Cmp->getType(), Res);
  514. Result.push_back(std::make_pair(ResC, P));
  515. }
  516. return !Result.empty();
  517. }
  518. // Try to find a constant value for the LHS of a comparison,
  519. // and evaluate it statically if we can.
  520. if (Constant *CmpConst = dyn_cast<Constant>(Cmp->getOperand(1))) {
  521. PredValueInfoTy LHSVals;
  522. ComputeValueKnownInPredecessors(I->getOperand(0), BB, LHSVals,
  523. WantInteger, CxtI);
  524. for (const auto &LHSVal : LHSVals) {
  525. Constant *V = LHSVal.first;
  526. Constant *Folded = ConstantExpr::getCompare(Cmp->getPredicate(),
  527. V, CmpConst);
  528. if (Constant *KC = getKnownConstant(Folded, WantInteger))
  529. Result.push_back(std::make_pair(KC, LHSVal.second));
  530. }
  531. return !Result.empty();
  532. }
  533. }
  534. }
  535. if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
  536. // Handle select instructions where at least one operand is a known constant
  537. // and we can figure out the condition value for any predecessor block.
  538. Constant *TrueVal = getKnownConstant(SI->getTrueValue(), Preference);
  539. Constant *FalseVal = getKnownConstant(SI->getFalseValue(), Preference);
  540. PredValueInfoTy Conds;
  541. if ((TrueVal || FalseVal) &&
  542. ComputeValueKnownInPredecessors(SI->getCondition(), BB, Conds,
  543. WantInteger, CxtI)) {
  544. for (auto &C : Conds) {
  545. Constant *Cond = C.first;
  546. // Figure out what value to use for the condition.
  547. bool KnownCond;
  548. if (ConstantInt *CI = dyn_cast<ConstantInt>(Cond)) {
  549. // A known boolean.
  550. KnownCond = CI->isOne();
  551. } else {
  552. assert(isa<UndefValue>(Cond) && "Unexpected condition value");
  553. // Either operand will do, so be sure to pick the one that's a known
  554. // constant.
  555. // FIXME: Do this more cleverly if both values are known constants?
  556. KnownCond = (TrueVal != nullptr);
  557. }
  558. // See if the select has a known constant value for this predecessor.
  559. if (Constant *Val = KnownCond ? TrueVal : FalseVal)
  560. Result.push_back(std::make_pair(Val, C.second));
  561. }
  562. return !Result.empty();
  563. }
  564. }
  565. // If all else fails, see if LVI can figure out a constant value for us.
  566. Constant *CI = LVI->getConstant(V, BB, CxtI);
  567. if (Constant *KC = getKnownConstant(CI, Preference)) {
  568. for (BasicBlock *Pred : predecessors(BB))
  569. Result.push_back(std::make_pair(KC, Pred));
  570. }
  571. return !Result.empty();
  572. }
  573. /// GetBestDestForBranchOnUndef - If we determine that the specified block ends
  574. /// in an undefined jump, decide which block is best to revector to.
  575. ///
  576. /// Since we can pick an arbitrary destination, we pick the successor with the
  577. /// fewest predecessors. This should reduce the in-degree of the others.
  578. ///
  579. static unsigned GetBestDestForJumpOnUndef(BasicBlock *BB) {
  580. TerminatorInst *BBTerm = BB->getTerminator();
  581. unsigned MinSucc = 0;
  582. BasicBlock *TestBB = BBTerm->getSuccessor(MinSucc);
  583. // Compute the successor with the minimum number of predecessors.
  584. unsigned MinNumPreds = std::distance(pred_begin(TestBB), pred_end(TestBB));
  585. for (unsigned i = 1, e = BBTerm->getNumSuccessors(); i != e; ++i) {
  586. TestBB = BBTerm->getSuccessor(i);
  587. unsigned NumPreds = std::distance(pred_begin(TestBB), pred_end(TestBB));
  588. if (NumPreds < MinNumPreds) {
  589. MinSucc = i;
  590. MinNumPreds = NumPreds;
  591. }
  592. }
  593. return MinSucc;
  594. }
  595. static bool hasAddressTakenAndUsed(BasicBlock *BB) {
  596. if (!BB->hasAddressTaken()) return false;
  597. // If the block has its address taken, it may be a tree of dead constants
  598. // hanging off of it. These shouldn't keep the block alive.
  599. BlockAddress *BA = BlockAddress::get(BB);
  600. BA->removeDeadConstantUsers();
  601. return !BA->use_empty();
  602. }
  603. /// ProcessBlock - If there are any predecessors whose control can be threaded
  604. /// through to a successor, transform them now.
  605. bool JumpThreadingPass::ProcessBlock(BasicBlock *BB) {
  606. // If the block is trivially dead, just return and let the caller nuke it.
  607. // This simplifies other transformations.
  608. if (pred_empty(BB) &&
  609. BB != &BB->getParent()->getEntryBlock())
  610. return false;
  611. // If this block has a single predecessor, and if that pred has a single
  612. // successor, merge the blocks. This encourages recursive jump threading
  613. // because now the condition in this block can be threaded through
  614. // predecessors of our predecessor block.
  615. if (BasicBlock *SinglePred = BB->getSinglePredecessor()) {
  616. const TerminatorInst *TI = SinglePred->getTerminator();
  617. if (!TI->isExceptional() && TI->getNumSuccessors() == 1 &&
  618. SinglePred != BB && !hasAddressTakenAndUsed(BB)) {
  619. // If SinglePred was a loop header, BB becomes one.
  620. if (LoopHeaders.erase(SinglePred))
  621. LoopHeaders.insert(BB);
  622. LVI->eraseBlock(SinglePred);
  623. MergeBasicBlockIntoOnlyPred(BB);
  624. return true;
  625. }
  626. }
  627. if (TryToUnfoldSelectInCurrBB(BB))
  628. return true;
  629. // Look if we can propagate guards to predecessors.
  630. if (HasGuards && ProcessGuards(BB))
  631. return true;
  632. // What kind of constant we're looking for.
  633. ConstantPreference Preference = WantInteger;
  634. // Look to see if the terminator is a conditional branch, switch or indirect
  635. // branch, if not we can't thread it.
  636. Value *Condition;
  637. Instruction *Terminator = BB->getTerminator();
  638. if (BranchInst *BI = dyn_cast<BranchInst>(Terminator)) {
  639. // Can't thread an unconditional jump.
  640. if (BI->isUnconditional()) return false;
  641. Condition = BI->getCondition();
  642. } else if (SwitchInst *SI = dyn_cast<SwitchInst>(Terminator)) {
  643. Condition = SI->getCondition();
  644. } else if (IndirectBrInst *IB = dyn_cast<IndirectBrInst>(Terminator)) {
  645. // Can't thread indirect branch with no successors.
  646. if (IB->getNumSuccessors() == 0) return false;
  647. Condition = IB->getAddress()->stripPointerCasts();
  648. Preference = WantBlockAddress;
  649. } else {
  650. return false; // Must be an invoke.
  651. }
  652. // Run constant folding to see if we can reduce the condition to a simple
  653. // constant.
  654. if (Instruction *I = dyn_cast<Instruction>(Condition)) {
  655. Value *SimpleVal =
  656. ConstantFoldInstruction(I, BB->getModule()->getDataLayout(), TLI);
  657. if (SimpleVal) {
  658. I->replaceAllUsesWith(SimpleVal);
  659. if (isInstructionTriviallyDead(I, TLI))
  660. I->eraseFromParent();
  661. Condition = SimpleVal;
  662. }
  663. }
  664. // If the terminator is branching on an undef, we can pick any of the
  665. // successors to branch to. Let GetBestDestForJumpOnUndef decide.
  666. if (isa<UndefValue>(Condition)) {
  667. unsigned BestSucc = GetBestDestForJumpOnUndef(BB);
  668. // Fold the branch/switch.
  669. TerminatorInst *BBTerm = BB->getTerminator();
  670. for (unsigned i = 0, e = BBTerm->getNumSuccessors(); i != e; ++i) {
  671. if (i == BestSucc) continue;
  672. BBTerm->getSuccessor(i)->removePredecessor(BB, true);
  673. }
  674. DEBUG(dbgs() << " In block '" << BB->getName()
  675. << "' folding undef terminator: " << *BBTerm << '\n');
  676. BranchInst::Create(BBTerm->getSuccessor(BestSucc), BBTerm);
  677. BBTerm->eraseFromParent();
  678. return true;
  679. }
  680. // If the terminator of this block is branching on a constant, simplify the
  681. // terminator to an unconditional branch. This can occur due to threading in
  682. // other blocks.
  683. if (getKnownConstant(Condition, Preference)) {
  684. DEBUG(dbgs() << " In block '" << BB->getName()
  685. << "' folding terminator: " << *BB->getTerminator() << '\n');
  686. ++NumFolds;
  687. ConstantFoldTerminator(BB, true);
  688. return true;
  689. }
  690. Instruction *CondInst = dyn_cast<Instruction>(Condition);
  691. // All the rest of our checks depend on the condition being an instruction.
  692. if (!CondInst) {
  693. // FIXME: Unify this with code below.
  694. if (ProcessThreadableEdges(Condition, BB, Preference, Terminator))
  695. return true;
  696. return false;
  697. }
  698. if (CmpInst *CondCmp = dyn_cast<CmpInst>(CondInst)) {
  699. // If we're branching on a conditional, LVI might be able to determine
  700. // it's value at the branch instruction. We only handle comparisons
  701. // against a constant at this time.
  702. // TODO: This should be extended to handle switches as well.
  703. BranchInst *CondBr = dyn_cast<BranchInst>(BB->getTerminator());
  704. Constant *CondConst = dyn_cast<Constant>(CondCmp->getOperand(1));
  705. if (CondBr && CondConst) {
  706. // We should have returned as soon as we turn a conditional branch to
  707. // unconditional. Because its no longer interesting as far as jump
  708. // threading is concerned.
  709. assert(CondBr->isConditional() && "Threading on unconditional terminator");
  710. LazyValueInfo::Tristate Ret =
  711. LVI->getPredicateAt(CondCmp->getPredicate(), CondCmp->getOperand(0),
  712. CondConst, CondBr);
  713. if (Ret != LazyValueInfo::Unknown) {
  714. unsigned ToRemove = Ret == LazyValueInfo::True ? 1 : 0;
  715. unsigned ToKeep = Ret == LazyValueInfo::True ? 0 : 1;
  716. CondBr->getSuccessor(ToRemove)->removePredecessor(BB, true);
  717. BranchInst::Create(CondBr->getSuccessor(ToKeep), CondBr);
  718. CondBr->eraseFromParent();
  719. if (CondCmp->use_empty())
  720. CondCmp->eraseFromParent();
  721. else if (CondCmp->getParent() == BB) {
  722. // If the fact we just learned is true for all uses of the
  723. // condition, replace it with a constant value
  724. auto *CI = Ret == LazyValueInfo::True ?
  725. ConstantInt::getTrue(CondCmp->getType()) :
  726. ConstantInt::getFalse(CondCmp->getType());
  727. CondCmp->replaceAllUsesWith(CI);
  728. CondCmp->eraseFromParent();
  729. }
  730. return true;
  731. }
  732. // We did not manage to simplify this branch, try to see whether
  733. // CondCmp depends on a known phi-select pattern.
  734. if (TryToUnfoldSelect(CondCmp, BB))
  735. return true;
  736. }
  737. }
  738. // Check for some cases that are worth simplifying. Right now we want to look
  739. // for loads that are used by a switch or by the condition for the branch. If
  740. // we see one, check to see if it's partially redundant. If so, insert a PHI
  741. // which can then be used to thread the values.
  742. //
  743. Value *SimplifyValue = CondInst;
  744. if (CmpInst *CondCmp = dyn_cast<CmpInst>(SimplifyValue))
  745. if (isa<Constant>(CondCmp->getOperand(1)))
  746. SimplifyValue = CondCmp->getOperand(0);
  747. // TODO: There are other places where load PRE would be profitable, such as
  748. // more complex comparisons.
  749. if (LoadInst *LI = dyn_cast<LoadInst>(SimplifyValue))
  750. if (SimplifyPartiallyRedundantLoad(LI))
  751. return true;
  752. // Handle a variety of cases where we are branching on something derived from
  753. // a PHI node in the current block. If we can prove that any predecessors
  754. // compute a predictable value based on a PHI node, thread those predecessors.
  755. //
  756. if (ProcessThreadableEdges(CondInst, BB, Preference, Terminator))
  757. return true;
  758. // If this is an otherwise-unfoldable branch on a phi node in the current
  759. // block, see if we can simplify.
  760. if (PHINode *PN = dyn_cast<PHINode>(CondInst))
  761. if (PN->getParent() == BB && isa<BranchInst>(BB->getTerminator()))
  762. return ProcessBranchOnPHI(PN);
  763. // If this is an otherwise-unfoldable branch on a XOR, see if we can simplify.
  764. if (CondInst->getOpcode() == Instruction::Xor &&
  765. CondInst->getParent() == BB && isa<BranchInst>(BB->getTerminator()))
  766. return ProcessBranchOnXOR(cast<BinaryOperator>(CondInst));
  767. // Search for a stronger dominating condition that can be used to simplify a
  768. // conditional branch leaving BB.
  769. if (ProcessImpliedCondition(BB))
  770. return true;
  771. return false;
  772. }
  773. bool JumpThreadingPass::ProcessImpliedCondition(BasicBlock *BB) {
  774. auto *BI = dyn_cast<BranchInst>(BB->getTerminator());
  775. if (!BI || !BI->isConditional())
  776. return false;
  777. Value *Cond = BI->getCondition();
  778. BasicBlock *CurrentBB = BB;
  779. BasicBlock *CurrentPred = BB->getSinglePredecessor();
  780. unsigned Iter = 0;
  781. auto &DL = BB->getModule()->getDataLayout();
  782. while (CurrentPred && Iter++ < ImplicationSearchThreshold) {
  783. auto *PBI = dyn_cast<BranchInst>(CurrentPred->getTerminator());
  784. if (!PBI || !PBI->isConditional())
  785. return false;
  786. if (PBI->getSuccessor(0) != CurrentBB && PBI->getSuccessor(1) != CurrentBB)
  787. return false;
  788. bool FalseDest = PBI->getSuccessor(1) == CurrentBB;
  789. Optional<bool> Implication =
  790. isImpliedCondition(PBI->getCondition(), Cond, DL, FalseDest);
  791. if (Implication) {
  792. BI->getSuccessor(*Implication ? 1 : 0)->removePredecessor(BB);
  793. BranchInst::Create(BI->getSuccessor(*Implication ? 0 : 1), BI);
  794. BI->eraseFromParent();
  795. return true;
  796. }
  797. CurrentBB = CurrentPred;
  798. CurrentPred = CurrentBB->getSinglePredecessor();
  799. }
  800. return false;
  801. }
  802. /// Return true if Op is an instruction defined in the given block.
  803. static bool isOpDefinedInBlock(Value *Op, BasicBlock *BB) {
  804. if (Instruction *OpInst = dyn_cast<Instruction>(Op))
  805. if (OpInst->getParent() == BB)
  806. return true;
  807. return false;
  808. }
  809. /// SimplifyPartiallyRedundantLoad - If LI is an obviously partially redundant
  810. /// load instruction, eliminate it by replacing it with a PHI node. This is an
  811. /// important optimization that encourages jump threading, and needs to be run
  812. /// interlaced with other jump threading tasks.
  813. bool JumpThreadingPass::SimplifyPartiallyRedundantLoad(LoadInst *LI) {
  814. // Don't hack volatile and ordered loads.
  815. if (!LI->isUnordered()) return false;
  816. // If the load is defined in a block with exactly one predecessor, it can't be
  817. // partially redundant.
  818. BasicBlock *LoadBB = LI->getParent();
  819. if (LoadBB->getSinglePredecessor())
  820. return false;
  821. // If the load is defined in an EH pad, it can't be partially redundant,
  822. // because the edges between the invoke and the EH pad cannot have other
  823. // instructions between them.
  824. if (LoadBB->isEHPad())
  825. return false;
  826. Value *LoadedPtr = LI->getOperand(0);
  827. // If the loaded operand is defined in the LoadBB and its not a phi,
  828. // it can't be available in predecessors.
  829. if (isOpDefinedInBlock(LoadedPtr, LoadBB) && !isa<PHINode>(LoadedPtr))
  830. return false;
  831. // Scan a few instructions up from the load, to see if it is obviously live at
  832. // the entry to its block.
  833. BasicBlock::iterator BBIt(LI);
  834. bool IsLoadCSE;
  835. if (Value *AvailableVal = FindAvailableLoadedValue(
  836. LI, LoadBB, BBIt, DefMaxInstsToScan, AA, &IsLoadCSE)) {
  837. // If the value of the load is locally available within the block, just use
  838. // it. This frequently occurs for reg2mem'd allocas.
  839. if (IsLoadCSE) {
  840. LoadInst *NLI = cast<LoadInst>(AvailableVal);
  841. combineMetadataForCSE(NLI, LI);
  842. };
  843. // If the returned value is the load itself, replace with an undef. This can
  844. // only happen in dead loops.
  845. if (AvailableVal == LI) AvailableVal = UndefValue::get(LI->getType());
  846. if (AvailableVal->getType() != LI->getType())
  847. AvailableVal =
  848. CastInst::CreateBitOrPointerCast(AvailableVal, LI->getType(), "", LI);
  849. LI->replaceAllUsesWith(AvailableVal);
  850. LI->eraseFromParent();
  851. return true;
  852. }
  853. // Otherwise, if we scanned the whole block and got to the top of the block,
  854. // we know the block is locally transparent to the load. If not, something
  855. // might clobber its value.
  856. if (BBIt != LoadBB->begin())
  857. return false;
  858. // If all of the loads and stores that feed the value have the same AA tags,
  859. // then we can propagate them onto any newly inserted loads.
  860. AAMDNodes AATags;
  861. LI->getAAMetadata(AATags);
  862. SmallPtrSet<BasicBlock*, 8> PredsScanned;
  863. typedef SmallVector<std::pair<BasicBlock*, Value*>, 8> AvailablePredsTy;
  864. AvailablePredsTy AvailablePreds;
  865. BasicBlock *OneUnavailablePred = nullptr;
  866. SmallVector<LoadInst*, 8> CSELoads;
  867. // If we got here, the loaded value is transparent through to the start of the
  868. // block. Check to see if it is available in any of the predecessor blocks.
  869. for (BasicBlock *PredBB : predecessors(LoadBB)) {
  870. // If we already scanned this predecessor, skip it.
  871. if (!PredsScanned.insert(PredBB).second)
  872. continue;
  873. BBIt = PredBB->end();
  874. unsigned NumScanedInst = 0;
  875. Value *PredAvailable = nullptr;
  876. // NOTE: We don't CSE load that is volatile or anything stronger than
  877. // unordered, that should have been checked when we entered the function.
  878. assert(LI->isUnordered() && "Attempting to CSE volatile or atomic loads");
  879. // If this is a load on a phi pointer, phi-translate it and search
  880. // for available load/store to the pointer in predecessors.
  881. Value *Ptr = LoadedPtr->DoPHITranslation(LoadBB, PredBB);
  882. PredAvailable = FindAvailablePtrLoadStore(
  883. Ptr, LI->getType(), LI->isAtomic(), PredBB, BBIt, DefMaxInstsToScan,
  884. AA, &IsLoadCSE, &NumScanedInst);
  885. // If PredBB has a single predecessor, continue scanning through the
  886. // single precessor.
  887. BasicBlock *SinglePredBB = PredBB;
  888. while (!PredAvailable && SinglePredBB && BBIt == SinglePredBB->begin() &&
  889. NumScanedInst < DefMaxInstsToScan) {
  890. SinglePredBB = SinglePredBB->getSinglePredecessor();
  891. if (SinglePredBB) {
  892. BBIt = SinglePredBB->end();
  893. PredAvailable = FindAvailablePtrLoadStore(
  894. Ptr, LI->getType(), LI->isAtomic(), SinglePredBB, BBIt,
  895. (DefMaxInstsToScan - NumScanedInst), AA, &IsLoadCSE,
  896. &NumScanedInst);
  897. }
  898. }
  899. if (!PredAvailable) {
  900. OneUnavailablePred = PredBB;
  901. continue;
  902. }
  903. if (IsLoadCSE)
  904. CSELoads.push_back(cast<LoadInst>(PredAvailable));
  905. // If so, this load is partially redundant. Remember this info so that we
  906. // can create a PHI node.
  907. AvailablePreds.push_back(std::make_pair(PredBB, PredAvailable));
  908. }
  909. // If the loaded value isn't available in any predecessor, it isn't partially
  910. // redundant.
  911. if (AvailablePreds.empty()) return false;
  912. // Okay, the loaded value is available in at least one (and maybe all!)
  913. // predecessors. If the value is unavailable in more than one unique
  914. // predecessor, we want to insert a merge block for those common predecessors.
  915. // This ensures that we only have to insert one reload, thus not increasing
  916. // code size.
  917. BasicBlock *UnavailablePred = nullptr;
  918. // If there is exactly one predecessor where the value is unavailable, the
  919. // already computed 'OneUnavailablePred' block is it. If it ends in an
  920. // unconditional branch, we know that it isn't a critical edge.
  921. if (PredsScanned.size() == AvailablePreds.size()+1 &&
  922. OneUnavailablePred->getTerminator()->getNumSuccessors() == 1) {
  923. UnavailablePred = OneUnavailablePred;
  924. } else if (PredsScanned.size() != AvailablePreds.size()) {
  925. // Otherwise, we had multiple unavailable predecessors or we had a critical
  926. // edge from the one.
  927. SmallVector<BasicBlock*, 8> PredsToSplit;
  928. SmallPtrSet<BasicBlock*, 8> AvailablePredSet;
  929. for (const auto &AvailablePred : AvailablePreds)
  930. AvailablePredSet.insert(AvailablePred.first);
  931. // Add all the unavailable predecessors to the PredsToSplit list.
  932. for (BasicBlock *P : predecessors(LoadBB)) {
  933. // If the predecessor is an indirect goto, we can't split the edge.
  934. if (isa<IndirectBrInst>(P->getTerminator()))
  935. return false;
  936. if (!AvailablePredSet.count(P))
  937. PredsToSplit.push_back(P);
  938. }
  939. // Split them out to their own block.
  940. UnavailablePred = SplitBlockPreds(LoadBB, PredsToSplit, "thread-pre-split");
  941. }
  942. // If the value isn't available in all predecessors, then there will be
  943. // exactly one where it isn't available. Insert a load on that edge and add
  944. // it to the AvailablePreds list.
  945. if (UnavailablePred) {
  946. assert(UnavailablePred->getTerminator()->getNumSuccessors() == 1 &&
  947. "Can't handle critical edge here!");
  948. LoadInst *NewVal = new LoadInst(
  949. LoadedPtr->DoPHITranslation(LoadBB, UnavailablePred),
  950. LI->getName() + ".pr", false, LI->getAlignment(), LI->getOrdering(),
  951. LI->getSynchScope(), UnavailablePred->getTerminator());
  952. NewVal->setDebugLoc(LI->getDebugLoc());
  953. if (AATags)
  954. NewVal->setAAMetadata(AATags);
  955. AvailablePreds.push_back(std::make_pair(UnavailablePred, NewVal));
  956. }
  957. // Now we know that each predecessor of this block has a value in
  958. // AvailablePreds, sort them for efficient access as we're walking the preds.
  959. array_pod_sort(AvailablePreds.begin(), AvailablePreds.end());
  960. // Create a PHI node at the start of the block for the PRE'd load value.
  961. pred_iterator PB = pred_begin(LoadBB), PE = pred_end(LoadBB);
  962. PHINode *PN = PHINode::Create(LI->getType(), std::distance(PB, PE), "",
  963. &LoadBB->front());
  964. PN->takeName(LI);
  965. PN->setDebugLoc(LI->getDebugLoc());
  966. // Insert new entries into the PHI for each predecessor. A single block may
  967. // have multiple entries here.
  968. for (pred_iterator PI = PB; PI != PE; ++PI) {
  969. BasicBlock *P = *PI;
  970. AvailablePredsTy::iterator I =
  971. std::lower_bound(AvailablePreds.begin(), AvailablePreds.end(),
  972. std::make_pair(P, (Value*)nullptr));
  973. assert(I != AvailablePreds.end() && I->first == P &&
  974. "Didn't find entry for predecessor!");
  975. // If we have an available predecessor but it requires casting, insert the
  976. // cast in the predecessor and use the cast. Note that we have to update the
  977. // AvailablePreds vector as we go so that all of the PHI entries for this
  978. // predecessor use the same bitcast.
  979. Value *&PredV = I->second;
  980. if (PredV->getType() != LI->getType())
  981. PredV = CastInst::CreateBitOrPointerCast(PredV, LI->getType(), "",
  982. P->getTerminator());
  983. PN->addIncoming(PredV, I->first);
  984. }
  985. for (LoadInst *PredLI : CSELoads) {
  986. combineMetadataForCSE(PredLI, LI);
  987. }
  988. LI->replaceAllUsesWith(PN);
  989. LI->eraseFromParent();
  990. return true;
  991. }
  992. /// FindMostPopularDest - The specified list contains multiple possible
  993. /// threadable destinations. Pick the one that occurs the most frequently in
  994. /// the list.
  995. static BasicBlock *
  996. FindMostPopularDest(BasicBlock *BB,
  997. const SmallVectorImpl<std::pair<BasicBlock*,
  998. BasicBlock*> > &PredToDestList) {
  999. assert(!PredToDestList.empty());
  1000. // Determine popularity. If there are multiple possible destinations, we
  1001. // explicitly choose to ignore 'undef' destinations. We prefer to thread
  1002. // blocks with known and real destinations to threading undef. We'll handle
  1003. // them later if interesting.
  1004. DenseMap<BasicBlock*, unsigned> DestPopularity;
  1005. for (const auto &PredToDest : PredToDestList)
  1006. if (PredToDest.second)
  1007. DestPopularity[PredToDest.second]++;
  1008. // Find the most popular dest.
  1009. DenseMap<BasicBlock*, unsigned>::iterator DPI = DestPopularity.begin();
  1010. BasicBlock *MostPopularDest = DPI->first;
  1011. unsigned Popularity = DPI->second;
  1012. SmallVector<BasicBlock*, 4> SamePopularity;
  1013. for (++DPI; DPI != DestPopularity.end(); ++DPI) {
  1014. // If the popularity of this entry isn't higher than the popularity we've
  1015. // seen so far, ignore it.
  1016. if (DPI->second < Popularity)
  1017. ; // ignore.
  1018. else if (DPI->second == Popularity) {
  1019. // If it is the same as what we've seen so far, keep track of it.
  1020. SamePopularity.push_back(DPI->first);
  1021. } else {
  1022. // If it is more popular, remember it.
  1023. SamePopularity.clear();
  1024. MostPopularDest = DPI->first;
  1025. Popularity = DPI->second;
  1026. }
  1027. }
  1028. // Okay, now we know the most popular destination. If there is more than one
  1029. // destination, we need to determine one. This is arbitrary, but we need
  1030. // to make a deterministic decision. Pick the first one that appears in the
  1031. // successor list.
  1032. if (!SamePopularity.empty()) {
  1033. SamePopularity.push_back(MostPopularDest);
  1034. TerminatorInst *TI = BB->getTerminator();
  1035. for (unsigned i = 0; ; ++i) {
  1036. assert(i != TI->getNumSuccessors() && "Didn't find any successor!");
  1037. if (!is_contained(SamePopularity, TI->getSuccessor(i)))
  1038. continue;
  1039. MostPopularDest = TI->getSuccessor(i);
  1040. break;
  1041. }
  1042. }
  1043. // Okay, we have finally picked the most popular destination.
  1044. return MostPopularDest;
  1045. }
  1046. bool JumpThreadingPass::ProcessThreadableEdges(Value *Cond, BasicBlock *BB,
  1047. ConstantPreference Preference,
  1048. Instruction *CxtI) {
  1049. // If threading this would thread across a loop header, don't even try to
  1050. // thread the edge.
  1051. if (LoopHeaders.count(BB))
  1052. return false;
  1053. PredValueInfoTy PredValues;
  1054. if (!ComputeValueKnownInPredecessors(Cond, BB, PredValues, Preference, CxtI))
  1055. return false;
  1056. assert(!PredValues.empty() &&
  1057. "ComputeValueKnownInPredecessors returned true with no values");
  1058. DEBUG(dbgs() << "IN BB: " << *BB;
  1059. for (const auto &PredValue : PredValues) {
  1060. dbgs() << " BB '" << BB->getName() << "': FOUND condition = "
  1061. << *PredValue.first
  1062. << " for pred '" << PredValue.second->getName() << "'.\n";
  1063. });
  1064. // Decide what we want to thread through. Convert our list of known values to
  1065. // a list of known destinations for each pred. This also discards duplicate
  1066. // predecessors and keeps track of the undefined inputs (which are represented
  1067. // as a null dest in the PredToDestList).
  1068. SmallPtrSet<BasicBlock*, 16> SeenPreds;
  1069. SmallVector<std::pair<BasicBlock*, BasicBlock*>, 16> PredToDestList;
  1070. BasicBlock *OnlyDest = nullptr;
  1071. BasicBlock *MultipleDestSentinel = (BasicBlock*)(intptr_t)~0ULL;
  1072. for (const auto &PredValue : PredValues) {
  1073. BasicBlock *Pred = PredValue.second;
  1074. if (!SeenPreds.insert(Pred).second)
  1075. continue; // Duplicate predecessor entry.
  1076. // If the predecessor ends with an indirect goto, we can't change its
  1077. // destination.
  1078. if (isa<IndirectBrInst>(Pred->getTerminator()))
  1079. continue;
  1080. Constant *Val = PredValue.first;
  1081. BasicBlock *DestBB;
  1082. if (isa<UndefValue>(Val))
  1083. DestBB = nullptr;
  1084. else if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator()))
  1085. DestBB = BI->getSuccessor(cast<ConstantInt>(Val)->isZero());
  1086. else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
  1087. DestBB = SI->findCaseValue(cast<ConstantInt>(Val))->getCaseSuccessor();
  1088. } else {
  1089. assert(isa<IndirectBrInst>(BB->getTerminator())
  1090. && "Unexpected terminator");
  1091. DestBB = cast<BlockAddress>(Val)->getBasicBlock();
  1092. }
  1093. // If we have exactly one destination, remember it for efficiency below.
  1094. if (PredToDestList.empty())
  1095. OnlyDest = DestBB;
  1096. else if (OnlyDest != DestBB)
  1097. OnlyDest = MultipleDestSentinel;
  1098. PredToDestList.push_back(std::make_pair(Pred, DestBB));
  1099. }
  1100. // If all edges were unthreadable, we fail.
  1101. if (PredToDestList.empty())
  1102. return false;
  1103. // Determine which is the most common successor. If we have many inputs and
  1104. // this block is a switch, we want to start by threading the batch that goes
  1105. // to the most popular destination first. If we only know about one
  1106. // threadable destination (the common case) we can avoid this.
  1107. BasicBlock *MostPopularDest = OnlyDest;
  1108. if (MostPopularDest == MultipleDestSentinel)
  1109. MostPopularDest = FindMostPopularDest(BB, PredToDestList);
  1110. // Now that we know what the most popular destination is, factor all
  1111. // predecessors that will jump to it into a single predecessor.
  1112. SmallVector<BasicBlock*, 16> PredsToFactor;
  1113. for (const auto &PredToDest : PredToDestList)
  1114. if (PredToDest.second == MostPopularDest) {
  1115. BasicBlock *Pred = PredToDest.first;
  1116. // This predecessor may be a switch or something else that has multiple
  1117. // edges to the block. Factor each of these edges by listing them
  1118. // according to # occurrences in PredsToFactor.
  1119. for (BasicBlock *Succ : successors(Pred))
  1120. if (Succ == BB)
  1121. PredsToFactor.push_back(Pred);
  1122. }
  1123. // If the threadable edges are branching on an undefined value, we get to pick
  1124. // the destination that these predecessors should get to.
  1125. if (!MostPopularDest)
  1126. MostPopularDest = BB->getTerminator()->
  1127. getSuccessor(GetBestDestForJumpOnUndef(BB));
  1128. // Ok, try to thread it!
  1129. return ThreadEdge(BB, PredsToFactor, MostPopularDest);
  1130. }
  1131. /// ProcessBranchOnPHI - We have an otherwise unthreadable conditional branch on
  1132. /// a PHI node in the current block. See if there are any simplifications we
  1133. /// can do based on inputs to the phi node.
  1134. ///
  1135. bool JumpThreadingPass::ProcessBranchOnPHI(PHINode *PN) {
  1136. BasicBlock *BB = PN->getParent();
  1137. // TODO: We could make use of this to do it once for blocks with common PHI
  1138. // values.
  1139. SmallVector<BasicBlock*, 1> PredBBs;
  1140. PredBBs.resize(1);
  1141. // If any of the predecessor blocks end in an unconditional branch, we can
  1142. // *duplicate* the conditional branch into that block in order to further
  1143. // encourage jump threading and to eliminate cases where we have branch on a
  1144. // phi of an icmp (branch on icmp is much better).
  1145. for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
  1146. BasicBlock *PredBB = PN->getIncomingBlock(i);
  1147. if (BranchInst *PredBr = dyn_cast<BranchInst>(PredBB->getTerminator()))
  1148. if (PredBr->isUnconditional()) {
  1149. PredBBs[0] = PredBB;
  1150. // Try to duplicate BB into PredBB.
  1151. if (DuplicateCondBranchOnPHIIntoPred(BB, PredBBs))
  1152. return true;
  1153. }
  1154. }
  1155. return false;
  1156. }
  1157. /// ProcessBranchOnXOR - We have an otherwise unthreadable conditional branch on
  1158. /// a xor instruction in the current block. See if there are any
  1159. /// simplifications we can do based on inputs to the xor.
  1160. ///
  1161. bool JumpThreadingPass::ProcessBranchOnXOR(BinaryOperator *BO) {
  1162. BasicBlock *BB = BO->getParent();
  1163. // If either the LHS or RHS of the xor is a constant, don't do this
  1164. // optimization.
  1165. if (isa<ConstantInt>(BO->getOperand(0)) ||
  1166. isa<ConstantInt>(BO->getOperand(1)))
  1167. return false;
  1168. // If the first instruction in BB isn't a phi, we won't be able to infer
  1169. // anything special about any particular predecessor.
  1170. if (!isa<PHINode>(BB->front()))
  1171. return false;
  1172. // If this BB is a landing pad, we won't be able to split the edge into it.
  1173. if (BB->isEHPad())
  1174. return false;
  1175. // If we have a xor as the branch input to this block, and we know that the
  1176. // LHS or RHS of the xor in any predecessor is true/false, then we can clone
  1177. // the condition into the predecessor and fix that value to true, saving some
  1178. // logical ops on that path and encouraging other paths to simplify.
  1179. //
  1180. // This copies something like this:
  1181. //
  1182. // BB:
  1183. // %X = phi i1 [1], [%X']
  1184. // %Y = icmp eq i32 %A, %B
  1185. // %Z = xor i1 %X, %Y
  1186. // br i1 %Z, ...
  1187. //
  1188. // Into:
  1189. // BB':
  1190. // %Y = icmp ne i32 %A, %B
  1191. // br i1 %Y, ...
  1192. PredValueInfoTy XorOpValues;
  1193. bool isLHS = true;
  1194. if (!ComputeValueKnownInPredecessors(BO->getOperand(0), BB, XorOpValues,
  1195. WantInteger, BO)) {
  1196. assert(XorOpValues.empty());
  1197. if (!ComputeValueKnownInPredecessors(BO->getOperand(1), BB, XorOpValues,
  1198. WantInteger, BO))
  1199. return false;
  1200. isLHS = false;
  1201. }
  1202. assert(!XorOpValues.empty() &&
  1203. "ComputeValueKnownInPredecessors returned true with no values");
  1204. // Scan the information to see which is most popular: true or false. The
  1205. // predecessors can be of the set true, false, or undef.
  1206. unsigned NumTrue = 0, NumFalse = 0;
  1207. for (const auto &XorOpValue : XorOpValues) {
  1208. if (isa<UndefValue>(XorOpValue.first))
  1209. // Ignore undefs for the count.
  1210. continue;
  1211. if (cast<ConstantInt>(XorOpValue.first)->isZero())
  1212. ++NumFalse;
  1213. else
  1214. ++NumTrue;
  1215. }
  1216. // Determine which value to split on, true, false, or undef if neither.
  1217. ConstantInt *SplitVal = nullptr;
  1218. if (NumTrue > NumFalse)
  1219. SplitVal = ConstantInt::getTrue(BB->getContext());
  1220. else if (NumTrue != 0 || NumFalse != 0)
  1221. SplitVal = ConstantInt::getFalse(BB->getContext());
  1222. // Collect all of the blocks that this can be folded into so that we can
  1223. // factor this once and clone it once.
  1224. SmallVector<BasicBlock*, 8> BlocksToFoldInto;
  1225. for (const auto &XorOpValue : XorOpValues) {
  1226. if (XorOpValue.first != SplitVal && !isa<UndefValue>(XorOpValue.first))
  1227. continue;
  1228. BlocksToFoldInto.push_back(XorOpValue.second);
  1229. }
  1230. // If we inferred a value for all of the predecessors, then duplication won't
  1231. // help us. However, we can just replace the LHS or RHS with the constant.
  1232. if (BlocksToFoldInto.size() ==
  1233. cast<PHINode>(BB->front()).getNumIncomingValues()) {
  1234. if (!SplitVal) {
  1235. // If all preds provide undef, just nuke the xor, because it is undef too.
  1236. BO->replaceAllUsesWith(UndefValue::get(BO->getType()));
  1237. BO->eraseFromParent();
  1238. } else if (SplitVal->isZero()) {
  1239. // If all preds provide 0, replace the xor with the other input.
  1240. BO->replaceAllUsesWith(BO->getOperand(isLHS));
  1241. BO->eraseFromParent();
  1242. } else {
  1243. // If all preds provide 1, set the computed value to 1.
  1244. BO->setOperand(!isLHS, SplitVal);
  1245. }
  1246. return true;
  1247. }
  1248. // Try to duplicate BB into PredBB.
  1249. return DuplicateCondBranchOnPHIIntoPred(BB, BlocksToFoldInto);
  1250. }
  1251. /// AddPHINodeEntriesForMappedBlock - We're adding 'NewPred' as a new
  1252. /// predecessor to the PHIBB block. If it has PHI nodes, add entries for
  1253. /// NewPred using the entries from OldPred (suitably mapped).
  1254. static void AddPHINodeEntriesForMappedBlock(BasicBlock *PHIBB,
  1255. BasicBlock *OldPred,
  1256. BasicBlock *NewPred,
  1257. DenseMap<Instruction*, Value*> &ValueMap) {
  1258. for (BasicBlock::iterator PNI = PHIBB->begin();
  1259. PHINode *PN = dyn_cast<PHINode>(PNI); ++PNI) {
  1260. // Ok, we have a PHI node. Figure out what the incoming value was for the
  1261. // DestBlock.
  1262. Value *IV = PN->getIncomingValueForBlock(OldPred);
  1263. // Remap the value if necessary.
  1264. if (Instruction *Inst = dyn_cast<Instruction>(IV)) {
  1265. DenseMap<Instruction*, Value*>::iterator I = ValueMap.find(Inst);
  1266. if (I != ValueMap.end())
  1267. IV = I->second;
  1268. }
  1269. PN->addIncoming(IV, NewPred);
  1270. }
  1271. }
  1272. /// ThreadEdge - We have decided that it is safe and profitable to factor the
  1273. /// blocks in PredBBs to one predecessor, then thread an edge from it to SuccBB
  1274. /// across BB. Transform the IR to reflect this change.
  1275. bool JumpThreadingPass::ThreadEdge(BasicBlock *BB,
  1276. const SmallVectorImpl<BasicBlock *> &PredBBs,
  1277. BasicBlock *SuccBB) {
  1278. // If threading to the same block as we come from, we would infinite loop.
  1279. if (SuccBB == BB) {
  1280. DEBUG(dbgs() << " Not threading across BB '" << BB->getName()
  1281. << "' - would thread to self!\n");
  1282. return false;
  1283. }
  1284. // If threading this would thread across a loop header, don't thread the edge.
  1285. // See the comments above FindLoopHeaders for justifications and caveats.
  1286. if (LoopHeaders.count(BB)) {
  1287. DEBUG(dbgs() << " Not threading across loop header BB '" << BB->getName()
  1288. << "' to dest BB '" << SuccBB->getName()
  1289. << "' - it might create an irreducible loop!\n");
  1290. return false;
  1291. }
  1292. unsigned JumpThreadCost =
  1293. getJumpThreadDuplicationCost(BB, BB->getTerminator(), BBDupThreshold);
  1294. if (JumpThreadCost > BBDupThreshold) {
  1295. DEBUG(dbgs() << " Not threading BB '" << BB->getName()
  1296. << "' - Cost is too high: " << JumpThreadCost << "\n");
  1297. return false;
  1298. }
  1299. // And finally, do it! Start by factoring the predecessors if needed.
  1300. BasicBlock *PredBB;
  1301. if (PredBBs.size() == 1)
  1302. PredBB = PredBBs[0];
  1303. else {
  1304. DEBUG(dbgs() << " Factoring out " << PredBBs.size()
  1305. << " common predecessors.\n");
  1306. PredBB = SplitBlockPreds(BB, PredBBs, ".thr_comm");
  1307. }
  1308. // And finally, do it!
  1309. DEBUG(dbgs() << " Threading edge from '" << PredBB->getName() << "' to '"
  1310. << SuccBB->getName() << "' with cost: " << JumpThreadCost
  1311. << ", across block:\n "
  1312. << *BB << "\n");
  1313. LVI->threadEdge(PredBB, BB, SuccBB);
  1314. // We are going to have to map operands from the original BB block to the new
  1315. // copy of the block 'NewBB'. If there are PHI nodes in BB, evaluate them to
  1316. // account for entry from PredBB.
  1317. DenseMap<Instruction*, Value*> ValueMapping;
  1318. BasicBlock *NewBB = BasicBlock::Create(BB->getContext(),
  1319. BB->getName()+".thread",
  1320. BB->getParent(), BB);
  1321. NewBB->moveAfter(PredBB);
  1322. // Set the block frequency of NewBB.
  1323. if (HasProfileData) {
  1324. auto NewBBFreq =
  1325. BFI->getBlockFreq(PredBB) * BPI->getEdgeProbability(PredBB, BB);
  1326. BFI->setBlockFreq(NewBB, NewBBFreq.getFrequency());
  1327. }
  1328. BasicBlock::iterator BI = BB->begin();
  1329. for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
  1330. ValueMapping[PN] = PN->getIncomingValueForBlock(PredBB);
  1331. // Clone the non-phi instructions of BB into NewBB, keeping track of the
  1332. // mapping and using it to remap operands in the cloned instructions.
  1333. for (; !isa<TerminatorInst>(BI); ++BI) {
  1334. Instruction *New = BI->clone();
  1335. New->setName(BI->getName());
  1336. NewBB->getInstList().push_back(New);
  1337. ValueMapping[&*BI] = New;
  1338. // Remap operands to patch up intra-block references.
  1339. for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
  1340. if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i))) {
  1341. DenseMap<Instruction*, Value*>::iterator I = ValueMapping.find(Inst);
  1342. if (I != ValueMapping.end())
  1343. New->setOperand(i, I->second);
  1344. }
  1345. }
  1346. // We didn't copy the terminator from BB over to NewBB, because there is now
  1347. // an unconditional jump to SuccBB. Insert the unconditional jump.
  1348. BranchInst *NewBI = BranchInst::Create(SuccBB, NewBB);
  1349. NewBI->setDebugLoc(BB->getTerminator()->getDebugLoc());
  1350. // Check to see if SuccBB has PHI nodes. If so, we need to add entries to the
  1351. // PHI nodes for NewBB now.
  1352. AddPHINodeEntriesForMappedBlock(SuccBB, BB, NewBB, ValueMapping);
  1353. // If there were values defined in BB that are used outside the block, then we
  1354. // now have to update all uses of the value to use either the original value,
  1355. // the cloned value, or some PHI derived value. This can require arbitrary
  1356. // PHI insertion, of which we are prepared to do, clean these up now.
  1357. SSAUpdater SSAUpdate;
  1358. SmallVector<Use*, 16> UsesToRename;
  1359. for (Instruction &I : *BB) {
  1360. // Scan all uses of this instruction to see if it is used outside of its
  1361. // block, and if so, record them in UsesToRename.
  1362. for (Use &U : I.uses()) {
  1363. Instruction *User = cast<Instruction>(U.getUser());
  1364. if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
  1365. if (UserPN->getIncomingBlock(U) == BB)
  1366. continue;
  1367. } else if (User->getParent() == BB)
  1368. continue;
  1369. UsesToRename.push_back(&U);
  1370. }
  1371. // If there are no uses outside the block, we're done with this instruction.
  1372. if (UsesToRename.empty())
  1373. continue;
  1374. DEBUG(dbgs() << "JT: Renaming non-local uses of: " << I << "\n");
  1375. // We found a use of I outside of BB. Rename all uses of I that are outside
  1376. // its block to be uses of the appropriate PHI node etc. See ValuesInBlocks
  1377. // with the two values we know.
  1378. SSAUpdate.Initialize(I.getType(), I.getName());
  1379. SSAUpdate.AddAvailableValue(BB, &I);
  1380. SSAUpdate.AddAvailableValue(NewBB, ValueMapping[&I]);
  1381. while (!UsesToRename.empty())
  1382. SSAUpdate.RewriteUse(*UsesToRename.pop_back_val());
  1383. DEBUG(dbgs() << "\n");
  1384. }
  1385. // Ok, NewBB is good to go. Update the terminator of PredBB to jump to
  1386. // NewBB instead of BB. This eliminates predecessors from BB, which requires
  1387. // us to simplify any PHI nodes in BB.
  1388. TerminatorInst *PredTerm = PredBB->getTerminator();
  1389. for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i)
  1390. if (PredTerm->getSuccessor(i) == BB) {
  1391. BB->removePredecessor(PredBB, true);
  1392. PredTerm->setSuccessor(i, NewBB);
  1393. }
  1394. // At this point, the IR is fully up to date and consistent. Do a quick scan
  1395. // over the new instructions and zap any that are constants or dead. This
  1396. // frequently happens because of phi translation.
  1397. SimplifyInstructionsInBlock(NewBB, TLI);
  1398. // Update the edge weight from BB to SuccBB, which should be less than before.
  1399. UpdateBlockFreqAndEdgeWeight(PredBB, BB, NewBB, SuccBB);
  1400. // Threaded an edge!
  1401. ++NumThreads;
  1402. return true;
  1403. }
  1404. /// Create a new basic block that will be the predecessor of BB and successor of
  1405. /// all blocks in Preds. When profile data is available, update the frequency of
  1406. /// this new block.
  1407. BasicBlock *JumpThreadingPass::SplitBlockPreds(BasicBlock *BB,
  1408. ArrayRef<BasicBlock *> Preds,
  1409. const char *Suffix) {
  1410. // Collect the frequencies of all predecessors of BB, which will be used to
  1411. // update the edge weight on BB->SuccBB.
  1412. BlockFrequency PredBBFreq(0);
  1413. if (HasProfileData)
  1414. for (auto Pred : Preds)
  1415. PredBBFreq += BFI->getBlockFreq(Pred) * BPI->getEdgeProbability(Pred, BB);
  1416. BasicBlock *PredBB = SplitBlockPredecessors(BB, Preds, Suffix);
  1417. // Set the block frequency of the newly created PredBB, which is the sum of
  1418. // frequencies of Preds.
  1419. if (HasProfileData)
  1420. BFI->setBlockFreq(PredBB, PredBBFreq.getFrequency());
  1421. return PredBB;
  1422. }
  1423. bool JumpThreadingPass::doesBlockHaveProfileData(BasicBlock *BB) {
  1424. const TerminatorInst *TI = BB->getTerminator();
  1425. assert(TI->getNumSuccessors() > 1 && "not a split");
  1426. MDNode *WeightsNode = TI->getMetadata(LLVMContext::MD_prof);
  1427. if (!WeightsNode)
  1428. return false;
  1429. MDString *MDName = cast<MDString>(WeightsNode->getOperand(0));
  1430. if (MDName->getString() != "branch_weights")
  1431. return false;
  1432. // Ensure there are weights for all of the successors. Note that the first
  1433. // operand to the metadata node is a name, not a weight.
  1434. return WeightsNode->getNumOperands() == TI->getNumSuccessors() + 1;
  1435. }
  1436. /// Update the block frequency of BB and branch weight and the metadata on the
  1437. /// edge BB->SuccBB. This is done by scaling the weight of BB->SuccBB by 1 -
  1438. /// Freq(PredBB->BB) / Freq(BB->SuccBB).
  1439. void JumpThreadingPass::UpdateBlockFreqAndEdgeWeight(BasicBlock *PredBB,
  1440. BasicBlock *BB,
  1441. BasicBlock *NewBB,
  1442. BasicBlock *SuccBB) {
  1443. if (!HasProfileData)
  1444. return;
  1445. assert(BFI && BPI && "BFI & BPI should have been created here");
  1446. // As the edge from PredBB to BB is deleted, we have to update the block
  1447. // frequency of BB.
  1448. auto BBOrigFreq = BFI->getBlockFreq(BB);
  1449. auto NewBBFreq = BFI->getBlockFreq(NewBB);
  1450. auto BB2SuccBBFreq = BBOrigFreq * BPI->getEdgeProbability(BB, SuccBB);
  1451. auto BBNewFreq = BBOrigFreq - NewBBFreq;
  1452. BFI->setBlockFreq(BB, BBNewFreq.getFrequency());
  1453. // Collect updated outgoing edges' frequencies from BB and use them to update
  1454. // edge probabilities.
  1455. SmallVector<uint64_t, 4> BBSuccFreq;
  1456. for (BasicBlock *Succ : successors(BB)) {
  1457. auto SuccFreq = (Succ == SuccBB)
  1458. ? BB2SuccBBFreq - NewBBFreq
  1459. : BBOrigFreq * BPI->getEdgeProbability(BB, Succ);
  1460. BBSuccFreq.push_back(SuccFreq.getFrequency());
  1461. }
  1462. uint64_t MaxBBSuccFreq =
  1463. *std::max_element(BBSuccFreq.begin(), BBSuccFreq.end());
  1464. SmallVector<BranchProbability, 4> BBSuccProbs;
  1465. if (MaxBBSuccFreq == 0)
  1466. BBSuccProbs.assign(BBSuccFreq.size(),
  1467. {1, static_cast<unsigned>(BBSuccFreq.size())});
  1468. else {
  1469. for (uint64_t Freq : BBSuccFreq)
  1470. BBSuccProbs.push_back(
  1471. BranchProbability::getBranchProbability(Freq, MaxBBSuccFreq));
  1472. // Normalize edge probabilities so that they sum up to one.
  1473. BranchProbability::normalizeProbabilities(BBSuccProbs.begin(),
  1474. BBSuccProbs.end());
  1475. }
  1476. // Update edge probabilities in BPI.
  1477. for (int I = 0, E = BBSuccProbs.size(); I < E; I++)
  1478. BPI->setEdgeProbability(BB, I, BBSuccProbs[I]);
  1479. // Update the profile metadata as well.
  1480. //
  1481. // Don't do this if the profile of the transformed blocks was statically
  1482. // estimated. (This could occur despite the function having an entry
  1483. // frequency in completely cold parts of the CFG.)
  1484. //
  1485. // In this case we don't want to suggest to subsequent passes that the
  1486. // calculated weights are fully consistent. Consider this graph:
  1487. //
  1488. // check_1
  1489. // 50% / |
  1490. // eq_1 | 50%
  1491. // \ |
  1492. // check_2
  1493. // 50% / |
  1494. // eq_2 | 50%
  1495. // \ |
  1496. // check_3
  1497. // 50% / |
  1498. // eq_3 | 50%
  1499. // \ |
  1500. //
  1501. // Assuming the blocks check_* all compare the same value against 1, 2 and 3,
  1502. // the overall probabilities are inconsistent; the total probability that the
  1503. // value is either 1, 2 or 3 is 150%.
  1504. //
  1505. // As a consequence if we thread eq_1 -> check_2 to check_3, check_2->check_3
  1506. // becomes 0%. This is even worse if the edge whose probability becomes 0% is
  1507. // the loop exit edge. Then based solely on static estimation we would assume
  1508. // the loop was extremely hot.
  1509. //
  1510. // FIXME this locally as well so that BPI and BFI are consistent as well. We
  1511. // shouldn't make edges extremely likely or unlikely based solely on static
  1512. // estimation.
  1513. if (BBSuccProbs.size() >= 2 && doesBlockHaveProfileData(BB)) {
  1514. SmallVector<uint32_t, 4> Weights;
  1515. for (auto Prob : BBSuccProbs)
  1516. Weights.push_back(Prob.getNumerator());
  1517. auto TI = BB->getTerminator();
  1518. TI->setMetadata(
  1519. LLVMContext::MD_prof,
  1520. MDBuilder(TI->getParent()->getContext()).createBranchWeights(Weights));
  1521. }
  1522. }
  1523. /// DuplicateCondBranchOnPHIIntoPred - PredBB contains an unconditional branch
  1524. /// to BB which contains an i1 PHI node and a conditional branch on that PHI.
  1525. /// If we can duplicate the contents of BB up into PredBB do so now, this
  1526. /// improves the odds that the branch will be on an analyzable instruction like
  1527. /// a compare.
  1528. bool JumpThreadingPass::DuplicateCondBranchOnPHIIntoPred(
  1529. BasicBlock *BB, const SmallVectorImpl<BasicBlock *> &PredBBs) {
  1530. assert(!PredBBs.empty() && "Can't handle an empty set");
  1531. // If BB is a loop header, then duplicating this block outside the loop would
  1532. // cause us to transform this into an irreducible loop, don't do this.
  1533. // See the comments above FindLoopHeaders for justifications and caveats.
  1534. if (LoopHeaders.count(BB)) {
  1535. DEBUG(dbgs() << " Not duplicating loop header '" << BB->getName()
  1536. << "' into predecessor block '" << PredBBs[0]->getName()
  1537. << "' - it might create an irreducible loop!\n");
  1538. return false;
  1539. }
  1540. unsigned DuplicationCost =
  1541. getJumpThreadDuplicationCost(BB, BB->getTerminator(), BBDupThreshold);
  1542. if (DuplicationCost > BBDupThreshold) {
  1543. DEBUG(dbgs() << " Not duplicating BB '" << BB->getName()
  1544. << "' - Cost is too high: " << DuplicationCost << "\n");
  1545. return false;
  1546. }
  1547. // And finally, do it! Start by factoring the predecessors if needed.
  1548. BasicBlock *PredBB;
  1549. if (PredBBs.size() == 1)
  1550. PredBB = PredBBs[0];
  1551. else {
  1552. DEBUG(dbgs() << " Factoring out " << PredBBs.size()
  1553. << " common predecessors.\n");
  1554. PredBB = SplitBlockPreds(BB, PredBBs, ".thr_comm");
  1555. }
  1556. // Okay, we decided to do this! Clone all the instructions in BB onto the end
  1557. // of PredBB.
  1558. DEBUG(dbgs() << " Duplicating block '" << BB->getName() << "' into end of '"
  1559. << PredBB->getName() << "' to eliminate branch on phi. Cost: "
  1560. << DuplicationCost << " block is:" << *BB << "\n");
  1561. // Unless PredBB ends with an unconditional branch, split the edge so that we
  1562. // can just clone the bits from BB into the end of the new PredBB.
  1563. BranchInst *OldPredBranch = dyn_cast<BranchInst>(PredBB->getTerminator());
  1564. if (!OldPredBranch || !OldPredBranch->isUnconditional()) {
  1565. PredBB = SplitEdge(PredBB, BB);
  1566. OldPredBranch = cast<BranchInst>(PredBB->getTerminator());
  1567. }
  1568. // We are going to have to map operands from the original BB block into the
  1569. // PredBB block. Evaluate PHI nodes in BB.
  1570. DenseMap<Instruction*, Value*> ValueMapping;
  1571. BasicBlock::iterator BI = BB->begin();
  1572. for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
  1573. ValueMapping[PN] = PN->getIncomingValueForBlock(PredBB);
  1574. // Clone the non-phi instructions of BB into PredBB, keeping track of the
  1575. // mapping and using it to remap operands in the cloned instructions.
  1576. for (; BI != BB->end(); ++BI) {
  1577. Instruction *New = BI->clone();
  1578. // Remap operands to patch up intra-block references.
  1579. for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
  1580. if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i))) {
  1581. DenseMap<Instruction*, Value*>::iterator I = ValueMapping.find(Inst);
  1582. if (I != ValueMapping.end())
  1583. New->setOperand(i, I->second);
  1584. }
  1585. // If this instruction can be simplified after the operands are updated,
  1586. // just use the simplified value instead. This frequently happens due to
  1587. // phi translation.
  1588. if (Value *IV =
  1589. SimplifyInstruction(New, BB->getModule()->getDataLayout())) {
  1590. ValueMapping[&*BI] = IV;
  1591. if (!New->mayHaveSideEffects()) {
  1592. delete New;
  1593. New = nullptr;
  1594. }
  1595. } else {
  1596. ValueMapping[&*BI] = New;
  1597. }
  1598. if (New) {
  1599. // Otherwise, insert the new instruction into the block.
  1600. New->setName(BI->getName());
  1601. PredBB->getInstList().insert(OldPredBranch->getIterator(), New);
  1602. }
  1603. }
  1604. // Check to see if the targets of the branch had PHI nodes. If so, we need to
  1605. // add entries to the PHI nodes for branch from PredBB now.
  1606. BranchInst *BBBranch = cast<BranchInst>(BB->getTerminator());
  1607. AddPHINodeEntriesForMappedBlock(BBBranch->getSuccessor(0), BB, PredBB,
  1608. ValueMapping);
  1609. AddPHINodeEntriesForMappedBlock(BBBranch->getSuccessor(1), BB, PredBB,
  1610. ValueMapping);
  1611. // If there were values defined in BB that are used outside the block, then we
  1612. // now have to update all uses of the value to use either the original value,
  1613. // the cloned value, or some PHI derived value. This can require arbitrary
  1614. // PHI insertion, of which we are prepared to do, clean these up now.
  1615. SSAUpdater SSAUpdate;
  1616. SmallVector<Use*, 16> UsesToRename;
  1617. for (Instruction &I : *BB) {
  1618. // Scan all uses of this instruction to see if it is used outside of its
  1619. // block, and if so, record them in UsesToRename.
  1620. for (Use &U : I.uses()) {
  1621. Instruction *User = cast<Instruction>(U.getUser());
  1622. if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
  1623. if (UserPN->getIncomingBlock(U) == BB)
  1624. continue;
  1625. } else if (User->getParent() == BB)
  1626. continue;
  1627. UsesToRename.push_back(&U);
  1628. }
  1629. // If there are no uses outside the block, we're done with this instruction.
  1630. if (UsesToRename.empty())
  1631. continue;
  1632. DEBUG(dbgs() << "JT: Renaming non-local uses of: " << I << "\n");
  1633. // We found a use of I outside of BB. Rename all uses of I that are outside
  1634. // its block to be uses of the appropriate PHI node etc. See ValuesInBlocks
  1635. // with the two values we know.
  1636. SSAUpdate.Initialize(I.getType(), I.getName());
  1637. SSAUpdate.AddAvailableValue(BB, &I);
  1638. SSAUpdate.AddAvailableValue(PredBB, ValueMapping[&I]);
  1639. while (!UsesToRename.empty())
  1640. SSAUpdate.RewriteUse(*UsesToRename.pop_back_val());
  1641. DEBUG(dbgs() << "\n");
  1642. }
  1643. // PredBB no longer jumps to BB, remove entries in the PHI node for the edge
  1644. // that we nuked.
  1645. BB->removePredecessor(PredBB, true);
  1646. // Remove the unconditional branch at the end of the PredBB block.
  1647. OldPredBranch->eraseFromParent();
  1648. ++NumDupes;
  1649. return true;
  1650. }
  1651. /// TryToUnfoldSelect - Look for blocks of the form
  1652. /// bb1:
  1653. /// %a = select
  1654. /// br bb2
  1655. ///
  1656. /// bb2:
  1657. /// %p = phi [%a, %bb1] ...
  1658. /// %c = icmp %p
  1659. /// br i1 %c
  1660. ///
  1661. /// And expand the select into a branch structure if one of its arms allows %c
  1662. /// to be folded. This later enables threading from bb1 over bb2.
  1663. bool JumpThreadingPass::TryToUnfoldSelect(CmpInst *CondCmp, BasicBlock *BB) {
  1664. BranchInst *CondBr = dyn_cast<BranchInst>(BB->getTerminator());
  1665. PHINode *CondLHS = dyn_cast<PHINode>(CondCmp->getOperand(0));
  1666. Constant *CondRHS = cast<Constant>(CondCmp->getOperand(1));
  1667. if (!CondBr || !CondBr->isConditional() || !CondLHS ||
  1668. CondLHS->getParent() != BB)
  1669. return false;
  1670. for (unsigned I = 0, E = CondLHS->getNumIncomingValues(); I != E; ++I) {
  1671. BasicBlock *Pred = CondLHS->getIncomingBlock(I);
  1672. SelectInst *SI = dyn_cast<SelectInst>(CondLHS->getIncomingValue(I));
  1673. // Look if one of the incoming values is a select in the corresponding
  1674. // predecessor.
  1675. if (!SI || SI->getParent() != Pred || !SI->hasOneUse())
  1676. continue;
  1677. BranchInst *PredTerm = dyn_cast<BranchInst>(Pred->getTerminator());
  1678. if (!PredTerm || !PredTerm->isUnconditional())
  1679. continue;
  1680. // Now check if one of the select values would allow us to constant fold the
  1681. // terminator in BB. We don't do the transform if both sides fold, those
  1682. // cases will be threaded in any case.
  1683. LazyValueInfo::Tristate LHSFolds =
  1684. LVI->getPredicateOnEdge(CondCmp->getPredicate(), SI->getOperand(1),
  1685. CondRHS, Pred, BB, CondCmp);
  1686. LazyValueInfo::Tristate RHSFolds =
  1687. LVI->getPredicateOnEdge(CondCmp->getPredicate(), SI->getOperand(2),
  1688. CondRHS, Pred, BB, CondCmp);
  1689. if ((LHSFolds != LazyValueInfo::Unknown ||
  1690. RHSFolds != LazyValueInfo::Unknown) &&
  1691. LHSFolds != RHSFolds) {
  1692. // Expand the select.
  1693. //
  1694. // Pred --
  1695. // | v
  1696. // | NewBB
  1697. // | |
  1698. // |-----
  1699. // v
  1700. // BB
  1701. BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), "select.unfold",
  1702. BB->getParent(), BB);
  1703. // Move the unconditional branch to NewBB.
  1704. PredTerm->removeFromParent();
  1705. NewBB->getInstList().insert(NewBB->end(), PredTerm);
  1706. // Create a conditional branch and update PHI nodes.
  1707. BranchInst::Create(NewBB, BB, SI->getCondition(), Pred);
  1708. CondLHS->setIncomingValue(I, SI->getFalseValue());
  1709. CondLHS->addIncoming(SI->getTrueValue(), NewBB);
  1710. // The select is now dead.
  1711. SI->eraseFromParent();
  1712. // Update any other PHI nodes in BB.
  1713. for (BasicBlock::iterator BI = BB->begin();
  1714. PHINode *Phi = dyn_cast<PHINode>(BI); ++BI)
  1715. if (Phi != CondLHS)
  1716. Phi->addIncoming(Phi->getIncomingValueForBlock(Pred), NewBB);
  1717. return true;
  1718. }
  1719. }
  1720. return false;
  1721. }
  1722. /// TryToUnfoldSelectInCurrBB - Look for PHI/Select in the same BB of the form
  1723. /// bb:
  1724. /// %p = phi [false, %bb1], [true, %bb2], [false, %bb3], [true, %bb4], ...
  1725. /// %s = select p, trueval, falseval
  1726. ///
  1727. /// And expand the select into a branch structure. This later enables
  1728. /// jump-threading over bb in this pass.
  1729. ///
  1730. /// Using the similar approach of SimplifyCFG::FoldCondBranchOnPHI(), unfold
  1731. /// select if the associated PHI has at least one constant. If the unfolded
  1732. /// select is not jump-threaded, it will be folded again in the later
  1733. /// optimizations.
  1734. bool JumpThreadingPass::TryToUnfoldSelectInCurrBB(BasicBlock *BB) {
  1735. // If threading this would thread across a loop header, don't thread the edge.
  1736. // See the comments above FindLoopHeaders for justifications and caveats.
  1737. if (LoopHeaders.count(BB))
  1738. return false;
  1739. // Look for a Phi/Select pair in the same basic block. The Phi feeds the
  1740. // condition of the Select and at least one of the incoming values is a
  1741. // constant.
  1742. for (BasicBlock::iterator BI = BB->begin();
  1743. PHINode *PN = dyn_cast<PHINode>(BI); ++BI) {
  1744. unsigned NumPHIValues = PN->getNumIncomingValues();
  1745. if (NumPHIValues == 0 || !PN->hasOneUse())
  1746. continue;
  1747. SelectInst *SI = dyn_cast<SelectInst>(PN->user_back());
  1748. if (!SI || SI->getParent() != BB)
  1749. continue;
  1750. Value *Cond = SI->getCondition();
  1751. if (!Cond || Cond != PN || !Cond->getType()->isIntegerTy(1))
  1752. continue;
  1753. bool HasConst = false;
  1754. for (unsigned i = 0; i != NumPHIValues; ++i) {
  1755. if (PN->getIncomingBlock(i) == BB)
  1756. return false;
  1757. if (isa<ConstantInt>(PN->getIncomingValue(i)))
  1758. HasConst = true;
  1759. }
  1760. if (HasConst) {
  1761. // Expand the select.
  1762. TerminatorInst *Term =
  1763. SplitBlockAndInsertIfThen(SI->getCondition(), SI, false);
  1764. PHINode *NewPN = PHINode::Create(SI->getType(), 2, "", SI);
  1765. NewPN->addIncoming(SI->getTrueValue(), Term->getParent());
  1766. NewPN->addIncoming(SI->getFalseValue(), BB);
  1767. SI->replaceAllUsesWith(NewPN);
  1768. SI->eraseFromParent();
  1769. return true;
  1770. }
  1771. }
  1772. return false;
  1773. }
  1774. /// Try to propagate a guard from the current BB into one of its predecessors
  1775. /// in case if another branch of execution implies that the condition of this
  1776. /// guard is always true. Currently we only process the simplest case that
  1777. /// looks like:
  1778. ///
  1779. /// Start:
  1780. /// %cond = ...
  1781. /// br i1 %cond, label %T1, label %F1
  1782. /// T1:
  1783. /// br label %Merge
  1784. /// F1:
  1785. /// br label %Merge
  1786. /// Merge:
  1787. /// %condGuard = ...
  1788. /// call void(i1, ...) @llvm.experimental.guard( i1 %condGuard )[ "deopt"() ]
  1789. ///
  1790. /// And cond either implies condGuard or !condGuard. In this case all the
  1791. /// instructions before the guard can be duplicated in both branches, and the
  1792. /// guard is then threaded to one of them.
  1793. bool JumpThreadingPass::ProcessGuards(BasicBlock *BB) {
  1794. using namespace PatternMatch;
  1795. // We only want to deal with two predecessors.
  1796. BasicBlock *Pred1, *Pred2;
  1797. auto PI = pred_begin(BB), PE = pred_end(BB);
  1798. if (PI == PE)
  1799. return false;
  1800. Pred1 = *PI++;
  1801. if (PI == PE)
  1802. return false;
  1803. Pred2 = *PI++;
  1804. if (PI != PE)
  1805. return false;
  1806. if (Pred1 == Pred2)
  1807. return false;
  1808. // Try to thread one of the guards of the block.
  1809. // TODO: Look up deeper than to immediate predecessor?
  1810. auto *Parent = Pred1->getSinglePredecessor();
  1811. if (!Parent || Parent != Pred2->getSinglePredecessor())
  1812. return false;
  1813. if (auto *BI = dyn_cast<BranchInst>(Parent->getTerminator()))
  1814. for (auto &I : *BB)
  1815. if (match(&I, m_Intrinsic<Intrinsic::experimental_guard>()))
  1816. if (ThreadGuard(BB, cast<IntrinsicInst>(&I), BI))
  1817. return true;
  1818. return false;
  1819. }
  1820. /// Try to propagate the guard from BB which is the lower block of a diamond
  1821. /// to one of its branches, in case if diamond's condition implies guard's
  1822. /// condition.
  1823. bool JumpThreadingPass::ThreadGuard(BasicBlock *BB, IntrinsicInst *Guard,
  1824. BranchInst *BI) {
  1825. assert(BI->getNumSuccessors() == 2 && "Wrong number of successors?");
  1826. assert(BI->isConditional() && "Unconditional branch has 2 successors?");
  1827. Value *GuardCond = Guard->getArgOperand(0);
  1828. Value *BranchCond = BI->getCondition();
  1829. BasicBlock *TrueDest = BI->getSuccessor(0);
  1830. BasicBlock *FalseDest = BI->getSuccessor(1);
  1831. auto &DL = BB->getModule()->getDataLayout();
  1832. bool TrueDestIsSafe = false;
  1833. bool FalseDestIsSafe = false;
  1834. // True dest is safe if BranchCond => GuardCond.
  1835. auto Impl = isImpliedCondition(BranchCond, GuardCond, DL);
  1836. if (Impl && *Impl)
  1837. TrueDestIsSafe = true;
  1838. else {
  1839. // False dest is safe if !BranchCond => GuardCond.
  1840. Impl =
  1841. isImpliedCondition(BranchCond, GuardCond, DL, /* InvertAPred */ true);
  1842. if (Impl && *Impl)
  1843. FalseDestIsSafe = true;
  1844. }
  1845. if (!TrueDestIsSafe && !FalseDestIsSafe)
  1846. return false;
  1847. BasicBlock *UnguardedBlock = TrueDestIsSafe ? TrueDest : FalseDest;
  1848. BasicBlock *GuardedBlock = FalseDestIsSafe ? TrueDest : FalseDest;
  1849. ValueToValueMapTy UnguardedMapping, GuardedMapping;
  1850. Instruction *AfterGuard = Guard->getNextNode();
  1851. unsigned Cost = getJumpThreadDuplicationCost(BB, AfterGuard, BBDupThreshold);
  1852. if (Cost > BBDupThreshold)
  1853. return false;
  1854. // Duplicate all instructions before the guard and the guard itself to the
  1855. // branch where implication is not proved.
  1856. GuardedBlock = DuplicateInstructionsInSplitBetween(
  1857. BB, GuardedBlock, AfterGuard, GuardedMapping);
  1858. assert(GuardedBlock && "Could not create the guarded block?");
  1859. // Duplicate all instructions before the guard in the unguarded branch.
  1860. // Since we have successfully duplicated the guarded block and this block
  1861. // has fewer instructions, we expect it to succeed.
  1862. UnguardedBlock = DuplicateInstructionsInSplitBetween(BB, UnguardedBlock,
  1863. Guard, UnguardedMapping);
  1864. assert(UnguardedBlock && "Could not create the unguarded block?");
  1865. DEBUG(dbgs() << "Moved guard " << *Guard << " to block "
  1866. << GuardedBlock->getName() << "\n");
  1867. // Some instructions before the guard may still have uses. For them, we need
  1868. // to create Phi nodes merging their copies in both guarded and unguarded
  1869. // branches. Those instructions that have no uses can be just removed.
  1870. SmallVector<Instruction *, 4> ToRemove;
  1871. for (auto BI = BB->begin(); &*BI != AfterGuard; ++BI)
  1872. if (!isa<PHINode>(&*BI))
  1873. ToRemove.push_back(&*BI);
  1874. Instruction *InsertionPoint = &*BB->getFirstInsertionPt();
  1875. assert(InsertionPoint && "Empty block?");
  1876. // Substitute with Phis & remove.
  1877. for (auto *Inst : reverse(ToRemove)) {
  1878. if (!Inst->use_empty()) {
  1879. PHINode *NewPN = PHINode::Create(Inst->getType(), 2);
  1880. NewPN->addIncoming(UnguardedMapping[Inst], UnguardedBlock);
  1881. NewPN->addIncoming(GuardedMapping[Inst], GuardedBlock);
  1882. NewPN->insertBefore(InsertionPoint);
  1883. Inst->replaceAllUsesWith(NewPN);
  1884. }
  1885. Inst->eraseFromParent();
  1886. }
  1887. return true;
  1888. }