LoopRerollPass.cpp 60 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724
  1. //===- LoopReroll.cpp - Loop rerolling pass -------------------------------===//
  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 implements a simple loop reroller.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "llvm/ADT/APInt.h"
  13. #include "llvm/ADT/BitVector.h"
  14. #include "llvm/ADT/DenseMap.h"
  15. #include "llvm/ADT/DenseSet.h"
  16. #include "llvm/ADT/MapVector.h"
  17. #include "llvm/ADT/STLExtras.h"
  18. #include "llvm/ADT/SmallPtrSet.h"
  19. #include "llvm/ADT/SmallVector.h"
  20. #include "llvm/ADT/Statistic.h"
  21. #include "llvm/Analysis/AliasAnalysis.h"
  22. #include "llvm/Analysis/AliasSetTracker.h"
  23. #include "llvm/Analysis/LoopInfo.h"
  24. #include "llvm/Analysis/LoopPass.h"
  25. #include "llvm/Analysis/ScalarEvolution.h"
  26. #include "llvm/Analysis/ScalarEvolutionExpressions.h"
  27. #include "llvm/Analysis/TargetLibraryInfo.h"
  28. #include "llvm/Analysis/ValueTracking.h"
  29. #include "llvm/IR/BasicBlock.h"
  30. #include "llvm/IR/Constants.h"
  31. #include "llvm/IR/Dominators.h"
  32. #include "llvm/IR/InstrTypes.h"
  33. #include "llvm/IR/Instruction.h"
  34. #include "llvm/IR/Instructions.h"
  35. #include "llvm/IR/IntrinsicInst.h"
  36. #include "llvm/IR/Module.h"
  37. #include "llvm/IR/Type.h"
  38. #include "llvm/IR/Use.h"
  39. #include "llvm/IR/User.h"
  40. #include "llvm/IR/Value.h"
  41. #include "llvm/InitializePasses.h"
  42. #include "llvm/Pass.h"
  43. #include "llvm/Support/Casting.h"
  44. #include "llvm/Support/CommandLine.h"
  45. #include "llvm/Support/Debug.h"
  46. #include "llvm/Support/raw_ostream.h"
  47. #include "llvm/Transforms/Scalar.h"
  48. #include "llvm/Transforms/Scalar/LoopReroll.h"
  49. #include "llvm/Transforms/Utils.h"
  50. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  51. #include "llvm/Transforms/Utils/Local.h"
  52. #include "llvm/Transforms/Utils/LoopUtils.h"
  53. #include "llvm/Transforms/Utils/ScalarEvolutionExpander.h"
  54. #include <cassert>
  55. #include <cstddef>
  56. #include <cstdint>
  57. #include <iterator>
  58. #include <map>
  59. #include <utility>
  60. using namespace llvm;
  61. #define DEBUG_TYPE "loop-reroll"
  62. STATISTIC(NumRerolledLoops, "Number of rerolled loops");
  63. static cl::opt<unsigned>
  64. NumToleratedFailedMatches("reroll-num-tolerated-failed-matches", cl::init(400),
  65. cl::Hidden,
  66. cl::desc("The maximum number of failures to tolerate"
  67. " during fuzzy matching. (default: 400)"));
  68. // This loop re-rolling transformation aims to transform loops like this:
  69. //
  70. // int foo(int a);
  71. // void bar(int *x) {
  72. // for (int i = 0; i < 500; i += 3) {
  73. // foo(i);
  74. // foo(i+1);
  75. // foo(i+2);
  76. // }
  77. // }
  78. //
  79. // into a loop like this:
  80. //
  81. // void bar(int *x) {
  82. // for (int i = 0; i < 500; ++i)
  83. // foo(i);
  84. // }
  85. //
  86. // It does this by looking for loops that, besides the latch code, are composed
  87. // of isomorphic DAGs of instructions, with each DAG rooted at some increment
  88. // to the induction variable, and where each DAG is isomorphic to the DAG
  89. // rooted at the induction variable (excepting the sub-DAGs which root the
  90. // other induction-variable increments). In other words, we're looking for loop
  91. // bodies of the form:
  92. //
  93. // %iv = phi [ (preheader, ...), (body, %iv.next) ]
  94. // f(%iv)
  95. // %iv.1 = add %iv, 1 <-- a root increment
  96. // f(%iv.1)
  97. // %iv.2 = add %iv, 2 <-- a root increment
  98. // f(%iv.2)
  99. // %iv.scale_m_1 = add %iv, scale-1 <-- a root increment
  100. // f(%iv.scale_m_1)
  101. // ...
  102. // %iv.next = add %iv, scale
  103. // %cmp = icmp(%iv, ...)
  104. // br %cmp, header, exit
  105. //
  106. // where each f(i) is a set of instructions that, collectively, are a function
  107. // only of i (and other loop-invariant values).
  108. //
  109. // As a special case, we can also reroll loops like this:
  110. //
  111. // int foo(int);
  112. // void bar(int *x) {
  113. // for (int i = 0; i < 500; ++i) {
  114. // x[3*i] = foo(0);
  115. // x[3*i+1] = foo(0);
  116. // x[3*i+2] = foo(0);
  117. // }
  118. // }
  119. //
  120. // into this:
  121. //
  122. // void bar(int *x) {
  123. // for (int i = 0; i < 1500; ++i)
  124. // x[i] = foo(0);
  125. // }
  126. //
  127. // in which case, we're looking for inputs like this:
  128. //
  129. // %iv = phi [ (preheader, ...), (body, %iv.next) ]
  130. // %scaled.iv = mul %iv, scale
  131. // f(%scaled.iv)
  132. // %scaled.iv.1 = add %scaled.iv, 1
  133. // f(%scaled.iv.1)
  134. // %scaled.iv.2 = add %scaled.iv, 2
  135. // f(%scaled.iv.2)
  136. // %scaled.iv.scale_m_1 = add %scaled.iv, scale-1
  137. // f(%scaled.iv.scale_m_1)
  138. // ...
  139. // %iv.next = add %iv, 1
  140. // %cmp = icmp(%iv, ...)
  141. // br %cmp, header, exit
  142. namespace {
  143. enum IterationLimits {
  144. /// The maximum number of iterations that we'll try and reroll.
  145. IL_MaxRerollIterations = 32,
  146. /// The bitvector index used by loop induction variables and other
  147. /// instructions that belong to all iterations.
  148. IL_All,
  149. IL_End
  150. };
  151. class LoopRerollLegacyPass : public LoopPass {
  152. public:
  153. static char ID; // Pass ID, replacement for typeid
  154. LoopRerollLegacyPass() : LoopPass(ID) {
  155. initializeLoopRerollLegacyPassPass(*PassRegistry::getPassRegistry());
  156. }
  157. bool runOnLoop(Loop *L, LPPassManager &LPM) override;
  158. void getAnalysisUsage(AnalysisUsage &AU) const override {
  159. AU.addRequired<TargetLibraryInfoWrapperPass>();
  160. getLoopAnalysisUsage(AU);
  161. }
  162. };
  163. class LoopReroll {
  164. public:
  165. LoopReroll(AliasAnalysis *AA, LoopInfo *LI, ScalarEvolution *SE,
  166. TargetLibraryInfo *TLI, DominatorTree *DT, bool PreserveLCSSA)
  167. : AA(AA), LI(LI), SE(SE), TLI(TLI), DT(DT),
  168. PreserveLCSSA(PreserveLCSSA) {}
  169. bool runOnLoop(Loop *L);
  170. protected:
  171. AliasAnalysis *AA;
  172. LoopInfo *LI;
  173. ScalarEvolution *SE;
  174. TargetLibraryInfo *TLI;
  175. DominatorTree *DT;
  176. bool PreserveLCSSA;
  177. using SmallInstructionVector = SmallVector<Instruction *, 16>;
  178. using SmallInstructionSet = SmallPtrSet<Instruction *, 16>;
  179. using TinyInstructionVector = SmallVector<Instruction *, 1>;
  180. // Map between induction variable and its increment
  181. DenseMap<Instruction *, int64_t> IVToIncMap;
  182. // For loop with multiple induction variables, remember the ones used only to
  183. // control the loop.
  184. TinyInstructionVector LoopControlIVs;
  185. // A chain of isomorphic instructions, identified by a single-use PHI
  186. // representing a reduction. Only the last value may be used outside the
  187. // loop.
  188. struct SimpleLoopReduction {
  189. SimpleLoopReduction(Instruction *P, Loop *L) : Instructions(1, P) {
  190. assert(isa<PHINode>(P) && "First reduction instruction must be a PHI");
  191. add(L);
  192. }
  193. bool valid() const {
  194. return Valid;
  195. }
  196. Instruction *getPHI() const {
  197. assert(Valid && "Using invalid reduction");
  198. return Instructions.front();
  199. }
  200. Instruction *getReducedValue() const {
  201. assert(Valid && "Using invalid reduction");
  202. return Instructions.back();
  203. }
  204. Instruction *get(size_t i) const {
  205. assert(Valid && "Using invalid reduction");
  206. return Instructions[i+1];
  207. }
  208. Instruction *operator [] (size_t i) const { return get(i); }
  209. // The size, ignoring the initial PHI.
  210. size_t size() const {
  211. assert(Valid && "Using invalid reduction");
  212. return Instructions.size()-1;
  213. }
  214. using iterator = SmallInstructionVector::iterator;
  215. using const_iterator = SmallInstructionVector::const_iterator;
  216. iterator begin() {
  217. assert(Valid && "Using invalid reduction");
  218. return std::next(Instructions.begin());
  219. }
  220. const_iterator begin() const {
  221. assert(Valid && "Using invalid reduction");
  222. return std::next(Instructions.begin());
  223. }
  224. iterator end() { return Instructions.end(); }
  225. const_iterator end() const { return Instructions.end(); }
  226. protected:
  227. bool Valid = false;
  228. SmallInstructionVector Instructions;
  229. void add(Loop *L);
  230. };
  231. // The set of all reductions, and state tracking of possible reductions
  232. // during loop instruction processing.
  233. struct ReductionTracker {
  234. using SmallReductionVector = SmallVector<SimpleLoopReduction, 16>;
  235. // Add a new possible reduction.
  236. void addSLR(SimpleLoopReduction &SLR) { PossibleReds.push_back(SLR); }
  237. // Setup to track possible reductions corresponding to the provided
  238. // rerolling scale. Only reductions with a number of non-PHI instructions
  239. // that is divisible by the scale are considered. Three instructions sets
  240. // are filled in:
  241. // - A set of all possible instructions in eligible reductions.
  242. // - A set of all PHIs in eligible reductions
  243. // - A set of all reduced values (last instructions) in eligible
  244. // reductions.
  245. void restrictToScale(uint64_t Scale,
  246. SmallInstructionSet &PossibleRedSet,
  247. SmallInstructionSet &PossibleRedPHISet,
  248. SmallInstructionSet &PossibleRedLastSet) {
  249. PossibleRedIdx.clear();
  250. PossibleRedIter.clear();
  251. Reds.clear();
  252. for (unsigned i = 0, e = PossibleReds.size(); i != e; ++i)
  253. if (PossibleReds[i].size() % Scale == 0) {
  254. PossibleRedLastSet.insert(PossibleReds[i].getReducedValue());
  255. PossibleRedPHISet.insert(PossibleReds[i].getPHI());
  256. PossibleRedSet.insert(PossibleReds[i].getPHI());
  257. PossibleRedIdx[PossibleReds[i].getPHI()] = i;
  258. for (Instruction *J : PossibleReds[i]) {
  259. PossibleRedSet.insert(J);
  260. PossibleRedIdx[J] = i;
  261. }
  262. }
  263. }
  264. // The functions below are used while processing the loop instructions.
  265. // Are the two instructions both from reductions, and furthermore, from
  266. // the same reduction?
  267. bool isPairInSame(Instruction *J1, Instruction *J2) {
  268. DenseMap<Instruction *, int>::iterator J1I = PossibleRedIdx.find(J1);
  269. if (J1I != PossibleRedIdx.end()) {
  270. DenseMap<Instruction *, int>::iterator J2I = PossibleRedIdx.find(J2);
  271. if (J2I != PossibleRedIdx.end() && J1I->second == J2I->second)
  272. return true;
  273. }
  274. return false;
  275. }
  276. // The two provided instructions, the first from the base iteration, and
  277. // the second from iteration i, form a matched pair. If these are part of
  278. // a reduction, record that fact.
  279. void recordPair(Instruction *J1, Instruction *J2, unsigned i) {
  280. if (PossibleRedIdx.count(J1)) {
  281. assert(PossibleRedIdx.count(J2) &&
  282. "Recording reduction vs. non-reduction instruction?");
  283. PossibleRedIter[J1] = 0;
  284. PossibleRedIter[J2] = i;
  285. int Idx = PossibleRedIdx[J1];
  286. assert(Idx == PossibleRedIdx[J2] &&
  287. "Recording pair from different reductions?");
  288. Reds.insert(Idx);
  289. }
  290. }
  291. // The functions below can be called after we've finished processing all
  292. // instructions in the loop, and we know which reductions were selected.
  293. bool validateSelected();
  294. void replaceSelected();
  295. protected:
  296. // The vector of all possible reductions (for any scale).
  297. SmallReductionVector PossibleReds;
  298. DenseMap<Instruction *, int> PossibleRedIdx;
  299. DenseMap<Instruction *, int> PossibleRedIter;
  300. DenseSet<int> Reds;
  301. };
  302. // A DAGRootSet models an induction variable being used in a rerollable
  303. // loop. For example,
  304. //
  305. // x[i*3+0] = y1
  306. // x[i*3+1] = y2
  307. // x[i*3+2] = y3
  308. //
  309. // Base instruction -> i*3
  310. // +---+----+
  311. // / | \
  312. // ST[y1] +1 +2 <-- Roots
  313. // | |
  314. // ST[y2] ST[y3]
  315. //
  316. // There may be multiple DAGRoots, for example:
  317. //
  318. // x[i*2+0] = ... (1)
  319. // x[i*2+1] = ... (1)
  320. // x[i*2+4] = ... (2)
  321. // x[i*2+5] = ... (2)
  322. // x[(i+1234)*2+5678] = ... (3)
  323. // x[(i+1234)*2+5679] = ... (3)
  324. //
  325. // The loop will be rerolled by adding a new loop induction variable,
  326. // one for the Base instruction in each DAGRootSet.
  327. //
  328. struct DAGRootSet {
  329. Instruction *BaseInst;
  330. SmallInstructionVector Roots;
  331. // The instructions between IV and BaseInst (but not including BaseInst).
  332. SmallInstructionSet SubsumedInsts;
  333. };
  334. // The set of all DAG roots, and state tracking of all roots
  335. // for a particular induction variable.
  336. struct DAGRootTracker {
  337. DAGRootTracker(LoopReroll *Parent, Loop *L, Instruction *IV,
  338. ScalarEvolution *SE, AliasAnalysis *AA,
  339. TargetLibraryInfo *TLI, DominatorTree *DT, LoopInfo *LI,
  340. bool PreserveLCSSA,
  341. DenseMap<Instruction *, int64_t> &IncrMap,
  342. TinyInstructionVector LoopCtrlIVs)
  343. : Parent(Parent), L(L), SE(SE), AA(AA), TLI(TLI), DT(DT), LI(LI),
  344. PreserveLCSSA(PreserveLCSSA), IV(IV), IVToIncMap(IncrMap),
  345. LoopControlIVs(LoopCtrlIVs) {}
  346. /// Stage 1: Find all the DAG roots for the induction variable.
  347. bool findRoots();
  348. /// Stage 2: Validate if the found roots are valid.
  349. bool validate(ReductionTracker &Reductions);
  350. /// Stage 3: Assuming validate() returned true, perform the
  351. /// replacement.
  352. /// @param BackedgeTakenCount The backedge-taken count of L.
  353. void replace(const SCEV *BackedgeTakenCount);
  354. protected:
  355. using UsesTy = MapVector<Instruction *, BitVector>;
  356. void findRootsRecursive(Instruction *IVU,
  357. SmallInstructionSet SubsumedInsts);
  358. bool findRootsBase(Instruction *IVU, SmallInstructionSet SubsumedInsts);
  359. bool collectPossibleRoots(Instruction *Base,
  360. std::map<int64_t,Instruction*> &Roots);
  361. bool validateRootSet(DAGRootSet &DRS);
  362. bool collectUsedInstructions(SmallInstructionSet &PossibleRedSet);
  363. void collectInLoopUserSet(const SmallInstructionVector &Roots,
  364. const SmallInstructionSet &Exclude,
  365. const SmallInstructionSet &Final,
  366. DenseSet<Instruction *> &Users);
  367. void collectInLoopUserSet(Instruction *Root,
  368. const SmallInstructionSet &Exclude,
  369. const SmallInstructionSet &Final,
  370. DenseSet<Instruction *> &Users);
  371. UsesTy::iterator nextInstr(int Val, UsesTy &In,
  372. const SmallInstructionSet &Exclude,
  373. UsesTy::iterator *StartI=nullptr);
  374. bool isBaseInst(Instruction *I);
  375. bool isRootInst(Instruction *I);
  376. bool instrDependsOn(Instruction *I,
  377. UsesTy::iterator Start,
  378. UsesTy::iterator End);
  379. void replaceIV(DAGRootSet &DRS, const SCEV *Start, const SCEV *IncrExpr);
  380. LoopReroll *Parent;
  381. // Members of Parent, replicated here for brevity.
  382. Loop *L;
  383. ScalarEvolution *SE;
  384. AliasAnalysis *AA;
  385. TargetLibraryInfo *TLI;
  386. DominatorTree *DT;
  387. LoopInfo *LI;
  388. bool PreserveLCSSA;
  389. // The loop induction variable.
  390. Instruction *IV;
  391. // Loop step amount.
  392. int64_t Inc;
  393. // Loop reroll count; if Inc == 1, this records the scaling applied
  394. // to the indvar: a[i*2+0] = ...; a[i*2+1] = ... ;
  395. // If Inc is not 1, Scale = Inc.
  396. uint64_t Scale;
  397. // The roots themselves.
  398. SmallVector<DAGRootSet,16> RootSets;
  399. // All increment instructions for IV.
  400. SmallInstructionVector LoopIncs;
  401. // Map of all instructions in the loop (in order) to the iterations
  402. // they are used in (or specially, IL_All for instructions
  403. // used in the loop increment mechanism).
  404. UsesTy Uses;
  405. // Map between induction variable and its increment
  406. DenseMap<Instruction *, int64_t> &IVToIncMap;
  407. TinyInstructionVector LoopControlIVs;
  408. };
  409. // Check if it is a compare-like instruction whose user is a branch
  410. bool isCompareUsedByBranch(Instruction *I) {
  411. auto *TI = I->getParent()->getTerminator();
  412. if (!isa<BranchInst>(TI) || !isa<CmpInst>(I))
  413. return false;
  414. return I->hasOneUse() && TI->getOperand(0) == I;
  415. };
  416. bool isLoopControlIV(Loop *L, Instruction *IV);
  417. void collectPossibleIVs(Loop *L, SmallInstructionVector &PossibleIVs);
  418. void collectPossibleReductions(Loop *L,
  419. ReductionTracker &Reductions);
  420. bool reroll(Instruction *IV, Loop *L, BasicBlock *Header,
  421. const SCEV *BackedgeTakenCount, ReductionTracker &Reductions);
  422. };
  423. } // end anonymous namespace
  424. char LoopRerollLegacyPass::ID = 0;
  425. INITIALIZE_PASS_BEGIN(LoopRerollLegacyPass, "loop-reroll", "Reroll loops",
  426. false, false)
  427. INITIALIZE_PASS_DEPENDENCY(LoopPass)
  428. INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
  429. INITIALIZE_PASS_END(LoopRerollLegacyPass, "loop-reroll", "Reroll loops", false,
  430. false)
  431. Pass *llvm::createLoopRerollPass() { return new LoopRerollLegacyPass; }
  432. // Returns true if the provided instruction is used outside the given loop.
  433. // This operates like Instruction::isUsedOutsideOfBlock, but considers PHIs in
  434. // non-loop blocks to be outside the loop.
  435. static bool hasUsesOutsideLoop(Instruction *I, Loop *L) {
  436. for (User *U : I->users()) {
  437. if (!L->contains(cast<Instruction>(U)))
  438. return true;
  439. }
  440. return false;
  441. }
  442. // Check if an IV is only used to control the loop. There are two cases:
  443. // 1. It only has one use which is loop increment, and the increment is only
  444. // used by comparison and the PHI (could has sext with nsw in between), and the
  445. // comparison is only used by branch.
  446. // 2. It is used by loop increment and the comparison, the loop increment is
  447. // only used by the PHI, and the comparison is used only by the branch.
  448. bool LoopReroll::isLoopControlIV(Loop *L, Instruction *IV) {
  449. unsigned IVUses = IV->getNumUses();
  450. if (IVUses != 2 && IVUses != 1)
  451. return false;
  452. for (auto *User : IV->users()) {
  453. int32_t IncOrCmpUses = User->getNumUses();
  454. bool IsCompInst = isCompareUsedByBranch(cast<Instruction>(User));
  455. // User can only have one or two uses.
  456. if (IncOrCmpUses != 2 && IncOrCmpUses != 1)
  457. return false;
  458. // Case 1
  459. if (IVUses == 1) {
  460. // The only user must be the loop increment.
  461. // The loop increment must have two uses.
  462. if (IsCompInst || IncOrCmpUses != 2)
  463. return false;
  464. }
  465. // Case 2
  466. if (IVUses == 2 && IncOrCmpUses != 1)
  467. return false;
  468. // The users of the IV must be a binary operation or a comparison
  469. if (auto *BO = dyn_cast<BinaryOperator>(User)) {
  470. if (BO->getOpcode() == Instruction::Add) {
  471. // Loop Increment
  472. // User of Loop Increment should be either PHI or CMP
  473. for (auto *UU : User->users()) {
  474. if (PHINode *PN = dyn_cast<PHINode>(UU)) {
  475. if (PN != IV)
  476. return false;
  477. }
  478. // Must be a CMP or an ext (of a value with nsw) then CMP
  479. else {
  480. auto *UUser = cast<Instruction>(UU);
  481. // Skip SExt if we are extending an nsw value
  482. // TODO: Allow ZExt too
  483. if (BO->hasNoSignedWrap() && UUser->hasOneUse() &&
  484. isa<SExtInst>(UUser))
  485. UUser = cast<Instruction>(*(UUser->user_begin()));
  486. if (!isCompareUsedByBranch(UUser))
  487. return false;
  488. }
  489. }
  490. } else
  491. return false;
  492. // Compare : can only have one use, and must be branch
  493. } else if (!IsCompInst)
  494. return false;
  495. }
  496. return true;
  497. }
  498. // Collect the list of loop induction variables with respect to which it might
  499. // be possible to reroll the loop.
  500. void LoopReroll::collectPossibleIVs(Loop *L,
  501. SmallInstructionVector &PossibleIVs) {
  502. for (Instruction &IV : L->getHeader()->phis()) {
  503. if (!IV.getType()->isIntegerTy() && !IV.getType()->isPointerTy())
  504. continue;
  505. if (const SCEVAddRecExpr *PHISCEV =
  506. dyn_cast<SCEVAddRecExpr>(SE->getSCEV(&IV))) {
  507. if (PHISCEV->getLoop() != L)
  508. continue;
  509. if (!PHISCEV->isAffine())
  510. continue;
  511. const auto *IncSCEV = dyn_cast<SCEVConstant>(PHISCEV->getStepRecurrence(*SE));
  512. if (IncSCEV) {
  513. IVToIncMap[&IV] = IncSCEV->getValue()->getSExtValue();
  514. LLVM_DEBUG(dbgs() << "LRR: Possible IV: " << IV << " = " << *PHISCEV
  515. << "\n");
  516. if (isLoopControlIV(L, &IV)) {
  517. LoopControlIVs.push_back(&IV);
  518. LLVM_DEBUG(dbgs() << "LRR: Loop control only IV: " << IV
  519. << " = " << *PHISCEV << "\n");
  520. } else
  521. PossibleIVs.push_back(&IV);
  522. }
  523. }
  524. }
  525. }
  526. // Add the remainder of the reduction-variable chain to the instruction vector
  527. // (the initial PHINode has already been added). If successful, the object is
  528. // marked as valid.
  529. void LoopReroll::SimpleLoopReduction::add(Loop *L) {
  530. assert(!Valid && "Cannot add to an already-valid chain");
  531. // The reduction variable must be a chain of single-use instructions
  532. // (including the PHI), except for the last value (which is used by the PHI
  533. // and also outside the loop).
  534. Instruction *C = Instructions.front();
  535. if (C->user_empty())
  536. return;
  537. do {
  538. C = cast<Instruction>(*C->user_begin());
  539. if (C->hasOneUse()) {
  540. if (!C->isBinaryOp())
  541. return;
  542. if (!(isa<PHINode>(Instructions.back()) ||
  543. C->isSameOperationAs(Instructions.back())))
  544. return;
  545. Instructions.push_back(C);
  546. }
  547. } while (C->hasOneUse());
  548. if (Instructions.size() < 2 ||
  549. !C->isSameOperationAs(Instructions.back()) ||
  550. C->use_empty())
  551. return;
  552. // C is now the (potential) last instruction in the reduction chain.
  553. for (User *U : C->users()) {
  554. // The only in-loop user can be the initial PHI.
  555. if (L->contains(cast<Instruction>(U)))
  556. if (cast<Instruction>(U) != Instructions.front())
  557. return;
  558. }
  559. Instructions.push_back(C);
  560. Valid = true;
  561. }
  562. // Collect the vector of possible reduction variables.
  563. void LoopReroll::collectPossibleReductions(Loop *L,
  564. ReductionTracker &Reductions) {
  565. BasicBlock *Header = L->getHeader();
  566. for (BasicBlock::iterator I = Header->begin(),
  567. IE = Header->getFirstInsertionPt(); I != IE; ++I) {
  568. if (!isa<PHINode>(I))
  569. continue;
  570. if (!I->getType()->isSingleValueType())
  571. continue;
  572. SimpleLoopReduction SLR(&*I, L);
  573. if (!SLR.valid())
  574. continue;
  575. LLVM_DEBUG(dbgs() << "LRR: Possible reduction: " << *I << " (with "
  576. << SLR.size() << " chained instructions)\n");
  577. Reductions.addSLR(SLR);
  578. }
  579. }
  580. // Collect the set of all users of the provided root instruction. This set of
  581. // users contains not only the direct users of the root instruction, but also
  582. // all users of those users, and so on. There are two exceptions:
  583. //
  584. // 1. Instructions in the set of excluded instructions are never added to the
  585. // use set (even if they are users). This is used, for example, to exclude
  586. // including root increments in the use set of the primary IV.
  587. //
  588. // 2. Instructions in the set of final instructions are added to the use set
  589. // if they are users, but their users are not added. This is used, for
  590. // example, to prevent a reduction update from forcing all later reduction
  591. // updates into the use set.
  592. void LoopReroll::DAGRootTracker::collectInLoopUserSet(
  593. Instruction *Root, const SmallInstructionSet &Exclude,
  594. const SmallInstructionSet &Final,
  595. DenseSet<Instruction *> &Users) {
  596. SmallInstructionVector Queue(1, Root);
  597. while (!Queue.empty()) {
  598. Instruction *I = Queue.pop_back_val();
  599. if (!Users.insert(I).second)
  600. continue;
  601. if (!Final.count(I))
  602. for (Use &U : I->uses()) {
  603. Instruction *User = cast<Instruction>(U.getUser());
  604. if (PHINode *PN = dyn_cast<PHINode>(User)) {
  605. // Ignore "wrap-around" uses to PHIs of this loop's header.
  606. if (PN->getIncomingBlock(U) == L->getHeader())
  607. continue;
  608. }
  609. if (L->contains(User) && !Exclude.count(User)) {
  610. Queue.push_back(User);
  611. }
  612. }
  613. // We also want to collect single-user "feeder" values.
  614. for (Use &U : I->operands()) {
  615. if (Instruction *Op = dyn_cast<Instruction>(U))
  616. if (Op->hasOneUse() && L->contains(Op) && !Exclude.count(Op) &&
  617. !Final.count(Op))
  618. Queue.push_back(Op);
  619. }
  620. }
  621. }
  622. // Collect all of the users of all of the provided root instructions (combined
  623. // into a single set).
  624. void LoopReroll::DAGRootTracker::collectInLoopUserSet(
  625. const SmallInstructionVector &Roots,
  626. const SmallInstructionSet &Exclude,
  627. const SmallInstructionSet &Final,
  628. DenseSet<Instruction *> &Users) {
  629. for (Instruction *Root : Roots)
  630. collectInLoopUserSet(Root, Exclude, Final, Users);
  631. }
  632. static bool isUnorderedLoadStore(Instruction *I) {
  633. if (LoadInst *LI = dyn_cast<LoadInst>(I))
  634. return LI->isUnordered();
  635. if (StoreInst *SI = dyn_cast<StoreInst>(I))
  636. return SI->isUnordered();
  637. if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I))
  638. return !MI->isVolatile();
  639. return false;
  640. }
  641. /// Return true if IVU is a "simple" arithmetic operation.
  642. /// This is used for narrowing the search space for DAGRoots; only arithmetic
  643. /// and GEPs can be part of a DAGRoot.
  644. static bool isSimpleArithmeticOp(User *IVU) {
  645. if (Instruction *I = dyn_cast<Instruction>(IVU)) {
  646. switch (I->getOpcode()) {
  647. default: return false;
  648. case Instruction::Add:
  649. case Instruction::Sub:
  650. case Instruction::Mul:
  651. case Instruction::Shl:
  652. case Instruction::AShr:
  653. case Instruction::LShr:
  654. case Instruction::GetElementPtr:
  655. case Instruction::Trunc:
  656. case Instruction::ZExt:
  657. case Instruction::SExt:
  658. return true;
  659. }
  660. }
  661. return false;
  662. }
  663. static bool isLoopIncrement(User *U, Instruction *IV) {
  664. BinaryOperator *BO = dyn_cast<BinaryOperator>(U);
  665. if ((BO && BO->getOpcode() != Instruction::Add) ||
  666. (!BO && !isa<GetElementPtrInst>(U)))
  667. return false;
  668. for (auto *UU : U->users()) {
  669. PHINode *PN = dyn_cast<PHINode>(UU);
  670. if (PN && PN == IV)
  671. return true;
  672. }
  673. return false;
  674. }
  675. bool LoopReroll::DAGRootTracker::
  676. collectPossibleRoots(Instruction *Base, std::map<int64_t,Instruction*> &Roots) {
  677. SmallInstructionVector BaseUsers;
  678. for (auto *I : Base->users()) {
  679. ConstantInt *CI = nullptr;
  680. if (isLoopIncrement(I, IV)) {
  681. LoopIncs.push_back(cast<Instruction>(I));
  682. continue;
  683. }
  684. // The root nodes must be either GEPs, ORs or ADDs.
  685. if (auto *BO = dyn_cast<BinaryOperator>(I)) {
  686. if (BO->getOpcode() == Instruction::Add ||
  687. BO->getOpcode() == Instruction::Or)
  688. CI = dyn_cast<ConstantInt>(BO->getOperand(1));
  689. } else if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) {
  690. Value *LastOperand = GEP->getOperand(GEP->getNumOperands()-1);
  691. CI = dyn_cast<ConstantInt>(LastOperand);
  692. }
  693. if (!CI) {
  694. if (Instruction *II = dyn_cast<Instruction>(I)) {
  695. BaseUsers.push_back(II);
  696. continue;
  697. } else {
  698. LLVM_DEBUG(dbgs() << "LRR: Aborting due to non-instruction: " << *I
  699. << "\n");
  700. return false;
  701. }
  702. }
  703. int64_t V = std::abs(CI->getValue().getSExtValue());
  704. if (Roots.find(V) != Roots.end())
  705. // No duplicates, please.
  706. return false;
  707. Roots[V] = cast<Instruction>(I);
  708. }
  709. // Make sure we have at least two roots.
  710. if (Roots.empty() || (Roots.size() == 1 && BaseUsers.empty()))
  711. return false;
  712. // If we found non-loop-inc, non-root users of Base, assume they are
  713. // for the zeroth root index. This is because "add %a, 0" gets optimized
  714. // away.
  715. if (BaseUsers.size()) {
  716. if (Roots.find(0) != Roots.end()) {
  717. LLVM_DEBUG(dbgs() << "LRR: Multiple roots found for base - aborting!\n");
  718. return false;
  719. }
  720. Roots[0] = Base;
  721. }
  722. // Calculate the number of users of the base, or lowest indexed, iteration.
  723. unsigned NumBaseUses = BaseUsers.size();
  724. if (NumBaseUses == 0)
  725. NumBaseUses = Roots.begin()->second->getNumUses();
  726. // Check that every node has the same number of users.
  727. for (auto &KV : Roots) {
  728. if (KV.first == 0)
  729. continue;
  730. if (!KV.second->hasNUses(NumBaseUses)) {
  731. LLVM_DEBUG(dbgs() << "LRR: Aborting - Root and Base #users not the same: "
  732. << "#Base=" << NumBaseUses
  733. << ", #Root=" << KV.second->getNumUses() << "\n");
  734. return false;
  735. }
  736. }
  737. return true;
  738. }
  739. void LoopReroll::DAGRootTracker::
  740. findRootsRecursive(Instruction *I, SmallInstructionSet SubsumedInsts) {
  741. // Does the user look like it could be part of a root set?
  742. // All its users must be simple arithmetic ops.
  743. if (I->hasNUsesOrMore(IL_MaxRerollIterations + 1))
  744. return;
  745. if (I != IV && findRootsBase(I, SubsumedInsts))
  746. return;
  747. SubsumedInsts.insert(I);
  748. for (User *V : I->users()) {
  749. Instruction *I = cast<Instruction>(V);
  750. if (is_contained(LoopIncs, I))
  751. continue;
  752. if (!isSimpleArithmeticOp(I))
  753. continue;
  754. // The recursive call makes a copy of SubsumedInsts.
  755. findRootsRecursive(I, SubsumedInsts);
  756. }
  757. }
  758. bool LoopReroll::DAGRootTracker::validateRootSet(DAGRootSet &DRS) {
  759. if (DRS.Roots.empty())
  760. return false;
  761. // If the value of the base instruction is used outside the loop, we cannot
  762. // reroll the loop. Check for other root instructions is unnecessary because
  763. // they don't match any base instructions if their values are used outside.
  764. if (hasUsesOutsideLoop(DRS.BaseInst, L))
  765. return false;
  766. // Consider a DAGRootSet with N-1 roots (so N different values including
  767. // BaseInst).
  768. // Define d = Roots[0] - BaseInst, which should be the same as
  769. // Roots[I] - Roots[I-1] for all I in [1..N).
  770. // Define D = BaseInst@J - BaseInst@J-1, where "@J" means the value at the
  771. // loop iteration J.
  772. //
  773. // Now, For the loop iterations to be consecutive:
  774. // D = d * N
  775. const auto *ADR = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(DRS.BaseInst));
  776. if (!ADR)
  777. return false;
  778. // Check that the first root is evenly spaced.
  779. unsigned N = DRS.Roots.size() + 1;
  780. const SCEV *StepSCEV = SE->getMinusSCEV(SE->getSCEV(DRS.Roots[0]), ADR);
  781. if (isa<SCEVCouldNotCompute>(StepSCEV) || StepSCEV->getType()->isPointerTy())
  782. return false;
  783. const SCEV *ScaleSCEV = SE->getConstant(StepSCEV->getType(), N);
  784. if (ADR->getStepRecurrence(*SE) != SE->getMulExpr(StepSCEV, ScaleSCEV))
  785. return false;
  786. // Check that the remainling roots are evenly spaced.
  787. for (unsigned i = 1; i < N - 1; ++i) {
  788. const SCEV *NewStepSCEV = SE->getMinusSCEV(SE->getSCEV(DRS.Roots[i]),
  789. SE->getSCEV(DRS.Roots[i-1]));
  790. if (NewStepSCEV != StepSCEV)
  791. return false;
  792. }
  793. return true;
  794. }
  795. bool LoopReroll::DAGRootTracker::
  796. findRootsBase(Instruction *IVU, SmallInstructionSet SubsumedInsts) {
  797. // The base of a RootSet must be an AddRec, so it can be erased.
  798. const auto *IVU_ADR = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(IVU));
  799. if (!IVU_ADR || IVU_ADR->getLoop() != L)
  800. return false;
  801. std::map<int64_t, Instruction*> V;
  802. if (!collectPossibleRoots(IVU, V))
  803. return false;
  804. // If we didn't get a root for index zero, then IVU must be
  805. // subsumed.
  806. if (V.find(0) == V.end())
  807. SubsumedInsts.insert(IVU);
  808. // Partition the vector into monotonically increasing indexes.
  809. DAGRootSet DRS;
  810. DRS.BaseInst = nullptr;
  811. SmallVector<DAGRootSet, 16> PotentialRootSets;
  812. for (auto &KV : V) {
  813. if (!DRS.BaseInst) {
  814. DRS.BaseInst = KV.second;
  815. DRS.SubsumedInsts = SubsumedInsts;
  816. } else if (DRS.Roots.empty()) {
  817. DRS.Roots.push_back(KV.second);
  818. } else if (V.find(KV.first - 1) != V.end()) {
  819. DRS.Roots.push_back(KV.second);
  820. } else {
  821. // Linear sequence terminated.
  822. if (!validateRootSet(DRS))
  823. return false;
  824. // Construct a new DAGRootSet with the next sequence.
  825. PotentialRootSets.push_back(DRS);
  826. DRS.BaseInst = KV.second;
  827. DRS.Roots.clear();
  828. }
  829. }
  830. if (!validateRootSet(DRS))
  831. return false;
  832. PotentialRootSets.push_back(DRS);
  833. RootSets.append(PotentialRootSets.begin(), PotentialRootSets.end());
  834. return true;
  835. }
  836. bool LoopReroll::DAGRootTracker::findRoots() {
  837. Inc = IVToIncMap[IV];
  838. assert(RootSets.empty() && "Unclean state!");
  839. if (std::abs(Inc) == 1) {
  840. for (auto *IVU : IV->users()) {
  841. if (isLoopIncrement(IVU, IV))
  842. LoopIncs.push_back(cast<Instruction>(IVU));
  843. }
  844. findRootsRecursive(IV, SmallInstructionSet());
  845. LoopIncs.push_back(IV);
  846. } else {
  847. if (!findRootsBase(IV, SmallInstructionSet()))
  848. return false;
  849. }
  850. // Ensure all sets have the same size.
  851. if (RootSets.empty()) {
  852. LLVM_DEBUG(dbgs() << "LRR: Aborting because no root sets found!\n");
  853. return false;
  854. }
  855. for (auto &V : RootSets) {
  856. if (V.Roots.empty() || V.Roots.size() != RootSets[0].Roots.size()) {
  857. LLVM_DEBUG(
  858. dbgs()
  859. << "LRR: Aborting because not all root sets have the same size\n");
  860. return false;
  861. }
  862. }
  863. Scale = RootSets[0].Roots.size() + 1;
  864. if (Scale > IL_MaxRerollIterations) {
  865. LLVM_DEBUG(dbgs() << "LRR: Aborting - too many iterations found. "
  866. << "#Found=" << Scale
  867. << ", #Max=" << IL_MaxRerollIterations << "\n");
  868. return false;
  869. }
  870. LLVM_DEBUG(dbgs() << "LRR: Successfully found roots: Scale=" << Scale
  871. << "\n");
  872. return true;
  873. }
  874. bool LoopReroll::DAGRootTracker::collectUsedInstructions(SmallInstructionSet &PossibleRedSet) {
  875. // Populate the MapVector with all instructions in the block, in order first,
  876. // so we can iterate over the contents later in perfect order.
  877. for (auto &I : *L->getHeader()) {
  878. Uses[&I].resize(IL_End);
  879. }
  880. SmallInstructionSet Exclude;
  881. for (auto &DRS : RootSets) {
  882. Exclude.insert(DRS.Roots.begin(), DRS.Roots.end());
  883. Exclude.insert(DRS.SubsumedInsts.begin(), DRS.SubsumedInsts.end());
  884. Exclude.insert(DRS.BaseInst);
  885. }
  886. Exclude.insert(LoopIncs.begin(), LoopIncs.end());
  887. for (auto &DRS : RootSets) {
  888. DenseSet<Instruction*> VBase;
  889. collectInLoopUserSet(DRS.BaseInst, Exclude, PossibleRedSet, VBase);
  890. for (auto *I : VBase) {
  891. Uses[I].set(0);
  892. }
  893. unsigned Idx = 1;
  894. for (auto *Root : DRS.Roots) {
  895. DenseSet<Instruction*> V;
  896. collectInLoopUserSet(Root, Exclude, PossibleRedSet, V);
  897. // While we're here, check the use sets are the same size.
  898. if (V.size() != VBase.size()) {
  899. LLVM_DEBUG(dbgs() << "LRR: Aborting - use sets are different sizes\n");
  900. return false;
  901. }
  902. for (auto *I : V) {
  903. Uses[I].set(Idx);
  904. }
  905. ++Idx;
  906. }
  907. // Make sure our subsumed instructions are remembered too.
  908. for (auto *I : DRS.SubsumedInsts) {
  909. Uses[I].set(IL_All);
  910. }
  911. }
  912. // Make sure the loop increments are also accounted for.
  913. Exclude.clear();
  914. for (auto &DRS : RootSets) {
  915. Exclude.insert(DRS.Roots.begin(), DRS.Roots.end());
  916. Exclude.insert(DRS.SubsumedInsts.begin(), DRS.SubsumedInsts.end());
  917. Exclude.insert(DRS.BaseInst);
  918. }
  919. DenseSet<Instruction*> V;
  920. collectInLoopUserSet(LoopIncs, Exclude, PossibleRedSet, V);
  921. for (auto *I : V) {
  922. if (I->mayHaveSideEffects()) {
  923. LLVM_DEBUG(dbgs() << "LRR: Aborting - "
  924. << "An instruction which does not belong to any root "
  925. << "sets must not have side effects: " << *I);
  926. return false;
  927. }
  928. Uses[I].set(IL_All);
  929. }
  930. return true;
  931. }
  932. /// Get the next instruction in "In" that is a member of set Val.
  933. /// Start searching from StartI, and do not return anything in Exclude.
  934. /// If StartI is not given, start from In.begin().
  935. LoopReroll::DAGRootTracker::UsesTy::iterator
  936. LoopReroll::DAGRootTracker::nextInstr(int Val, UsesTy &In,
  937. const SmallInstructionSet &Exclude,
  938. UsesTy::iterator *StartI) {
  939. UsesTy::iterator I = StartI ? *StartI : In.begin();
  940. while (I != In.end() && (I->second.test(Val) == 0 ||
  941. Exclude.contains(I->first)))
  942. ++I;
  943. return I;
  944. }
  945. bool LoopReroll::DAGRootTracker::isBaseInst(Instruction *I) {
  946. for (auto &DRS : RootSets) {
  947. if (DRS.BaseInst == I)
  948. return true;
  949. }
  950. return false;
  951. }
  952. bool LoopReroll::DAGRootTracker::isRootInst(Instruction *I) {
  953. for (auto &DRS : RootSets) {
  954. if (is_contained(DRS.Roots, I))
  955. return true;
  956. }
  957. return false;
  958. }
  959. /// Return true if instruction I depends on any instruction between
  960. /// Start and End.
  961. bool LoopReroll::DAGRootTracker::instrDependsOn(Instruction *I,
  962. UsesTy::iterator Start,
  963. UsesTy::iterator End) {
  964. for (auto *U : I->users()) {
  965. for (auto It = Start; It != End; ++It)
  966. if (U == It->first)
  967. return true;
  968. }
  969. return false;
  970. }
  971. static bool isIgnorableInst(const Instruction *I) {
  972. if (isa<DbgInfoIntrinsic>(I))
  973. return true;
  974. const IntrinsicInst* II = dyn_cast<IntrinsicInst>(I);
  975. if (!II)
  976. return false;
  977. switch (II->getIntrinsicID()) {
  978. default:
  979. return false;
  980. case Intrinsic::annotation:
  981. case Intrinsic::ptr_annotation:
  982. case Intrinsic::var_annotation:
  983. // TODO: the following intrinsics may also be allowed:
  984. // lifetime_start, lifetime_end, invariant_start, invariant_end
  985. return true;
  986. }
  987. return false;
  988. }
  989. bool LoopReroll::DAGRootTracker::validate(ReductionTracker &Reductions) {
  990. // We now need to check for equivalence of the use graph of each root with
  991. // that of the primary induction variable (excluding the roots). Our goal
  992. // here is not to solve the full graph isomorphism problem, but rather to
  993. // catch common cases without a lot of work. As a result, we will assume
  994. // that the relative order of the instructions in each unrolled iteration
  995. // is the same (although we will not make an assumption about how the
  996. // different iterations are intermixed). Note that while the order must be
  997. // the same, the instructions may not be in the same basic block.
  998. // An array of just the possible reductions for this scale factor. When we
  999. // collect the set of all users of some root instructions, these reduction
  1000. // instructions are treated as 'final' (their uses are not considered).
  1001. // This is important because we don't want the root use set to search down
  1002. // the reduction chain.
  1003. SmallInstructionSet PossibleRedSet;
  1004. SmallInstructionSet PossibleRedLastSet;
  1005. SmallInstructionSet PossibleRedPHISet;
  1006. Reductions.restrictToScale(Scale, PossibleRedSet,
  1007. PossibleRedPHISet, PossibleRedLastSet);
  1008. // Populate "Uses" with where each instruction is used.
  1009. if (!collectUsedInstructions(PossibleRedSet))
  1010. return false;
  1011. // Make sure we mark the reduction PHIs as used in all iterations.
  1012. for (auto *I : PossibleRedPHISet) {
  1013. Uses[I].set(IL_All);
  1014. }
  1015. // Make sure we mark loop-control-only PHIs as used in all iterations. See
  1016. // comment above LoopReroll::isLoopControlIV for more information.
  1017. BasicBlock *Header = L->getHeader();
  1018. for (Instruction *LoopControlIV : LoopControlIVs) {
  1019. for (auto *U : LoopControlIV->users()) {
  1020. Instruction *IVUser = dyn_cast<Instruction>(U);
  1021. // IVUser could be loop increment or compare
  1022. Uses[IVUser].set(IL_All);
  1023. for (auto *UU : IVUser->users()) {
  1024. Instruction *UUser = dyn_cast<Instruction>(UU);
  1025. // UUser could be compare, PHI or branch
  1026. Uses[UUser].set(IL_All);
  1027. // Skip SExt
  1028. if (isa<SExtInst>(UUser)) {
  1029. UUser = dyn_cast<Instruction>(*(UUser->user_begin()));
  1030. Uses[UUser].set(IL_All);
  1031. }
  1032. // Is UUser a compare instruction?
  1033. if (UU->hasOneUse()) {
  1034. Instruction *BI = dyn_cast<BranchInst>(*UUser->user_begin());
  1035. if (BI == cast<BranchInst>(Header->getTerminator()))
  1036. Uses[BI].set(IL_All);
  1037. }
  1038. }
  1039. }
  1040. }
  1041. // Make sure all instructions in the loop are in one and only one
  1042. // set.
  1043. for (auto &KV : Uses) {
  1044. if (KV.second.count() != 1 && !isIgnorableInst(KV.first)) {
  1045. LLVM_DEBUG(
  1046. dbgs() << "LRR: Aborting - instruction is not used in 1 iteration: "
  1047. << *KV.first << " (#uses=" << KV.second.count() << ")\n");
  1048. return false;
  1049. }
  1050. }
  1051. LLVM_DEBUG(for (auto &KV
  1052. : Uses) {
  1053. dbgs() << "LRR: " << KV.second.find_first() << "\t" << *KV.first << "\n";
  1054. });
  1055. BatchAAResults BatchAA(*AA);
  1056. for (unsigned Iter = 1; Iter < Scale; ++Iter) {
  1057. // In addition to regular aliasing information, we need to look for
  1058. // instructions from later (future) iterations that have side effects
  1059. // preventing us from reordering them past other instructions with side
  1060. // effects.
  1061. bool FutureSideEffects = false;
  1062. AliasSetTracker AST(BatchAA);
  1063. // The map between instructions in f(%iv.(i+1)) and f(%iv).
  1064. DenseMap<Value *, Value *> BaseMap;
  1065. // Compare iteration Iter to the base.
  1066. SmallInstructionSet Visited;
  1067. auto BaseIt = nextInstr(0, Uses, Visited);
  1068. auto RootIt = nextInstr(Iter, Uses, Visited);
  1069. auto LastRootIt = Uses.begin();
  1070. while (BaseIt != Uses.end() && RootIt != Uses.end()) {
  1071. Instruction *BaseInst = BaseIt->first;
  1072. Instruction *RootInst = RootIt->first;
  1073. // Skip over the IV or root instructions; only match their users.
  1074. bool Continue = false;
  1075. if (isBaseInst(BaseInst)) {
  1076. Visited.insert(BaseInst);
  1077. BaseIt = nextInstr(0, Uses, Visited);
  1078. Continue = true;
  1079. }
  1080. if (isRootInst(RootInst)) {
  1081. LastRootIt = RootIt;
  1082. Visited.insert(RootInst);
  1083. RootIt = nextInstr(Iter, Uses, Visited);
  1084. Continue = true;
  1085. }
  1086. if (Continue) continue;
  1087. if (!BaseInst->isSameOperationAs(RootInst)) {
  1088. // Last chance saloon. We don't try and solve the full isomorphism
  1089. // problem, but try and at least catch the case where two instructions
  1090. // *of different types* are round the wrong way. We won't be able to
  1091. // efficiently tell, given two ADD instructions, which way around we
  1092. // should match them, but given an ADD and a SUB, we can at least infer
  1093. // which one is which.
  1094. //
  1095. // This should allow us to deal with a greater subset of the isomorphism
  1096. // problem. It does however change a linear algorithm into a quadratic
  1097. // one, so limit the number of probes we do.
  1098. auto TryIt = RootIt;
  1099. unsigned N = NumToleratedFailedMatches;
  1100. while (TryIt != Uses.end() &&
  1101. !BaseInst->isSameOperationAs(TryIt->first) &&
  1102. N--) {
  1103. ++TryIt;
  1104. TryIt = nextInstr(Iter, Uses, Visited, &TryIt);
  1105. }
  1106. if (TryIt == Uses.end() || TryIt == RootIt ||
  1107. instrDependsOn(TryIt->first, RootIt, TryIt)) {
  1108. LLVM_DEBUG(dbgs() << "LRR: iteration root match failed at "
  1109. << *BaseInst << " vs. " << *RootInst << "\n");
  1110. return false;
  1111. }
  1112. RootIt = TryIt;
  1113. RootInst = TryIt->first;
  1114. }
  1115. // All instructions between the last root and this root
  1116. // may belong to some other iteration. If they belong to a
  1117. // future iteration, then they're dangerous to alias with.
  1118. //
  1119. // Note that because we allow a limited amount of flexibility in the order
  1120. // that we visit nodes, LastRootIt might be *before* RootIt, in which
  1121. // case we've already checked this set of instructions so we shouldn't
  1122. // do anything.
  1123. for (; LastRootIt < RootIt; ++LastRootIt) {
  1124. Instruction *I = LastRootIt->first;
  1125. if (LastRootIt->second.find_first() < (int)Iter)
  1126. continue;
  1127. if (I->mayWriteToMemory())
  1128. AST.add(I);
  1129. // Note: This is specifically guarded by a check on isa<PHINode>,
  1130. // which while a valid (somewhat arbitrary) micro-optimization, is
  1131. // needed because otherwise isSafeToSpeculativelyExecute returns
  1132. // false on PHI nodes.
  1133. if (!isa<PHINode>(I) && !isUnorderedLoadStore(I) &&
  1134. !isSafeToSpeculativelyExecute(I))
  1135. // Intervening instructions cause side effects.
  1136. FutureSideEffects = true;
  1137. }
  1138. // Make sure that this instruction, which is in the use set of this
  1139. // root instruction, does not also belong to the base set or the set of
  1140. // some other root instruction.
  1141. if (RootIt->second.count() > 1) {
  1142. LLVM_DEBUG(dbgs() << "LRR: iteration root match failed at " << *BaseInst
  1143. << " vs. " << *RootInst << " (prev. case overlap)\n");
  1144. return false;
  1145. }
  1146. // Make sure that we don't alias with any instruction in the alias set
  1147. // tracker. If we do, then we depend on a future iteration, and we
  1148. // can't reroll.
  1149. if (RootInst->mayReadFromMemory()) {
  1150. for (auto &K : AST) {
  1151. if (isModOrRefSet(K.aliasesUnknownInst(RootInst, BatchAA))) {
  1152. LLVM_DEBUG(dbgs() << "LRR: iteration root match failed at "
  1153. << *BaseInst << " vs. " << *RootInst
  1154. << " (depends on future store)\n");
  1155. return false;
  1156. }
  1157. }
  1158. }
  1159. // If we've past an instruction from a future iteration that may have
  1160. // side effects, and this instruction might also, then we can't reorder
  1161. // them, and this matching fails. As an exception, we allow the alias
  1162. // set tracker to handle regular (unordered) load/store dependencies.
  1163. if (FutureSideEffects && ((!isUnorderedLoadStore(BaseInst) &&
  1164. !isSafeToSpeculativelyExecute(BaseInst)) ||
  1165. (!isUnorderedLoadStore(RootInst) &&
  1166. !isSafeToSpeculativelyExecute(RootInst)))) {
  1167. LLVM_DEBUG(dbgs() << "LRR: iteration root match failed at " << *BaseInst
  1168. << " vs. " << *RootInst
  1169. << " (side effects prevent reordering)\n");
  1170. return false;
  1171. }
  1172. // For instructions that are part of a reduction, if the operation is
  1173. // associative, then don't bother matching the operands (because we
  1174. // already know that the instructions are isomorphic, and the order
  1175. // within the iteration does not matter). For non-associative reductions,
  1176. // we do need to match the operands, because we need to reject
  1177. // out-of-order instructions within an iteration!
  1178. // For example (assume floating-point addition), we need to reject this:
  1179. // x += a[i]; x += b[i];
  1180. // x += a[i+1]; x += b[i+1];
  1181. // x += b[i+2]; x += a[i+2];
  1182. bool InReduction = Reductions.isPairInSame(BaseInst, RootInst);
  1183. if (!(InReduction && BaseInst->isAssociative())) {
  1184. bool Swapped = false, SomeOpMatched = false;
  1185. for (unsigned j = 0; j < BaseInst->getNumOperands(); ++j) {
  1186. Value *Op2 = RootInst->getOperand(j);
  1187. // If this is part of a reduction (and the operation is not
  1188. // associatve), then we match all operands, but not those that are
  1189. // part of the reduction.
  1190. if (InReduction)
  1191. if (Instruction *Op2I = dyn_cast<Instruction>(Op2))
  1192. if (Reductions.isPairInSame(RootInst, Op2I))
  1193. continue;
  1194. DenseMap<Value *, Value *>::iterator BMI = BaseMap.find(Op2);
  1195. if (BMI != BaseMap.end()) {
  1196. Op2 = BMI->second;
  1197. } else {
  1198. for (auto &DRS : RootSets) {
  1199. if (DRS.Roots[Iter-1] == (Instruction*) Op2) {
  1200. Op2 = DRS.BaseInst;
  1201. break;
  1202. }
  1203. }
  1204. }
  1205. if (BaseInst->getOperand(Swapped ? unsigned(!j) : j) != Op2) {
  1206. // If we've not already decided to swap the matched operands, and
  1207. // we've not already matched our first operand (note that we could
  1208. // have skipped matching the first operand because it is part of a
  1209. // reduction above), and the instruction is commutative, then try
  1210. // the swapped match.
  1211. if (!Swapped && BaseInst->isCommutative() && !SomeOpMatched &&
  1212. BaseInst->getOperand(!j) == Op2) {
  1213. Swapped = true;
  1214. } else {
  1215. LLVM_DEBUG(dbgs()
  1216. << "LRR: iteration root match failed at " << *BaseInst
  1217. << " vs. " << *RootInst << " (operand " << j << ")\n");
  1218. return false;
  1219. }
  1220. }
  1221. SomeOpMatched = true;
  1222. }
  1223. }
  1224. if ((!PossibleRedLastSet.count(BaseInst) &&
  1225. hasUsesOutsideLoop(BaseInst, L)) ||
  1226. (!PossibleRedLastSet.count(RootInst) &&
  1227. hasUsesOutsideLoop(RootInst, L))) {
  1228. LLVM_DEBUG(dbgs() << "LRR: iteration root match failed at " << *BaseInst
  1229. << " vs. " << *RootInst << " (uses outside loop)\n");
  1230. return false;
  1231. }
  1232. Reductions.recordPair(BaseInst, RootInst, Iter);
  1233. BaseMap.insert(std::make_pair(RootInst, BaseInst));
  1234. LastRootIt = RootIt;
  1235. Visited.insert(BaseInst);
  1236. Visited.insert(RootInst);
  1237. BaseIt = nextInstr(0, Uses, Visited);
  1238. RootIt = nextInstr(Iter, Uses, Visited);
  1239. }
  1240. assert(BaseIt == Uses.end() && RootIt == Uses.end() &&
  1241. "Mismatched set sizes!");
  1242. }
  1243. LLVM_DEBUG(dbgs() << "LRR: Matched all iteration increments for " << *IV
  1244. << "\n");
  1245. return true;
  1246. }
  1247. void LoopReroll::DAGRootTracker::replace(const SCEV *BackedgeTakenCount) {
  1248. BasicBlock *Header = L->getHeader();
  1249. // Compute the start and increment for each BaseInst before we start erasing
  1250. // instructions.
  1251. SmallVector<const SCEV *, 8> StartExprs;
  1252. SmallVector<const SCEV *, 8> IncrExprs;
  1253. for (auto &DRS : RootSets) {
  1254. const SCEVAddRecExpr *IVSCEV =
  1255. cast<SCEVAddRecExpr>(SE->getSCEV(DRS.BaseInst));
  1256. StartExprs.push_back(IVSCEV->getStart());
  1257. IncrExprs.push_back(SE->getMinusSCEV(SE->getSCEV(DRS.Roots[0]), IVSCEV));
  1258. }
  1259. // Remove instructions associated with non-base iterations.
  1260. for (Instruction &Inst : llvm::make_early_inc_range(llvm::reverse(*Header))) {
  1261. unsigned I = Uses[&Inst].find_first();
  1262. if (I > 0 && I < IL_All) {
  1263. LLVM_DEBUG(dbgs() << "LRR: removing: " << Inst << "\n");
  1264. Inst.eraseFromParent();
  1265. }
  1266. }
  1267. // Rewrite each BaseInst using SCEV.
  1268. for (size_t i = 0, e = RootSets.size(); i != e; ++i)
  1269. // Insert the new induction variable.
  1270. replaceIV(RootSets[i], StartExprs[i], IncrExprs[i]);
  1271. { // Limit the lifetime of SCEVExpander.
  1272. BranchInst *BI = cast<BranchInst>(Header->getTerminator());
  1273. const DataLayout &DL = Header->getModule()->getDataLayout();
  1274. SCEVExpander Expander(*SE, DL, "reroll");
  1275. auto Zero = SE->getZero(BackedgeTakenCount->getType());
  1276. auto One = SE->getOne(BackedgeTakenCount->getType());
  1277. auto NewIVSCEV = SE->getAddRecExpr(Zero, One, L, SCEV::FlagAnyWrap);
  1278. Value *NewIV =
  1279. Expander.expandCodeFor(NewIVSCEV, BackedgeTakenCount->getType(),
  1280. Header->getFirstNonPHIOrDbg());
  1281. // FIXME: This arithmetic can overflow.
  1282. auto TripCount = SE->getAddExpr(BackedgeTakenCount, One);
  1283. auto ScaledTripCount = SE->getMulExpr(
  1284. TripCount, SE->getConstant(BackedgeTakenCount->getType(), Scale));
  1285. auto ScaledBECount = SE->getMinusSCEV(ScaledTripCount, One);
  1286. Value *TakenCount =
  1287. Expander.expandCodeFor(ScaledBECount, BackedgeTakenCount->getType(),
  1288. Header->getFirstNonPHIOrDbg());
  1289. Value *Cond =
  1290. new ICmpInst(BI, CmpInst::ICMP_EQ, NewIV, TakenCount, "exitcond");
  1291. BI->setCondition(Cond);
  1292. if (BI->getSuccessor(1) != Header)
  1293. BI->swapSuccessors();
  1294. }
  1295. SimplifyInstructionsInBlock(Header, TLI);
  1296. DeleteDeadPHIs(Header, TLI);
  1297. }
  1298. void LoopReroll::DAGRootTracker::replaceIV(DAGRootSet &DRS,
  1299. const SCEV *Start,
  1300. const SCEV *IncrExpr) {
  1301. BasicBlock *Header = L->getHeader();
  1302. Instruction *Inst = DRS.BaseInst;
  1303. const SCEV *NewIVSCEV =
  1304. SE->getAddRecExpr(Start, IncrExpr, L, SCEV::FlagAnyWrap);
  1305. { // Limit the lifetime of SCEVExpander.
  1306. const DataLayout &DL = Header->getModule()->getDataLayout();
  1307. SCEVExpander Expander(*SE, DL, "reroll");
  1308. Value *NewIV = Expander.expandCodeFor(NewIVSCEV, Inst->getType(),
  1309. Header->getFirstNonPHIOrDbg());
  1310. for (auto &KV : Uses)
  1311. if (KV.second.find_first() == 0)
  1312. KV.first->replaceUsesOfWith(Inst, NewIV);
  1313. }
  1314. }
  1315. // Validate the selected reductions. All iterations must have an isomorphic
  1316. // part of the reduction chain and, for non-associative reductions, the chain
  1317. // entries must appear in order.
  1318. bool LoopReroll::ReductionTracker::validateSelected() {
  1319. // For a non-associative reduction, the chain entries must appear in order.
  1320. for (int i : Reds) {
  1321. int PrevIter = 0, BaseCount = 0, Count = 0;
  1322. for (Instruction *J : PossibleReds[i]) {
  1323. // Note that all instructions in the chain must have been found because
  1324. // all instructions in the function must have been assigned to some
  1325. // iteration.
  1326. int Iter = PossibleRedIter[J];
  1327. if (Iter != PrevIter && Iter != PrevIter + 1 &&
  1328. !PossibleReds[i].getReducedValue()->isAssociative()) {
  1329. LLVM_DEBUG(dbgs() << "LRR: Out-of-order non-associative reduction: "
  1330. << J << "\n");
  1331. return false;
  1332. }
  1333. if (Iter != PrevIter) {
  1334. if (Count != BaseCount) {
  1335. LLVM_DEBUG(dbgs()
  1336. << "LRR: Iteration " << PrevIter << " reduction use count "
  1337. << Count << " is not equal to the base use count "
  1338. << BaseCount << "\n");
  1339. return false;
  1340. }
  1341. Count = 0;
  1342. }
  1343. ++Count;
  1344. if (Iter == 0)
  1345. ++BaseCount;
  1346. PrevIter = Iter;
  1347. }
  1348. }
  1349. return true;
  1350. }
  1351. // For all selected reductions, remove all parts except those in the first
  1352. // iteration (and the PHI). Replace outside uses of the reduced value with uses
  1353. // of the first-iteration reduced value (in other words, reroll the selected
  1354. // reductions).
  1355. void LoopReroll::ReductionTracker::replaceSelected() {
  1356. // Fixup reductions to refer to the last instruction associated with the
  1357. // first iteration (not the last).
  1358. for (int i : Reds) {
  1359. int j = 0;
  1360. for (int e = PossibleReds[i].size(); j != e; ++j)
  1361. if (PossibleRedIter[PossibleReds[i][j]] != 0) {
  1362. --j;
  1363. break;
  1364. }
  1365. // Replace users with the new end-of-chain value.
  1366. SmallInstructionVector Users;
  1367. for (User *U : PossibleReds[i].getReducedValue()->users()) {
  1368. Users.push_back(cast<Instruction>(U));
  1369. }
  1370. for (Instruction *User : Users)
  1371. User->replaceUsesOfWith(PossibleReds[i].getReducedValue(),
  1372. PossibleReds[i][j]);
  1373. }
  1374. }
  1375. // Reroll the provided loop with respect to the provided induction variable.
  1376. // Generally, we're looking for a loop like this:
  1377. //
  1378. // %iv = phi [ (preheader, ...), (body, %iv.next) ]
  1379. // f(%iv)
  1380. // %iv.1 = add %iv, 1 <-- a root increment
  1381. // f(%iv.1)
  1382. // %iv.2 = add %iv, 2 <-- a root increment
  1383. // f(%iv.2)
  1384. // %iv.scale_m_1 = add %iv, scale-1 <-- a root increment
  1385. // f(%iv.scale_m_1)
  1386. // ...
  1387. // %iv.next = add %iv, scale
  1388. // %cmp = icmp(%iv, ...)
  1389. // br %cmp, header, exit
  1390. //
  1391. // Notably, we do not require that f(%iv), f(%iv.1), etc. be isolated groups of
  1392. // instructions. In other words, the instructions in f(%iv), f(%iv.1), etc. can
  1393. // be intermixed with eachother. The restriction imposed by this algorithm is
  1394. // that the relative order of the isomorphic instructions in f(%iv), f(%iv.1),
  1395. // etc. be the same.
  1396. //
  1397. // First, we collect the use set of %iv, excluding the other increment roots.
  1398. // This gives us f(%iv). Then we iterate over the loop instructions (scale-1)
  1399. // times, having collected the use set of f(%iv.(i+1)), during which we:
  1400. // - Ensure that the next unmatched instruction in f(%iv) is isomorphic to
  1401. // the next unmatched instruction in f(%iv.(i+1)).
  1402. // - Ensure that both matched instructions don't have any external users
  1403. // (with the exception of last-in-chain reduction instructions).
  1404. // - Track the (aliasing) write set, and other side effects, of all
  1405. // instructions that belong to future iterations that come before the matched
  1406. // instructions. If the matched instructions read from that write set, then
  1407. // f(%iv) or f(%iv.(i+1)) has some dependency on instructions in
  1408. // f(%iv.(j+1)) for some j > i, and we cannot reroll the loop. Similarly,
  1409. // if any of these future instructions had side effects (could not be
  1410. // speculatively executed), and so do the matched instructions, when we
  1411. // cannot reorder those side-effect-producing instructions, and rerolling
  1412. // fails.
  1413. //
  1414. // Finally, we make sure that all loop instructions are either loop increment
  1415. // roots, belong to simple latch code, parts of validated reductions, part of
  1416. // f(%iv) or part of some f(%iv.i). If all of that is true (and all reductions
  1417. // have been validated), then we reroll the loop.
  1418. bool LoopReroll::reroll(Instruction *IV, Loop *L, BasicBlock *Header,
  1419. const SCEV *BackedgeTakenCount,
  1420. ReductionTracker &Reductions) {
  1421. DAGRootTracker DAGRoots(this, L, IV, SE, AA, TLI, DT, LI, PreserveLCSSA,
  1422. IVToIncMap, LoopControlIVs);
  1423. if (!DAGRoots.findRoots())
  1424. return false;
  1425. LLVM_DEBUG(dbgs() << "LRR: Found all root induction increments for: " << *IV
  1426. << "\n");
  1427. if (!DAGRoots.validate(Reductions))
  1428. return false;
  1429. if (!Reductions.validateSelected())
  1430. return false;
  1431. // At this point, we've validated the rerolling, and we're committed to
  1432. // making changes!
  1433. Reductions.replaceSelected();
  1434. DAGRoots.replace(BackedgeTakenCount);
  1435. ++NumRerolledLoops;
  1436. return true;
  1437. }
  1438. bool LoopReroll::runOnLoop(Loop *L) {
  1439. BasicBlock *Header = L->getHeader();
  1440. LLVM_DEBUG(dbgs() << "LRR: F[" << Header->getParent()->getName() << "] Loop %"
  1441. << Header->getName() << " (" << L->getNumBlocks()
  1442. << " block(s))\n");
  1443. // For now, we'll handle only single BB loops.
  1444. if (L->getNumBlocks() > 1)
  1445. return false;
  1446. if (!SE->hasLoopInvariantBackedgeTakenCount(L))
  1447. return false;
  1448. const SCEV *BackedgeTakenCount = SE->getBackedgeTakenCount(L);
  1449. LLVM_DEBUG(dbgs() << "\n Before Reroll:\n" << *(L->getHeader()) << "\n");
  1450. LLVM_DEBUG(dbgs() << "LRR: backedge-taken count = " << *BackedgeTakenCount
  1451. << "\n");
  1452. // First, we need to find the induction variable with respect to which we can
  1453. // reroll (there may be several possible options).
  1454. SmallInstructionVector PossibleIVs;
  1455. IVToIncMap.clear();
  1456. LoopControlIVs.clear();
  1457. collectPossibleIVs(L, PossibleIVs);
  1458. if (PossibleIVs.empty()) {
  1459. LLVM_DEBUG(dbgs() << "LRR: No possible IVs found\n");
  1460. return false;
  1461. }
  1462. ReductionTracker Reductions;
  1463. collectPossibleReductions(L, Reductions);
  1464. bool Changed = false;
  1465. // For each possible IV, collect the associated possible set of 'root' nodes
  1466. // (i+1, i+2, etc.).
  1467. for (Instruction *PossibleIV : PossibleIVs)
  1468. if (reroll(PossibleIV, L, Header, BackedgeTakenCount, Reductions)) {
  1469. Changed = true;
  1470. break;
  1471. }
  1472. LLVM_DEBUG(dbgs() << "\n After Reroll:\n" << *(L->getHeader()) << "\n");
  1473. // Trip count of L has changed so SE must be re-evaluated.
  1474. if (Changed)
  1475. SE->forgetLoop(L);
  1476. return Changed;
  1477. }
  1478. bool LoopRerollLegacyPass::runOnLoop(Loop *L, LPPassManager &LPM) {
  1479. if (skipLoop(L))
  1480. return false;
  1481. auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
  1482. auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
  1483. auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
  1484. auto *TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(
  1485. *L->getHeader()->getParent());
  1486. auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
  1487. bool PreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
  1488. return LoopReroll(AA, LI, SE, TLI, DT, PreserveLCSSA).runOnLoop(L);
  1489. }
  1490. PreservedAnalyses LoopRerollPass::run(Loop &L, LoopAnalysisManager &AM,
  1491. LoopStandardAnalysisResults &AR,
  1492. LPMUpdater &U) {
  1493. return LoopReroll(&AR.AA, &AR.LI, &AR.SE, &AR.TLI, &AR.DT, true).runOnLoop(&L)
  1494. ? getLoopPassPreservedAnalyses()
  1495. : PreservedAnalyses::all();
  1496. }