JumpThreading.cpp 67 KB

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