LoopUnswitch.cpp 73 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882
  1. //===- LoopUnswitch.cpp - Hoist loop-invariant conditionals in loop -------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This pass transforms loops that contain branches on loop-invariant conditions
  10. // to multiple loops. For example, it turns the left into the right code:
  11. //
  12. // for (...) if (lic)
  13. // A for (...)
  14. // if (lic) A; B; C
  15. // B else
  16. // C for (...)
  17. // A; C
  18. //
  19. // This can increase the size of the code exponentially (doubling it every time
  20. // a loop is unswitched) so we only unswitch if the resultant code will be
  21. // smaller than a threshold.
  22. //
  23. // This pass expects LICM to be run before it to hoist invariant conditions out
  24. // of the loop, to make the unswitching opportunity obvious.
  25. //
  26. //===----------------------------------------------------------------------===//
  27. #include "llvm/ADT/DenseMap.h"
  28. #include "llvm/ADT/SmallPtrSet.h"
  29. #include "llvm/ADT/SmallVector.h"
  30. #include "llvm/ADT/Statistic.h"
  31. #include "llvm/Analysis/AssumptionCache.h"
  32. #include "llvm/Analysis/CodeMetrics.h"
  33. #include "llvm/Analysis/InstructionSimplify.h"
  34. #include "llvm/Analysis/LazyBlockFrequencyInfo.h"
  35. #include "llvm/Analysis/LegacyDivergenceAnalysis.h"
  36. #include "llvm/Analysis/LoopInfo.h"
  37. #include "llvm/Analysis/LoopIterator.h"
  38. #include "llvm/Analysis/LoopPass.h"
  39. #include "llvm/Analysis/MemorySSA.h"
  40. #include "llvm/Analysis/MemorySSAUpdater.h"
  41. #include "llvm/Analysis/MustExecute.h"
  42. #include "llvm/Analysis/ScalarEvolution.h"
  43. #include "llvm/Analysis/TargetTransformInfo.h"
  44. #include "llvm/IR/Attributes.h"
  45. #include "llvm/IR/BasicBlock.h"
  46. #include "llvm/IR/Constant.h"
  47. #include "llvm/IR/Constants.h"
  48. #include "llvm/IR/DerivedTypes.h"
  49. #include "llvm/IR/Dominators.h"
  50. #include "llvm/IR/Function.h"
  51. #include "llvm/IR/IRBuilder.h"
  52. #include "llvm/IR/InstrTypes.h"
  53. #include "llvm/IR/Instruction.h"
  54. #include "llvm/IR/Instructions.h"
  55. #include "llvm/IR/IntrinsicInst.h"
  56. #include "llvm/IR/Intrinsics.h"
  57. #include "llvm/IR/Module.h"
  58. #include "llvm/IR/Type.h"
  59. #include "llvm/IR/User.h"
  60. #include "llvm/IR/Value.h"
  61. #include "llvm/IR/ValueHandle.h"
  62. #include "llvm/InitializePasses.h"
  63. #include "llvm/Pass.h"
  64. #include "llvm/Support/Casting.h"
  65. #include "llvm/Support/CommandLine.h"
  66. #include "llvm/Support/Debug.h"
  67. #include "llvm/Support/raw_ostream.h"
  68. #include "llvm/Transforms/Scalar.h"
  69. #include "llvm/Transforms/Scalar/LoopPassManager.h"
  70. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  71. #include "llvm/Transforms/Utils/Cloning.h"
  72. #include "llvm/Transforms/Utils/Local.h"
  73. #include "llvm/Transforms/Utils/LoopUtils.h"
  74. #include "llvm/Transforms/Utils/ValueMapper.h"
  75. #include <algorithm>
  76. #include <cassert>
  77. #include <map>
  78. #include <set>
  79. #include <tuple>
  80. #include <utility>
  81. #include <vector>
  82. using namespace llvm;
  83. #define DEBUG_TYPE "loop-unswitch"
  84. STATISTIC(NumBranches, "Number of branches unswitched");
  85. STATISTIC(NumSwitches, "Number of switches unswitched");
  86. STATISTIC(NumGuards, "Number of guards unswitched");
  87. STATISTIC(NumSelects , "Number of selects unswitched");
  88. STATISTIC(NumTrivial , "Number of unswitches that are trivial");
  89. STATISTIC(NumSimplify, "Number of simplifications of unswitched code");
  90. STATISTIC(TotalInsts, "Total number of instructions analyzed");
  91. // The specific value of 100 here was chosen based only on intuition and a
  92. // few specific examples.
  93. static cl::opt<unsigned>
  94. Threshold("loop-unswitch-threshold", cl::desc("Max loop size to unswitch"),
  95. cl::init(100), cl::Hidden);
  96. static cl::opt<unsigned>
  97. MSSAThreshold("loop-unswitch-memoryssa-threshold",
  98. cl::desc("Max number of memory uses to explore during "
  99. "partial unswitching analysis"),
  100. cl::init(100), cl::Hidden);
  101. namespace {
  102. class LUAnalysisCache {
  103. using UnswitchedValsMap =
  104. DenseMap<const SwitchInst *, SmallPtrSet<const Value *, 8>>;
  105. using UnswitchedValsIt = UnswitchedValsMap::iterator;
  106. struct LoopProperties {
  107. unsigned CanBeUnswitchedCount;
  108. unsigned WasUnswitchedCount;
  109. unsigned SizeEstimation;
  110. UnswitchedValsMap UnswitchedVals;
  111. };
  112. // Here we use std::map instead of DenseMap, since we need to keep valid
  113. // LoopProperties pointer for current loop for better performance.
  114. using LoopPropsMap = std::map<const Loop *, LoopProperties>;
  115. using LoopPropsMapIt = LoopPropsMap::iterator;
  116. LoopPropsMap LoopsProperties;
  117. UnswitchedValsMap *CurLoopInstructions = nullptr;
  118. LoopProperties *CurrentLoopProperties = nullptr;
  119. // A loop unswitching with an estimated cost above this threshold
  120. // is not performed. MaxSize is turned into unswitching quota for
  121. // the current loop, and reduced correspondingly, though note that
  122. // the quota is returned by releaseMemory() when the loop has been
  123. // processed, so that MaxSize will return to its previous
  124. // value. So in most cases MaxSize will equal the Threshold flag
  125. // when a new loop is processed. An exception to that is that
  126. // MaxSize will have a smaller value while processing nested loops
  127. // that were introduced due to loop unswitching of an outer loop.
  128. //
  129. // FIXME: The way that MaxSize works is subtle and depends on the
  130. // pass manager processing loops and calling releaseMemory() in a
  131. // specific order. It would be good to find a more straightforward
  132. // way of doing what MaxSize does.
  133. unsigned MaxSize;
  134. public:
  135. LUAnalysisCache() : MaxSize(Threshold) {}
  136. // Analyze loop. Check its size, calculate is it possible to unswitch
  137. // it. Returns true if we can unswitch this loop.
  138. bool countLoop(const Loop *L, const TargetTransformInfo &TTI,
  139. AssumptionCache *AC);
  140. // Clean all data related to given loop.
  141. void forgetLoop(const Loop *L);
  142. // Mark case value as unswitched.
  143. // Since SI instruction can be partly unswitched, in order to avoid
  144. // extra unswitching in cloned loops keep track all unswitched values.
  145. void setUnswitched(const SwitchInst *SI, const Value *V);
  146. // Check was this case value unswitched before or not.
  147. bool isUnswitched(const SwitchInst *SI, const Value *V);
  148. // Returns true if another unswitching could be done within the cost
  149. // threshold.
  150. bool costAllowsUnswitching();
  151. // Clone all loop-unswitch related loop properties.
  152. // Redistribute unswitching quotas.
  153. // Note, that new loop data is stored inside the VMap.
  154. void cloneData(const Loop *NewLoop, const Loop *OldLoop,
  155. const ValueToValueMapTy &VMap);
  156. };
  157. class LoopUnswitch : public LoopPass {
  158. LoopInfo *LI; // Loop information
  159. LPPassManager *LPM;
  160. AssumptionCache *AC;
  161. // Used to check if second loop needs processing after
  162. // rewriteLoopBodyWithConditionConstant rewrites first loop.
  163. std::vector<Loop*> LoopProcessWorklist;
  164. LUAnalysisCache BranchesInfo;
  165. bool OptimizeForSize;
  166. bool RedoLoop = false;
  167. Loop *CurrentLoop = nullptr;
  168. DominatorTree *DT = nullptr;
  169. MemorySSA *MSSA = nullptr;
  170. AAResults *AA = nullptr;
  171. std::unique_ptr<MemorySSAUpdater> MSSAU;
  172. BasicBlock *LoopHeader = nullptr;
  173. BasicBlock *LoopPreheader = nullptr;
  174. bool SanitizeMemory;
  175. SimpleLoopSafetyInfo SafetyInfo;
  176. // LoopBlocks contains all of the basic blocks of the loop, including the
  177. // preheader of the loop, the body of the loop, and the exit blocks of the
  178. // loop, in that order.
  179. std::vector<BasicBlock*> LoopBlocks;
  180. // NewBlocks contained cloned copy of basic blocks from LoopBlocks.
  181. std::vector<BasicBlock*> NewBlocks;
  182. bool HasBranchDivergence;
  183. public:
  184. static char ID; // Pass ID, replacement for typeid
  185. explicit LoopUnswitch(bool Os = false, bool HasBranchDivergence = false)
  186. : LoopPass(ID), OptimizeForSize(Os),
  187. HasBranchDivergence(HasBranchDivergence) {
  188. initializeLoopUnswitchPass(*PassRegistry::getPassRegistry());
  189. }
  190. bool runOnLoop(Loop *L, LPPassManager &LPM) override;
  191. bool processCurrentLoop();
  192. bool isUnreachableDueToPreviousUnswitching(BasicBlock *);
  193. /// This transformation requires natural loop information & requires that
  194. /// loop preheaders be inserted into the CFG.
  195. ///
  196. void getAnalysisUsage(AnalysisUsage &AU) const override {
  197. // Lazy BFI and BPI are marked as preserved here so Loop Unswitching
  198. // can remain part of the same loop pass as LICM
  199. AU.addPreserved<LazyBlockFrequencyInfoPass>();
  200. AU.addPreserved<LazyBranchProbabilityInfoPass>();
  201. AU.addRequired<AssumptionCacheTracker>();
  202. AU.addRequired<TargetTransformInfoWrapperPass>();
  203. if (EnableMSSALoopDependency) {
  204. AU.addRequired<MemorySSAWrapperPass>();
  205. AU.addPreserved<MemorySSAWrapperPass>();
  206. }
  207. if (HasBranchDivergence)
  208. AU.addRequired<LegacyDivergenceAnalysis>();
  209. getLoopAnalysisUsage(AU);
  210. }
  211. private:
  212. void releaseMemory() override { BranchesInfo.forgetLoop(CurrentLoop); }
  213. void initLoopData() {
  214. LoopHeader = CurrentLoop->getHeader();
  215. LoopPreheader = CurrentLoop->getLoopPreheader();
  216. }
  217. /// Split all of the edges from inside the loop to their exit blocks.
  218. /// Update the appropriate Phi nodes as we do so.
  219. void splitExitEdges(Loop *L,
  220. const SmallVectorImpl<BasicBlock *> &ExitBlocks);
  221. bool tryTrivialLoopUnswitch(bool &Changed);
  222. bool unswitchIfProfitable(Value *LoopCond, Constant *Val,
  223. Instruction *TI = nullptr,
  224. ArrayRef<Instruction *> ToDuplicate = {});
  225. void unswitchTrivialCondition(Loop *L, Value *Cond, Constant *Val,
  226. BasicBlock *ExitBlock, Instruction *TI);
  227. void unswitchNontrivialCondition(Value *LIC, Constant *OnVal, Loop *L,
  228. Instruction *TI,
  229. ArrayRef<Instruction *> ToDuplicate = {});
  230. void rewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
  231. Constant *Val, bool IsEqual);
  232. void
  233. emitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
  234. BasicBlock *TrueDest, BasicBlock *FalseDest,
  235. BranchInst *OldBranch, Instruction *TI,
  236. ArrayRef<Instruction *> ToDuplicate = {});
  237. void simplifyCode(std::vector<Instruction *> &Worklist, Loop *L);
  238. /// Given that the Invariant is not equal to Val. Simplify instructions
  239. /// in the loop.
  240. Value *simplifyInstructionWithNotEqual(Instruction *Inst, Value *Invariant,
  241. Constant *Val);
  242. };
  243. } // end anonymous namespace
  244. // Analyze loop. Check its size, calculate is it possible to unswitch
  245. // it. Returns true if we can unswitch this loop.
  246. bool LUAnalysisCache::countLoop(const Loop *L, const TargetTransformInfo &TTI,
  247. AssumptionCache *AC) {
  248. LoopPropsMapIt PropsIt;
  249. bool Inserted;
  250. std::tie(PropsIt, Inserted) =
  251. LoopsProperties.insert(std::make_pair(L, LoopProperties()));
  252. LoopProperties &Props = PropsIt->second;
  253. if (Inserted) {
  254. // New loop.
  255. // Limit the number of instructions to avoid causing significant code
  256. // expansion, and the number of basic blocks, to avoid loops with
  257. // large numbers of branches which cause loop unswitching to go crazy.
  258. // This is a very ad-hoc heuristic.
  259. SmallPtrSet<const Value *, 32> EphValues;
  260. CodeMetrics::collectEphemeralValues(L, AC, EphValues);
  261. // FIXME: This is overly conservative because it does not take into
  262. // consideration code simplification opportunities and code that can
  263. // be shared by the resultant unswitched loops.
  264. CodeMetrics Metrics;
  265. for (Loop::block_iterator I = L->block_begin(), E = L->block_end(); I != E;
  266. ++I)
  267. Metrics.analyzeBasicBlock(*I, TTI, EphValues);
  268. Props.SizeEstimation = Metrics.NumInsts;
  269. Props.CanBeUnswitchedCount = MaxSize / (Props.SizeEstimation);
  270. Props.WasUnswitchedCount = 0;
  271. MaxSize -= Props.SizeEstimation * Props.CanBeUnswitchedCount;
  272. if (Metrics.notDuplicatable) {
  273. LLVM_DEBUG(dbgs() << "NOT unswitching loop %" << L->getHeader()->getName()
  274. << ", contents cannot be "
  275. << "duplicated!\n");
  276. return false;
  277. }
  278. }
  279. // Be careful. This links are good only before new loop addition.
  280. CurrentLoopProperties = &Props;
  281. CurLoopInstructions = &Props.UnswitchedVals;
  282. return true;
  283. }
  284. // Clean all data related to given loop.
  285. void LUAnalysisCache::forgetLoop(const Loop *L) {
  286. LoopPropsMapIt LIt = LoopsProperties.find(L);
  287. if (LIt != LoopsProperties.end()) {
  288. LoopProperties &Props = LIt->second;
  289. MaxSize += (Props.CanBeUnswitchedCount + Props.WasUnswitchedCount) *
  290. Props.SizeEstimation;
  291. LoopsProperties.erase(LIt);
  292. }
  293. CurrentLoopProperties = nullptr;
  294. CurLoopInstructions = nullptr;
  295. }
  296. // Mark case value as unswitched.
  297. // Since SI instruction can be partly unswitched, in order to avoid
  298. // extra unswitching in cloned loops keep track all unswitched values.
  299. void LUAnalysisCache::setUnswitched(const SwitchInst *SI, const Value *V) {
  300. (*CurLoopInstructions)[SI].insert(V);
  301. }
  302. // Check was this case value unswitched before or not.
  303. bool LUAnalysisCache::isUnswitched(const SwitchInst *SI, const Value *V) {
  304. return (*CurLoopInstructions)[SI].count(V);
  305. }
  306. bool LUAnalysisCache::costAllowsUnswitching() {
  307. return CurrentLoopProperties->CanBeUnswitchedCount > 0;
  308. }
  309. // Clone all loop-unswitch related loop properties.
  310. // Redistribute unswitching quotas.
  311. // Note, that new loop data is stored inside the VMap.
  312. void LUAnalysisCache::cloneData(const Loop *NewLoop, const Loop *OldLoop,
  313. const ValueToValueMapTy &VMap) {
  314. LoopProperties &NewLoopProps = LoopsProperties[NewLoop];
  315. LoopProperties &OldLoopProps = *CurrentLoopProperties;
  316. UnswitchedValsMap &Insts = OldLoopProps.UnswitchedVals;
  317. // Reallocate "can-be-unswitched quota"
  318. --OldLoopProps.CanBeUnswitchedCount;
  319. ++OldLoopProps.WasUnswitchedCount;
  320. NewLoopProps.WasUnswitchedCount = 0;
  321. unsigned Quota = OldLoopProps.CanBeUnswitchedCount;
  322. NewLoopProps.CanBeUnswitchedCount = Quota / 2;
  323. OldLoopProps.CanBeUnswitchedCount = Quota - Quota / 2;
  324. NewLoopProps.SizeEstimation = OldLoopProps.SizeEstimation;
  325. // Clone unswitched values info:
  326. // for new loop switches we clone info about values that was
  327. // already unswitched and has redundant successors.
  328. for (UnswitchedValsIt I = Insts.begin(); I != Insts.end(); ++I) {
  329. const SwitchInst *OldInst = I->first;
  330. Value *NewI = VMap.lookup(OldInst);
  331. const SwitchInst *NewInst = cast_or_null<SwitchInst>(NewI);
  332. assert(NewInst && "All instructions that are in SrcBB must be in VMap.");
  333. NewLoopProps.UnswitchedVals[NewInst] = OldLoopProps.UnswitchedVals[OldInst];
  334. }
  335. }
  336. char LoopUnswitch::ID = 0;
  337. INITIALIZE_PASS_BEGIN(LoopUnswitch, "loop-unswitch", "Unswitch loops",
  338. false, false)
  339. INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
  340. INITIALIZE_PASS_DEPENDENCY(LoopPass)
  341. INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
  342. INITIALIZE_PASS_DEPENDENCY(LegacyDivergenceAnalysis)
  343. INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
  344. INITIALIZE_PASS_END(LoopUnswitch, "loop-unswitch", "Unswitch loops",
  345. false, false)
  346. Pass *llvm::createLoopUnswitchPass(bool Os, bool HasBranchDivergence) {
  347. return new LoopUnswitch(Os, HasBranchDivergence);
  348. }
  349. /// Operator chain lattice.
  350. enum OperatorChain {
  351. OC_OpChainNone, ///< There is no operator.
  352. OC_OpChainOr, ///< There are only ORs.
  353. OC_OpChainAnd, ///< There are only ANDs.
  354. OC_OpChainMixed ///< There are ANDs and ORs.
  355. };
  356. /// Cond is a condition that occurs in L. If it is invariant in the loop, or has
  357. /// an invariant piece, return the invariant. Otherwise, return null.
  358. //
  359. /// NOTE: findLIVLoopCondition will not return a partial LIV by walking up a
  360. /// mixed operator chain, as we can not reliably find a value which will
  361. /// simplify the operator chain. If the chain is AND-only or OR-only, we can use
  362. /// 0 or ~0 to simplify the chain.
  363. ///
  364. /// NOTE: In case a partial LIV and a mixed operator chain, we may be able to
  365. /// simplify the condition itself to a loop variant condition, but at the
  366. /// cost of creating an entirely new loop.
  367. static Value *findLIVLoopCondition(Value *Cond, Loop *L, bool &Changed,
  368. OperatorChain &ParentChain,
  369. DenseMap<Value *, Value *> &Cache,
  370. MemorySSAUpdater *MSSAU) {
  371. auto CacheIt = Cache.find(Cond);
  372. if (CacheIt != Cache.end())
  373. return CacheIt->second;
  374. // We started analyze new instruction, increment scanned instructions counter.
  375. ++TotalInsts;
  376. // We can never unswitch on vector conditions.
  377. if (Cond->getType()->isVectorTy())
  378. return nullptr;
  379. // Constants should be folded, not unswitched on!
  380. if (isa<Constant>(Cond)) return nullptr;
  381. // TODO: Handle: br (VARIANT|INVARIANT).
  382. // Hoist simple values out.
  383. if (L->makeLoopInvariant(Cond, Changed, nullptr, MSSAU)) {
  384. Cache[Cond] = Cond;
  385. return Cond;
  386. }
  387. // Walk up the operator chain to find partial invariant conditions.
  388. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Cond))
  389. if (BO->getOpcode() == Instruction::And ||
  390. BO->getOpcode() == Instruction::Or) {
  391. // Given the previous operator, compute the current operator chain status.
  392. OperatorChain NewChain;
  393. switch (ParentChain) {
  394. case OC_OpChainNone:
  395. NewChain = BO->getOpcode() == Instruction::And ? OC_OpChainAnd :
  396. OC_OpChainOr;
  397. break;
  398. case OC_OpChainOr:
  399. NewChain = BO->getOpcode() == Instruction::Or ? OC_OpChainOr :
  400. OC_OpChainMixed;
  401. break;
  402. case OC_OpChainAnd:
  403. NewChain = BO->getOpcode() == Instruction::And ? OC_OpChainAnd :
  404. OC_OpChainMixed;
  405. break;
  406. case OC_OpChainMixed:
  407. NewChain = OC_OpChainMixed;
  408. break;
  409. }
  410. // If we reach a Mixed state, we do not want to keep walking up as we can not
  411. // reliably find a value that will simplify the chain. With this check, we
  412. // will return null on the first sight of mixed chain and the caller will
  413. // either backtrack to find partial LIV in other operand or return null.
  414. if (NewChain != OC_OpChainMixed) {
  415. // Update the current operator chain type before we search up the chain.
  416. ParentChain = NewChain;
  417. // If either the left or right side is invariant, we can unswitch on this,
  418. // which will cause the branch to go away in one loop and the condition to
  419. // simplify in the other one.
  420. if (Value *LHS = findLIVLoopCondition(BO->getOperand(0), L, Changed,
  421. ParentChain, Cache, MSSAU)) {
  422. Cache[Cond] = LHS;
  423. return LHS;
  424. }
  425. // We did not manage to find a partial LIV in operand(0). Backtrack and try
  426. // operand(1).
  427. ParentChain = NewChain;
  428. if (Value *RHS = findLIVLoopCondition(BO->getOperand(1), L, Changed,
  429. ParentChain, Cache, MSSAU)) {
  430. Cache[Cond] = RHS;
  431. return RHS;
  432. }
  433. }
  434. }
  435. Cache[Cond] = nullptr;
  436. return nullptr;
  437. }
  438. /// Cond is a condition that occurs in L. If it is invariant in the loop, or has
  439. /// an invariant piece, return the invariant along with the operator chain type.
  440. /// Otherwise, return null.
  441. static std::pair<Value *, OperatorChain>
  442. findLIVLoopCondition(Value *Cond, Loop *L, bool &Changed,
  443. MemorySSAUpdater *MSSAU) {
  444. DenseMap<Value *, Value *> Cache;
  445. OperatorChain OpChain = OC_OpChainNone;
  446. Value *FCond = findLIVLoopCondition(Cond, L, Changed, OpChain, Cache, MSSAU);
  447. // In case we do find a LIV, it can not be obtained by walking up a mixed
  448. // operator chain.
  449. assert((!FCond || OpChain != OC_OpChainMixed) &&
  450. "Do not expect a partial LIV with mixed operator chain");
  451. return {FCond, OpChain};
  452. }
  453. bool LoopUnswitch::runOnLoop(Loop *L, LPPassManager &LPMRef) {
  454. if (skipLoop(L))
  455. return false;
  456. AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(
  457. *L->getHeader()->getParent());
  458. LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
  459. LPM = &LPMRef;
  460. DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
  461. AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
  462. if (EnableMSSALoopDependency) {
  463. MSSA = &getAnalysis<MemorySSAWrapperPass>().getMSSA();
  464. MSSAU = std::make_unique<MemorySSAUpdater>(MSSA);
  465. assert(DT && "Cannot update MemorySSA without a valid DomTree.");
  466. }
  467. CurrentLoop = L;
  468. Function *F = CurrentLoop->getHeader()->getParent();
  469. SanitizeMemory = F->hasFnAttribute(Attribute::SanitizeMemory);
  470. if (SanitizeMemory)
  471. SafetyInfo.computeLoopSafetyInfo(L);
  472. if (MSSA && VerifyMemorySSA)
  473. MSSA->verifyMemorySSA();
  474. bool Changed = false;
  475. do {
  476. assert(CurrentLoop->isLCSSAForm(*DT));
  477. if (MSSA && VerifyMemorySSA)
  478. MSSA->verifyMemorySSA();
  479. RedoLoop = false;
  480. Changed |= processCurrentLoop();
  481. } while (RedoLoop);
  482. if (MSSA && VerifyMemorySSA)
  483. MSSA->verifyMemorySSA();
  484. return Changed;
  485. }
  486. // Return true if the BasicBlock BB is unreachable from the loop header.
  487. // Return false, otherwise.
  488. bool LoopUnswitch::isUnreachableDueToPreviousUnswitching(BasicBlock *BB) {
  489. auto *Node = DT->getNode(BB)->getIDom();
  490. BasicBlock *DomBB = Node->getBlock();
  491. while (CurrentLoop->contains(DomBB)) {
  492. BranchInst *BInst = dyn_cast<BranchInst>(DomBB->getTerminator());
  493. Node = DT->getNode(DomBB)->getIDom();
  494. DomBB = Node->getBlock();
  495. if (!BInst || !BInst->isConditional())
  496. continue;
  497. Value *Cond = BInst->getCondition();
  498. if (!isa<ConstantInt>(Cond))
  499. continue;
  500. BasicBlock *UnreachableSucc =
  501. Cond == ConstantInt::getTrue(Cond->getContext())
  502. ? BInst->getSuccessor(1)
  503. : BInst->getSuccessor(0);
  504. if (DT->dominates(UnreachableSucc, BB))
  505. return true;
  506. }
  507. return false;
  508. }
  509. /// FIXME: Remove this workaround when freeze related patches are done.
  510. /// LoopUnswitch and Equality propagation in GVN have discrepancy about
  511. /// whether branch on undef/poison has undefine behavior. Here it is to
  512. /// rule out some common cases that we found such discrepancy already
  513. /// causing problems. Detail could be found in PR31652. Note if the
  514. /// func returns true, it is unsafe. But if it is false, it doesn't mean
  515. /// it is necessarily safe.
  516. static bool equalityPropUnSafe(Value &LoopCond) {
  517. ICmpInst *CI = dyn_cast<ICmpInst>(&LoopCond);
  518. if (!CI || !CI->isEquality())
  519. return false;
  520. Value *LHS = CI->getOperand(0);
  521. Value *RHS = CI->getOperand(1);
  522. if (isa<UndefValue>(LHS) || isa<UndefValue>(RHS))
  523. return true;
  524. auto HasUndefInPHI = [](PHINode &PN) {
  525. for (Value *Opd : PN.incoming_values()) {
  526. if (isa<UndefValue>(Opd))
  527. return true;
  528. }
  529. return false;
  530. };
  531. PHINode *LPHI = dyn_cast<PHINode>(LHS);
  532. PHINode *RPHI = dyn_cast<PHINode>(RHS);
  533. if ((LPHI && HasUndefInPHI(*LPHI)) || (RPHI && HasUndefInPHI(*RPHI)))
  534. return true;
  535. auto HasUndefInSelect = [](SelectInst &SI) {
  536. if (isa<UndefValue>(SI.getTrueValue()) ||
  537. isa<UndefValue>(SI.getFalseValue()))
  538. return true;
  539. return false;
  540. };
  541. SelectInst *LSI = dyn_cast<SelectInst>(LHS);
  542. SelectInst *RSI = dyn_cast<SelectInst>(RHS);
  543. if ((LSI && HasUndefInSelect(*LSI)) || (RSI && HasUndefInSelect(*RSI)))
  544. return true;
  545. return false;
  546. }
  547. /// Check if the loop header has a conditional branch that is not
  548. /// loop-invariant, because it involves load instructions. If all paths from
  549. /// either the true or false successor to the header or loop exists do not
  550. /// modify the memory feeding the condition, perform 'partial unswitching'. That
  551. /// is, duplicate the instructions feeding the condition in the pre-header. Then
  552. /// unswitch on the duplicated condition. The condition is now known in the
  553. /// unswitched version for the 'invariant' path through the original loop.
  554. ///
  555. /// If the branch condition of the header is partially invariant, return a pair
  556. /// containing the instructions to duplicate and a boolean Constant to update
  557. /// the condition in the loops created for the true or false successors.
  558. static std::pair<SmallVector<Instruction *, 4>, Constant *>
  559. hasPartialIVCondition(Loop *L, MemorySSA &MSSA, AAResults *AA) {
  560. SmallVector<Instruction *, 4> ToDuplicate;
  561. auto *TI = dyn_cast<BranchInst>(L->getHeader()->getTerminator());
  562. if (!TI || !TI->isConditional())
  563. return {};
  564. auto *CondI = dyn_cast<CmpInst>(TI->getCondition());
  565. // The case with the condition outside the loop should already be handled
  566. // earlier.
  567. if (!CondI || !L->contains(CondI))
  568. return {};
  569. ToDuplicate.push_back(CondI);
  570. SmallVector<Value *, 4> WorkList;
  571. WorkList.append(CondI->op_begin(), CondI->op_end());
  572. SmallVector<MemoryAccess *, 4> AccessesToCheck;
  573. SmallVector<MemoryLocation, 4> AccessedLocs;
  574. while (!WorkList.empty()) {
  575. Instruction *I = dyn_cast<Instruction>(WorkList.pop_back_val());
  576. if (!I || !L->contains(I))
  577. continue;
  578. // TODO: support additional instructions.
  579. if (!isa<LoadInst>(I) && !isa<GetElementPtrInst>(I))
  580. return {};
  581. // Do not duplicate volatile and atomic loads.
  582. if (auto *LI = dyn_cast<LoadInst>(I))
  583. if (LI->isVolatile() || LI->isAtomic())
  584. return {};
  585. ToDuplicate.push_back(I);
  586. if (MemoryAccess *MA = MSSA.getMemoryAccess(I)) {
  587. if (auto *MemUse = dyn_cast_or_null<MemoryUse>(MA)) {
  588. // Queue the defining access to check for alias checks.
  589. AccessesToCheck.push_back(MemUse->getDefiningAccess());
  590. AccessedLocs.push_back(MemoryLocation::get(I));
  591. } else {
  592. // MemoryDefs may clobber the location or may be atomic memory
  593. // operations. Bail out.
  594. return {};
  595. }
  596. }
  597. WorkList.append(I->op_begin(), I->op_end());
  598. }
  599. if (ToDuplicate.size() <= 1)
  600. return {};
  601. auto HasNoClobbersOnPath =
  602. [L, AA, &AccessedLocs](BasicBlock *Succ, BasicBlock *Header,
  603. SmallVector<MemoryAccess *, 4> AccessesToCheck) {
  604. // First, collect all blocks in the loop that are on a patch from Succ
  605. // to the header.
  606. SmallVector<BasicBlock *, 4> WorkList;
  607. WorkList.push_back(Succ);
  608. WorkList.push_back(Header);
  609. SmallPtrSet<BasicBlock *, 4> Seen;
  610. Seen.insert(Header);
  611. while (!WorkList.empty()) {
  612. BasicBlock *Current = WorkList.pop_back_val();
  613. if (!L->contains(Current))
  614. continue;
  615. const auto &SeenIns = Seen.insert(Current);
  616. if (!SeenIns.second)
  617. continue;
  618. WorkList.append(succ_begin(Current), succ_end(Current));
  619. }
  620. // Require at least 2 blocks on a path through the loop. This skips
  621. // paths that directly exit the loop.
  622. if (Seen.size() < 2)
  623. return false;
  624. // Next, check if there are any MemoryDefs that are on the path through
  625. // the loop (in the Seen set) and they may-alias any of the locations in
  626. // AccessedLocs. If that is the case, they may modify the condition and
  627. // partial unswitching is not possible.
  628. SmallPtrSet<MemoryAccess *, 4> SeenAccesses;
  629. while (!AccessesToCheck.empty()) {
  630. MemoryAccess *Current = AccessesToCheck.pop_back_val();
  631. auto SeenI = SeenAccesses.insert(Current);
  632. if (!SeenI.second || !Seen.contains(Current->getBlock()))
  633. continue;
  634. // Bail out if exceeded the threshold.
  635. if (SeenAccesses.size() >= MSSAThreshold)
  636. return false;
  637. // MemoryUse are read-only accesses.
  638. if (isa<MemoryUse>(Current))
  639. continue;
  640. // For a MemoryDef, check if is aliases any of the location feeding
  641. // the original condition.
  642. if (auto *CurrentDef = dyn_cast<MemoryDef>(Current)) {
  643. if (any_of(AccessedLocs, [AA, CurrentDef](MemoryLocation &Loc) {
  644. return isModSet(
  645. AA->getModRefInfo(CurrentDef->getMemoryInst(), Loc));
  646. }))
  647. return false;
  648. }
  649. for (Use &U : Current->uses())
  650. AccessesToCheck.push_back(cast<MemoryAccess>(U.getUser()));
  651. }
  652. return true;
  653. };
  654. // If we branch to the same successor, partial unswitching will not be
  655. // beneficial.
  656. if (TI->getSuccessor(0) == TI->getSuccessor(1))
  657. return {};
  658. if (HasNoClobbersOnPath(TI->getSuccessor(0), L->getHeader(), AccessesToCheck))
  659. return {ToDuplicate, ConstantInt::getTrue(TI->getContext())};
  660. if (HasNoClobbersOnPath(TI->getSuccessor(1), L->getHeader(), AccessesToCheck))
  661. return {ToDuplicate, ConstantInt::getFalse(TI->getContext())};
  662. return {};
  663. }
  664. /// Do actual work and unswitch loop if possible and profitable.
  665. bool LoopUnswitch::processCurrentLoop() {
  666. bool Changed = false;
  667. initLoopData();
  668. // If LoopSimplify was unable to form a preheader, don't do any unswitching.
  669. if (!LoopPreheader)
  670. return false;
  671. // Loops with indirectbr cannot be cloned.
  672. if (!CurrentLoop->isSafeToClone())
  673. return false;
  674. // Without dedicated exits, splitting the exit edge may fail.
  675. if (!CurrentLoop->hasDedicatedExits())
  676. return false;
  677. LLVMContext &Context = LoopHeader->getContext();
  678. // Analyze loop cost, and stop unswitching if loop content can not be duplicated.
  679. if (!BranchesInfo.countLoop(
  680. CurrentLoop,
  681. getAnalysis<TargetTransformInfoWrapperPass>().getTTI(
  682. *CurrentLoop->getHeader()->getParent()),
  683. AC))
  684. return false;
  685. // Try trivial unswitch first before loop over other basic blocks in the loop.
  686. if (tryTrivialLoopUnswitch(Changed)) {
  687. return true;
  688. }
  689. // Do not do non-trivial unswitch while optimizing for size.
  690. // FIXME: Use Function::hasOptSize().
  691. if (OptimizeForSize ||
  692. LoopHeader->getParent()->hasFnAttribute(Attribute::OptimizeForSize))
  693. return Changed;
  694. // Run through the instructions in the loop, keeping track of three things:
  695. //
  696. // - That we do not unswitch loops containing convergent operations, as we
  697. // might be making them control dependent on the unswitch value when they
  698. // were not before.
  699. // FIXME: This could be refined to only bail if the convergent operation is
  700. // not already control-dependent on the unswitch value.
  701. //
  702. // - That basic blocks in the loop contain invokes whose predecessor edges we
  703. // cannot split.
  704. //
  705. // - The set of guard intrinsics encountered (these are non terminator
  706. // instructions that are also profitable to be unswitched).
  707. SmallVector<IntrinsicInst *, 4> Guards;
  708. for (const auto BB : CurrentLoop->blocks()) {
  709. for (auto &I : *BB) {
  710. auto *CB = dyn_cast<CallBase>(&I);
  711. if (!CB)
  712. continue;
  713. if (CB->isConvergent())
  714. return Changed;
  715. if (auto *II = dyn_cast<InvokeInst>(&I))
  716. if (!II->getUnwindDest()->canSplitPredecessors())
  717. return Changed;
  718. if (auto *II = dyn_cast<IntrinsicInst>(&I))
  719. if (II->getIntrinsicID() == Intrinsic::experimental_guard)
  720. Guards.push_back(II);
  721. }
  722. }
  723. for (IntrinsicInst *Guard : Guards) {
  724. Value *LoopCond = findLIVLoopCondition(Guard->getOperand(0), CurrentLoop,
  725. Changed, MSSAU.get())
  726. .first;
  727. if (LoopCond &&
  728. unswitchIfProfitable(LoopCond, ConstantInt::getTrue(Context))) {
  729. // NB! Unswitching (if successful) could have erased some of the
  730. // instructions in Guards leaving dangling pointers there. This is fine
  731. // because we're returning now, and won't look at Guards again.
  732. ++NumGuards;
  733. return true;
  734. }
  735. }
  736. // Loop over all of the basic blocks in the loop. If we find an interior
  737. // block that is branching on a loop-invariant condition, we can unswitch this
  738. // loop.
  739. for (Loop::block_iterator I = CurrentLoop->block_begin(),
  740. E = CurrentLoop->block_end();
  741. I != E; ++I) {
  742. Instruction *TI = (*I)->getTerminator();
  743. // Unswitching on a potentially uninitialized predicate is not
  744. // MSan-friendly. Limit this to the cases when the original predicate is
  745. // guaranteed to execute, to avoid creating a use-of-uninitialized-value
  746. // in the code that did not have one.
  747. // This is a workaround for the discrepancy between LLVM IR and MSan
  748. // semantics. See PR28054 for more details.
  749. if (SanitizeMemory &&
  750. !SafetyInfo.isGuaranteedToExecute(*TI, DT, CurrentLoop))
  751. continue;
  752. if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
  753. // Some branches may be rendered unreachable because of previous
  754. // unswitching.
  755. // Unswitch only those branches that are reachable.
  756. if (isUnreachableDueToPreviousUnswitching(*I))
  757. continue;
  758. // If this isn't branching on an invariant condition, we can't unswitch
  759. // it.
  760. if (BI->isConditional()) {
  761. // See if this, or some part of it, is loop invariant. If so, we can
  762. // unswitch on it if we desire.
  763. Value *LoopCond = findLIVLoopCondition(BI->getCondition(), CurrentLoop,
  764. Changed, MSSAU.get())
  765. .first;
  766. if (LoopCond && !equalityPropUnSafe(*LoopCond) &&
  767. unswitchIfProfitable(LoopCond, ConstantInt::getTrue(Context), TI)) {
  768. ++NumBranches;
  769. return true;
  770. }
  771. }
  772. } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
  773. Value *SC = SI->getCondition();
  774. Value *LoopCond;
  775. OperatorChain OpChain;
  776. std::tie(LoopCond, OpChain) =
  777. findLIVLoopCondition(SC, CurrentLoop, Changed, MSSAU.get());
  778. unsigned NumCases = SI->getNumCases();
  779. if (LoopCond && NumCases) {
  780. // Find a value to unswitch on:
  781. // FIXME: this should chose the most expensive case!
  782. // FIXME: scan for a case with a non-critical edge?
  783. Constant *UnswitchVal = nullptr;
  784. // Find a case value such that at least one case value is unswitched
  785. // out.
  786. if (OpChain == OC_OpChainAnd) {
  787. // If the chain only has ANDs and the switch has a case value of 0.
  788. // Dropping in a 0 to the chain will unswitch out the 0-casevalue.
  789. auto *AllZero = cast<ConstantInt>(Constant::getNullValue(SC->getType()));
  790. if (BranchesInfo.isUnswitched(SI, AllZero))
  791. continue;
  792. // We are unswitching 0 out.
  793. UnswitchVal = AllZero;
  794. } else if (OpChain == OC_OpChainOr) {
  795. // If the chain only has ORs and the switch has a case value of ~0.
  796. // Dropping in a ~0 to the chain will unswitch out the ~0-casevalue.
  797. auto *AllOne = cast<ConstantInt>(Constant::getAllOnesValue(SC->getType()));
  798. if (BranchesInfo.isUnswitched(SI, AllOne))
  799. continue;
  800. // We are unswitching ~0 out.
  801. UnswitchVal = AllOne;
  802. } else {
  803. assert(OpChain == OC_OpChainNone &&
  804. "Expect to unswitch on trivial chain");
  805. // Do not process same value again and again.
  806. // At this point we have some cases already unswitched and
  807. // some not yet unswitched. Let's find the first not yet unswitched one.
  808. for (auto Case : SI->cases()) {
  809. Constant *UnswitchValCandidate = Case.getCaseValue();
  810. if (!BranchesInfo.isUnswitched(SI, UnswitchValCandidate)) {
  811. UnswitchVal = UnswitchValCandidate;
  812. break;
  813. }
  814. }
  815. }
  816. if (!UnswitchVal)
  817. continue;
  818. if (unswitchIfProfitable(LoopCond, UnswitchVal)) {
  819. ++NumSwitches;
  820. // In case of a full LIV, UnswitchVal is the value we unswitched out.
  821. // In case of a partial LIV, we only unswitch when its an AND-chain
  822. // or OR-chain. In both cases switch input value simplifies to
  823. // UnswitchVal.
  824. BranchesInfo.setUnswitched(SI, UnswitchVal);
  825. return true;
  826. }
  827. }
  828. }
  829. // Scan the instructions to check for unswitchable values.
  830. for (BasicBlock::iterator BBI = (*I)->begin(), E = (*I)->end();
  831. BBI != E; ++BBI)
  832. if (SelectInst *SI = dyn_cast<SelectInst>(BBI)) {
  833. Value *LoopCond = findLIVLoopCondition(SI->getCondition(), CurrentLoop,
  834. Changed, MSSAU.get())
  835. .first;
  836. if (LoopCond &&
  837. unswitchIfProfitable(LoopCond, ConstantInt::getTrue(Context))) {
  838. ++NumSelects;
  839. return true;
  840. }
  841. }
  842. }
  843. // Check if there is a header condition that is invariant along the patch from
  844. // either the true or false successors to the header. This allows unswitching
  845. // conditions depending on memory accesses, if there's a path not clobbering
  846. // the memory locations. Check if this transform has been disabled using
  847. // metadata, to avoid unswitching the same loop multiple times.
  848. if (MSSA &&
  849. !findOptionMDForLoop(CurrentLoop, "llvm.loop.unswitch.partial.disable")) {
  850. auto ToDuplicate = hasPartialIVCondition(CurrentLoop, *MSSA, AA);
  851. if (!ToDuplicate.first.empty()) {
  852. LLVM_DEBUG(dbgs() << "loop-unswitch: Found partially invariant condition "
  853. << *ToDuplicate.first[0] << "\n");
  854. ++NumBranches;
  855. unswitchIfProfitable(ToDuplicate.first[0], ToDuplicate.second,
  856. CurrentLoop->getHeader()->getTerminator(),
  857. ToDuplicate.first);
  858. RedoLoop = false;
  859. return true;
  860. }
  861. }
  862. return Changed;
  863. }
  864. /// Check to see if all paths from BB exit the loop with no side effects
  865. /// (including infinite loops).
  866. ///
  867. /// If true, we return true and set ExitBB to the block we
  868. /// exit through.
  869. ///
  870. static bool isTrivialLoopExitBlockHelper(Loop *L, BasicBlock *BB,
  871. BasicBlock *&ExitBB,
  872. std::set<BasicBlock*> &Visited) {
  873. if (!Visited.insert(BB).second) {
  874. // Already visited. Without more analysis, this could indicate an infinite
  875. // loop.
  876. return false;
  877. }
  878. if (!L->contains(BB)) {
  879. // Otherwise, this is a loop exit, this is fine so long as this is the
  880. // first exit.
  881. if (ExitBB) return false;
  882. ExitBB = BB;
  883. return true;
  884. }
  885. // Otherwise, this is an unvisited intra-loop node. Check all successors.
  886. for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI) {
  887. // Check to see if the successor is a trivial loop exit.
  888. if (!isTrivialLoopExitBlockHelper(L, *SI, ExitBB, Visited))
  889. return false;
  890. }
  891. // Okay, everything after this looks good, check to make sure that this block
  892. // doesn't include any side effects.
  893. for (Instruction &I : *BB)
  894. if (I.mayHaveSideEffects())
  895. return false;
  896. return true;
  897. }
  898. /// Return true if the specified block unconditionally leads to an exit from
  899. /// the specified loop, and has no side-effects in the process. If so, return
  900. /// the block that is exited to, otherwise return null.
  901. static BasicBlock *isTrivialLoopExitBlock(Loop *L, BasicBlock *BB) {
  902. std::set<BasicBlock*> Visited;
  903. Visited.insert(L->getHeader()); // Branches to header make infinite loops.
  904. BasicBlock *ExitBB = nullptr;
  905. if (isTrivialLoopExitBlockHelper(L, BB, ExitBB, Visited))
  906. return ExitBB;
  907. return nullptr;
  908. }
  909. /// We have found that we can unswitch CurrentLoop when LoopCond == Val to
  910. /// simplify the loop. If we decide that this is profitable,
  911. /// unswitch the loop, reprocess the pieces, then return true.
  912. bool LoopUnswitch::unswitchIfProfitable(Value *LoopCond, Constant *Val,
  913. Instruction *TI,
  914. ArrayRef<Instruction *> ToDuplicate) {
  915. // Check to see if it would be profitable to unswitch current loop.
  916. if (!BranchesInfo.costAllowsUnswitching()) {
  917. LLVM_DEBUG(dbgs() << "NOT unswitching loop %"
  918. << CurrentLoop->getHeader()->getName()
  919. << " at non-trivial condition '" << *Val
  920. << "' == " << *LoopCond << "\n"
  921. << ". Cost too high.\n");
  922. return false;
  923. }
  924. if (HasBranchDivergence &&
  925. getAnalysis<LegacyDivergenceAnalysis>().isDivergent(LoopCond)) {
  926. LLVM_DEBUG(dbgs() << "NOT unswitching loop %"
  927. << CurrentLoop->getHeader()->getName()
  928. << " at non-trivial condition '" << *Val
  929. << "' == " << *LoopCond << "\n"
  930. << ". Condition is divergent.\n");
  931. return false;
  932. }
  933. unswitchNontrivialCondition(LoopCond, Val, CurrentLoop, TI, ToDuplicate);
  934. return true;
  935. }
  936. /// Emit a conditional branch on two values if LIC == Val, branch to TrueDst,
  937. /// otherwise branch to FalseDest. Insert the code immediately before OldBranch
  938. /// and remove (but not erase!) it from the function.
  939. void LoopUnswitch::emitPreheaderBranchOnCondition(
  940. Value *LIC, Constant *Val, BasicBlock *TrueDest, BasicBlock *FalseDest,
  941. BranchInst *OldBranch, Instruction *TI,
  942. ArrayRef<Instruction *> ToDuplicate) {
  943. assert(OldBranch->isUnconditional() && "Preheader is not split correctly");
  944. assert(TrueDest != FalseDest && "Branch targets should be different");
  945. // Insert a conditional branch on LIC to the two preheaders. The original
  946. // code is the true version and the new code is the false version.
  947. Value *BranchVal = LIC;
  948. bool Swapped = false;
  949. if (!ToDuplicate.empty()) {
  950. ValueToValueMapTy Old2New;
  951. for (Instruction *I : reverse(ToDuplicate)) {
  952. auto *New = I->clone();
  953. New->insertBefore(OldBranch);
  954. RemapInstruction(New, Old2New,
  955. RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
  956. Old2New[I] = New;
  957. if (MSSAU) {
  958. MemorySSA *MSSA = MSSAU->getMemorySSA();
  959. auto *MemA = dyn_cast_or_null<MemoryUse>(MSSA->getMemoryAccess(I));
  960. if (!MemA)
  961. continue;
  962. Loop *L = LI->getLoopFor(I->getParent());
  963. auto *DefiningAccess = MemA->getDefiningAccess();
  964. // Get the first defining access before the loop.
  965. while (L->contains(DefiningAccess->getBlock())) {
  966. // If the defining access is a MemoryPhi, get the incoming
  967. // value for the pre-header as defining access.
  968. if (auto *MemPhi = dyn_cast<MemoryPhi>(DefiningAccess)) {
  969. DefiningAccess =
  970. MemPhi->getIncomingValueForBlock(L->getLoopPreheader());
  971. } else {
  972. DefiningAccess =
  973. cast<MemoryDef>(DefiningAccess)->getDefiningAccess();
  974. }
  975. }
  976. MSSAU->createMemoryAccessInBB(New, DefiningAccess, New->getParent(),
  977. MemorySSA::BeforeTerminator);
  978. }
  979. }
  980. BranchVal = Old2New[ToDuplicate[0]];
  981. } else {
  982. if (!isa<ConstantInt>(Val) ||
  983. Val->getType() != Type::getInt1Ty(LIC->getContext()))
  984. BranchVal = new ICmpInst(OldBranch, ICmpInst::ICMP_EQ, LIC, Val);
  985. else if (Val != ConstantInt::getTrue(Val->getContext())) {
  986. // We want to enter the new loop when the condition is true.
  987. std::swap(TrueDest, FalseDest);
  988. Swapped = true;
  989. }
  990. }
  991. // Old branch will be removed, so save its parent and successor to update the
  992. // DomTree.
  993. auto *OldBranchSucc = OldBranch->getSuccessor(0);
  994. auto *OldBranchParent = OldBranch->getParent();
  995. // Insert the new branch.
  996. BranchInst *BI =
  997. IRBuilder<>(OldBranch).CreateCondBr(BranchVal, TrueDest, FalseDest, TI);
  998. if (Swapped)
  999. BI->swapProfMetadata();
  1000. // Remove the old branch so there is only one branch at the end. This is
  1001. // needed to perform DomTree's internal DFS walk on the function's CFG.
  1002. OldBranch->removeFromParent();
  1003. // Inform the DT about the new branch.
  1004. if (DT) {
  1005. // First, add both successors.
  1006. SmallVector<DominatorTree::UpdateType, 3> Updates;
  1007. if (TrueDest != OldBranchSucc)
  1008. Updates.push_back({DominatorTree::Insert, OldBranchParent, TrueDest});
  1009. if (FalseDest != OldBranchSucc)
  1010. Updates.push_back({DominatorTree::Insert, OldBranchParent, FalseDest});
  1011. // If both of the new successors are different from the old one, inform the
  1012. // DT that the edge was deleted.
  1013. if (OldBranchSucc != TrueDest && OldBranchSucc != FalseDest) {
  1014. Updates.push_back({DominatorTree::Delete, OldBranchParent, OldBranchSucc});
  1015. }
  1016. if (MSSAU)
  1017. MSSAU->applyUpdates(Updates, *DT, /*UpdateDT=*/true);
  1018. else
  1019. DT->applyUpdates(Updates);
  1020. }
  1021. // If either edge is critical, split it. This helps preserve LoopSimplify
  1022. // form for enclosing loops.
  1023. auto Options =
  1024. CriticalEdgeSplittingOptions(DT, LI, MSSAU.get()).setPreserveLCSSA();
  1025. SplitCriticalEdge(BI, 0, Options);
  1026. SplitCriticalEdge(BI, 1, Options);
  1027. }
  1028. /// Given a loop that has a trivial unswitchable condition in it (a cond branch
  1029. /// from its header block to its latch block, where the path through the loop
  1030. /// that doesn't execute its body has no side-effects), unswitch it. This
  1031. /// doesn't involve any code duplication, just moving the conditional branch
  1032. /// outside of the loop and updating loop info.
  1033. void LoopUnswitch::unswitchTrivialCondition(Loop *L, Value *Cond, Constant *Val,
  1034. BasicBlock *ExitBlock,
  1035. Instruction *TI) {
  1036. LLVM_DEBUG(dbgs() << "loop-unswitch: Trivial-Unswitch loop %"
  1037. << LoopHeader->getName() << " [" << L->getBlocks().size()
  1038. << " blocks] in Function "
  1039. << L->getHeader()->getParent()->getName()
  1040. << " on cond: " << *Val << " == " << *Cond << "\n");
  1041. // We are going to make essential changes to CFG. This may invalidate cached
  1042. // information for L or one of its parent loops in SCEV.
  1043. if (auto *SEWP = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>())
  1044. SEWP->getSE().forgetTopmostLoop(L);
  1045. // First step, split the preheader, so that we know that there is a safe place
  1046. // to insert the conditional branch. We will change LoopPreheader to have a
  1047. // conditional branch on Cond.
  1048. BasicBlock *NewPH = SplitEdge(LoopPreheader, LoopHeader, DT, LI, MSSAU.get());
  1049. // Now that we have a place to insert the conditional branch, create a place
  1050. // to branch to: this is the exit block out of the loop that we should
  1051. // short-circuit to.
  1052. // Split this block now, so that the loop maintains its exit block, and so
  1053. // that the jump from the preheader can execute the contents of the exit block
  1054. // without actually branching to it (the exit block should be dominated by the
  1055. // loop header, not the preheader).
  1056. assert(!L->contains(ExitBlock) && "Exit block is in the loop?");
  1057. BasicBlock *NewExit =
  1058. SplitBlock(ExitBlock, &ExitBlock->front(), DT, LI, MSSAU.get());
  1059. // Okay, now we have a position to branch from and a position to branch to,
  1060. // insert the new conditional branch.
  1061. auto *OldBranch = dyn_cast<BranchInst>(LoopPreheader->getTerminator());
  1062. assert(OldBranch && "Failed to split the preheader");
  1063. emitPreheaderBranchOnCondition(Cond, Val, NewExit, NewPH, OldBranch, TI);
  1064. // emitPreheaderBranchOnCondition removed the OldBranch from the function.
  1065. // Delete it, as it is no longer needed.
  1066. delete OldBranch;
  1067. // We need to reprocess this loop, it could be unswitched again.
  1068. RedoLoop = true;
  1069. // Now that we know that the loop is never entered when this condition is a
  1070. // particular value, rewrite the loop with this info. We know that this will
  1071. // at least eliminate the old branch.
  1072. rewriteLoopBodyWithConditionConstant(L, Cond, Val, /*IsEqual=*/false);
  1073. ++NumTrivial;
  1074. }
  1075. /// Check if the first non-constant condition starting from the loop header is
  1076. /// a trivial unswitch condition: that is, a condition controls whether or not
  1077. /// the loop does anything at all. If it is a trivial condition, unswitching
  1078. /// produces no code duplications (equivalently, it produces a simpler loop and
  1079. /// a new empty loop, which gets deleted). Therefore always unswitch trivial
  1080. /// condition.
  1081. bool LoopUnswitch::tryTrivialLoopUnswitch(bool &Changed) {
  1082. BasicBlock *CurrentBB = CurrentLoop->getHeader();
  1083. Instruction *CurrentTerm = CurrentBB->getTerminator();
  1084. LLVMContext &Context = CurrentBB->getContext();
  1085. // If loop header has only one reachable successor (currently via an
  1086. // unconditional branch or constant foldable conditional branch, but
  1087. // should also consider adding constant foldable switch instruction in
  1088. // future), we should keep looking for trivial condition candidates in
  1089. // the successor as well. An alternative is to constant fold conditions
  1090. // and merge successors into loop header (then we only need to check header's
  1091. // terminator). The reason for not doing this in LoopUnswitch pass is that
  1092. // it could potentially break LoopPassManager's invariants. Folding dead
  1093. // branches could either eliminate the current loop or make other loops
  1094. // unreachable. LCSSA form might also not be preserved after deleting
  1095. // branches. The following code keeps traversing loop header's successors
  1096. // until it finds the trivial condition candidate (condition that is not a
  1097. // constant). Since unswitching generates branches with constant conditions,
  1098. // this scenario could be very common in practice.
  1099. SmallPtrSet<BasicBlock*, 8> Visited;
  1100. while (true) {
  1101. // If we exit loop or reach a previous visited block, then
  1102. // we can not reach any trivial condition candidates (unfoldable
  1103. // branch instructions or switch instructions) and no unswitch
  1104. // can happen. Exit and return false.
  1105. if (!CurrentLoop->contains(CurrentBB) || !Visited.insert(CurrentBB).second)
  1106. return false;
  1107. // Check if this loop will execute any side-effecting instructions (e.g.
  1108. // stores, calls, volatile loads) in the part of the loop that the code
  1109. // *would* execute. Check the header first.
  1110. for (Instruction &I : *CurrentBB)
  1111. if (I.mayHaveSideEffects())
  1112. return false;
  1113. if (BranchInst *BI = dyn_cast<BranchInst>(CurrentTerm)) {
  1114. if (BI->isUnconditional()) {
  1115. CurrentBB = BI->getSuccessor(0);
  1116. } else if (BI->getCondition() == ConstantInt::getTrue(Context)) {
  1117. CurrentBB = BI->getSuccessor(0);
  1118. } else if (BI->getCondition() == ConstantInt::getFalse(Context)) {
  1119. CurrentBB = BI->getSuccessor(1);
  1120. } else {
  1121. // Found a trivial condition candidate: non-foldable conditional branch.
  1122. break;
  1123. }
  1124. } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurrentTerm)) {
  1125. // At this point, any constant-foldable instructions should have probably
  1126. // been folded.
  1127. ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition());
  1128. if (!Cond)
  1129. break;
  1130. // Find the target block we are definitely going to.
  1131. CurrentBB = SI->findCaseValue(Cond)->getCaseSuccessor();
  1132. } else {
  1133. // We do not understand these terminator instructions.
  1134. break;
  1135. }
  1136. CurrentTerm = CurrentBB->getTerminator();
  1137. }
  1138. // CondVal is the condition that controls the trivial condition.
  1139. // LoopExitBB is the BasicBlock that loop exits when meets trivial condition.
  1140. Constant *CondVal = nullptr;
  1141. BasicBlock *LoopExitBB = nullptr;
  1142. if (BranchInst *BI = dyn_cast<BranchInst>(CurrentTerm)) {
  1143. // If this isn't branching on an invariant condition, we can't unswitch it.
  1144. if (!BI->isConditional())
  1145. return false;
  1146. Value *LoopCond = findLIVLoopCondition(BI->getCondition(), CurrentLoop,
  1147. Changed, MSSAU.get())
  1148. .first;
  1149. // Unswitch only if the trivial condition itself is an LIV (not
  1150. // partial LIV which could occur in and/or)
  1151. if (!LoopCond || LoopCond != BI->getCondition())
  1152. return false;
  1153. // Check to see if a successor of the branch is guaranteed to
  1154. // exit through a unique exit block without having any
  1155. // side-effects. If so, determine the value of Cond that causes
  1156. // it to do this.
  1157. if ((LoopExitBB =
  1158. isTrivialLoopExitBlock(CurrentLoop, BI->getSuccessor(0)))) {
  1159. CondVal = ConstantInt::getTrue(Context);
  1160. } else if ((LoopExitBB =
  1161. isTrivialLoopExitBlock(CurrentLoop, BI->getSuccessor(1)))) {
  1162. CondVal = ConstantInt::getFalse(Context);
  1163. }
  1164. // If we didn't find a single unique LoopExit block, or if the loop exit
  1165. // block contains phi nodes, this isn't trivial.
  1166. if (!LoopExitBB || isa<PHINode>(LoopExitBB->begin()))
  1167. return false; // Can't handle this.
  1168. if (equalityPropUnSafe(*LoopCond))
  1169. return false;
  1170. unswitchTrivialCondition(CurrentLoop, LoopCond, CondVal, LoopExitBB,
  1171. CurrentTerm);
  1172. ++NumBranches;
  1173. return true;
  1174. } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurrentTerm)) {
  1175. // If this isn't switching on an invariant condition, we can't unswitch it.
  1176. Value *LoopCond = findLIVLoopCondition(SI->getCondition(), CurrentLoop,
  1177. Changed, MSSAU.get())
  1178. .first;
  1179. // Unswitch only if the trivial condition itself is an LIV (not
  1180. // partial LIV which could occur in and/or)
  1181. if (!LoopCond || LoopCond != SI->getCondition())
  1182. return false;
  1183. // Check to see if a successor of the switch is guaranteed to go to the
  1184. // latch block or exit through a one exit block without having any
  1185. // side-effects. If so, determine the value of Cond that causes it to do
  1186. // this.
  1187. // Note that we can't trivially unswitch on the default case or
  1188. // on already unswitched cases.
  1189. for (auto Case : SI->cases()) {
  1190. BasicBlock *LoopExitCandidate;
  1191. if ((LoopExitCandidate =
  1192. isTrivialLoopExitBlock(CurrentLoop, Case.getCaseSuccessor()))) {
  1193. // Okay, we found a trivial case, remember the value that is trivial.
  1194. ConstantInt *CaseVal = Case.getCaseValue();
  1195. // Check that it was not unswitched before, since already unswitched
  1196. // trivial vals are looks trivial too.
  1197. if (BranchesInfo.isUnswitched(SI, CaseVal))
  1198. continue;
  1199. LoopExitBB = LoopExitCandidate;
  1200. CondVal = CaseVal;
  1201. break;
  1202. }
  1203. }
  1204. // If we didn't find a single unique LoopExit block, or if the loop exit
  1205. // block contains phi nodes, this isn't trivial.
  1206. if (!LoopExitBB || isa<PHINode>(LoopExitBB->begin()))
  1207. return false; // Can't handle this.
  1208. unswitchTrivialCondition(CurrentLoop, LoopCond, CondVal, LoopExitBB,
  1209. nullptr);
  1210. // We are only unswitching full LIV.
  1211. BranchesInfo.setUnswitched(SI, CondVal);
  1212. ++NumSwitches;
  1213. return true;
  1214. }
  1215. return false;
  1216. }
  1217. /// Split all of the edges from inside the loop to their exit blocks.
  1218. /// Update the appropriate Phi nodes as we do so.
  1219. void LoopUnswitch::splitExitEdges(
  1220. Loop *L, const SmallVectorImpl<BasicBlock *> &ExitBlocks) {
  1221. for (unsigned I = 0, E = ExitBlocks.size(); I != E; ++I) {
  1222. BasicBlock *ExitBlock = ExitBlocks[I];
  1223. SmallVector<BasicBlock *, 4> Preds(pred_begin(ExitBlock),
  1224. pred_end(ExitBlock));
  1225. // Although SplitBlockPredecessors doesn't preserve loop-simplify in
  1226. // general, if we call it on all predecessors of all exits then it does.
  1227. SplitBlockPredecessors(ExitBlock, Preds, ".us-lcssa", DT, LI, MSSAU.get(),
  1228. /*PreserveLCSSA*/ true);
  1229. }
  1230. }
  1231. /// We determined that the loop is profitable to unswitch when LIC equal Val.
  1232. /// Split it into loop versions and test the condition outside of either loop.
  1233. /// Return the loops created as Out1/Out2.
  1234. void LoopUnswitch::unswitchNontrivialCondition(
  1235. Value *LIC, Constant *Val, Loop *L, Instruction *TI,
  1236. ArrayRef<Instruction *> ToDuplicate) {
  1237. Function *F = LoopHeader->getParent();
  1238. LLVM_DEBUG(dbgs() << "loop-unswitch: Unswitching loop %"
  1239. << LoopHeader->getName() << " [" << L->getBlocks().size()
  1240. << " blocks] in Function " << F->getName() << " when '"
  1241. << *Val << "' == " << *LIC << "\n");
  1242. // We are going to make essential changes to CFG. This may invalidate cached
  1243. // information for L or one of its parent loops in SCEV.
  1244. if (auto *SEWP = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>())
  1245. SEWP->getSE().forgetTopmostLoop(L);
  1246. LoopBlocks.clear();
  1247. NewBlocks.clear();
  1248. if (MSSAU && VerifyMemorySSA)
  1249. MSSA->verifyMemorySSA();
  1250. // First step, split the preheader and exit blocks, and add these blocks to
  1251. // the LoopBlocks list.
  1252. BasicBlock *NewPreheader =
  1253. SplitEdge(LoopPreheader, LoopHeader, DT, LI, MSSAU.get());
  1254. LoopBlocks.push_back(NewPreheader);
  1255. // We want the loop to come after the preheader, but before the exit blocks.
  1256. llvm::append_range(LoopBlocks, L->blocks());
  1257. SmallVector<BasicBlock*, 8> ExitBlocks;
  1258. L->getUniqueExitBlocks(ExitBlocks);
  1259. // Split all of the edges from inside the loop to their exit blocks. Update
  1260. // the appropriate Phi nodes as we do so.
  1261. splitExitEdges(L, ExitBlocks);
  1262. // The exit blocks may have been changed due to edge splitting, recompute.
  1263. ExitBlocks.clear();
  1264. L->getUniqueExitBlocks(ExitBlocks);
  1265. // Add exit blocks to the loop blocks.
  1266. llvm::append_range(LoopBlocks, ExitBlocks);
  1267. // Next step, clone all of the basic blocks that make up the loop (including
  1268. // the loop preheader and exit blocks), keeping track of the mapping between
  1269. // the instructions and blocks.
  1270. NewBlocks.reserve(LoopBlocks.size());
  1271. ValueToValueMapTy VMap;
  1272. for (unsigned I = 0, E = LoopBlocks.size(); I != E; ++I) {
  1273. BasicBlock *NewBB = CloneBasicBlock(LoopBlocks[I], VMap, ".us", F);
  1274. NewBlocks.push_back(NewBB);
  1275. VMap[LoopBlocks[I]] = NewBB; // Keep the BB mapping.
  1276. }
  1277. // Splice the newly inserted blocks into the function right before the
  1278. // original preheader.
  1279. F->getBasicBlockList().splice(NewPreheader->getIterator(),
  1280. F->getBasicBlockList(),
  1281. NewBlocks[0]->getIterator(), F->end());
  1282. // Now we create the new Loop object for the versioned loop.
  1283. Loop *NewLoop = cloneLoop(L, L->getParentLoop(), VMap, LI, LPM);
  1284. // Recalculate unswitching quota, inherit simplified switches info for NewBB,
  1285. // Probably clone more loop-unswitch related loop properties.
  1286. BranchesInfo.cloneData(NewLoop, L, VMap);
  1287. Loop *ParentLoop = L->getParentLoop();
  1288. if (ParentLoop) {
  1289. // Make sure to add the cloned preheader and exit blocks to the parent loop
  1290. // as well.
  1291. ParentLoop->addBasicBlockToLoop(NewBlocks[0], *LI);
  1292. }
  1293. for (unsigned EBI = 0, EBE = ExitBlocks.size(); EBI != EBE; ++EBI) {
  1294. BasicBlock *NewExit = cast<BasicBlock>(VMap[ExitBlocks[EBI]]);
  1295. // The new exit block should be in the same loop as the old one.
  1296. if (Loop *ExitBBLoop = LI->getLoopFor(ExitBlocks[EBI]))
  1297. ExitBBLoop->addBasicBlockToLoop(NewExit, *LI);
  1298. assert(NewExit->getTerminator()->getNumSuccessors() == 1 &&
  1299. "Exit block should have been split to have one successor!");
  1300. BasicBlock *ExitSucc = NewExit->getTerminator()->getSuccessor(0);
  1301. // If the successor of the exit block had PHI nodes, add an entry for
  1302. // NewExit.
  1303. for (PHINode &PN : ExitSucc->phis()) {
  1304. Value *V = PN.getIncomingValueForBlock(ExitBlocks[EBI]);
  1305. ValueToValueMapTy::iterator It = VMap.find(V);
  1306. if (It != VMap.end()) V = It->second;
  1307. PN.addIncoming(V, NewExit);
  1308. }
  1309. if (LandingPadInst *LPad = NewExit->getLandingPadInst()) {
  1310. PHINode *PN = PHINode::Create(LPad->getType(), 0, "",
  1311. &*ExitSucc->getFirstInsertionPt());
  1312. for (pred_iterator I = pred_begin(ExitSucc), E = pred_end(ExitSucc);
  1313. I != E; ++I) {
  1314. BasicBlock *BB = *I;
  1315. LandingPadInst *LPI = BB->getLandingPadInst();
  1316. LPI->replaceAllUsesWith(PN);
  1317. PN->addIncoming(LPI, BB);
  1318. }
  1319. }
  1320. }
  1321. // Rewrite the code to refer to itself.
  1322. for (unsigned NBI = 0, NBE = NewBlocks.size(); NBI != NBE; ++NBI) {
  1323. for (Instruction &I : *NewBlocks[NBI]) {
  1324. RemapInstruction(&I, VMap,
  1325. RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
  1326. if (auto *II = dyn_cast<IntrinsicInst>(&I))
  1327. if (II->getIntrinsicID() == Intrinsic::assume)
  1328. AC->registerAssumption(II);
  1329. }
  1330. }
  1331. // Rewrite the original preheader to select between versions of the loop.
  1332. BranchInst *OldBR = cast<BranchInst>(LoopPreheader->getTerminator());
  1333. assert(OldBR->isUnconditional() && OldBR->getSuccessor(0) == LoopBlocks[0] &&
  1334. "Preheader splitting did not work correctly!");
  1335. if (MSSAU) {
  1336. // Update MemorySSA after cloning, and before splitting to unreachables,
  1337. // since that invalidates the 1:1 mapping of clones in VMap.
  1338. LoopBlocksRPO LBRPO(L);
  1339. LBRPO.perform(LI);
  1340. MSSAU->updateForClonedLoop(LBRPO, ExitBlocks, VMap);
  1341. }
  1342. // Emit the new branch that selects between the two versions of this loop.
  1343. emitPreheaderBranchOnCondition(LIC, Val, NewBlocks[0], LoopBlocks[0], OldBR,
  1344. TI, ToDuplicate);
  1345. if (MSSAU) {
  1346. // Update MemoryPhis in Exit blocks.
  1347. MSSAU->updateExitBlocksForClonedLoop(ExitBlocks, VMap, *DT);
  1348. if (VerifyMemorySSA)
  1349. MSSA->verifyMemorySSA();
  1350. }
  1351. // The OldBr was replaced by a new one and removed (but not erased) by
  1352. // emitPreheaderBranchOnCondition. It is no longer needed, so delete it.
  1353. delete OldBR;
  1354. LoopProcessWorklist.push_back(NewLoop);
  1355. RedoLoop = true;
  1356. // Keep a WeakTrackingVH holding onto LIC. If the first call to
  1357. // RewriteLoopBody
  1358. // deletes the instruction (for example by simplifying a PHI that feeds into
  1359. // the condition that we're unswitching on), we don't rewrite the second
  1360. // iteration.
  1361. WeakTrackingVH LICHandle(LIC);
  1362. if (ToDuplicate.empty()) {
  1363. // Now we rewrite the original code to know that the condition is true and
  1364. // the new code to know that the condition is false.
  1365. rewriteLoopBodyWithConditionConstant(L, LIC, Val, /*IsEqual=*/false);
  1366. // It's possible that simplifying one loop could cause the other to be
  1367. // changed to another value or a constant. If its a constant, don't
  1368. // simplify it.
  1369. if (!LoopProcessWorklist.empty() && LoopProcessWorklist.back() == NewLoop &&
  1370. LICHandle && !isa<Constant>(LICHandle))
  1371. rewriteLoopBodyWithConditionConstant(NewLoop, LICHandle, Val,
  1372. /*IsEqual=*/true);
  1373. } else {
  1374. // Partial unswitching. Update the condition in the right loop with the
  1375. // constant.
  1376. auto *CC = cast<ConstantInt>(Val);
  1377. if (CC->isOneValue()) {
  1378. rewriteLoopBodyWithConditionConstant(NewLoop, VMap[LIC], Val,
  1379. /*IsEqual=*/true);
  1380. } else
  1381. rewriteLoopBodyWithConditionConstant(L, LIC, Val, /*IsEqual=*/true);
  1382. // Mark the new loop as partially unswitched, to avoid unswitching on the
  1383. // same condition again.
  1384. auto &Context = NewLoop->getHeader()->getContext();
  1385. MDNode *DisableUnswitchMD = MDNode::get(
  1386. Context, MDString::get(Context, "llvm.loop.unswitch.partial.disable"));
  1387. MDNode *NewLoopID = makePostTransformationMetadata(
  1388. Context, L->getLoopID(), {"llvm.loop.unswitch.partial"},
  1389. {DisableUnswitchMD});
  1390. NewLoop->setLoopID(NewLoopID);
  1391. }
  1392. if (MSSA && VerifyMemorySSA)
  1393. MSSA->verifyMemorySSA();
  1394. }
  1395. /// Remove all instances of I from the worklist vector specified.
  1396. static void removeFromWorklist(Instruction *I,
  1397. std::vector<Instruction *> &Worklist) {
  1398. llvm::erase_value(Worklist, I);
  1399. }
  1400. /// When we find that I really equals V, remove I from the
  1401. /// program, replacing all uses with V and update the worklist.
  1402. static void replaceUsesOfWith(Instruction *I, Value *V,
  1403. std::vector<Instruction *> &Worklist, Loop *L,
  1404. LPPassManager *LPM, MemorySSAUpdater *MSSAU) {
  1405. LLVM_DEBUG(dbgs() << "Replace with '" << *V << "': " << *I << "\n");
  1406. // Add uses to the worklist, which may be dead now.
  1407. for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
  1408. if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
  1409. Worklist.push_back(Use);
  1410. // Add users to the worklist which may be simplified now.
  1411. for (User *U : I->users())
  1412. Worklist.push_back(cast<Instruction>(U));
  1413. removeFromWorklist(I, Worklist);
  1414. I->replaceAllUsesWith(V);
  1415. if (!I->mayHaveSideEffects()) {
  1416. if (MSSAU)
  1417. MSSAU->removeMemoryAccess(I);
  1418. I->eraseFromParent();
  1419. }
  1420. ++NumSimplify;
  1421. }
  1422. /// We know either that the value LIC has the value specified by Val in the
  1423. /// specified loop, or we know it does NOT have that value.
  1424. /// Rewrite any uses of LIC or of properties correlated to it.
  1425. void LoopUnswitch::rewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
  1426. Constant *Val,
  1427. bool IsEqual) {
  1428. assert(!isa<Constant>(LIC) && "Why are we unswitching on a constant?");
  1429. // FIXME: Support correlated properties, like:
  1430. // for (...)
  1431. // if (li1 < li2)
  1432. // ...
  1433. // if (li1 > li2)
  1434. // ...
  1435. // FOLD boolean conditions (X|LIC), (X&LIC). Fold conditional branches,
  1436. // selects, switches.
  1437. std::vector<Instruction*> Worklist;
  1438. LLVMContext &Context = Val->getContext();
  1439. // If we know that LIC == Val, or that LIC == NotVal, just replace uses of LIC
  1440. // in the loop with the appropriate one directly.
  1441. if (IsEqual || (isa<ConstantInt>(Val) &&
  1442. Val->getType()->isIntegerTy(1))) {
  1443. Value *Replacement;
  1444. if (IsEqual)
  1445. Replacement = Val;
  1446. else
  1447. Replacement = ConstantInt::get(Type::getInt1Ty(Val->getContext()),
  1448. !cast<ConstantInt>(Val)->getZExtValue());
  1449. for (User *U : LIC->users()) {
  1450. Instruction *UI = dyn_cast<Instruction>(U);
  1451. if (!UI || !L->contains(UI))
  1452. continue;
  1453. Worklist.push_back(UI);
  1454. }
  1455. for (Instruction *UI : Worklist)
  1456. UI->replaceUsesOfWith(LIC, Replacement);
  1457. simplifyCode(Worklist, L);
  1458. return;
  1459. }
  1460. // Otherwise, we don't know the precise value of LIC, but we do know that it
  1461. // is certainly NOT "Val". As such, simplify any uses in the loop that we
  1462. // can. This case occurs when we unswitch switch statements.
  1463. for (User *U : LIC->users()) {
  1464. Instruction *UI = dyn_cast<Instruction>(U);
  1465. if (!UI || !L->contains(UI))
  1466. continue;
  1467. // At this point, we know LIC is definitely not Val. Try to use some simple
  1468. // logic to simplify the user w.r.t. to the context.
  1469. if (Value *Replacement = simplifyInstructionWithNotEqual(UI, LIC, Val)) {
  1470. if (LI->replacementPreservesLCSSAForm(UI, Replacement)) {
  1471. // This in-loop instruction has been simplified w.r.t. its context,
  1472. // i.e. LIC != Val, make sure we propagate its replacement value to
  1473. // all its users.
  1474. //
  1475. // We can not yet delete UI, the LIC user, yet, because that would invalidate
  1476. // the LIC->users() iterator !. However, we can make this instruction
  1477. // dead by replacing all its users and push it onto the worklist so that
  1478. // it can be properly deleted and its operands simplified.
  1479. UI->replaceAllUsesWith(Replacement);
  1480. }
  1481. }
  1482. // This is a LIC user, push it into the worklist so that simplifyCode can
  1483. // attempt to simplify it.
  1484. Worklist.push_back(UI);
  1485. // If we know that LIC is not Val, use this info to simplify code.
  1486. SwitchInst *SI = dyn_cast<SwitchInst>(UI);
  1487. if (!SI || !isa<ConstantInt>(Val)) continue;
  1488. // NOTE: if a case value for the switch is unswitched out, we record it
  1489. // after the unswitch finishes. We can not record it here as the switch
  1490. // is not a direct user of the partial LIV.
  1491. SwitchInst::CaseHandle DeadCase =
  1492. *SI->findCaseValue(cast<ConstantInt>(Val));
  1493. // Default case is live for multiple values.
  1494. if (DeadCase == *SI->case_default())
  1495. continue;
  1496. // Found a dead case value. Don't remove PHI nodes in the
  1497. // successor if they become single-entry, those PHI nodes may
  1498. // be in the Users list.
  1499. BasicBlock *Switch = SI->getParent();
  1500. BasicBlock *SISucc = DeadCase.getCaseSuccessor();
  1501. BasicBlock *Latch = L->getLoopLatch();
  1502. if (!SI->findCaseDest(SISucc)) continue; // Edge is critical.
  1503. // If the DeadCase successor dominates the loop latch, then the
  1504. // transformation isn't safe since it will delete the sole predecessor edge
  1505. // to the latch.
  1506. if (Latch && DT->dominates(SISucc, Latch))
  1507. continue;
  1508. // FIXME: This is a hack. We need to keep the successor around
  1509. // and hooked up so as to preserve the loop structure, because
  1510. // trying to update it is complicated. So instead we preserve the
  1511. // loop structure and put the block on a dead code path.
  1512. SplitEdge(Switch, SISucc, DT, LI, MSSAU.get());
  1513. // Compute the successors instead of relying on the return value
  1514. // of SplitEdge, since it may have split the switch successor
  1515. // after PHI nodes.
  1516. BasicBlock *NewSISucc = DeadCase.getCaseSuccessor();
  1517. BasicBlock *OldSISucc = *succ_begin(NewSISucc);
  1518. // Create an "unreachable" destination.
  1519. BasicBlock *Abort = BasicBlock::Create(Context, "us-unreachable",
  1520. Switch->getParent(),
  1521. OldSISucc);
  1522. new UnreachableInst(Context, Abort);
  1523. // Force the new case destination to branch to the "unreachable"
  1524. // block while maintaining a (dead) CFG edge to the old block.
  1525. NewSISucc->getTerminator()->eraseFromParent();
  1526. BranchInst::Create(Abort, OldSISucc,
  1527. ConstantInt::getTrue(Context), NewSISucc);
  1528. // Release the PHI operands for this edge.
  1529. for (PHINode &PN : NewSISucc->phis())
  1530. PN.setIncomingValueForBlock(Switch, UndefValue::get(PN.getType()));
  1531. // Tell the domtree about the new block. We don't fully update the
  1532. // domtree here -- instead we force it to do a full recomputation
  1533. // after the pass is complete -- but we do need to inform it of
  1534. // new blocks.
  1535. DT->addNewBlock(Abort, NewSISucc);
  1536. }
  1537. simplifyCode(Worklist, L);
  1538. }
  1539. /// Now that we have simplified some instructions in the loop, walk over it and
  1540. /// constant prop, dce, and fold control flow where possible. Note that this is
  1541. /// effectively a very simple loop-structure-aware optimizer. During processing
  1542. /// of this loop, L could very well be deleted, so it must not be used.
  1543. ///
  1544. /// FIXME: When the loop optimizer is more mature, separate this out to a new
  1545. /// pass.
  1546. ///
  1547. void LoopUnswitch::simplifyCode(std::vector<Instruction *> &Worklist, Loop *L) {
  1548. const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
  1549. while (!Worklist.empty()) {
  1550. Instruction *I = Worklist.back();
  1551. Worklist.pop_back();
  1552. // Simple DCE.
  1553. if (isInstructionTriviallyDead(I)) {
  1554. LLVM_DEBUG(dbgs() << "Remove dead instruction '" << *I << "\n");
  1555. // Add uses to the worklist, which may be dead now.
  1556. for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
  1557. if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
  1558. Worklist.push_back(Use);
  1559. removeFromWorklist(I, Worklist);
  1560. if (MSSAU)
  1561. MSSAU->removeMemoryAccess(I);
  1562. I->eraseFromParent();
  1563. ++NumSimplify;
  1564. continue;
  1565. }
  1566. // See if instruction simplification can hack this up. This is common for
  1567. // things like "select false, X, Y" after unswitching made the condition be
  1568. // 'false'. TODO: update the domtree properly so we can pass it here.
  1569. if (Value *V = SimplifyInstruction(I, DL))
  1570. if (LI->replacementPreservesLCSSAForm(I, V)) {
  1571. replaceUsesOfWith(I, V, Worklist, L, LPM, MSSAU.get());
  1572. continue;
  1573. }
  1574. // Special case hacks that appear commonly in unswitched code.
  1575. if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
  1576. if (BI->isUnconditional()) {
  1577. // If BI's parent is the only pred of the successor, fold the two blocks
  1578. // together.
  1579. BasicBlock *Pred = BI->getParent();
  1580. (void)Pred;
  1581. BasicBlock *Succ = BI->getSuccessor(0);
  1582. BasicBlock *SinglePred = Succ->getSinglePredecessor();
  1583. if (!SinglePred) continue; // Nothing to do.
  1584. assert(SinglePred == Pred && "CFG broken");
  1585. // Make the LPM and Worklist updates specific to LoopUnswitch.
  1586. removeFromWorklist(BI, Worklist);
  1587. auto SuccIt = Succ->begin();
  1588. while (PHINode *PN = dyn_cast<PHINode>(SuccIt++)) {
  1589. for (unsigned It = 0, E = PN->getNumOperands(); It != E; ++It)
  1590. if (Instruction *Use = dyn_cast<Instruction>(PN->getOperand(It)))
  1591. Worklist.push_back(Use);
  1592. for (User *U : PN->users())
  1593. Worklist.push_back(cast<Instruction>(U));
  1594. removeFromWorklist(PN, Worklist);
  1595. ++NumSimplify;
  1596. }
  1597. // Merge the block and make the remaining analyses updates.
  1598. DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager);
  1599. MergeBlockIntoPredecessor(Succ, &DTU, LI, MSSAU.get());
  1600. ++NumSimplify;
  1601. continue;
  1602. }
  1603. continue;
  1604. }
  1605. }
  1606. }
  1607. /// Simple simplifications we can do given the information that Cond is
  1608. /// definitely not equal to Val.
  1609. Value *LoopUnswitch::simplifyInstructionWithNotEqual(Instruction *Inst,
  1610. Value *Invariant,
  1611. Constant *Val) {
  1612. // icmp eq cond, val -> false
  1613. ICmpInst *CI = dyn_cast<ICmpInst>(Inst);
  1614. if (CI && CI->isEquality()) {
  1615. Value *Op0 = CI->getOperand(0);
  1616. Value *Op1 = CI->getOperand(1);
  1617. if ((Op0 == Invariant && Op1 == Val) || (Op0 == Val && Op1 == Invariant)) {
  1618. LLVMContext &Ctx = Inst->getContext();
  1619. if (CI->getPredicate() == CmpInst::ICMP_EQ)
  1620. return ConstantInt::getFalse(Ctx);
  1621. else
  1622. return ConstantInt::getTrue(Ctx);
  1623. }
  1624. }
  1625. // FIXME: there may be other opportunities, e.g. comparison with floating
  1626. // point, or Invariant - Val != 0, etc.
  1627. return nullptr;
  1628. }