LoopRerollPass.cpp 60 KB

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