DependenceAnalysis.h 42 KB

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