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