DependenceAnalysis.h 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===-- llvm/Analysis/DependenceAnalysis.h -------------------- -*- C++ -*-===//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. //
  14. // DependenceAnalysis is an LLVM pass that analyses dependences between memory
  15. // accesses. Currently, it is an implementation of the approach described in
  16. //
  17. // Practical Dependence Testing
  18. // Goff, Kennedy, Tseng
  19. // PLDI 1991
  20. //
  21. // There's a single entry point that analyzes the dependence between a pair
  22. // of memory references in a function, returning either NULL, for no dependence,
  23. // or a more-or-less detailed description of the dependence between them.
  24. //
  25. // This pass exists to support the DependenceGraph pass. There are two separate
  26. // passes because there's a useful separation of concerns. A dependence exists
  27. // if two conditions are met:
  28. //
  29. // 1) Two instructions reference the same memory location, and
  30. // 2) There is a flow of control leading from one instruction to the other.
  31. //
  32. // DependenceAnalysis attacks the first condition; DependenceGraph will attack
  33. // the second (it's not yet ready).
  34. //
  35. // Please note that this is work in progress and the interface is subject to
  36. // change.
  37. //
  38. // Plausible changes:
  39. // Return a set of more precise dependences instead of just one dependence
  40. // summarizing all.
  41. //
  42. //===----------------------------------------------------------------------===//
  43. #ifndef LLVM_ANALYSIS_DEPENDENCEANALYSIS_H
  44. #define LLVM_ANALYSIS_DEPENDENCEANALYSIS_H
  45. #include "llvm/ADT/SmallBitVector.h"
  46. #include "llvm/IR/Instructions.h"
  47. #include "llvm/IR/PassManager.h"
  48. #include "llvm/Pass.h"
  49. namespace llvm {
  50. class AAResults;
  51. template <typename T> class ArrayRef;
  52. class Loop;
  53. class LoopInfo;
  54. class ScalarEvolution;
  55. class SCEV;
  56. class SCEVConstant;
  57. class raw_ostream;
  58. /// Dependence - This class represents a dependence between two memory
  59. /// memory references in a function. It contains minimal information and
  60. /// is used in the very common situation where the compiler is unable to
  61. /// determine anything beyond the existence of a dependence; that is, it
  62. /// represents a confused dependence (see also FullDependence). In most
  63. /// cases (for output, flow, and anti dependences), the dependence implies
  64. /// an ordering, where the source must precede the destination; in contrast,
  65. /// input dependences are unordered.
  66. ///
  67. /// When a dependence graph is built, each Dependence will be a member of
  68. /// the set of predecessor edges for its destination instruction and a set
  69. /// if successor edges for its source instruction. These sets are represented
  70. /// as singly-linked lists, with the "next" fields stored in the dependence
  71. /// itelf.
  72. class Dependence {
  73. protected:
  74. Dependence(Dependence &&) = default;
  75. Dependence &operator=(Dependence &&) = default;
  76. public:
  77. Dependence(Instruction *Source, Instruction *Destination)
  78. : Src(Source), Dst(Destination) {}
  79. virtual ~Dependence() = default;
  80. /// Dependence::DVEntry - Each level in the distance/direction vector
  81. /// has a direction (or perhaps a union of several directions), and
  82. /// perhaps a distance.
  83. struct DVEntry {
  84. enum : unsigned char {
  85. NONE = 0,
  86. LT = 1,
  87. EQ = 2,
  88. LE = 3,
  89. GT = 4,
  90. NE = 5,
  91. GE = 6,
  92. ALL = 7
  93. };
  94. unsigned char Direction : 3; // Init to ALL, then refine.
  95. bool Scalar : 1; // Init to true.
  96. bool PeelFirst : 1; // Peeling the first iteration will break dependence.
  97. bool PeelLast : 1; // Peeling the last iteration will break the dependence.
  98. bool Splitable : 1; // Splitting the loop will break dependence.
  99. const SCEV *Distance = nullptr; // NULL implies no distance available.
  100. DVEntry()
  101. : Direction(ALL), Scalar(true), PeelFirst(false), PeelLast(false),
  102. Splitable(false) {}
  103. };
  104. /// getSrc - Returns the source instruction for this dependence.
  105. ///
  106. Instruction *getSrc() const { return Src; }
  107. /// getDst - Returns the destination instruction for this dependence.
  108. ///
  109. Instruction *getDst() const { return Dst; }
  110. /// isInput - Returns true if this is an input dependence.
  111. ///
  112. bool isInput() const;
  113. /// isOutput - Returns true if this is an output dependence.
  114. ///
  115. bool isOutput() const;
  116. /// isFlow - Returns true if this is a flow (aka true) dependence.
  117. ///
  118. bool isFlow() const;
  119. /// isAnti - Returns true if this is an anti dependence.
  120. ///
  121. bool isAnti() const;
  122. /// isOrdered - Returns true if dependence is Output, Flow, or Anti
  123. ///
  124. bool isOrdered() const { return isOutput() || isFlow() || isAnti(); }
  125. /// isUnordered - Returns true if dependence is Input
  126. ///
  127. bool isUnordered() const { return isInput(); }
  128. /// isLoopIndependent - Returns true if this is a loop-independent
  129. /// dependence.
  130. virtual bool isLoopIndependent() const { return true; }
  131. /// isConfused - Returns true if this dependence is confused
  132. /// (the compiler understands nothing and makes worst-case
  133. /// assumptions).
  134. virtual bool isConfused() const { return true; }
  135. /// isConsistent - Returns true if this dependence is consistent
  136. /// (occurs every time the source and destination are executed).
  137. virtual bool isConsistent() const { return false; }
  138. /// getLevels - Returns the number of common loops surrounding the
  139. /// source and destination of the dependence.
  140. virtual unsigned getLevels() const { return 0; }
  141. /// getDirection - Returns the direction associated with a particular
  142. /// level.
  143. virtual unsigned getDirection(unsigned Level) const { return DVEntry::ALL; }
  144. /// getDistance - Returns the distance (or NULL) associated with a
  145. /// particular level.
  146. virtual const SCEV *getDistance(unsigned Level) const { return nullptr; }
  147. /// Check if the direction vector is negative. A negative direction
  148. /// vector means Src and Dst are reversed in the actual program.
  149. virtual bool isDirectionNegative() const { return false; }
  150. /// If the direction vector is negative, normalize the direction
  151. /// vector to make it non-negative. Normalization is done by reversing
  152. /// Src and Dst, plus reversing the dependence directions and distances
  153. /// in the vector.
  154. virtual bool normalize(ScalarEvolution *SE) { return false; }
  155. /// isPeelFirst - Returns true if peeling the first iteration from
  156. /// this loop will break this dependence.
  157. virtual bool isPeelFirst(unsigned Level) const { return false; }
  158. /// isPeelLast - Returns true if peeling the last iteration from
  159. /// this loop will break this dependence.
  160. virtual bool isPeelLast(unsigned Level) const { return false; }
  161. /// isSplitable - Returns true if splitting this loop will break
  162. /// the dependence.
  163. virtual bool isSplitable(unsigned Level) const { return false; }
  164. /// isScalar - Returns true if a particular level is scalar; that is,
  165. /// if no subscript in the source or destination mention the induction
  166. /// variable associated with the loop at this level.
  167. virtual bool isScalar(unsigned Level) const;
  168. /// getNextPredecessor - Returns the value of the NextPredecessor
  169. /// field.
  170. const Dependence *getNextPredecessor() const { return NextPredecessor; }
  171. /// getNextSuccessor - Returns the value of the NextSuccessor
  172. /// field.
  173. const Dependence *getNextSuccessor() const { return NextSuccessor; }
  174. /// setNextPredecessor - Sets the value of the NextPredecessor
  175. /// field.
  176. void setNextPredecessor(const Dependence *pred) { NextPredecessor = pred; }
  177. /// setNextSuccessor - Sets the value of the NextSuccessor
  178. /// field.
  179. void setNextSuccessor(const Dependence *succ) { NextSuccessor = succ; }
  180. /// dump - For debugging purposes, dumps a dependence to OS.
  181. ///
  182. void dump(raw_ostream &OS) const;
  183. protected:
  184. Instruction *Src, *Dst;
  185. private:
  186. const Dependence *NextPredecessor = nullptr, *NextSuccessor = nullptr;
  187. friend class DependenceInfo;
  188. };
  189. /// FullDependence - This class represents a dependence between two memory
  190. /// references in a function. It contains detailed information about the
  191. /// dependence (direction vectors, etc.) and is used when the compiler is
  192. /// able to accurately analyze the interaction of the references; that is,
  193. /// it is not a confused dependence (see Dependence). In most cases
  194. /// (for output, flow, and anti dependences), the dependence implies an
  195. /// ordering, where the source must precede the destination; in contrast,
  196. /// input dependences are unordered.
  197. class FullDependence final : public Dependence {
  198. public:
  199. FullDependence(Instruction *Src, Instruction *Dst, bool LoopIndependent,
  200. unsigned Levels);
  201. /// isLoopIndependent - Returns true if this is a loop-independent
  202. /// dependence.
  203. bool isLoopIndependent() const override { return LoopIndependent; }
  204. /// isConfused - Returns true if this dependence is confused
  205. /// (the compiler understands nothing and makes worst-case
  206. /// assumptions).
  207. bool isConfused() const override { return false; }
  208. /// isConsistent - Returns true if this dependence is consistent
  209. /// (occurs every time the source and destination are executed).
  210. bool isConsistent() const override { return Consistent; }
  211. /// getLevels - Returns the number of common loops surrounding the
  212. /// source and destination of the dependence.
  213. unsigned getLevels() const override { return Levels; }
  214. /// getDirection - Returns the direction associated with a particular
  215. /// level.
  216. unsigned getDirection(unsigned Level) const override;
  217. /// getDistance - Returns the distance (or NULL) associated with a
  218. /// particular level.
  219. const SCEV *getDistance(unsigned Level) const override;
  220. /// Check if the direction vector is negative. A negative direction
  221. /// vector means Src and Dst are reversed in the actual program.
  222. bool isDirectionNegative() const override;
  223. /// If the direction vector is negative, normalize the direction
  224. /// vector to make it non-negative. Normalization is done by reversing
  225. /// Src and Dst, plus reversing the dependence directions and distances
  226. /// in the vector.
  227. bool normalize(ScalarEvolution *SE) override;
  228. /// isPeelFirst - Returns true if peeling the first iteration from
  229. /// this loop will break this dependence.
  230. bool isPeelFirst(unsigned Level) const override;
  231. /// isPeelLast - Returns true if peeling the last iteration from
  232. /// this loop will break this dependence.
  233. bool isPeelLast(unsigned Level) const override;
  234. /// isSplitable - Returns true if splitting the loop will break
  235. /// the dependence.
  236. bool isSplitable(unsigned Level) const override;
  237. /// isScalar - Returns true if a particular level is scalar; that is,
  238. /// if no subscript in the source or destination mention the induction
  239. /// variable associated with the loop at this level.
  240. bool isScalar(unsigned Level) const override;
  241. private:
  242. unsigned short Levels;
  243. bool LoopIndependent;
  244. bool Consistent; // Init to true, then refine.
  245. std::unique_ptr<DVEntry[]> DV;
  246. friend class DependenceInfo;
  247. };
  248. /// DependenceInfo - This class is the main dependence-analysis driver.
  249. ///
  250. class DependenceInfo {
  251. public:
  252. DependenceInfo(Function *F, AAResults *AA, ScalarEvolution *SE,
  253. LoopInfo *LI)
  254. : AA(AA), SE(SE), LI(LI), F(F) {}
  255. /// Handle transitive invalidation when the cached analysis results go away.
  256. bool invalidate(Function &F, const PreservedAnalyses &PA,
  257. FunctionAnalysisManager::Invalidator &Inv);
  258. /// depends - Tests for a dependence between the Src and Dst instructions.
  259. /// Returns NULL if no dependence; otherwise, returns a Dependence (or a
  260. /// FullDependence) with as much information as can be gleaned.
  261. /// The flag PossiblyLoopIndependent should be set by the caller
  262. /// if it appears that control flow can reach from Src to Dst
  263. /// without traversing a loop back edge.
  264. std::unique_ptr<Dependence> depends(Instruction *Src,
  265. Instruction *Dst,
  266. bool PossiblyLoopIndependent);
  267. /// getSplitIteration - Give a dependence that's splittable at some
  268. /// particular level, return the iteration that should be used to split
  269. /// the loop.
  270. ///
  271. /// Generally, the dependence analyzer will be used to build
  272. /// a dependence graph for a function (basically a map from instructions
  273. /// to dependences). Looking for cycles in the graph shows us loops
  274. /// that cannot be trivially vectorized/parallelized.
  275. ///
  276. /// We can try to improve the situation by examining all the dependences
  277. /// that make up the cycle, looking for ones we can break.
  278. /// Sometimes, peeling the first or last iteration of a loop will break
  279. /// dependences, and there are flags for those possibilities.
  280. /// Sometimes, splitting a loop at some other iteration will do the trick,
  281. /// and we've got a flag for that case. Rather than waste the space to
  282. /// record the exact iteration (since we rarely know), we provide
  283. /// a method that calculates the iteration. It's a drag that it must work
  284. /// from scratch, but wonderful in that it's possible.
  285. ///
  286. /// Here's an example:
  287. ///
  288. /// for (i = 0; i < 10; i++)
  289. /// A[i] = ...
  290. /// ... = A[11 - i]
  291. ///
  292. /// There's a loop-carried flow dependence from the store to the load,
  293. /// found by the weak-crossing SIV test. The dependence will have a flag,
  294. /// indicating that the dependence can be broken by splitting the loop.
  295. /// Calling getSplitIteration will return 5.
  296. /// Splitting the loop breaks the dependence, like so:
  297. ///
  298. /// for (i = 0; i <= 5; i++)
  299. /// A[i] = ...
  300. /// ... = A[11 - i]
  301. /// for (i = 6; i < 10; i++)
  302. /// A[i] = ...
  303. /// ... = A[11 - i]
  304. ///
  305. /// breaks the dependence and allows us to vectorize/parallelize
  306. /// both loops.
  307. const SCEV *getSplitIteration(const Dependence &Dep, unsigned Level);
  308. Function *getFunction() const { return F; }
  309. private:
  310. AAResults *AA;
  311. ScalarEvolution *SE;
  312. LoopInfo *LI;
  313. Function *F;
  314. /// Subscript - This private struct represents a pair of subscripts from
  315. /// a pair of potentially multi-dimensional array references. We use a
  316. /// vector of them to guide subscript partitioning.
  317. struct Subscript {
  318. const SCEV *Src;
  319. const SCEV *Dst;
  320. enum ClassificationKind { ZIV, SIV, RDIV, MIV, NonLinear } Classification;
  321. SmallBitVector Loops;
  322. SmallBitVector GroupLoops;
  323. SmallBitVector Group;
  324. };
  325. struct CoefficientInfo {
  326. const SCEV *Coeff;
  327. const SCEV *PosPart;
  328. const SCEV *NegPart;
  329. const SCEV *Iterations;
  330. };
  331. struct BoundInfo {
  332. const SCEV *Iterations;
  333. const SCEV *Upper[8];
  334. const SCEV *Lower[8];
  335. unsigned char Direction;
  336. unsigned char DirSet;
  337. };
  338. /// Constraint - This private class represents a constraint, as defined
  339. /// in the paper
  340. ///
  341. /// Practical Dependence Testing
  342. /// Goff, Kennedy, Tseng
  343. /// PLDI 1991
  344. ///
  345. /// There are 5 kinds of constraint, in a hierarchy.
  346. /// 1) Any - indicates no constraint, any dependence is possible.
  347. /// 2) Line - A line ax + by = c, where a, b, and c are parameters,
  348. /// representing the dependence equation.
  349. /// 3) Distance - The value d of the dependence distance;
  350. /// 4) Point - A point <x, y> representing the dependence from
  351. /// iteration x to iteration y.
  352. /// 5) Empty - No dependence is possible.
  353. class Constraint {
  354. private:
  355. enum ConstraintKind { Empty, Point, Distance, Line, Any } Kind;
  356. ScalarEvolution *SE;
  357. const SCEV *A;
  358. const SCEV *B;
  359. const SCEV *C;
  360. const Loop *AssociatedLoop;
  361. public:
  362. /// isEmpty - Return true if the constraint is of kind Empty.
  363. bool isEmpty() const { return Kind == Empty; }
  364. /// isPoint - Return true if the constraint is of kind Point.
  365. bool isPoint() const { return Kind == Point; }
  366. /// isDistance - Return true if the constraint is of kind Distance.
  367. bool isDistance() const { return Kind == Distance; }
  368. /// isLine - Return true if the constraint is of kind Line.
  369. /// Since Distance's can also be represented as Lines, we also return
  370. /// true if the constraint is of kind Distance.
  371. bool isLine() const { return Kind == Line || Kind == Distance; }
  372. /// isAny - Return true if the constraint is of kind Any;
  373. bool isAny() const { return Kind == Any; }
  374. /// getX - If constraint is a point <X, Y>, returns X.
  375. /// Otherwise assert.
  376. const SCEV *getX() const;
  377. /// getY - If constraint is a point <X, Y>, returns Y.
  378. /// Otherwise assert.
  379. const SCEV *getY() const;
  380. /// getA - If constraint is a line AX + BY = C, returns A.
  381. /// Otherwise assert.
  382. const SCEV *getA() const;
  383. /// getB - If constraint is a line AX + BY = C, returns B.
  384. /// Otherwise assert.
  385. const SCEV *getB() const;
  386. /// getC - If constraint is a line AX + BY = C, returns C.
  387. /// Otherwise assert.
  388. const SCEV *getC() const;
  389. /// getD - If constraint is a distance, returns D.
  390. /// Otherwise assert.
  391. const SCEV *getD() const;
  392. /// getAssociatedLoop - Returns the loop associated with this constraint.
  393. const Loop *getAssociatedLoop() const;
  394. /// setPoint - Change a constraint to Point.
  395. void setPoint(const SCEV *X, const SCEV *Y, const Loop *CurrentLoop);
  396. /// setLine - Change a constraint to Line.
  397. void setLine(const SCEV *A, const SCEV *B,
  398. const SCEV *C, const Loop *CurrentLoop);
  399. /// setDistance - Change a constraint to Distance.
  400. void setDistance(const SCEV *D, const Loop *CurrentLoop);
  401. /// setEmpty - Change a constraint to Empty.
  402. void setEmpty();
  403. /// setAny - Change a constraint to Any.
  404. void setAny(ScalarEvolution *SE);
  405. /// dump - For debugging purposes. Dumps the constraint
  406. /// out to OS.
  407. void dump(raw_ostream &OS) const;
  408. };
  409. /// establishNestingLevels - Examines the loop nesting of the Src and Dst
  410. /// instructions and establishes their shared loops. Sets the variables
  411. /// CommonLevels, SrcLevels, and MaxLevels.
  412. /// The source and destination instructions needn't be contained in the same
  413. /// loop. The routine establishNestingLevels finds the level of most deeply
  414. /// nested loop that contains them both, CommonLevels. An instruction that's
  415. /// not contained in a loop is at level = 0. MaxLevels is equal to the level
  416. /// of the source plus the level of the destination, minus CommonLevels.
  417. /// This lets us allocate vectors MaxLevels in length, with room for every
  418. /// distinct loop referenced in both the source and destination subscripts.
  419. /// The variable SrcLevels is the nesting depth of the source instruction.
  420. /// It's used to help calculate distinct loops referenced by the destination.
  421. /// Here's the map from loops to levels:
  422. /// 0 - unused
  423. /// 1 - outermost common loop
  424. /// ... - other common loops
  425. /// CommonLevels - innermost common loop
  426. /// ... - loops containing Src but not Dst
  427. /// SrcLevels - innermost loop containing Src but not Dst
  428. /// ... - loops containing Dst but not Src
  429. /// MaxLevels - innermost loop containing Dst but not Src
  430. /// Consider the follow code fragment:
  431. /// for (a = ...) {
  432. /// for (b = ...) {
  433. /// for (c = ...) {
  434. /// for (d = ...) {
  435. /// A[] = ...;
  436. /// }
  437. /// }
  438. /// for (e = ...) {
  439. /// for (f = ...) {
  440. /// for (g = ...) {
  441. /// ... = A[];
  442. /// }
  443. /// }
  444. /// }
  445. /// }
  446. /// }
  447. /// If we're looking at the possibility of a dependence between the store
  448. /// to A (the Src) and the load from A (the Dst), we'll note that they
  449. /// have 2 loops in common, so CommonLevels will equal 2 and the direction
  450. /// vector for Result will have 2 entries. SrcLevels = 4 and MaxLevels = 7.
  451. /// A map from loop names to level indices would look like
  452. /// a - 1
  453. /// b - 2 = CommonLevels
  454. /// c - 3
  455. /// d - 4 = SrcLevels
  456. /// e - 5
  457. /// f - 6
  458. /// g - 7 = MaxLevels
  459. void establishNestingLevels(const Instruction *Src,
  460. const Instruction *Dst);
  461. unsigned CommonLevels, SrcLevels, MaxLevels;
  462. /// mapSrcLoop - Given one of the loops containing the source, return
  463. /// its level index in our numbering scheme.
  464. unsigned mapSrcLoop(const Loop *SrcLoop) const;
  465. /// mapDstLoop - Given one of the loops containing the destination,
  466. /// return its level index in our numbering scheme.
  467. unsigned mapDstLoop(const Loop *DstLoop) const;
  468. /// isLoopInvariant - Returns true if Expression is loop invariant
  469. /// in LoopNest.
  470. bool isLoopInvariant(const SCEV *Expression, const Loop *LoopNest) const;
  471. /// Makes sure all subscript pairs share the same integer type by
  472. /// sign-extending as necessary.
  473. /// Sign-extending a subscript is safe because getelementptr assumes the
  474. /// array subscripts are signed.
  475. void unifySubscriptType(ArrayRef<Subscript *> Pairs);
  476. /// removeMatchingExtensions - Examines a subscript pair.
  477. /// If the source and destination are identically sign (or zero)
  478. /// extended, it strips off the extension in an effort to
  479. /// simplify the actual analysis.
  480. void removeMatchingExtensions(Subscript *Pair);
  481. /// collectCommonLoops - Finds the set of loops from the LoopNest that
  482. /// have a level <= CommonLevels and are referred to by the SCEV Expression.
  483. void collectCommonLoops(const SCEV *Expression,
  484. const Loop *LoopNest,
  485. SmallBitVector &Loops) const;
  486. /// checkSrcSubscript - Examines the SCEV Src, returning true iff it's
  487. /// linear. Collect the set of loops mentioned by Src.
  488. bool checkSrcSubscript(const SCEV *Src,
  489. const Loop *LoopNest,
  490. SmallBitVector &Loops);
  491. /// checkDstSubscript - Examines the SCEV Dst, returning true iff it's
  492. /// linear. Collect the set of loops mentioned by Dst.
  493. bool checkDstSubscript(const SCEV *Dst,
  494. const Loop *LoopNest,
  495. SmallBitVector &Loops);
  496. /// isKnownPredicate - Compare X and Y using the predicate Pred.
  497. /// Basically a wrapper for SCEV::isKnownPredicate,
  498. /// but tries harder, especially in the presence of sign and zero
  499. /// extensions and symbolics.
  500. bool isKnownPredicate(ICmpInst::Predicate Pred,
  501. const SCEV *X,
  502. const SCEV *Y) const;
  503. /// isKnownLessThan - Compare to see if S is less than Size
  504. /// Another wrapper for isKnownNegative(S - max(Size, 1)) with some extra
  505. /// checking if S is an AddRec and we can prove lessthan using the loop
  506. /// bounds.
  507. bool isKnownLessThan(const SCEV *S, const SCEV *Size) const;
  508. /// isKnownNonNegative - Compare to see if S is known not to be negative
  509. /// Uses the fact that S comes from Ptr, which may be an inbound GEP,
  510. /// Proving there is no wrapping going on.
  511. bool isKnownNonNegative(const SCEV *S, const Value *Ptr) const;
  512. /// collectUpperBound - All subscripts are the same type (on my machine,
  513. /// an i64). The loop bound may be a smaller type. collectUpperBound
  514. /// find the bound, if available, and zero extends it to the Type T.
  515. /// (I zero extend since the bound should always be >= 0.)
  516. /// If no upper bound is available, return NULL.
  517. const SCEV *collectUpperBound(const Loop *l, Type *T) const;
  518. /// collectConstantUpperBound - Calls collectUpperBound(), then
  519. /// attempts to cast it to SCEVConstant. If the cast fails,
  520. /// returns NULL.
  521. const SCEVConstant *collectConstantUpperBound(const Loop *l, Type *T) const;
  522. /// classifyPair - Examines the subscript pair (the Src and Dst SCEVs)
  523. /// and classifies it as either ZIV, SIV, RDIV, MIV, or Nonlinear.
  524. /// Collects the associated loops in a set.
  525. Subscript::ClassificationKind classifyPair(const SCEV *Src,
  526. const Loop *SrcLoopNest,
  527. const SCEV *Dst,
  528. const Loop *DstLoopNest,
  529. SmallBitVector &Loops);
  530. /// testZIV - Tests the ZIV subscript pair (Src and Dst) for dependence.
  531. /// Returns true if any possible dependence is disproved.
  532. /// If there might be a dependence, returns false.
  533. /// If the dependence isn't proven to exist,
  534. /// marks the Result as inconsistent.
  535. bool testZIV(const SCEV *Src,
  536. const SCEV *Dst,
  537. FullDependence &Result) const;
  538. /// testSIV - Tests the SIV subscript pair (Src and Dst) for dependence.
  539. /// Things of the form [c1 + a1*i] and [c2 + a2*j], where
  540. /// i and j are induction variables, c1 and c2 are loop invariant,
  541. /// and a1 and a2 are constant.
  542. /// Returns true if any possible dependence is disproved.
  543. /// If there might be a dependence, returns false.
  544. /// Sets appropriate direction vector entry and, when possible,
  545. /// the distance vector entry.
  546. /// If the dependence isn't proven to exist,
  547. /// marks the Result as inconsistent.
  548. bool testSIV(const SCEV *Src,
  549. const SCEV *Dst,
  550. unsigned &Level,
  551. FullDependence &Result,
  552. Constraint &NewConstraint,
  553. const SCEV *&SplitIter) const;
  554. /// testRDIV - Tests the RDIV subscript pair (Src and Dst) for dependence.
  555. /// Things of the form [c1 + a1*i] and [c2 + a2*j]
  556. /// where i and j are induction variables, c1 and c2 are loop invariant,
  557. /// and a1 and a2 are constant.
  558. /// With minor algebra, this test can also be used for things like
  559. /// [c1 + a1*i + a2*j][c2].
  560. /// Returns true if any possible dependence is disproved.
  561. /// If there might be a dependence, returns false.
  562. /// Marks the Result as inconsistent.
  563. bool testRDIV(const SCEV *Src,
  564. const SCEV *Dst,
  565. FullDependence &Result) const;
  566. /// testMIV - Tests the MIV subscript pair (Src and Dst) for dependence.
  567. /// Returns true if dependence disproved.
  568. /// Can sometimes refine direction vectors.
  569. bool testMIV(const SCEV *Src,
  570. const SCEV *Dst,
  571. const SmallBitVector &Loops,
  572. FullDependence &Result) const;
  573. /// strongSIVtest - Tests the strong SIV subscript pair (Src and Dst)
  574. /// for dependence.
  575. /// Things of the form [c1 + a*i] and [c2 + a*i],
  576. /// where i is an induction variable, c1 and c2 are loop invariant,
  577. /// and a is a constant
  578. /// Returns true if any possible dependence is disproved.
  579. /// If there might be a dependence, returns false.
  580. /// Sets appropriate direction and distance.
  581. bool strongSIVtest(const SCEV *Coeff,
  582. const SCEV *SrcConst,
  583. const SCEV *DstConst,
  584. const Loop *CurrentLoop,
  585. unsigned Level,
  586. FullDependence &Result,
  587. Constraint &NewConstraint) const;
  588. /// weakCrossingSIVtest - Tests the weak-crossing SIV subscript pair
  589. /// (Src and Dst) for dependence.
  590. /// Things of the form [c1 + a*i] and [c2 - a*i],
  591. /// where i is an induction variable, c1 and c2 are loop invariant,
  592. /// and a is a constant.
  593. /// Returns true if any possible dependence is disproved.
  594. /// If there might be a dependence, returns false.
  595. /// Sets appropriate direction entry.
  596. /// Set consistent to false.
  597. /// Marks the dependence as splitable.
  598. bool weakCrossingSIVtest(const SCEV *SrcCoeff,
  599. const SCEV *SrcConst,
  600. const SCEV *DstConst,
  601. const Loop *CurrentLoop,
  602. unsigned Level,
  603. FullDependence &Result,
  604. Constraint &NewConstraint,
  605. const SCEV *&SplitIter) const;
  606. /// ExactSIVtest - Tests the SIV subscript pair
  607. /// (Src and Dst) for dependence.
  608. /// Things of the form [c1 + a1*i] and [c2 + a2*i],
  609. /// where i is an induction variable, c1 and c2 are loop invariant,
  610. /// and a1 and a2 are constant.
  611. /// Returns true if any possible dependence is disproved.
  612. /// If there might be a dependence, returns false.
  613. /// Sets appropriate direction entry.
  614. /// Set consistent to false.
  615. bool exactSIVtest(const SCEV *SrcCoeff,
  616. const SCEV *DstCoeff,
  617. const SCEV *SrcConst,
  618. const SCEV *DstConst,
  619. const Loop *CurrentLoop,
  620. unsigned Level,
  621. FullDependence &Result,
  622. Constraint &NewConstraint) const;
  623. /// weakZeroSrcSIVtest - Tests the weak-zero SIV subscript pair
  624. /// (Src and Dst) for dependence.
  625. /// Things of the form [c1] and [c2 + a*i],
  626. /// where i is an induction variable, c1 and c2 are loop invariant,
  627. /// and a is a constant. See also weakZeroDstSIVtest.
  628. /// Returns true if any possible dependence is disproved.
  629. /// If there might be a dependence, returns false.
  630. /// Sets appropriate direction entry.
  631. /// Set consistent to false.
  632. /// If loop peeling will break the dependence, mark appropriately.
  633. bool weakZeroSrcSIVtest(const SCEV *DstCoeff,
  634. const SCEV *SrcConst,
  635. const SCEV *DstConst,
  636. const Loop *CurrentLoop,
  637. unsigned Level,
  638. FullDependence &Result,
  639. Constraint &NewConstraint) const;
  640. /// weakZeroDstSIVtest - Tests the weak-zero SIV subscript pair
  641. /// (Src and Dst) for dependence.
  642. /// Things of the form [c1 + a*i] and [c2],
  643. /// where i is an induction variable, c1 and c2 are loop invariant,
  644. /// and a is a constant. See also weakZeroSrcSIVtest.
  645. /// Returns true if any possible dependence is disproved.
  646. /// If there might be a dependence, returns false.
  647. /// Sets appropriate direction entry.
  648. /// Set consistent to false.
  649. /// If loop peeling will break the dependence, mark appropriately.
  650. bool weakZeroDstSIVtest(const SCEV *SrcCoeff,
  651. const SCEV *SrcConst,
  652. const SCEV *DstConst,
  653. const Loop *CurrentLoop,
  654. unsigned Level,
  655. FullDependence &Result,
  656. Constraint &NewConstraint) const;
  657. /// exactRDIVtest - Tests the RDIV subscript pair for dependence.
  658. /// Things of the form [c1 + a*i] and [c2 + b*j],
  659. /// where i and j are induction variable, c1 and c2 are loop invariant,
  660. /// and a and b are constants.
  661. /// Returns true if any possible dependence is disproved.
  662. /// Marks the result as inconsistent.
  663. /// Works in some cases that symbolicRDIVtest doesn't,
  664. /// and vice versa.
  665. bool exactRDIVtest(const SCEV *SrcCoeff,
  666. const SCEV *DstCoeff,
  667. const SCEV *SrcConst,
  668. const SCEV *DstConst,
  669. const Loop *SrcLoop,
  670. const Loop *DstLoop,
  671. FullDependence &Result) const;
  672. /// symbolicRDIVtest - Tests the RDIV subscript pair for dependence.
  673. /// Things of the form [c1 + a*i] and [c2 + b*j],
  674. /// where i and j are induction variable, c1 and c2 are loop invariant,
  675. /// and a and b are constants.
  676. /// Returns true if any possible dependence is disproved.
  677. /// Marks the result as inconsistent.
  678. /// Works in some cases that exactRDIVtest doesn't,
  679. /// and vice versa. Can also be used as a backup for
  680. /// ordinary SIV tests.
  681. bool symbolicRDIVtest(const SCEV *SrcCoeff,
  682. const SCEV *DstCoeff,
  683. const SCEV *SrcConst,
  684. const SCEV *DstConst,
  685. const Loop *SrcLoop,
  686. const Loop *DstLoop) const;
  687. /// gcdMIVtest - Tests an MIV subscript pair for dependence.
  688. /// Returns true if any possible dependence is disproved.
  689. /// Marks the result as inconsistent.
  690. /// Can sometimes disprove the equal direction for 1 or more loops.
  691. // Can handle some symbolics that even the SIV tests don't get,
  692. /// so we use it as a backup for everything.
  693. bool gcdMIVtest(const SCEV *Src,
  694. const SCEV *Dst,
  695. FullDependence &Result) const;
  696. /// banerjeeMIVtest - Tests an MIV subscript pair for dependence.
  697. /// Returns true if any possible dependence is disproved.
  698. /// Marks the result as inconsistent.
  699. /// Computes directions.
  700. bool banerjeeMIVtest(const SCEV *Src,
  701. const SCEV *Dst,
  702. const SmallBitVector &Loops,
  703. FullDependence &Result) const;
  704. /// collectCoefficientInfo - Walks through the subscript,
  705. /// collecting each coefficient, the associated loop bounds,
  706. /// and recording its positive and negative parts for later use.
  707. CoefficientInfo *collectCoeffInfo(const SCEV *Subscript,
  708. bool SrcFlag,
  709. const SCEV *&Constant) const;
  710. /// getPositivePart - X^+ = max(X, 0).
  711. ///
  712. const SCEV *getPositivePart(const SCEV *X) const;
  713. /// getNegativePart - X^- = min(X, 0).
  714. ///
  715. const SCEV *getNegativePart(const SCEV *X) const;
  716. /// getLowerBound - Looks through all the bounds info and
  717. /// computes the lower bound given the current direction settings
  718. /// at each level.
  719. const SCEV *getLowerBound(BoundInfo *Bound) const;
  720. /// getUpperBound - Looks through all the bounds info and
  721. /// computes the upper bound given the current direction settings
  722. /// at each level.
  723. const SCEV *getUpperBound(BoundInfo *Bound) const;
  724. /// exploreDirections - Hierarchically expands the direction vector
  725. /// search space, combining the directions of discovered dependences
  726. /// in the DirSet field of Bound. Returns the number of distinct
  727. /// dependences discovered. If the dependence is disproved,
  728. /// it will return 0.
  729. unsigned exploreDirections(unsigned Level,
  730. CoefficientInfo *A,
  731. CoefficientInfo *B,
  732. BoundInfo *Bound,
  733. const SmallBitVector &Loops,
  734. unsigned &DepthExpanded,
  735. const SCEV *Delta) const;
  736. /// testBounds - Returns true iff the current bounds are plausible.
  737. bool testBounds(unsigned char DirKind,
  738. unsigned Level,
  739. BoundInfo *Bound,
  740. const SCEV *Delta) const;
  741. /// findBoundsALL - Computes the upper and lower bounds for level K
  742. /// using the * direction. Records them in Bound.
  743. void findBoundsALL(CoefficientInfo *A,
  744. CoefficientInfo *B,
  745. BoundInfo *Bound,
  746. unsigned K) const;
  747. /// findBoundsLT - Computes the upper and lower bounds for level K
  748. /// using the < direction. Records them in Bound.
  749. void findBoundsLT(CoefficientInfo *A,
  750. CoefficientInfo *B,
  751. BoundInfo *Bound,
  752. unsigned K) const;
  753. /// findBoundsGT - Computes the upper and lower bounds for level K
  754. /// using the > direction. Records them in Bound.
  755. void findBoundsGT(CoefficientInfo *A,
  756. CoefficientInfo *B,
  757. BoundInfo *Bound,
  758. unsigned K) const;
  759. /// findBoundsEQ - Computes the upper and lower bounds for level K
  760. /// using the = direction. Records them in Bound.
  761. void findBoundsEQ(CoefficientInfo *A,
  762. CoefficientInfo *B,
  763. BoundInfo *Bound,
  764. unsigned K) const;
  765. /// intersectConstraints - Updates X with the intersection
  766. /// of the Constraints X and Y. Returns true if X has changed.
  767. bool intersectConstraints(Constraint *X,
  768. const Constraint *Y);
  769. /// propagate - Review the constraints, looking for opportunities
  770. /// to simplify a subscript pair (Src and Dst).
  771. /// Return true if some simplification occurs.
  772. /// If the simplification isn't exact (that is, if it is conservative
  773. /// in terms of dependence), set consistent to false.
  774. bool propagate(const SCEV *&Src,
  775. const SCEV *&Dst,
  776. SmallBitVector &Loops,
  777. SmallVectorImpl<Constraint> &Constraints,
  778. bool &Consistent);
  779. /// propagateDistance - Attempt to propagate a distance
  780. /// constraint into a subscript pair (Src and Dst).
  781. /// Return true if some simplification occurs.
  782. /// If the simplification isn't exact (that is, if it is conservative
  783. /// in terms of dependence), set consistent to false.
  784. bool propagateDistance(const SCEV *&Src,
  785. const SCEV *&Dst,
  786. Constraint &CurConstraint,
  787. bool &Consistent);
  788. /// propagatePoint - Attempt to propagate a point
  789. /// constraint into a subscript pair (Src and Dst).
  790. /// Return true if some simplification occurs.
  791. bool propagatePoint(const SCEV *&Src,
  792. const SCEV *&Dst,
  793. Constraint &CurConstraint);
  794. /// propagateLine - Attempt to propagate a line
  795. /// constraint into a subscript pair (Src and Dst).
  796. /// Return true if some simplification occurs.
  797. /// If the simplification isn't exact (that is, if it is conservative
  798. /// in terms of dependence), set consistent to false.
  799. bool propagateLine(const SCEV *&Src,
  800. const SCEV *&Dst,
  801. Constraint &CurConstraint,
  802. bool &Consistent);
  803. /// findCoefficient - Given a linear SCEV,
  804. /// return the coefficient corresponding to specified loop.
  805. /// If there isn't one, return the SCEV constant 0.
  806. /// For example, given a*i + b*j + c*k, returning the coefficient
  807. /// corresponding to the j loop would yield b.
  808. const SCEV *findCoefficient(const SCEV *Expr,
  809. const Loop *TargetLoop) const;
  810. /// zeroCoefficient - Given a linear SCEV,
  811. /// return the SCEV given by zeroing out the coefficient
  812. /// corresponding to the specified loop.
  813. /// For example, given a*i + b*j + c*k, zeroing the coefficient
  814. /// corresponding to the j loop would yield a*i + c*k.
  815. const SCEV *zeroCoefficient(const SCEV *Expr,
  816. const Loop *TargetLoop) const;
  817. /// addToCoefficient - Given a linear SCEV Expr,
  818. /// return the SCEV given by adding some Value to the
  819. /// coefficient corresponding to the specified TargetLoop.
  820. /// For example, given a*i + b*j + c*k, adding 1 to the coefficient
  821. /// corresponding to the j loop would yield a*i + (b+1)*j + c*k.
  822. const SCEV *addToCoefficient(const SCEV *Expr,
  823. const Loop *TargetLoop,
  824. const SCEV *Value) const;
  825. /// updateDirection - Update direction vector entry
  826. /// based on the current constraint.
  827. void updateDirection(Dependence::DVEntry &Level,
  828. const Constraint &CurConstraint) const;
  829. /// Given a linear access function, tries to recover subscripts
  830. /// for each dimension of the array element access.
  831. bool tryDelinearize(Instruction *Src, Instruction *Dst,
  832. SmallVectorImpl<Subscript> &Pair);
  833. /// Tries to delinearize \p Src and \p Dst access functions for a fixed size
  834. /// multi-dimensional array. Calls tryDelinearizeFixedSizeImpl() to
  835. /// delinearize \p Src and \p Dst separately,
  836. bool tryDelinearizeFixedSize(Instruction *Src, Instruction *Dst,
  837. const SCEV *SrcAccessFn,
  838. const SCEV *DstAccessFn,
  839. SmallVectorImpl<const SCEV *> &SrcSubscripts,
  840. SmallVectorImpl<const SCEV *> &DstSubscripts);
  841. /// Tries to delinearize access function for a multi-dimensional array with
  842. /// symbolic runtime sizes.
  843. /// Returns true upon success and false otherwise.
  844. bool tryDelinearizeParametricSize(
  845. Instruction *Src, Instruction *Dst, const SCEV *SrcAccessFn,
  846. const SCEV *DstAccessFn, SmallVectorImpl<const SCEV *> &SrcSubscripts,
  847. SmallVectorImpl<const SCEV *> &DstSubscripts);
  848. /// checkSubscript - Helper function for checkSrcSubscript and
  849. /// checkDstSubscript to avoid duplicate code
  850. bool checkSubscript(const SCEV *Expr, const Loop *LoopNest,
  851. SmallBitVector &Loops, bool IsSrc);
  852. }; // class DependenceInfo
  853. /// AnalysisPass to compute dependence information in a function
  854. class DependenceAnalysis : public AnalysisInfoMixin<DependenceAnalysis> {
  855. public:
  856. typedef DependenceInfo Result;
  857. Result run(Function &F, FunctionAnalysisManager &FAM);
  858. private:
  859. static AnalysisKey Key;
  860. friend struct AnalysisInfoMixin<DependenceAnalysis>;
  861. }; // class DependenceAnalysis
  862. /// Printer pass to dump DA results.
  863. struct DependenceAnalysisPrinterPass
  864. : public PassInfoMixin<DependenceAnalysisPrinterPass> {
  865. DependenceAnalysisPrinterPass(raw_ostream &OS,
  866. bool NormalizeResults = false)
  867. : OS(OS), NormalizeResults(NormalizeResults) {}
  868. PreservedAnalyses run(Function &F, FunctionAnalysisManager &FAM);
  869. private:
  870. raw_ostream &OS;
  871. bool NormalizeResults;
  872. }; // class DependenceAnalysisPrinterPass
  873. /// Legacy pass manager pass to access dependence information
  874. class DependenceAnalysisWrapperPass : public FunctionPass {
  875. public:
  876. static char ID; // Class identification, replacement for typeinfo
  877. DependenceAnalysisWrapperPass();
  878. bool runOnFunction(Function &F) override;
  879. void releaseMemory() override;
  880. void getAnalysisUsage(AnalysisUsage &) const override;
  881. void print(raw_ostream &, const Module * = nullptr) const override;
  882. DependenceInfo &getDI() const;
  883. private:
  884. std::unique_ptr<DependenceInfo> info;
  885. }; // class DependenceAnalysisWrapperPass
  886. /// createDependenceAnalysisPass - This creates an instance of the
  887. /// DependenceAnalysis wrapper pass.
  888. FunctionPass *createDependenceAnalysisWrapperPass();
  889. } // namespace llvm
  890. #endif
  891. #ifdef __GNUC__
  892. #pragma GCC diagnostic pop
  893. #endif