LoopUnswitch.cpp 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231
  1. //===-- LoopUnswitch.cpp - Hoist loop-invariant conditionals in loop ------===//
  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 pass transforms loops that contain branches on loop-invariant conditions
  11. // to have multiple loops. For example, it turns the left into the right code:
  12. //
  13. // for (...) if (lic)
  14. // A for (...)
  15. // if (lic) A; B; C
  16. // B else
  17. // C for (...)
  18. // A; C
  19. //
  20. // This can increase the size of the code exponentially (doubling it every time
  21. // a loop is unswitched) so we only unswitch if the resultant code will be
  22. // smaller than a threshold.
  23. //
  24. // This pass expects LICM to be run before it to hoist invariant conditions out
  25. // of the loop, to make the unswitching opportunity obvious.
  26. //
  27. //===----------------------------------------------------------------------===//
  28. #include "llvm/Transforms/Scalar.h"
  29. #include "llvm/ADT/STLExtras.h"
  30. #include "llvm/ADT/SmallPtrSet.h"
  31. #include "llvm/ADT/Statistic.h"
  32. #include "llvm/Analysis/AssumptionCache.h"
  33. #include "llvm/Analysis/CodeMetrics.h"
  34. #include "llvm/Analysis/InstructionSimplify.h"
  35. #include "llvm/Analysis/LoopInfo.h"
  36. #include "llvm/Analysis/LoopPass.h"
  37. #include "llvm/Analysis/ScalarEvolution.h"
  38. #include "llvm/Analysis/TargetTransformInfo.h"
  39. #include "llvm/IR/Constants.h"
  40. #include "llvm/IR/DerivedTypes.h"
  41. #include "llvm/IR/Dominators.h"
  42. #include "llvm/IR/Function.h"
  43. #include "llvm/IR/Instructions.h"
  44. #include "llvm/IR/Module.h"
  45. #include "llvm/IR/MDBuilder.h"
  46. #include "llvm/Support/CommandLine.h"
  47. #include "llvm/Support/Debug.h"
  48. #include "llvm/Support/raw_ostream.h"
  49. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  50. #include "llvm/Transforms/Utils/Cloning.h"
  51. #include "llvm/Transforms/Utils/Local.h"
  52. #include <algorithm>
  53. #include <map>
  54. #include <set>
  55. using namespace llvm;
  56. #define DEBUG_TYPE "loop-unswitch"
  57. STATISTIC(NumBranches, "Number of branches unswitched");
  58. STATISTIC(NumSwitches, "Number of switches unswitched");
  59. STATISTIC(NumSelects , "Number of selects unswitched");
  60. STATISTIC(NumTrivial , "Number of unswitches that are trivial");
  61. STATISTIC(NumSimplify, "Number of simplifications of unswitched code");
  62. STATISTIC(TotalInsts, "Total number of instructions analyzed");
  63. // The specific value of 100 here was chosen based only on intuition and a
  64. // few specific examples.
  65. #if 0 // HLSL Change Starts - option pending
  66. static cl::opt<unsigned>
  67. Threshold("loop-unswitch-threshold", cl::desc("Max loop size to unswitch"),
  68. cl::init(100), cl::Hidden);
  69. #else
  70. static const unsigned Threshold = 100;
  71. #endif
  72. namespace {
  73. class LUAnalysisCache {
  74. typedef DenseMap<const SwitchInst*, SmallPtrSet<const Value *, 8> >
  75. UnswitchedValsMap;
  76. typedef UnswitchedValsMap::iterator UnswitchedValsIt;
  77. struct LoopProperties {
  78. unsigned CanBeUnswitchedCount;
  79. unsigned WasUnswitchedCount;
  80. unsigned SizeEstimation;
  81. UnswitchedValsMap UnswitchedVals;
  82. };
  83. // Here we use std::map instead of DenseMap, since we need to keep valid
  84. // LoopProperties pointer for current loop for better performance.
  85. typedef std::map<const Loop*, LoopProperties> LoopPropsMap;
  86. typedef LoopPropsMap::iterator LoopPropsMapIt;
  87. LoopPropsMap LoopsProperties;
  88. UnswitchedValsMap *CurLoopInstructions;
  89. LoopProperties *CurrentLoopProperties;
  90. // A loop unswitching with an estimated cost above this threshold
  91. // is not performed. MaxSize is turned into unswitching quota for
  92. // the current loop, and reduced correspondingly, though note that
  93. // the quota is returned by releaseMemory() when the loop has been
  94. // processed, so that MaxSize will return to its previous
  95. // value. So in most cases MaxSize will equal the Threshold flag
  96. // when a new loop is processed. An exception to that is that
  97. // MaxSize will have a smaller value while processing nested loops
  98. // that were introduced due to loop unswitching of an outer loop.
  99. //
  100. // FIXME: The way that MaxSize works is subtle and depends on the
  101. // pass manager processing loops and calling releaseMemory() in a
  102. // specific order. It would be good to find a more straightforward
  103. // way of doing what MaxSize does.
  104. unsigned MaxSize;
  105. public:
  106. LUAnalysisCache()
  107. : CurLoopInstructions(nullptr), CurrentLoopProperties(nullptr),
  108. MaxSize(Threshold) {}
  109. // Analyze loop. Check its size, calculate is it possible to unswitch
  110. // it. Returns true if we can unswitch this loop.
  111. bool countLoop(const Loop *L, const TargetTransformInfo &TTI,
  112. AssumptionCache *AC);
  113. // Clean all data related to given loop.
  114. void forgetLoop(const Loop *L);
  115. // Mark case value as unswitched.
  116. // Since SI instruction can be partly unswitched, in order to avoid
  117. // extra unswitching in cloned loops keep track all unswitched values.
  118. void setUnswitched(const SwitchInst *SI, const Value *V);
  119. // Check was this case value unswitched before or not.
  120. bool isUnswitched(const SwitchInst *SI, const Value *V);
  121. // Returns true if another unswitching could be done within the cost
  122. // threshold.
  123. bool CostAllowsUnswitching();
  124. // Clone all loop-unswitch related loop properties.
  125. // Redistribute unswitching quotas.
  126. // Note, that new loop data is stored inside the VMap.
  127. void cloneData(const Loop *NewLoop, const Loop *OldLoop,
  128. const ValueToValueMapTy &VMap);
  129. };
  130. class LoopUnswitch : public LoopPass {
  131. LoopInfo *LI; // Loop information
  132. LPPassManager *LPM;
  133. AssumptionCache *AC;
  134. // LoopProcessWorklist - Used to check if second loop needs processing
  135. // after RewriteLoopBodyWithConditionConstant rewrites first loop.
  136. std::vector<Loop*> LoopProcessWorklist;
  137. LUAnalysisCache BranchesInfo;
  138. bool OptimizeForSize;
  139. bool redoLoop;
  140. Loop *currentLoop;
  141. DominatorTree *DT;
  142. BasicBlock *loopHeader;
  143. BasicBlock *loopPreheader;
  144. // LoopBlocks contains all of the basic blocks of the loop, including the
  145. // preheader of the loop, the body of the loop, and the exit blocks of the
  146. // loop, in that order.
  147. std::vector<BasicBlock*> LoopBlocks;
  148. // NewBlocks contained cloned copy of basic blocks from LoopBlocks.
  149. std::vector<BasicBlock*> NewBlocks;
  150. public:
  151. static char ID; // Pass ID, replacement for typeid
  152. explicit LoopUnswitch(bool Os = false) :
  153. LoopPass(ID), OptimizeForSize(Os), redoLoop(false),
  154. currentLoop(nullptr), DT(nullptr), loopHeader(nullptr),
  155. loopPreheader(nullptr) {
  156. initializeLoopUnswitchPass(*PassRegistry::getPassRegistry());
  157. }
  158. bool runOnLoop(Loop *L, LPPassManager &LPM) override;
  159. bool processCurrentLoop();
  160. /// This transformation requires natural loop information & requires that
  161. /// loop preheaders be inserted into the CFG.
  162. ///
  163. void getAnalysisUsage(AnalysisUsage &AU) const override {
  164. AU.addRequired<AssumptionCacheTracker>();
  165. AU.addRequiredID(LoopSimplifyID);
  166. AU.addPreservedID(LoopSimplifyID);
  167. AU.addRequired<LoopInfoWrapperPass>();
  168. AU.addPreserved<LoopInfoWrapperPass>();
  169. AU.addRequiredID(LCSSAID);
  170. AU.addPreservedID(LCSSAID);
  171. AU.addPreserved<DominatorTreeWrapperPass>();
  172. AU.addPreserved<ScalarEvolution>();
  173. AU.addRequired<TargetTransformInfoWrapperPass>();
  174. }
  175. private:
  176. void releaseMemory() override {
  177. BranchesInfo.forgetLoop(currentLoop);
  178. }
  179. void initLoopData() {
  180. loopHeader = currentLoop->getHeader();
  181. loopPreheader = currentLoop->getLoopPreheader();
  182. }
  183. /// Split all of the edges from inside the loop to their exit blocks.
  184. /// Update the appropriate Phi nodes as we do so.
  185. void SplitExitEdges(Loop *L, const SmallVectorImpl<BasicBlock *> &ExitBlocks);
  186. bool UnswitchIfProfitable(Value *LoopCond, Constant *Val,
  187. TerminatorInst *TI = nullptr);
  188. void UnswitchTrivialCondition(Loop *L, Value *Cond, Constant *Val,
  189. BasicBlock *ExitBlock, TerminatorInst *TI);
  190. void UnswitchNontrivialCondition(Value *LIC, Constant *OnVal, Loop *L,
  191. TerminatorInst *TI);
  192. void RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
  193. Constant *Val, bool isEqual);
  194. void EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
  195. BasicBlock *TrueDest,
  196. BasicBlock *FalseDest,
  197. Instruction *InsertPt,
  198. TerminatorInst *TI);
  199. void SimplifyCode(std::vector<Instruction*> &Worklist, Loop *L);
  200. bool IsTrivialUnswitchCondition(Value *Cond, Constant **Val = nullptr,
  201. BasicBlock **LoopExit = nullptr);
  202. };
  203. }
  204. // Analyze loop. Check its size, calculate is it possible to unswitch
  205. // it. Returns true if we can unswitch this loop.
  206. bool LUAnalysisCache::countLoop(const Loop *L, const TargetTransformInfo &TTI,
  207. AssumptionCache *AC) {
  208. LoopPropsMapIt PropsIt;
  209. bool Inserted;
  210. std::tie(PropsIt, Inserted) =
  211. LoopsProperties.insert(std::make_pair(L, LoopProperties()));
  212. LoopProperties &Props = PropsIt->second;
  213. if (Inserted) {
  214. // New loop.
  215. // Limit the number of instructions to avoid causing significant code
  216. // expansion, and the number of basic blocks, to avoid loops with
  217. // large numbers of branches which cause loop unswitching to go crazy.
  218. // This is a very ad-hoc heuristic.
  219. SmallPtrSet<const Value *, 32> EphValues;
  220. CodeMetrics::collectEphemeralValues(L, AC, EphValues);
  221. // FIXME: This is overly conservative because it does not take into
  222. // consideration code simplification opportunities and code that can
  223. // be shared by the resultant unswitched loops.
  224. CodeMetrics Metrics;
  225. for (Loop::block_iterator I = L->block_begin(), E = L->block_end(); I != E;
  226. ++I)
  227. Metrics.analyzeBasicBlock(*I, TTI, EphValues);
  228. Props.SizeEstimation = Metrics.NumInsts;
  229. Props.CanBeUnswitchedCount = MaxSize / (Props.SizeEstimation);
  230. Props.WasUnswitchedCount = 0;
  231. MaxSize -= Props.SizeEstimation * Props.CanBeUnswitchedCount;
  232. if (Metrics.notDuplicatable) {
  233. DEBUG(dbgs() << "NOT unswitching loop %"
  234. << L->getHeader()->getName() << ", contents cannot be "
  235. << "duplicated!\n");
  236. return false;
  237. }
  238. }
  239. // Be careful. This links are good only before new loop addition.
  240. CurrentLoopProperties = &Props;
  241. CurLoopInstructions = &Props.UnswitchedVals;
  242. return true;
  243. }
  244. // Clean all data related to given loop.
  245. void LUAnalysisCache::forgetLoop(const Loop *L) {
  246. LoopPropsMapIt LIt = LoopsProperties.find(L);
  247. if (LIt != LoopsProperties.end()) {
  248. LoopProperties &Props = LIt->second;
  249. MaxSize += (Props.CanBeUnswitchedCount + Props.WasUnswitchedCount) *
  250. Props.SizeEstimation;
  251. LoopsProperties.erase(LIt);
  252. }
  253. CurrentLoopProperties = nullptr;
  254. CurLoopInstructions = nullptr;
  255. }
  256. // Mark case value as unswitched.
  257. // Since SI instruction can be partly unswitched, in order to avoid
  258. // extra unswitching in cloned loops keep track all unswitched values.
  259. void LUAnalysisCache::setUnswitched(const SwitchInst *SI, const Value *V) {
  260. (*CurLoopInstructions)[SI].insert(V);
  261. }
  262. // Check was this case value unswitched before or not.
  263. bool LUAnalysisCache::isUnswitched(const SwitchInst *SI, const Value *V) {
  264. return (*CurLoopInstructions)[SI].count(V);
  265. }
  266. bool LUAnalysisCache::CostAllowsUnswitching() {
  267. return CurrentLoopProperties->CanBeUnswitchedCount > 0;
  268. }
  269. // Clone all loop-unswitch related loop properties.
  270. // Redistribute unswitching quotas.
  271. // Note, that new loop data is stored inside the VMap.
  272. void LUAnalysisCache::cloneData(const Loop *NewLoop, const Loop *OldLoop,
  273. const ValueToValueMapTy &VMap) {
  274. LoopProperties &NewLoopProps = LoopsProperties[NewLoop];
  275. LoopProperties &OldLoopProps = *CurrentLoopProperties;
  276. UnswitchedValsMap &Insts = OldLoopProps.UnswitchedVals;
  277. // Reallocate "can-be-unswitched quota"
  278. --OldLoopProps.CanBeUnswitchedCount;
  279. ++OldLoopProps.WasUnswitchedCount;
  280. NewLoopProps.WasUnswitchedCount = 0;
  281. unsigned Quota = OldLoopProps.CanBeUnswitchedCount;
  282. NewLoopProps.CanBeUnswitchedCount = Quota / 2;
  283. OldLoopProps.CanBeUnswitchedCount = Quota - Quota / 2;
  284. NewLoopProps.SizeEstimation = OldLoopProps.SizeEstimation;
  285. // Clone unswitched values info:
  286. // for new loop switches we clone info about values that was
  287. // already unswitched and has redundant successors.
  288. for (UnswitchedValsIt I = Insts.begin(); I != Insts.end(); ++I) {
  289. const SwitchInst *OldInst = I->first;
  290. Value *NewI = VMap.lookup(OldInst);
  291. const SwitchInst *NewInst = cast_or_null<SwitchInst>(NewI);
  292. assert(NewInst && "All instructions that are in SrcBB must be in VMap.");
  293. NewLoopProps.UnswitchedVals[NewInst] = OldLoopProps.UnswitchedVals[OldInst];
  294. }
  295. }
  296. char LoopUnswitch::ID = 0;
  297. INITIALIZE_PASS_BEGIN(LoopUnswitch, "loop-unswitch", "Unswitch loops",
  298. false, false)
  299. INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
  300. INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
  301. INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
  302. INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
  303. INITIALIZE_PASS_DEPENDENCY(LCSSA)
  304. INITIALIZE_PASS_END(LoopUnswitch, "loop-unswitch", "Unswitch loops",
  305. false, false)
  306. Pass *llvm::createLoopUnswitchPass(bool Os) {
  307. return new LoopUnswitch(Os);
  308. }
  309. /// FindLIVLoopCondition - Cond is a condition that occurs in L. If it is
  310. /// invariant in the loop, or has an invariant piece, return the invariant.
  311. /// Otherwise, return null.
  312. static Value *FindLIVLoopCondition(Value *Cond, Loop *L, bool &Changed) {
  313. // We started analyze new instruction, increment scanned instructions counter.
  314. ++TotalInsts;
  315. // We can never unswitch on vector conditions.
  316. if (Cond->getType()->isVectorTy())
  317. return nullptr;
  318. // Constants should be folded, not unswitched on!
  319. if (isa<Constant>(Cond)) return nullptr;
  320. // TODO: Handle: br (VARIANT|INVARIANT).
  321. // Hoist simple values out.
  322. if (L->makeLoopInvariant(Cond, Changed))
  323. return Cond;
  324. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Cond))
  325. if (BO->getOpcode() == Instruction::And ||
  326. BO->getOpcode() == Instruction::Or) {
  327. // If either the left or right side is invariant, we can unswitch on this,
  328. // which will cause the branch to go away in one loop and the condition to
  329. // simplify in the other one.
  330. if (Value *LHS = FindLIVLoopCondition(BO->getOperand(0), L, Changed))
  331. return LHS;
  332. if (Value *RHS = FindLIVLoopCondition(BO->getOperand(1), L, Changed))
  333. return RHS;
  334. }
  335. return nullptr;
  336. }
  337. bool LoopUnswitch::runOnLoop(Loop *L, LPPassManager &LPM_Ref) {
  338. if (skipOptnoneFunction(L))
  339. return false;
  340. AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(
  341. *L->getHeader()->getParent());
  342. LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
  343. LPM = &LPM_Ref;
  344. DominatorTreeWrapperPass *DTWP =
  345. getAnalysisIfAvailable<DominatorTreeWrapperPass>();
  346. DT = DTWP ? &DTWP->getDomTree() : nullptr;
  347. currentLoop = L;
  348. Function *F = currentLoop->getHeader()->getParent();
  349. bool Changed = false;
  350. do {
  351. assert(currentLoop->isLCSSAForm(*DT));
  352. redoLoop = false;
  353. Changed |= processCurrentLoop();
  354. } while(redoLoop);
  355. if (Changed) {
  356. // FIXME: Reconstruct dom info, because it is not preserved properly.
  357. if (DT)
  358. DT->recalculate(*F);
  359. }
  360. return Changed;
  361. }
  362. /// processCurrentLoop - Do actual work and unswitch loop if possible
  363. /// and profitable.
  364. bool LoopUnswitch::processCurrentLoop() {
  365. bool Changed = false;
  366. initLoopData();
  367. // If LoopSimplify was unable to form a preheader, don't do any unswitching.
  368. if (!loopPreheader)
  369. return false;
  370. // Loops with indirectbr cannot be cloned.
  371. if (!currentLoop->isSafeToClone())
  372. return false;
  373. // Without dedicated exits, splitting the exit edge may fail.
  374. if (!currentLoop->hasDedicatedExits())
  375. return false;
  376. LLVMContext &Context = loopHeader->getContext();
  377. // Probably we reach the quota of branches for this loop. If so
  378. // stop unswitching.
  379. if (!BranchesInfo.countLoop(
  380. currentLoop, getAnalysis<TargetTransformInfoWrapperPass>().getTTI(
  381. *currentLoop->getHeader()->getParent()),
  382. AC))
  383. return false;
  384. // Loop over all of the basic blocks in the loop. If we find an interior
  385. // block that is branching on a loop-invariant condition, we can unswitch this
  386. // loop.
  387. for (Loop::block_iterator I = currentLoop->block_begin(),
  388. E = currentLoop->block_end(); I != E; ++I) {
  389. TerminatorInst *TI = (*I)->getTerminator();
  390. if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
  391. // If this isn't branching on an invariant condition, we can't unswitch
  392. // it.
  393. if (BI->isConditional()) {
  394. // See if this, or some part of it, is loop invariant. If so, we can
  395. // unswitch on it if we desire.
  396. Value *LoopCond = FindLIVLoopCondition(BI->getCondition(),
  397. currentLoop, Changed);
  398. if (LoopCond &&
  399. UnswitchIfProfitable(LoopCond, ConstantInt::getTrue(Context), TI)) {
  400. ++NumBranches;
  401. return true;
  402. }
  403. }
  404. } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
  405. Value *LoopCond = FindLIVLoopCondition(SI->getCondition(),
  406. currentLoop, Changed);
  407. unsigned NumCases = SI->getNumCases();
  408. if (LoopCond && NumCases) {
  409. // Find a value to unswitch on:
  410. // FIXME: this should chose the most expensive case!
  411. // FIXME: scan for a case with a non-critical edge?
  412. Constant *UnswitchVal = nullptr;
  413. // Do not process same value again and again.
  414. // At this point we have some cases already unswitched and
  415. // some not yet unswitched. Let's find the first not yet unswitched one.
  416. for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
  417. i != e; ++i) {
  418. Constant *UnswitchValCandidate = i.getCaseValue();
  419. if (!BranchesInfo.isUnswitched(SI, UnswitchValCandidate)) {
  420. UnswitchVal = UnswitchValCandidate;
  421. break;
  422. }
  423. }
  424. if (!UnswitchVal)
  425. continue;
  426. if (UnswitchIfProfitable(LoopCond, UnswitchVal)) {
  427. ++NumSwitches;
  428. return true;
  429. }
  430. }
  431. }
  432. // Scan the instructions to check for unswitchable values.
  433. for (BasicBlock::iterator BBI = (*I)->begin(), E = (*I)->end();
  434. BBI != E; ++BBI)
  435. if (SelectInst *SI = dyn_cast<SelectInst>(BBI)) {
  436. Value *LoopCond = FindLIVLoopCondition(SI->getCondition(),
  437. currentLoop, Changed);
  438. if (LoopCond && UnswitchIfProfitable(LoopCond,
  439. ConstantInt::getTrue(Context))) {
  440. ++NumSelects;
  441. return true;
  442. }
  443. }
  444. }
  445. return Changed;
  446. }
  447. /// isTrivialLoopExitBlock - Check to see if all paths from BB exit the
  448. /// loop with no side effects (including infinite loops).
  449. ///
  450. /// If true, we return true and set ExitBB to the block we
  451. /// exit through.
  452. ///
  453. static bool isTrivialLoopExitBlockHelper(Loop *L, BasicBlock *BB,
  454. BasicBlock *&ExitBB,
  455. std::set<BasicBlock*> &Visited) {
  456. if (!Visited.insert(BB).second) {
  457. // Already visited. Without more analysis, this could indicate an infinite
  458. // loop.
  459. return false;
  460. }
  461. if (!L->contains(BB)) {
  462. // Otherwise, this is a loop exit, this is fine so long as this is the
  463. // first exit.
  464. if (ExitBB) return false;
  465. ExitBB = BB;
  466. return true;
  467. }
  468. // Otherwise, this is an unvisited intra-loop node. Check all successors.
  469. for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI) {
  470. // Check to see if the successor is a trivial loop exit.
  471. if (!isTrivialLoopExitBlockHelper(L, *SI, ExitBB, Visited))
  472. return false;
  473. }
  474. // Okay, everything after this looks good, check to make sure that this block
  475. // doesn't include any side effects.
  476. for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
  477. if (I->mayHaveSideEffects())
  478. return false;
  479. return true;
  480. }
  481. /// isTrivialLoopExitBlock - Return true if the specified block unconditionally
  482. /// leads to an exit from the specified loop, and has no side-effects in the
  483. /// process. If so, return the block that is exited to, otherwise return null.
  484. static BasicBlock *isTrivialLoopExitBlock(Loop *L, BasicBlock *BB) {
  485. std::set<BasicBlock*> Visited;
  486. Visited.insert(L->getHeader()); // Branches to header make infinite loops.
  487. BasicBlock *ExitBB = nullptr;
  488. if (isTrivialLoopExitBlockHelper(L, BB, ExitBB, Visited))
  489. return ExitBB;
  490. return nullptr;
  491. }
  492. /// IsTrivialUnswitchCondition - Check to see if this unswitch condition is
  493. /// trivial: that is, that the condition controls whether or not the loop does
  494. /// anything at all. If this is a trivial condition, unswitching produces no
  495. /// code duplications (equivalently, it produces a simpler loop and a new empty
  496. /// loop, which gets deleted).
  497. ///
  498. /// If this is a trivial condition, return true, otherwise return false. When
  499. /// returning true, this sets Cond and Val to the condition that controls the
  500. /// trivial condition: when Cond dynamically equals Val, the loop is known to
  501. /// exit. Finally, this sets LoopExit to the BB that the loop exits to when
  502. /// Cond == Val.
  503. ///
  504. bool LoopUnswitch::IsTrivialUnswitchCondition(Value *Cond, Constant **Val,
  505. BasicBlock **LoopExit) {
  506. BasicBlock *Header = currentLoop->getHeader();
  507. TerminatorInst *HeaderTerm = Header->getTerminator();
  508. LLVMContext &Context = Header->getContext();
  509. BasicBlock *LoopExitBB = nullptr;
  510. if (BranchInst *BI = dyn_cast<BranchInst>(HeaderTerm)) {
  511. // If the header block doesn't end with a conditional branch on Cond, we
  512. // can't handle it.
  513. if (!BI->isConditional() || BI->getCondition() != Cond)
  514. return false;
  515. // Check to see if a successor of the branch is guaranteed to
  516. // exit through a unique exit block without having any
  517. // side-effects. If so, determine the value of Cond that causes it to do
  518. // this.
  519. if ((LoopExitBB = isTrivialLoopExitBlock(currentLoop,
  520. BI->getSuccessor(0)))) {
  521. if (Val) *Val = ConstantInt::getTrue(Context);
  522. } else if ((LoopExitBB = isTrivialLoopExitBlock(currentLoop,
  523. BI->getSuccessor(1)))) {
  524. if (Val) *Val = ConstantInt::getFalse(Context);
  525. }
  526. } else if (SwitchInst *SI = dyn_cast<SwitchInst>(HeaderTerm)) {
  527. // If this isn't a switch on Cond, we can't handle it.
  528. if (SI->getCondition() != Cond) return false;
  529. // Check to see if a successor of the switch is guaranteed to go to the
  530. // latch block or exit through a one exit block without having any
  531. // side-effects. If so, determine the value of Cond that causes it to do
  532. // this.
  533. // Note that we can't trivially unswitch on the default case or
  534. // on already unswitched cases.
  535. for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
  536. i != e; ++i) {
  537. BasicBlock *LoopExitCandidate;
  538. if ((LoopExitCandidate = isTrivialLoopExitBlock(currentLoop,
  539. i.getCaseSuccessor()))) {
  540. // Okay, we found a trivial case, remember the value that is trivial.
  541. ConstantInt *CaseVal = i.getCaseValue();
  542. // Check that it was not unswitched before, since already unswitched
  543. // trivial vals are looks trivial too.
  544. if (BranchesInfo.isUnswitched(SI, CaseVal))
  545. continue;
  546. LoopExitBB = LoopExitCandidate;
  547. if (Val) *Val = CaseVal;
  548. break;
  549. }
  550. }
  551. }
  552. // If we didn't find a single unique LoopExit block, or if the loop exit block
  553. // contains phi nodes, this isn't trivial.
  554. if (!LoopExitBB || isa<PHINode>(LoopExitBB->begin()))
  555. return false; // Can't handle this.
  556. if (LoopExit) *LoopExit = LoopExitBB;
  557. // We already know that nothing uses any scalar values defined inside of this
  558. // loop. As such, we just have to check to see if this loop will execute any
  559. // side-effecting instructions (e.g. stores, calls, volatile loads) in the
  560. // part of the loop that the code *would* execute. We already checked the
  561. // tail, check the header now.
  562. for (BasicBlock::iterator I = Header->begin(), E = Header->end(); I != E; ++I)
  563. if (I->mayHaveSideEffects())
  564. return false;
  565. return true;
  566. }
  567. /// UnswitchIfProfitable - We have found that we can unswitch currentLoop when
  568. /// LoopCond == Val to simplify the loop. If we decide that this is profitable,
  569. /// unswitch the loop, reprocess the pieces, then return true.
  570. bool LoopUnswitch::UnswitchIfProfitable(Value *LoopCond, Constant *Val,
  571. TerminatorInst *TI) {
  572. Function *F = loopHeader->getParent();
  573. Constant *CondVal = nullptr;
  574. BasicBlock *ExitBlock = nullptr;
  575. if (IsTrivialUnswitchCondition(LoopCond, &CondVal, &ExitBlock)) {
  576. // If the condition is trivial, always unswitch. There is no code growth
  577. // for this case.
  578. UnswitchTrivialCondition(currentLoop, LoopCond, CondVal, ExitBlock, TI);
  579. return true;
  580. }
  581. // Check to see if it would be profitable to unswitch current loop.
  582. if (!BranchesInfo.CostAllowsUnswitching()) {
  583. DEBUG(dbgs() << "NOT unswitching loop %"
  584. << currentLoop->getHeader()->getName()
  585. << " at non-trivial condition '" << *Val
  586. << "' == " << *LoopCond << "\n"
  587. << ". Cost too high.\n");
  588. return false;
  589. }
  590. // Do not do non-trivial unswitch while optimizing for size.
  591. if (OptimizeForSize || F->hasFnAttribute(Attribute::OptimizeForSize))
  592. return false;
  593. UnswitchNontrivialCondition(LoopCond, Val, currentLoop, TI);
  594. return true;
  595. }
  596. /// CloneLoop - Recursively clone the specified loop and all of its children,
  597. /// mapping the blocks with the specified map.
  598. static Loop *CloneLoop(Loop *L, Loop *PL, ValueToValueMapTy &VM,
  599. LoopInfo *LI, LPPassManager *LPM) {
  600. Loop *New = new Loop();
  601. LPM->insertLoop(New, PL);
  602. // Add all of the blocks in L to the new loop.
  603. for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
  604. I != E; ++I)
  605. if (LI->getLoopFor(*I) == L)
  606. New->addBasicBlockToLoop(cast<BasicBlock>(VM[*I]), *LI);
  607. // Add all of the subloops to the new loop.
  608. for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
  609. CloneLoop(*I, New, VM, LI, LPM);
  610. return New;
  611. }
  612. static void copyMetadata(Instruction *DstInst, const Instruction *SrcInst,
  613. bool Swapped) {
  614. if (!SrcInst || !SrcInst->hasMetadata())
  615. return;
  616. SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
  617. SrcInst->getAllMetadata(MDs);
  618. for (auto &MD : MDs) {
  619. switch (MD.first) {
  620. default:
  621. break;
  622. case LLVMContext::MD_prof:
  623. if (Swapped && MD.second->getNumOperands() == 3 &&
  624. isa<MDString>(MD.second->getOperand(0))) {
  625. MDString *MDName = cast<MDString>(MD.second->getOperand(0));
  626. if (MDName->getString() == "branch_weights") {
  627. auto *ValT = cast_or_null<ConstantAsMetadata>(
  628. MD.second->getOperand(1))->getValue();
  629. auto *ValF = cast_or_null<ConstantAsMetadata>(
  630. MD.second->getOperand(2))->getValue();
  631. assert(ValT && ValF && "Invalid Operands of branch_weights");
  632. auto NewMD =
  633. MDBuilder(DstInst->getParent()->getContext())
  634. .createBranchWeights(cast<ConstantInt>(ValF)->getZExtValue(),
  635. cast<ConstantInt>(ValT)->getZExtValue());
  636. MD.second = NewMD;
  637. }
  638. }
  639. // fallthrough.
  640. case LLVMContext::MD_dbg:
  641. DstInst->setMetadata(MD.first, MD.second);
  642. }
  643. }
  644. }
  645. /// EmitPreheaderBranchOnCondition - Emit a conditional branch on two values
  646. /// if LIC == Val, branch to TrueDst, otherwise branch to FalseDest. Insert the
  647. /// code immediately before InsertPt.
  648. void LoopUnswitch::EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
  649. BasicBlock *TrueDest,
  650. BasicBlock *FalseDest,
  651. Instruction *InsertPt,
  652. TerminatorInst *TI) {
  653. // Insert a conditional branch on LIC to the two preheaders. The original
  654. // code is the true version and the new code is the false version.
  655. Value *BranchVal = LIC;
  656. bool Swapped = false;
  657. if (!isa<ConstantInt>(Val) ||
  658. Val->getType() != Type::getInt1Ty(LIC->getContext()))
  659. BranchVal = new ICmpInst(InsertPt, ICmpInst::ICMP_EQ, LIC, Val);
  660. else if (Val != ConstantInt::getTrue(Val->getContext())) {
  661. // We want to enter the new loop when the condition is true.
  662. std::swap(TrueDest, FalseDest);
  663. Swapped = true;
  664. }
  665. // Insert the new branch.
  666. BranchInst *BI = BranchInst::Create(TrueDest, FalseDest, BranchVal, InsertPt);
  667. copyMetadata(BI, TI, Swapped);
  668. // If either edge is critical, split it. This helps preserve LoopSimplify
  669. // form for enclosing loops.
  670. auto Options = CriticalEdgeSplittingOptions(DT, LI).setPreserveLCSSA();
  671. SplitCriticalEdge(BI, 0, Options);
  672. SplitCriticalEdge(BI, 1, Options);
  673. }
  674. /// UnswitchTrivialCondition - Given a loop that has a trivial unswitchable
  675. /// condition in it (a cond branch from its header block to its latch block,
  676. /// where the path through the loop that doesn't execute its body has no
  677. /// side-effects), unswitch it. This doesn't involve any code duplication, just
  678. /// moving the conditional branch outside of the loop and updating loop info.
  679. void LoopUnswitch::UnswitchTrivialCondition(Loop *L, Value *Cond, Constant *Val,
  680. BasicBlock *ExitBlock,
  681. TerminatorInst *TI) {
  682. DEBUG(dbgs() << "loop-unswitch: Trivial-Unswitch loop %"
  683. << loopHeader->getName() << " [" << L->getBlocks().size()
  684. << " blocks] in Function "
  685. << L->getHeader()->getParent()->getName() << " on cond: " << *Val
  686. << " == " << *Cond << "\n");
  687. // First step, split the preheader, so that we know that there is a safe place
  688. // to insert the conditional branch. We will change loopPreheader to have a
  689. // conditional branch on Cond.
  690. BasicBlock *NewPH = SplitEdge(loopPreheader, loopHeader, DT, LI);
  691. // Now that we have a place to insert the conditional branch, create a place
  692. // to branch to: this is the exit block out of the loop that we should
  693. // short-circuit to.
  694. // Split this block now, so that the loop maintains its exit block, and so
  695. // that the jump from the preheader can execute the contents of the exit block
  696. // without actually branching to it (the exit block should be dominated by the
  697. // loop header, not the preheader).
  698. assert(!L->contains(ExitBlock) && "Exit block is in the loop?");
  699. BasicBlock *NewExit = SplitBlock(ExitBlock, ExitBlock->begin(), DT, LI);
  700. // Okay, now we have a position to branch from and a position to branch to,
  701. // insert the new conditional branch.
  702. EmitPreheaderBranchOnCondition(Cond, Val, NewExit, NewPH,
  703. loopPreheader->getTerminator(), TI);
  704. LPM->deleteSimpleAnalysisValue(loopPreheader->getTerminator(), L);
  705. loopPreheader->getTerminator()->eraseFromParent();
  706. // We need to reprocess this loop, it could be unswitched again.
  707. redoLoop = true;
  708. // Now that we know that the loop is never entered when this condition is a
  709. // particular value, rewrite the loop with this info. We know that this will
  710. // at least eliminate the old branch.
  711. RewriteLoopBodyWithConditionConstant(L, Cond, Val, false);
  712. ++NumTrivial;
  713. }
  714. /// SplitExitEdges - Split all of the edges from inside the loop to their exit
  715. /// blocks. Update the appropriate Phi nodes as we do so.
  716. void LoopUnswitch::SplitExitEdges(Loop *L,
  717. const SmallVectorImpl<BasicBlock *> &ExitBlocks){
  718. for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
  719. BasicBlock *ExitBlock = ExitBlocks[i];
  720. SmallVector<BasicBlock *, 4> Preds(pred_begin(ExitBlock),
  721. pred_end(ExitBlock));
  722. // Although SplitBlockPredecessors doesn't preserve loop-simplify in
  723. // general, if we call it on all predecessors of all exits then it does.
  724. SplitBlockPredecessors(ExitBlock, Preds, ".us-lcssa",
  725. /*AliasAnalysis*/ nullptr, DT, LI,
  726. /*PreserveLCSSA*/ true);
  727. }
  728. }
  729. /// UnswitchNontrivialCondition - We determined that the loop is profitable
  730. /// to unswitch when LIC equal Val. Split it into loop versions and test the
  731. /// condition outside of either loop. Return the loops created as Out1/Out2.
  732. void LoopUnswitch::UnswitchNontrivialCondition(Value *LIC, Constant *Val,
  733. Loop *L, TerminatorInst *TI) {
  734. Function *F = loopHeader->getParent();
  735. DEBUG(dbgs() << "loop-unswitch: Unswitching loop %"
  736. << loopHeader->getName() << " [" << L->getBlocks().size()
  737. << " blocks] in Function " << F->getName()
  738. << " when '" << *Val << "' == " << *LIC << "\n");
  739. if (ScalarEvolution *SE = getAnalysisIfAvailable<ScalarEvolution>())
  740. SE->forgetLoop(L);
  741. LoopBlocks.clear();
  742. NewBlocks.clear();
  743. // First step, split the preheader and exit blocks, and add these blocks to
  744. // the LoopBlocks list.
  745. BasicBlock *NewPreheader = SplitEdge(loopPreheader, loopHeader, DT, LI);
  746. LoopBlocks.push_back(NewPreheader);
  747. // We want the loop to come after the preheader, but before the exit blocks.
  748. LoopBlocks.insert(LoopBlocks.end(), L->block_begin(), L->block_end());
  749. SmallVector<BasicBlock*, 8> ExitBlocks;
  750. L->getUniqueExitBlocks(ExitBlocks);
  751. // Split all of the edges from inside the loop to their exit blocks. Update
  752. // the appropriate Phi nodes as we do so.
  753. SplitExitEdges(L, ExitBlocks);
  754. // The exit blocks may have been changed due to edge splitting, recompute.
  755. ExitBlocks.clear();
  756. L->getUniqueExitBlocks(ExitBlocks);
  757. // Add exit blocks to the loop blocks.
  758. LoopBlocks.insert(LoopBlocks.end(), ExitBlocks.begin(), ExitBlocks.end());
  759. // Next step, clone all of the basic blocks that make up the loop (including
  760. // the loop preheader and exit blocks), keeping track of the mapping between
  761. // the instructions and blocks.
  762. NewBlocks.reserve(LoopBlocks.size());
  763. ValueToValueMapTy VMap;
  764. for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) {
  765. BasicBlock *NewBB = CloneBasicBlock(LoopBlocks[i], VMap, ".us", F);
  766. NewBlocks.push_back(NewBB);
  767. VMap[LoopBlocks[i]] = NewBB; // Keep the BB mapping.
  768. LPM->cloneBasicBlockSimpleAnalysis(LoopBlocks[i], NewBB, L);
  769. }
  770. // Splice the newly inserted blocks into the function right before the
  771. // original preheader.
  772. F->getBasicBlockList().splice(NewPreheader, F->getBasicBlockList(),
  773. NewBlocks[0], F->end());
  774. // FIXME: We could register any cloned assumptions instead of clearing the
  775. // whole function's cache.
  776. AC->clear();
  777. // Now we create the new Loop object for the versioned loop.
  778. Loop *NewLoop = CloneLoop(L, L->getParentLoop(), VMap, LI, LPM);
  779. // Recalculate unswitching quota, inherit simplified switches info for NewBB,
  780. // Probably clone more loop-unswitch related loop properties.
  781. BranchesInfo.cloneData(NewLoop, L, VMap);
  782. Loop *ParentLoop = L->getParentLoop();
  783. if (ParentLoop) {
  784. // Make sure to add the cloned preheader and exit blocks to the parent loop
  785. // as well.
  786. ParentLoop->addBasicBlockToLoop(NewBlocks[0], *LI);
  787. }
  788. for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
  789. BasicBlock *NewExit = cast<BasicBlock>(VMap[ExitBlocks[i]]);
  790. // The new exit block should be in the same loop as the old one.
  791. if (Loop *ExitBBLoop = LI->getLoopFor(ExitBlocks[i]))
  792. ExitBBLoop->addBasicBlockToLoop(NewExit, *LI);
  793. assert(NewExit->getTerminator()->getNumSuccessors() == 1 &&
  794. "Exit block should have been split to have one successor!");
  795. BasicBlock *ExitSucc = NewExit->getTerminator()->getSuccessor(0);
  796. // If the successor of the exit block had PHI nodes, add an entry for
  797. // NewExit.
  798. for (BasicBlock::iterator I = ExitSucc->begin();
  799. PHINode *PN = dyn_cast<PHINode>(I); ++I) {
  800. Value *V = PN->getIncomingValueForBlock(ExitBlocks[i]);
  801. ValueToValueMapTy::iterator It = VMap.find(V);
  802. if (It != VMap.end()) V = It->second;
  803. PN->addIncoming(V, NewExit);
  804. }
  805. if (LandingPadInst *LPad = NewExit->getLandingPadInst()) {
  806. PHINode *PN = PHINode::Create(LPad->getType(), 0, "",
  807. ExitSucc->getFirstInsertionPt());
  808. for (pred_iterator I = pred_begin(ExitSucc), E = pred_end(ExitSucc);
  809. I != E; ++I) {
  810. BasicBlock *BB = *I;
  811. LandingPadInst *LPI = BB->getLandingPadInst();
  812. LPI->replaceAllUsesWith(PN);
  813. PN->addIncoming(LPI, BB);
  814. }
  815. }
  816. }
  817. // Rewrite the code to refer to itself.
  818. for (unsigned i = 0, e = NewBlocks.size(); i != e; ++i)
  819. for (BasicBlock::iterator I = NewBlocks[i]->begin(),
  820. E = NewBlocks[i]->end(); I != E; ++I)
  821. RemapInstruction(I, VMap,RF_NoModuleLevelChanges|RF_IgnoreMissingEntries);
  822. // Rewrite the original preheader to select between versions of the loop.
  823. BranchInst *OldBR = cast<BranchInst>(loopPreheader->getTerminator());
  824. assert(OldBR->isUnconditional() && OldBR->getSuccessor(0) == LoopBlocks[0] &&
  825. "Preheader splitting did not work correctly!");
  826. // Emit the new branch that selects between the two versions of this loop.
  827. EmitPreheaderBranchOnCondition(LIC, Val, NewBlocks[0], LoopBlocks[0], OldBR,
  828. TI);
  829. LPM->deleteSimpleAnalysisValue(OldBR, L);
  830. OldBR->eraseFromParent();
  831. LoopProcessWorklist.push_back(NewLoop);
  832. redoLoop = true;
  833. // Keep a WeakVH holding onto LIC. If the first call to RewriteLoopBody
  834. // deletes the instruction (for example by simplifying a PHI that feeds into
  835. // the condition that we're unswitching on), we don't rewrite the second
  836. // iteration.
  837. WeakVH LICHandle(LIC);
  838. // Now we rewrite the original code to know that the condition is true and the
  839. // new code to know that the condition is false.
  840. RewriteLoopBodyWithConditionConstant(L, LIC, Val, false);
  841. // It's possible that simplifying one loop could cause the other to be
  842. // changed to another value or a constant. If its a constant, don't simplify
  843. // it.
  844. if (!LoopProcessWorklist.empty() && LoopProcessWorklist.back() == NewLoop &&
  845. LICHandle && !isa<Constant>(LICHandle))
  846. RewriteLoopBodyWithConditionConstant(NewLoop, LICHandle, Val, true);
  847. }
  848. /// RemoveFromWorklist - Remove all instances of I from the worklist vector
  849. /// specified.
  850. static void RemoveFromWorklist(Instruction *I,
  851. std::vector<Instruction*> &Worklist) {
  852. Worklist.erase(std::remove(Worklist.begin(), Worklist.end(), I),
  853. Worklist.end());
  854. }
  855. /// ReplaceUsesOfWith - When we find that I really equals V, remove I from the
  856. /// program, replacing all uses with V and update the worklist.
  857. static void ReplaceUsesOfWith(Instruction *I, Value *V,
  858. std::vector<Instruction*> &Worklist,
  859. Loop *L, LPPassManager *LPM) {
  860. DEBUG(dbgs() << "Replace with '" << *V << "': " << *I);
  861. // Add uses to the worklist, which may be dead now.
  862. for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
  863. if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
  864. Worklist.push_back(Use);
  865. // Add users to the worklist which may be simplified now.
  866. for (User *U : I->users())
  867. Worklist.push_back(cast<Instruction>(U));
  868. LPM->deleteSimpleAnalysisValue(I, L);
  869. RemoveFromWorklist(I, Worklist);
  870. I->replaceAllUsesWith(V);
  871. I->eraseFromParent();
  872. ++NumSimplify;
  873. }
  874. // RewriteLoopBodyWithConditionConstant - We know either that the value LIC has
  875. // the value specified by Val in the specified loop, or we know it does NOT have
  876. // that value. Rewrite any uses of LIC or of properties correlated to it.
  877. void LoopUnswitch::RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
  878. Constant *Val,
  879. bool IsEqual) {
  880. assert(!isa<Constant>(LIC) && "Why are we unswitching on a constant?");
  881. // FIXME: Support correlated properties, like:
  882. // for (...)
  883. // if (li1 < li2)
  884. // ...
  885. // if (li1 > li2)
  886. // ...
  887. // FOLD boolean conditions (X|LIC), (X&LIC). Fold conditional branches,
  888. // selects, switches.
  889. std::vector<Instruction*> Worklist;
  890. LLVMContext &Context = Val->getContext();
  891. // If we know that LIC == Val, or that LIC == NotVal, just replace uses of LIC
  892. // in the loop with the appropriate one directly.
  893. if (IsEqual || (isa<ConstantInt>(Val) &&
  894. Val->getType()->isIntegerTy(1))) {
  895. Value *Replacement;
  896. if (IsEqual)
  897. Replacement = Val;
  898. else
  899. Replacement = ConstantInt::get(Type::getInt1Ty(Val->getContext()),
  900. !cast<ConstantInt>(Val)->getZExtValue());
  901. for (User *U : LIC->users()) {
  902. Instruction *UI = dyn_cast<Instruction>(U);
  903. if (!UI || !L->contains(UI))
  904. continue;
  905. Worklist.push_back(UI);
  906. }
  907. for (std::vector<Instruction*>::iterator UI = Worklist.begin(),
  908. UE = Worklist.end(); UI != UE; ++UI)
  909. (*UI)->replaceUsesOfWith(LIC, Replacement);
  910. SimplifyCode(Worklist, L);
  911. return;
  912. }
  913. // Otherwise, we don't know the precise value of LIC, but we do know that it
  914. // is certainly NOT "Val". As such, simplify any uses in the loop that we
  915. // can. This case occurs when we unswitch switch statements.
  916. for (User *U : LIC->users()) {
  917. Instruction *UI = dyn_cast<Instruction>(U);
  918. if (!UI || !L->contains(UI))
  919. continue;
  920. Worklist.push_back(UI);
  921. // TODO: We could do other simplifications, for example, turning
  922. // 'icmp eq LIC, Val' -> false.
  923. // If we know that LIC is not Val, use this info to simplify code.
  924. SwitchInst *SI = dyn_cast<SwitchInst>(UI);
  925. if (!SI || !isa<ConstantInt>(Val)) continue;
  926. SwitchInst::CaseIt DeadCase = SI->findCaseValue(cast<ConstantInt>(Val));
  927. // Default case is live for multiple values.
  928. if (DeadCase == SI->case_default()) continue;
  929. // Found a dead case value. Don't remove PHI nodes in the
  930. // successor if they become single-entry, those PHI nodes may
  931. // be in the Users list.
  932. BasicBlock *Switch = SI->getParent();
  933. BasicBlock *SISucc = DeadCase.getCaseSuccessor();
  934. BasicBlock *Latch = L->getLoopLatch();
  935. BranchesInfo.setUnswitched(SI, Val);
  936. if (!SI->findCaseDest(SISucc)) continue; // Edge is critical.
  937. // If the DeadCase successor dominates the loop latch, then the
  938. // transformation isn't safe since it will delete the sole predecessor edge
  939. // to the latch.
  940. if (Latch && DT->dominates(SISucc, Latch))
  941. continue;
  942. // FIXME: This is a hack. We need to keep the successor around
  943. // and hooked up so as to preserve the loop structure, because
  944. // trying to update it is complicated. So instead we preserve the
  945. // loop structure and put the block on a dead code path.
  946. SplitEdge(Switch, SISucc, DT, LI);
  947. // Compute the successors instead of relying on the return value
  948. // of SplitEdge, since it may have split the switch successor
  949. // after PHI nodes.
  950. BasicBlock *NewSISucc = DeadCase.getCaseSuccessor();
  951. BasicBlock *OldSISucc = *succ_begin(NewSISucc);
  952. // Create an "unreachable" destination.
  953. BasicBlock *Abort = BasicBlock::Create(Context, "us-unreachable",
  954. Switch->getParent(),
  955. OldSISucc);
  956. new UnreachableInst(Context, Abort);
  957. // Force the new case destination to branch to the "unreachable"
  958. // block while maintaining a (dead) CFG edge to the old block.
  959. NewSISucc->getTerminator()->eraseFromParent();
  960. BranchInst::Create(Abort, OldSISucc,
  961. ConstantInt::getTrue(Context), NewSISucc);
  962. // Release the PHI operands for this edge.
  963. for (BasicBlock::iterator II = NewSISucc->begin();
  964. PHINode *PN = dyn_cast<PHINode>(II); ++II)
  965. PN->setIncomingValue(PN->getBasicBlockIndex(Switch),
  966. UndefValue::get(PN->getType()));
  967. // Tell the domtree about the new block. We don't fully update the
  968. // domtree here -- instead we force it to do a full recomputation
  969. // after the pass is complete -- but we do need to inform it of
  970. // new blocks.
  971. if (DT)
  972. DT->addNewBlock(Abort, NewSISucc);
  973. }
  974. SimplifyCode(Worklist, L);
  975. }
  976. /// SimplifyCode - Okay, now that we have simplified some instructions in the
  977. /// loop, walk over it and constant prop, dce, and fold control flow where
  978. /// possible. Note that this is effectively a very simple loop-structure-aware
  979. /// optimizer. During processing of this loop, L could very well be deleted, so
  980. /// it must not be used.
  981. ///
  982. /// FIXME: When the loop optimizer is more mature, separate this out to a new
  983. /// pass.
  984. ///
  985. void LoopUnswitch::SimplifyCode(std::vector<Instruction*> &Worklist, Loop *L) {
  986. const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
  987. while (!Worklist.empty()) {
  988. Instruction *I = Worklist.back();
  989. Worklist.pop_back();
  990. // Simple DCE.
  991. if (isInstructionTriviallyDead(I)) {
  992. DEBUG(dbgs() << "Remove dead instruction '" << *I);
  993. // Add uses to the worklist, which may be dead now.
  994. for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
  995. if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
  996. Worklist.push_back(Use);
  997. LPM->deleteSimpleAnalysisValue(I, L);
  998. RemoveFromWorklist(I, Worklist);
  999. I->eraseFromParent();
  1000. ++NumSimplify;
  1001. continue;
  1002. }
  1003. // See if instruction simplification can hack this up. This is common for
  1004. // things like "select false, X, Y" after unswitching made the condition be
  1005. // 'false'. TODO: update the domtree properly so we can pass it here.
  1006. if (Value *V = SimplifyInstruction(I, DL))
  1007. if (LI->replacementPreservesLCSSAForm(I, V)) {
  1008. ReplaceUsesOfWith(I, V, Worklist, L, LPM);
  1009. continue;
  1010. }
  1011. // Special case hacks that appear commonly in unswitched code.
  1012. if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
  1013. if (BI->isUnconditional()) {
  1014. // If BI's parent is the only pred of the successor, fold the two blocks
  1015. // together.
  1016. BasicBlock *Pred = BI->getParent();
  1017. BasicBlock *Succ = BI->getSuccessor(0);
  1018. BasicBlock *SinglePred = Succ->getSinglePredecessor();
  1019. if (!SinglePred) continue; // Nothing to do.
  1020. assert(SinglePred == Pred && "CFG broken");
  1021. DEBUG(dbgs() << "Merging blocks: " << Pred->getName() << " <- "
  1022. << Succ->getName() << "\n");
  1023. // Resolve any single entry PHI nodes in Succ.
  1024. while (PHINode *PN = dyn_cast<PHINode>(Succ->begin()))
  1025. ReplaceUsesOfWith(PN, PN->getIncomingValue(0), Worklist, L, LPM);
  1026. // If Succ has any successors with PHI nodes, update them to have
  1027. // entries coming from Pred instead of Succ.
  1028. Succ->replaceAllUsesWith(Pred);
  1029. // Move all of the successor contents from Succ to Pred.
  1030. Pred->getInstList().splice(BI, Succ->getInstList(), Succ->begin(),
  1031. Succ->end());
  1032. LPM->deleteSimpleAnalysisValue(BI, L);
  1033. BI->eraseFromParent();
  1034. RemoveFromWorklist(BI, Worklist);
  1035. // Remove Succ from the loop tree.
  1036. LI->removeBlock(Succ);
  1037. LPM->deleteSimpleAnalysisValue(Succ, L);
  1038. Succ->eraseFromParent();
  1039. ++NumSimplify;
  1040. continue;
  1041. }
  1042. continue;
  1043. }
  1044. }
  1045. }