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 /// The dependency information could be across a single loop level or across
86 /// two separate levels that have the same trip count and nesting depth,
87 /// which helps to provide information for loop fusion candidation.
88 /// For example, loops b and c have the same iteration count and depth:
89 /// for (a = ...) {
90 /// for (b = 0; b < 10; b++) {
91 /// }
92 /// for (c = 0; c < 10; c++) {
93 /// }
94 /// }
95 struct DVEntry {
96 enum : unsigned char {
97 NONE = 0,
98 LT = 1,
99 EQ = 2,
100 LE = 3,
101 GT = 4,
102 NE = 5,
103 GE = 6,
104 ALL = 7
105 };
106 unsigned char Direction : 3; // Init to ALL, then refine.
107 bool Scalar : 1; // Init to true.
108 bool PeelFirst : 1; // Peeling the first iteration will break dependence.
109 bool PeelLast : 1; // Peeling the last iteration will break the dependence.
110 const SCEV *Distance = nullptr; // NULL implies no distance available.
113 };
114
115 /// getSrc - Returns the source instruction for this dependence.
116 Instruction *getSrc() const { return Src; }
117
118 /// getDst - Returns the destination instruction for this dependence.
119 Instruction *getDst() const { return Dst; }
120
121 /// isInput - Returns true if this is an input dependence.
122 bool isInput() const;
123
124 /// isOutput - Returns true if this is an output dependence.
125 bool isOutput() const;
126
127 /// isFlow - Returns true if this is a flow (aka true) dependence.
128 bool isFlow() const;
129
130 /// isAnti - Returns true if this is an anti dependence.
131 bool isAnti() const;
132
133 /// isOrdered - Returns true if dependence is Output, Flow, or Anti
134 bool isOrdered() const { return isOutput() || isFlow() || isAnti(); }
135
136 /// isUnordered - Returns true if dependence is Input
137 bool isUnordered() const { return isInput(); }
138
139 /// isLoopIndependent - Returns true if this is a loop-independent
140 /// dependence.
141 virtual bool isLoopIndependent() const { return true; }
142
143 /// isConfused - Returns true if this dependence is confused
144 /// (the compiler understands nothing and makes worst-case 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 /// getSameSDLevels - Returns the number of separate SameSD loops surrounding
156 /// the source and destination of the dependence.
157 virtual unsigned getSameSDLevels() const { return 0; }
158
159 /// getDVEntry - Returns the DV entry associated with a regular or a
160 /// SameSD level
161 DVEntry getDVEntry(unsigned Level, bool IsSameSD) const;
162
163 /// getDirection - Returns the direction associated with a particular
164 /// common or SameSD level.
165 virtual unsigned getDirection(unsigned Level, bool SameSD = false) const {
166 return DVEntry::ALL;
167 }
168
169 /// getDistance - Returns the distance (or NULL) associated with a
170 /// particular common or SameSD level.
171 virtual const SCEV *getDistance(unsigned Level, bool SameSD = false) const {
172 return nullptr;
173 }
174
175 /// Check if the direction vector is negative. A negative direction
176 /// vector means Src and Dst are reversed in the actual program.
177 virtual bool isDirectionNegative() const { return false; }
178
179 /// If the direction vector is negative, normalize the direction
180 /// vector to make it non-negative. Normalization is done by reversing
181 /// Src and Dst, plus reversing the dependence directions and distances
182 /// in the vector.
183 virtual bool normalize(ScalarEvolution *SE) { return false; }
184
185 /// isPeelFirst - Returns true if peeling the first iteration from
186 /// this regular or SameSD loop level will break this dependence.
187 virtual bool isPeelFirst(unsigned Level, bool SameSD = false) const {
188 return false;
189 }
190
191 /// isPeelLast - Returns true if peeling the last iteration from
192 /// this regular or SameSD loop level will break this dependence.
193 virtual bool isPeelLast(unsigned Level, bool SameSD = false) const {
194 return false;
195 }
196
197 /// inSameSDLoops - Returns true if this level is an SameSD level, i.e.,
198 /// performed across two separate loop nests that have the Same Iteration and
199 /// Depth.
200 virtual bool inSameSDLoops(unsigned Level) const { return false; }
201
202 /// isScalar - Returns true if a particular regular or SameSD level is
203 /// scalar; that is, if no subscript in the source or destination mention
204 /// the induction variable associated with the loop at this level.
205 virtual bool isScalar(unsigned Level, bool SameSD = false) const;
206
207 /// getNextPredecessor - Returns the value of the NextPredecessor field.
208 const Dependence *getNextPredecessor() const { return NextPredecessor; }
209
210 /// getNextSuccessor - Returns the value of the NextSuccessor field.
211 const Dependence *getNextSuccessor() const { return NextSuccessor; }
212
213 /// setNextPredecessor - Sets the value of the NextPredecessor
214 /// field.
215 void setNextPredecessor(const Dependence *pred) { NextPredecessor = pred; }
216
217 /// setNextSuccessor - Sets the value of the NextSuccessor field.
218 void setNextSuccessor(const Dependence *succ) { NextSuccessor = succ; }
219
220 /// getRuntimeAssumptions - Returns the runtime assumptions under which this
221 /// Dependence relation is valid.
222 SCEVUnionPredicate getRuntimeAssumptions() const { return Assumptions; }
223
224 /// dump - For debugging purposes, dumps a dependence to OS.
225 void dump(raw_ostream &OS) const;
226
227 /// dumpImp - For debugging purposes. Dumps a dependence to OS with or
228 /// without considering the SameSD levels.
229 void dumpImp(raw_ostream &OS, bool IsSameSD = false) const;
230
231protected:
233
234private:
235 SCEVUnionPredicate Assumptions;
236 const Dependence *NextPredecessor = nullptr, *NextSuccessor = nullptr;
237 friend class DependenceInfo;
238};
239
240/// FullDependence - This class represents a dependence between two memory
241/// references in a function. It contains detailed information about the
242/// dependence (direction vectors, etc.) and is used when the compiler is
243/// able to accurately analyze the interaction of the references; that is,
244/// it is not a confused dependence (see Dependence). In most cases
245/// (for output, flow, and anti dependences), the dependence implies an
246/// ordering, where the source must precede the destination; in contrast,
247/// input dependences are unordered.
248class LLVM_ABI FullDependence final : public Dependence {
249public:
250 FullDependence(Instruction *Source, Instruction *Destination,
251 const SCEVUnionPredicate &Assumes,
252 bool PossiblyLoopIndependent, unsigned Levels);
253
254 /// isLoopIndependent - Returns true if this is a loop-independent
255 /// dependence.
256 bool isLoopIndependent() const override { return LoopIndependent; }
257
258 /// isConfused - Returns true if this dependence is confused
259 /// (the compiler understands nothing and makes worst-case
260 /// assumptions).
261 bool isConfused() const override { return false; }
262
263 /// isConsistent - Returns true if this dependence is consistent
264 /// (occurs every time the source and destination are executed).
265 bool isConsistent() const override { return Consistent; }
266
267 /// getLevels - Returns the number of common loops surrounding the
268 /// source and destination of the dependence.
269 unsigned getLevels() const override { return Levels; }
270
271 /// getSameSDLevels - Returns the number of separate SameSD loops surrounding
272 /// the source and destination of the dependence.
273 unsigned getSameSDLevels() const override { return SameSDLevels; }
274
275 /// getDVEntry - Returns the DV entry associated with a regular or a
276 /// SameSD level.
277 DVEntry getDVEntry(unsigned Level, bool IsSameSD) const {
278 if (!IsSameSD) {
279 assert(0 < Level && Level <= Levels && "Level out of range");
280 return DV[Level - 1];
281 } else {
282 assert(Levels < Level &&
283 Level <= static_cast<unsigned>(Levels) + SameSDLevels &&
284 "isSameSD level out of range");
285 return DVSameSD[Level - Levels - 1];
286 }
287 }
288
289 /// getDirection - Returns the direction associated with a particular
290 /// common or SameSD level.
291 unsigned getDirection(unsigned Level, bool SameSD = false) const override;
292
293 /// getDistance - Returns the distance (or NULL) associated with a
294 /// particular common or SameSD level.
295 const SCEV *getDistance(unsigned Level, bool SameSD = false) const override;
296
297 /// Check if the direction vector is negative. A negative direction
298 /// vector means Src and Dst are reversed in the actual program.
299 bool isDirectionNegative() const override;
300
301 /// If the direction vector is negative, normalize the direction
302 /// vector to make it non-negative. Normalization is done by reversing
303 /// Src and Dst, plus reversing the dependence directions and distances
304 /// in the vector.
305 bool normalize(ScalarEvolution *SE) override;
306
307 /// isPeelFirst - Returns true if peeling the first iteration from
308 /// this regular or SameSD loop level will break this dependence.
309 bool isPeelFirst(unsigned Level, bool SameSD = false) const override;
310
311 /// isPeelLast - Returns true if peeling the last iteration from
312 /// this regular or SameSD loop level will break this dependence.
313 bool isPeelLast(unsigned Level, bool SameSD = false) const override;
314
315 /// inSameSDLoops - Returns true if this level is an SameSD level, i.e.,
316 /// performed across two separate loop nests that have the Same Iteration and
317 /// Depth.
318 bool inSameSDLoops(unsigned Level) const override;
319
320 /// isScalar - Returns true if a particular regular or SameSD level is
321 /// scalar; that is, if no subscript in the source or destination mention
322 /// the induction variable associated with the loop at this level.
323 bool isScalar(unsigned Level, bool SameSD = false) const override;
324
325private:
326 unsigned short Levels;
327 unsigned short SameSDLevels;
328 bool LoopIndependent;
329 bool Consistent; // Init to true, then refine.
330 std::unique_ptr<DVEntry[]> DV;
331 std::unique_ptr<DVEntry[]> DVSameSD; // DV entries on SameSD levels
332 friend class DependenceInfo;
333};
334
335/// DependenceInfo - This class is the main dependence-analysis driver.
337public:
339 : AA(AA), SE(SE), LI(LI), F(F) {}
340
341 /// Handle transitive invalidation when the cached analysis results go away.
343 FunctionAnalysisManager::Invalidator &Inv);
344
345 /// depends - Tests for a dependence between the Src and Dst instructions.
346 /// Returns NULL if no dependence; otherwise, returns a Dependence (or a
347 /// FullDependence) with as much information as can be gleaned. By default,
348 /// the dependence test collects a set of runtime assumptions that cannot be
349 /// solved at compilation time. By default UnderRuntimeAssumptions is false
350 /// for a safe approximation of the dependence relation that does not
351 /// require runtime checks.
352 LLVM_ABI std::unique_ptr<Dependence>
354 bool UnderRuntimeAssumptions = false);
355
356 Function *getFunction() const { return F; }
357
358 /// getRuntimeAssumptions - Returns all the runtime assumptions under which
359 /// the dependence test is valid.
361
362private:
363 AAResults *AA;
364 ScalarEvolution *SE;
365 LoopInfo *LI;
366 Function *F;
368
369 /// Subscript - This private struct represents a pair of subscripts from
370 /// a pair of potentially multi-dimensional array references. We use a
371 /// vector of them to guide subscript partitioning.
372 struct Subscript {
373 const SCEV *Src;
374 const SCEV *Dst;
375 enum ClassificationKind { ZIV, SIV, RDIV, MIV, NonLinear } Classification;
376 SmallBitVector Loops;
377 SmallBitVector GroupLoops;
378 SmallBitVector Group;
379 };
380
381 struct CoefficientInfo {
382 const SCEV *Coeff;
383 const SCEV *PosPart;
384 const SCEV *NegPart;
385 const SCEV *Iterations;
386 };
387
388 struct BoundInfo {
389 const SCEV *Iterations;
390 const SCEV *Upper[8];
391 const SCEV *Lower[8];
392 unsigned char Direction;
393 unsigned char DirSet;
394 };
395
396 /// Returns true if two loops have the Same iteration Space and Depth. To be
397 /// more specific, two loops have SameSD if they are in the same nesting
398 /// depth and have the same backedge count. SameSD stands for Same iteration
399 /// Space and Depth.
400 bool haveSameSD(const Loop *SrcLoop, const Loop *DstLoop) const;
401
402 /// establishNestingLevels - Examines the loop nesting of the Src and Dst
403 /// instructions and establishes their shared loops. Sets the variables
404 /// CommonLevels, SrcLevels, and MaxLevels.
405 /// The source and destination instructions needn't be contained in the same
406 /// loop. The routine establishNestingLevels finds the level of most deeply
407 /// nested loop that contains them both, CommonLevels. An instruction that's
408 /// not contained in a loop is at level = 0. MaxLevels is equal to the level
409 /// of the source plus the level of the destination, minus CommonLevels.
410 /// This lets us allocate vectors MaxLevels in length, with room for every
411 /// distinct loop referenced in both the source and destination subscripts.
412 /// The variable SrcLevels is the nesting depth of the source instruction.
413 /// It's used to help calculate distinct loops referenced by the destination.
414 /// Here's the map from loops to levels:
415 /// 0 - unused
416 /// 1 - outermost common loop
417 /// ... - other common loops
418 /// CommonLevels - innermost common loop
419 /// ... - loops containing Src but not Dst
420 /// SrcLevels - innermost loop containing Src but not Dst
421 /// ... - loops containing Dst but not Src
422 /// MaxLevels - innermost loop containing Dst but not Src
423 /// Consider the follow code fragment:
424 /// for (a = ...) {
425 /// for (b = ...) {
426 /// for (c = ...) {
427 /// for (d = ...) {
428 /// A[] = ...;
429 /// }
430 /// }
431 /// for (e = ...) {
432 /// for (f = ...) {
433 /// for (g = ...) {
434 /// ... = A[];
435 /// }
436 /// }
437 /// }
438 /// }
439 /// }
440 /// If we're looking at the possibility of a dependence between the store
441 /// to A (the Src) and the load from A (the Dst), we'll note that they
442 /// have 2 loops in common, so CommonLevels will equal 2 and the direction
443 /// vector for Result will have 2 entries. SrcLevels = 4 and MaxLevels = 7.
444 /// A map from loop names to level indices would look like
445 /// a - 1
446 /// b - 2 = CommonLevels
447 /// c - 3
448 /// d - 4 = SrcLevels
449 /// e - 5
450 /// f - 6
451 /// g - 7 = MaxLevels
452 /// SameSDLevels counts the number of levels after common levels that are
453 /// not common but have the same iteration space and depth. Internally this
454 /// is checked using haveSameSD. Assume that in this code fragment, levels c
455 /// and e have the same iteration space and depth, but levels d and f does
456 /// not. Then SameSDLevels is set to 1. In that case the level numbers for the
457 /// previous code look like
458 /// a - 1
459 /// b - 2
460 /// c,e - 3 = CommonLevels
461 /// d - 4 = SrcLevels
462 /// f - 5
463 /// g - 6 = MaxLevels
464 void establishNestingLevels(const Instruction *Src, const Instruction *Dst);
465
466 unsigned CommonLevels, SrcLevels, MaxLevels, SameSDLevels;
467
468 /// mapSrcLoop - Given one of the loops containing the source, return
469 /// its level index in our numbering scheme.
470 unsigned mapSrcLoop(const Loop *SrcLoop) const;
471
472 /// mapDstLoop - Given one of the loops containing the destination,
473 /// return its level index in our numbering scheme.
474 unsigned mapDstLoop(const Loop *DstLoop) const;
475
476 /// isLoopInvariant - Returns true if Expression is loop invariant
477 /// in LoopNest.
478 bool isLoopInvariant(const SCEV *Expression, const Loop *LoopNest) const;
479
480 /// Makes sure all subscript pairs share the same integer type by
481 /// sign-extending as necessary.
482 /// Sign-extending a subscript is safe because getelementptr assumes the
483 /// array subscripts are signed.
484 void unifySubscriptType(ArrayRef<Subscript *> Pairs);
485
486 /// removeMatchingExtensions - Examines a subscript pair.
487 /// If the source and destination are identically sign (or zero)
488 /// extended, it strips off the extension in an effort to
489 /// simplify the actual analysis.
490 void removeMatchingExtensions(Subscript *Pair);
491
492 /// collectCommonLoops - Finds the set of loops from the LoopNest that
493 /// have a level <= CommonLevels and are referred to by the SCEV Expression.
494 void collectCommonLoops(const SCEV *Expression, const Loop *LoopNest,
495 SmallBitVector &Loops) const;
496
497 /// checkSrcSubscript - Examines the SCEV Src, returning true iff it's
498 /// linear. Collect the set of loops mentioned by Src.
499 bool checkSrcSubscript(const SCEV *Src, const Loop *LoopNest,
500 SmallBitVector &Loops);
501
502 /// checkDstSubscript - Examines the SCEV Dst, returning true iff it's
503 /// linear. Collect the set of loops mentioned by Dst.
504 bool checkDstSubscript(const SCEV *Dst, const Loop *LoopNest,
505 SmallBitVector &Loops);
506
507 /// isKnownPredicate - Compare X and Y using the predicate Pred.
508 /// Basically a wrapper for SCEV::isKnownPredicate,
509 /// but tries harder, especially in the presence of sign and zero
510 /// extensions and symbolics.
511 bool isKnownPredicate(ICmpInst::Predicate Pred, const SCEV *X,
512 const SCEV *Y) const;
513
514 /// isKnownLessThan - Compare to see if S is less than Size
515 /// Another wrapper for isKnownNegative(S - max(Size, 1)) with some extra
516 /// checking if S is an AddRec and we can prove lessthan using the loop
517 /// bounds.
518 bool isKnownLessThan(const SCEV *S, const SCEV *Size) const;
519
520 /// isKnownNonNegative - Compare to see if S is known not to be negative
521 /// Uses the fact that S comes from Ptr, which may be an inbound GEP,
522 /// Proving there is no wrapping going on.
523 bool isKnownNonNegative(const SCEV *S, const Value *Ptr) const;
524
525 /// collectUpperBound - All subscripts are the same type (on my machine,
526 /// an i64). The loop bound may be a smaller type. collectUpperBound
527 /// find the bound, if available, and zero extends it to the Type T.
528 /// (I zero extend since the bound should always be >= 0.)
529 /// If no upper bound is available, return NULL.
530 const SCEV *collectUpperBound(const Loop *l, Type *T) const;
531
532 /// collectConstantUpperBound - Calls collectUpperBound(), then
533 /// attempts to cast it to SCEVConstant. If the cast fails,
534 /// returns NULL.
535 const SCEVConstant *collectConstantUpperBound(const Loop *l, Type *T) const;
536
537 /// classifyPair - Examines the subscript pair (the Src and Dst SCEVs)
538 /// and classifies it as either ZIV, SIV, RDIV, MIV, or Nonlinear.
539 /// Collects the associated loops in a set.
540 Subscript::ClassificationKind
541 classifyPair(const SCEV *Src, const Loop *SrcLoopNest, const SCEV *Dst,
542 const Loop *DstLoopNest, SmallBitVector &Loops);
543
544 /// testZIV - Tests the ZIV subscript pair (Src and Dst) for dependence.
545 /// Returns true if any possible dependence is disproved.
546 /// If there might be a dependence, returns false.
547 /// If the dependence isn't proven to exist,
548 /// marks the Result as inconsistent.
549 bool testZIV(const SCEV *Src, const SCEV *Dst, FullDependence &Result) const;
550
551 /// testSIV - Tests the SIV subscript pair (Src and Dst) for dependence.
552 /// Things of the form [c1 + a1*i] and [c2 + a2*j], where
553 /// i and j are induction variables, c1 and c2 are loop invariant,
554 /// and a1 and a2 are constant.
555 /// Returns true if any possible dependence is disproved.
556 /// If there might be a dependence, returns false.
557 /// Sets appropriate direction vector entry and, when possible,
558 /// the distance vector entry.
559 /// If the dependence isn't proven to exist,
560 /// marks the Result as inconsistent.
561 bool testSIV(const SCEV *Src, const SCEV *Dst, unsigned &Level,
562 FullDependence &Result) const;
563
564 /// testRDIV - Tests the RDIV subscript pair (Src and Dst) for dependence.
565 /// Things of the form [c1 + a1*i] and [c2 + a2*j]
566 /// where i and j are induction variables, c1 and c2 are loop invariant,
567 /// and a1 and a2 are constant.
568 /// With minor algebra, this test can also be used for things like
569 /// [c1 + a1*i + a2*j][c2].
570 /// Returns true if any possible dependence is disproved.
571 /// If there might be a dependence, returns false.
572 /// Marks the Result as inconsistent.
573 bool testRDIV(const SCEV *Src, const SCEV *Dst, FullDependence &Result) const;
574
575 /// testMIV - Tests the MIV subscript pair (Src and Dst) for dependence.
576 /// Returns true if dependence disproved.
577 /// Can sometimes refine direction vectors.
578 bool testMIV(const SCEV *Src, const SCEV *Dst, const SmallBitVector &Loops,
579 FullDependence &Result) const;
580
581 /// strongSIVtest - Tests the strong SIV subscript pair (Src and Dst)
582 /// for dependence.
583 /// Things of the form [c1 + a*i] and [c2 + a*i],
584 /// where i is an induction variable, c1 and c2 are loop invariant,
585 /// and a is a constant
586 /// Returns true if any possible dependence is disproved.
587 /// If there might be a dependence, returns false.
588 /// Sets appropriate direction and distance.
589 bool strongSIVtest(const SCEV *Coeff, const SCEV *SrcConst,
590 const SCEV *DstConst, const Loop *CurrentSrcLoop,
591 const Loop *CurrentDstLoop, unsigned Level,
592 FullDependence &Result) const;
593
594 /// weakCrossingSIVtest - Tests the weak-crossing SIV subscript pair
595 /// (Src and Dst) for dependence.
596 /// Things of the form [c1 + a*i] and [c2 - a*i],
597 /// where i is an induction variable, c1 and c2 are loop invariant,
598 /// and a is a constant.
599 /// Returns true if any possible dependence is disproved.
600 /// If there might be a dependence, returns false.
601 /// Sets appropriate direction entry.
602 /// Set consistent to false.
603 bool weakCrossingSIVtest(const SCEV *SrcCoeff, const SCEV *SrcConst,
604 const SCEV *DstConst, const Loop *CurrentSrcLoop,
605 const Loop *CurrentDstLoop, unsigned Level,
606 FullDependence &Result) const;
607
608 /// ExactSIVtest - Tests the SIV subscript pair
609 /// (Src and Dst) for dependence.
610 /// Things of the form [c1 + a1*i] and [c2 + a2*i],
611 /// where i is an induction variable, c1 and c2 are loop invariant,
612 /// and a1 and a2 are constant.
613 /// Returns true if any possible dependence is disproved.
614 /// If there might be a dependence, returns false.
615 /// Sets appropriate direction entry.
616 /// Set consistent to false.
617 bool exactSIVtest(const SCEV *SrcCoeff, const SCEV *DstCoeff,
618 const SCEV *SrcConst, const SCEV *DstConst,
619 const Loop *CurrentSrcLoop, const Loop *CurrentDstLoop,
620 unsigned Level, FullDependence &Result) const;
621
622 /// weakZeroSrcSIVtest - Tests the weak-zero SIV subscript pair
623 /// (Src and Dst) for dependence.
624 /// Things of the form [c1] and [c2 + a*i],
625 /// where i is an induction variable, c1 and c2 are loop invariant,
626 /// and a is a constant. See also weakZeroDstSIVtest.
627 /// Returns true if any possible dependence is disproved.
628 /// If there might be a dependence, returns false.
629 /// Sets appropriate direction entry.
630 /// Set consistent to false.
631 /// If loop peeling will break the dependence, mark appropriately.
632 bool weakZeroSrcSIVtest(const SCEV *DstCoeff, const SCEV *SrcConst,
633 const SCEV *DstConst, const Loop *CurrentSrcLoop,
634 const Loop *CurrentDstLoop, unsigned Level,
635 FullDependence &Result) const;
636
637 /// weakZeroDstSIVtest - Tests the weak-zero SIV subscript pair
638 /// (Src and Dst) for dependence.
639 /// Things of the form [c1 + a*i] and [c2],
640 /// where i is an induction variable, c1 and c2 are loop invariant,
641 /// and a is a constant. See also weakZeroSrcSIVtest.
642 /// Returns true if any possible dependence is disproved.
643 /// If there might be a dependence, returns false.
644 /// Sets appropriate direction entry.
645 /// Set consistent to false.
646 /// If loop peeling will break the dependence, mark appropriately.
647 bool weakZeroDstSIVtest(const SCEV *SrcCoeff, const SCEV *SrcConst,
648 const SCEV *DstConst, const Loop *CurrentSrcLoop,
649 const Loop *CurrentDstLoop, unsigned Level,
650 FullDependence &Result) const;
651
652 /// exactRDIVtest - Tests the RDIV subscript pair for dependence.
653 /// Things of the form [c1 + a*i] and [c2 + b*j],
654 /// where i and j are induction variable, c1 and c2 are loop invariant,
655 /// and a and b are constants.
656 /// Returns true if any possible dependence is disproved.
657 /// Marks the result as inconsistent.
658 /// Works in some cases that symbolicRDIVtest doesn't,
659 /// and vice versa.
660 bool exactRDIVtest(const SCEV *SrcCoeff, const SCEV *DstCoeff,
661 const SCEV *SrcConst, const SCEV *DstConst,
662 const Loop *SrcLoop, const Loop *DstLoop,
663 FullDependence &Result) const;
664
665 /// symbolicRDIVtest - Tests the RDIV subscript pair for dependence.
666 /// Things of the form [c1 + a*i] and [c2 + b*j],
667 /// where i and j are induction variable, c1 and c2 are loop invariant,
668 /// and a and b are constants.
669 /// Returns true if any possible dependence is disproved.
670 /// Marks the result as inconsistent.
671 /// Works in some cases that exactRDIVtest doesn't,
672 /// and vice versa. Can also be used as a backup for
673 /// ordinary SIV tests.
674 bool symbolicRDIVtest(const SCEV *SrcCoeff, const SCEV *DstCoeff,
675 const SCEV *SrcConst, const SCEV *DstConst,
676 const Loop *SrcLoop, const Loop *DstLoop) const;
677
678 /// gcdMIVtest - Tests an MIV subscript pair for dependence.
679 /// Returns true if any possible dependence is disproved.
680 /// Marks the result as inconsistent.
681 /// Can sometimes disprove the equal direction for 1 or more loops.
682 // Can handle some symbolics that even the SIV tests don't get,
683 /// so we use it as a backup for everything.
684 bool gcdMIVtest(const SCEV *Src, const SCEV *Dst,
685 FullDependence &Result) const;
686
687 /// banerjeeMIVtest - Tests an MIV subscript pair for dependence.
688 /// Returns true if any possible dependence is disproved.
689 /// Marks the result as inconsistent.
690 /// Computes directions.
691 bool banerjeeMIVtest(const SCEV *Src, const SCEV *Dst,
692 const SmallBitVector &Loops,
693 FullDependence &Result) const;
694
695 /// collectCoeffInfo - Walks through the subscript, collecting each
696 /// coefficient, the associated loop bounds, and recording its positive and
697 /// negative parts for later use.
698 CoefficientInfo *collectCoeffInfo(const SCEV *Subscript, bool SrcFlag,
699 const SCEV *&Constant) const;
700
701 /// Given \p Expr of the form
702 ///
703 /// c_0*X_0*i_0 + c_1*X_1*i_1 + ...c_n*X_n*i_n + C
704 ///
705 /// compute
706 ///
707 /// RunningGCD = gcd(RunningGCD, c_0, c_1, ..., c_n)
708 ///
709 /// where c_0, c_1, ..., and c_n are the constant values. The result is stored
710 /// in \p RunningGCD. Also, the initial value of \p RunningGCD affects the
711 /// result. If we find a term like (c_k * X_k * i_k), where i_k is the
712 /// induction variable of \p CurLoop, c_k is stored in \p CurLoopCoeff and not
713 /// included in the GCD computation. Returns false if we fail to find a
714 /// constant coefficient for some loop, e.g., when a term like (X+Y)*i is
715 /// present. Otherwise returns true.
716 bool accumulateCoefficientsGCD(const SCEV *Expr, const Loop *CurLoop,
717 const SCEV *&CurLoopCoeff,
718 APInt &RunningGCD) const;
719
720 /// getPositivePart - X^+ = max(X, 0).
721 const SCEV *getPositivePart(const SCEV *X) const;
722
723 /// getNegativePart - X^- = min(X, 0).
724 const SCEV *getNegativePart(const SCEV *X) const;
725
726 /// getLowerBound - Looks through all the bounds info and
727 /// computes the lower bound given the current direction settings
728 /// at each level.
729 const SCEV *getLowerBound(BoundInfo *Bound) const;
730
731 /// getUpperBound - Looks through all the bounds info and
732 /// computes the upper bound given the current direction settings
733 /// at each level.
734 const SCEV *getUpperBound(BoundInfo *Bound) const;
735
736 /// exploreDirections - Hierarchically expands the direction vector
737 /// search space, combining the directions of discovered dependences
738 /// in the DirSet field of Bound. Returns the number of distinct
739 /// dependences discovered. If the dependence is disproved,
740 /// it will return 0.
741 unsigned exploreDirections(unsigned Level, CoefficientInfo *A,
742 CoefficientInfo *B, BoundInfo *Bound,
743 const SmallBitVector &Loops,
744 unsigned &DepthExpanded, const SCEV *Delta) const;
745
746 /// testBounds - Returns true iff the current bounds are plausible.
747 bool testBounds(unsigned char DirKind, unsigned Level, BoundInfo *Bound,
748 const SCEV *Delta) const;
749
750 /// findBoundsALL - Computes the upper and lower bounds for level K
751 /// using the * direction. Records them in Bound.
752 void findBoundsALL(CoefficientInfo *A, CoefficientInfo *B, BoundInfo *Bound,
753 unsigned K) const;
754
755 /// findBoundsLT - Computes the upper and lower bounds for level K
756 /// using the < direction. Records them in Bound.
757 void findBoundsLT(CoefficientInfo *A, CoefficientInfo *B, BoundInfo *Bound,
758 unsigned K) const;
759
760 /// findBoundsGT - Computes the upper and lower bounds for level K
761 /// using the > direction. Records them in Bound.
762 void findBoundsGT(CoefficientInfo *A, CoefficientInfo *B, BoundInfo *Bound,
763 unsigned K) const;
764
765 /// findBoundsEQ - Computes the upper and lower bounds for level K
766 /// using the = direction. Records them in Bound.
767 void findBoundsEQ(CoefficientInfo *A, CoefficientInfo *B, BoundInfo *Bound,
768 unsigned K) const;
769
770 /// Given a linear access function, tries to recover subscripts
771 /// for each dimension of the array element access.
772 bool tryDelinearize(Instruction *Src, Instruction *Dst,
773 SmallVectorImpl<Subscript> &Pair);
774
775 /// Tries to delinearize \p Src and \p Dst access functions for a fixed size
776 /// multi-dimensional array. Calls tryDelinearizeFixedSizeImpl() to
777 /// delinearize \p Src and \p Dst separately,
778 bool tryDelinearizeFixedSize(Instruction *Src, Instruction *Dst,
779 const SCEV *SrcAccessFn, const SCEV *DstAccessFn,
780 SmallVectorImpl<const SCEV *> &SrcSubscripts,
781 SmallVectorImpl<const SCEV *> &DstSubscripts);
782
783 /// Tries to delinearize access function for a multi-dimensional array with
784 /// symbolic runtime sizes.
785 /// Returns true upon success and false otherwise.
786 bool
787 tryDelinearizeParametricSize(Instruction *Src, Instruction *Dst,
788 const SCEV *SrcAccessFn, const SCEV *DstAccessFn,
789 SmallVectorImpl<const SCEV *> &SrcSubscripts,
790 SmallVectorImpl<const SCEV *> &DstSubscripts);
791
792 /// checkSubscript - Helper function for checkSrcSubscript and
793 /// checkDstSubscript to avoid duplicate code
794 bool checkSubscript(const SCEV *Expr, const Loop *LoopNest,
795 SmallBitVector &Loops, bool IsSrc);
796}; // class DependenceInfo
797
798/// AnalysisPass to compute dependence information in a function
799class DependenceAnalysis : public AnalysisInfoMixin<DependenceAnalysis> {
800public:
803
804private:
807}; // class DependenceAnalysis
808
809/// Printer pass to dump DA results.
811 : public PassInfoMixin<DependenceAnalysisPrinterPass> {
812 DependenceAnalysisPrinterPass(raw_ostream &OS, bool NormalizeResults = false)
813 : OS(OS), NormalizeResults(NormalizeResults) {}
814
816
817 static bool isRequired() { return true; }
818
819private:
820 raw_ostream &OS;
821 bool NormalizeResults;
822}; // class DependenceAnalysisPrinterPass
823
824/// Legacy pass manager pass to access dependence information
826public:
827 static char ID; // Class identification, replacement for typeinfo
829
830 bool runOnFunction(Function &F) override;
831 void releaseMemory() override;
832 void getAnalysisUsage(AnalysisUsage &) const override;
833 void print(raw_ostream &, const Module * = nullptr) const override;
834 DependenceInfo &getDI() const;
835
836private:
837 std::unique_ptr<DependenceInfo> info;
838}; // class DependenceAnalysisWrapperPass
839
840/// createDependenceAnalysisPass - This creates an instance of the
841/// DependenceAnalysis wrapper pass.
843
844} // namespace llvm
845
846#endif
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val)
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define LLVM_ABI
Definition Compiler.h:213
static bool runOnFunction(Function &F, bool PostInlining)
Hexagon Hardware Loops
This header defines various interfaces for pass management in LLVM.
#define F(x, y, z)
Definition MD5.cpp:54
#define T
static bool isInput(const ArrayRef< StringRef > &Prefixes, StringRef Arg)
Definition OptTable.cpp:148
FunctionAnalysisManager FAM
This file implements the SmallBitVector class.
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
static TableGen::Emitter::OptClass< SkeletonEmitter > X("gen-skeleton-class", "Generate example skeleton class")
Represent the analysis usage information of a pass.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:676
void getAnalysisUsage(AnalysisUsage &) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
void releaseMemory() override
releaseMemory() - This member can be implemented by a pass if it wants to be able to release its memo...
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.
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.
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.
friend class DependenceInfo
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...
DVEntry getDVEntry(unsigned Level, bool IsSameSD) const
getDVEntry - Returns the DV entry associated with a regular or a SameSD level
virtual bool isConfused() const
isConfused - Returns true if this dependence is confused (the compiler understands nothing and makes ...
virtual unsigned getSameSDLevels() const
getSameSDLevels - Returns the number of separate SameSD loops surrounding the source and destination ...
virtual const SCEV * getDistance(unsigned Level, bool SameSD=false) const
getDistance - Returns the distance (or NULL) associated with a particular common or SameSD level.
virtual bool isPeelLast(unsigned Level, bool SameSD=false) const
isPeelLast - Returns true if peeling the last iteration from this regular or SameSD loop level will b...
virtual bool isConsistent() const
isConsistent - Returns true if this dependence is consistent (occurs every time the source and destin...
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 unsigned getDirection(unsigned Level, bool SameSD=false) const
getDirection - Returns the direction associated with a particular common or SameSD level.
bool isFlow() const
isFlow - Returns true if this is a flow (aka true) dependence.
virtual bool isPeelFirst(unsigned Level, bool SameSD=false) const
isPeelFirst - Returns true if peeling the first iteration from this regular or SameSD loop level will...
virtual ~Dependence()=default
virtual bool normalize(ScalarEvolution *SE)
If the direction vector is negative, normalize the direction vector to make it non-negative.
bool isAnti() const
isAnti - Returns true if this is an anti dependence.
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.
bool isOutput() const
isOutput - Returns true if this is an output dependence.
void setNextPredecessor(const Dependence *pred)
setNextPredecessor - Sets the value of the NextPredecessor field.
virtual bool inSameSDLoops(unsigned Level) const
inSameSDLoops - Returns true if this level is an SameSD level, i.e., performed across two separate lo...
FullDependence(Instruction *Source, Instruction *Destination, const SCEVUnionPredicate &Assumes, bool PossiblyLoopIndependent, unsigned Levels)
bool isConfused() const override
isConfused - Returns true if this dependence is confused (the compiler understands nothing and makes ...
DVEntry getDVEntry(unsigned Level, bool IsSameSD) const
getDVEntry - Returns the DV entry associated with a regular or a SameSD level.
bool isLoopIndependent() const override
isLoopIndependent - Returns true if this is a loop-independent dependence.
unsigned getSameSDLevels() const override
getSameSDLevels - Returns the number of separate SameSD loops surrounding the source and destination ...
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
FunctionPass(char &pid)
Definition Pass.h:316
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
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 constant integer value.
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.
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
Abstract Attribute helper functions.
Definition Attributor.h:165
This is an optimization pass for GlobalISel generic memory operations.
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
FunctionAddr VTableAddr Value
Definition InstrProf.h:137
ArrayRef(const T &OneElt) -> ArrayRef< T >
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
LLVM_ABI FunctionPass * createDependenceAnalysisWrapperPass()
createDependenceAnalysisPass - This creates an instance of the DependenceAnalysis wrapper pass.
A CRTP mix-in that provides informational APIs needed for analysis passes.
Definition PassManager.h:92
A special type used by analysis passes to provide an address that identifies that particular analysis...
Definition Analysis.h:29
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:69