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