blob: 54078b9052379d7efa14a7393f3bd31931c33076 [file] [log] [blame]
Sebastian Pop59b61b92012-10-11 07:32:34 +00001//===-- DependenceAnalysis.cpp - DA Implementation --------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// DependenceAnalysis is an LLVM pass that analyses dependences between memory
11// accesses. Currently, it is an (incomplete) implementation of the approach
12// described in
13//
14// Practical Dependence Testing
15// Goff, Kennedy, Tseng
16// PLDI 1991
17//
18// There's a single entry point that analyzes the dependence between a pair
19// of memory references in a function, returning either NULL, for no dependence,
20// or a more-or-less detailed description of the dependence between them.
21//
22// Currently, the implementation cannot propagate constraints between
23// coupled RDIV subscripts and lacks a multi-subscript MIV test.
24// Both of these are conservative weaknesses;
25// that is, not a source of correctness problems.
26//
Sebastian Popbf6e1c22018-03-06 21:55:59 +000027// Since Clang linearizes some array subscripts, the dependence
Sebastian Pop7ee14722013-11-13 22:37:58 +000028// analysis is using SCEV->delinearize to recover the representation of multiple
29// subscripts, and thus avoid the more expensive and less precise MIV tests. The
30// delinearization is controlled by the flag -da-delinearize.
Sebastian Pop59b61b92012-10-11 07:32:34 +000031//
32// We should pay some careful attention to the possibility of integer overflow
33// in the implementation of the various tests. This could happen with Add,
34// Subtract, or Multiply, with both APInt's and SCEV's.
35//
36// Some non-linear subscript pairs can be handled by the GCD test
37// (and perhaps other tests).
38// Should explore how often these things occur.
39//
40// Finally, it seems like certain test cases expose weaknesses in the SCEV
41// simplification, especially in the handling of sign and zero extensions.
42// It could be useful to spend time exploring these.
43//
44// Please note that this is work in progress and the interface is subject to
45// change.
46//
47//===----------------------------------------------------------------------===//
48// //
49// In memory of Ken Kennedy, 1945 - 2007 //
50// //
51//===----------------------------------------------------------------------===//
52
Sebastian Pop59b61b92012-10-11 07:32:34 +000053#include "llvm/Analysis/DependenceAnalysis.h"
Benjamin Kramer0a446fd2015-03-01 21:28:53 +000054#include "llvm/ADT/STLExtras.h"
Sebastian Pop59b61b92012-10-11 07:32:34 +000055#include "llvm/ADT/Statistic.h"
Benjamin Kramer71a35122012-10-25 16:15:22 +000056#include "llvm/Analysis/AliasAnalysis.h"
57#include "llvm/Analysis/LoopInfo.h"
Benjamin Kramer71a35122012-10-25 16:15:22 +000058#include "llvm/Analysis/ScalarEvolution.h"
59#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000060#include "llvm/Analysis/ValueTracking.h"
Nico Weber432a3882018-04-30 14:59:11 +000061#include "llvm/Config/llvm-config.h"
Chandler Carruth83948572014-03-04 10:30:26 +000062#include "llvm/IR/InstIterator.h"
Mehdi Aminia28d91d2015-03-10 02:37:25 +000063#include "llvm/IR/Module.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000064#include "llvm/IR/Operator.h"
Sebastian Popc62c6792013-11-12 22:47:20 +000065#include "llvm/Support/CommandLine.h"
Sebastian Pop59b61b92012-10-11 07:32:34 +000066#include "llvm/Support/Debug.h"
67#include "llvm/Support/ErrorHandling.h"
Benjamin Kramer71a35122012-10-25 16:15:22 +000068#include "llvm/Support/raw_ostream.h"
Sebastian Pop59b61b92012-10-11 07:32:34 +000069
70using namespace llvm;
71
Chandler Carruthf1221bd2014-04-22 02:48:03 +000072#define DEBUG_TYPE "da"
73
Sebastian Pop59b61b92012-10-11 07:32:34 +000074//===----------------------------------------------------------------------===//
75// statistics
76
77STATISTIC(TotalArrayPairs, "Array pairs tested");
78STATISTIC(SeparableSubscriptPairs, "Separable subscript pairs");
79STATISTIC(CoupledSubscriptPairs, "Coupled subscript pairs");
80STATISTIC(NonlinearSubscriptPairs, "Nonlinear subscript pairs");
81STATISTIC(ZIVapplications, "ZIV applications");
82STATISTIC(ZIVindependence, "ZIV independence");
83STATISTIC(StrongSIVapplications, "Strong SIV applications");
84STATISTIC(StrongSIVsuccesses, "Strong SIV successes");
85STATISTIC(StrongSIVindependence, "Strong SIV independence");
86STATISTIC(WeakCrossingSIVapplications, "Weak-Crossing SIV applications");
87STATISTIC(WeakCrossingSIVsuccesses, "Weak-Crossing SIV successes");
88STATISTIC(WeakCrossingSIVindependence, "Weak-Crossing SIV independence");
89STATISTIC(ExactSIVapplications, "Exact SIV applications");
90STATISTIC(ExactSIVsuccesses, "Exact SIV successes");
91STATISTIC(ExactSIVindependence, "Exact SIV independence");
92STATISTIC(WeakZeroSIVapplications, "Weak-Zero SIV applications");
93STATISTIC(WeakZeroSIVsuccesses, "Weak-Zero SIV successes");
94STATISTIC(WeakZeroSIVindependence, "Weak-Zero SIV independence");
95STATISTIC(ExactRDIVapplications, "Exact RDIV applications");
96STATISTIC(ExactRDIVindependence, "Exact RDIV independence");
97STATISTIC(SymbolicRDIVapplications, "Symbolic RDIV applications");
98STATISTIC(SymbolicRDIVindependence, "Symbolic RDIV independence");
99STATISTIC(DeltaApplications, "Delta applications");
100STATISTIC(DeltaSuccesses, "Delta successes");
101STATISTIC(DeltaIndependence, "Delta independence");
102STATISTIC(DeltaPropagations, "Delta propagations");
103STATISTIC(GCDapplications, "GCD applications");
104STATISTIC(GCDsuccesses, "GCD successes");
105STATISTIC(GCDindependence, "GCD independence");
106STATISTIC(BanerjeeApplications, "Banerjee applications");
107STATISTIC(BanerjeeIndependence, "Banerjee independence");
108STATISTIC(BanerjeeSuccesses, "Banerjee successes");
109
Sebastian Popc62c6792013-11-12 22:47:20 +0000110static cl::opt<bool>
David Greend143c652018-06-21 11:53:16 +0000111 Delinearize("da-delinearize", cl::init(true), cl::Hidden, cl::ZeroOrMore,
112 cl::desc("Try to delinearize array references."));
Sebastian Popc62c6792013-11-12 22:47:20 +0000113
Sebastian Pop59b61b92012-10-11 07:32:34 +0000114//===----------------------------------------------------------------------===//
115// basics
116
Chandler Carruth49c22192016-05-12 22:19:39 +0000117DependenceAnalysis::Result
118DependenceAnalysis::run(Function &F, FunctionAnalysisManager &FAM) {
119 auto &AA = FAM.getResult<AAManager>(F);
120 auto &SE = FAM.getResult<ScalarEvolutionAnalysis>(F);
121 auto &LI = FAM.getResult<LoopAnalysis>(F);
122 return DependenceInfo(&F, &AA, &SE, &LI);
123}
124
Chandler Carruthdab4eae2016-11-23 17:53:26 +0000125AnalysisKey DependenceAnalysis::Key;
Chandler Carruth49c22192016-05-12 22:19:39 +0000126
127INITIALIZE_PASS_BEGIN(DependenceAnalysisWrapperPass, "da",
Sebastian Pop59b61b92012-10-11 07:32:34 +0000128 "Dependence Analysis", true, true)
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000129INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000130INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
Chandler Carruth7b560d42015-09-09 17:55:00 +0000131INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
Chandler Carruth49c22192016-05-12 22:19:39 +0000132INITIALIZE_PASS_END(DependenceAnalysisWrapperPass, "da", "Dependence Analysis",
133 true, true)
Sebastian Pop59b61b92012-10-11 07:32:34 +0000134
Chandler Carruth49c22192016-05-12 22:19:39 +0000135char DependenceAnalysisWrapperPass::ID = 0;
Sebastian Pop59b61b92012-10-11 07:32:34 +0000136
Chandler Carruth49c22192016-05-12 22:19:39 +0000137FunctionPass *llvm::createDependenceAnalysisWrapperPass() {
138 return new DependenceAnalysisWrapperPass();
Sebastian Pop59b61b92012-10-11 07:32:34 +0000139}
140
Chandler Carruth49c22192016-05-12 22:19:39 +0000141bool DependenceAnalysisWrapperPass::runOnFunction(Function &F) {
142 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
143 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
144 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
145 info.reset(new DependenceInfo(&F, &AA, &SE, &LI));
Sebastian Pop59b61b92012-10-11 07:32:34 +0000146 return false;
147}
148
Chandler Carruth49c22192016-05-12 22:19:39 +0000149DependenceInfo &DependenceAnalysisWrapperPass::getDI() const { return *info; }
Sebastian Pop59b61b92012-10-11 07:32:34 +0000150
Chandler Carruth49c22192016-05-12 22:19:39 +0000151void DependenceAnalysisWrapperPass::releaseMemory() { info.reset(); }
Sebastian Pop59b61b92012-10-11 07:32:34 +0000152
Chandler Carruth49c22192016-05-12 22:19:39 +0000153void DependenceAnalysisWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
Sebastian Pop59b61b92012-10-11 07:32:34 +0000154 AU.setPreservesAll();
Chandler Carruth7b560d42015-09-09 17:55:00 +0000155 AU.addRequiredTransitive<AAResultsWrapperPass>();
Chandler Carruth2f1fd162015-08-17 02:08:17 +0000156 AU.addRequiredTransitive<ScalarEvolutionWrapperPass>();
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000157 AU.addRequiredTransitive<LoopInfoWrapperPass>();
Sebastian Pop59b61b92012-10-11 07:32:34 +0000158}
159
160
161// Used to test the dependence analyzer.
Benjamin Kramer3eb15632012-11-13 12:12:02 +0000162// Looks through the function, noting loads and stores.
163// Calls depends() on every possible pair and prints out the result.
Sebastian Pop59b61b92012-10-11 07:32:34 +0000164// Ignores all other instructions.
Chandler Carruth49c22192016-05-12 22:19:39 +0000165static void dumpExampleDependence(raw_ostream &OS, DependenceInfo *DA) {
166 auto *F = DA->getFunction();
167 for (inst_iterator SrcI = inst_begin(F), SrcE = inst_end(F); SrcI != SrcE;
168 ++SrcI) {
Benjamin Kramer3eb15632012-11-13 12:12:02 +0000169 if (isa<StoreInst>(*SrcI) || isa<LoadInst>(*SrcI)) {
Sebastian Pop59b61b92012-10-11 07:32:34 +0000170 for (inst_iterator DstI = SrcI, DstE = inst_end(F);
171 DstI != DstE; ++DstI) {
Benjamin Kramer3eb15632012-11-13 12:12:02 +0000172 if (isa<StoreInst>(*DstI) || isa<LoadInst>(*DstI)) {
Sebastian Pop59b61b92012-10-11 07:32:34 +0000173 OS << "da analyze - ";
Dylan Noblesmith2cae60e2014-08-25 00:28:39 +0000174 if (auto D = DA->depends(&*SrcI, &*DstI, true)) {
Sebastian Pop59b61b92012-10-11 07:32:34 +0000175 D->dump(OS);
176 for (unsigned Level = 1; Level <= D->getLevels(); Level++) {
177 if (D->isSplitable(Level)) {
178 OS << "da analyze - split level = " << Level;
Dylan Noblesmithd96ce662014-08-25 00:28:35 +0000179 OS << ", iteration = " << *DA->getSplitIteration(*D, Level);
Sebastian Pop59b61b92012-10-11 07:32:34 +0000180 OS << "!\n";
181 }
182 }
Sebastian Pop59b61b92012-10-11 07:32:34 +0000183 }
184 else
185 OS << "none!\n";
Sebastian Pop59b61b92012-10-11 07:32:34 +0000186 }
187 }
188 }
189 }
190}
191
Chandler Carruth49c22192016-05-12 22:19:39 +0000192void DependenceAnalysisWrapperPass::print(raw_ostream &OS,
193 const Module *) const {
194 dumpExampleDependence(OS, info.get());
Sebastian Pop59b61b92012-10-11 07:32:34 +0000195}
196
197//===----------------------------------------------------------------------===//
198// Dependence methods
199
200// Returns true if this is an input dependence.
201bool Dependence::isInput() const {
202 return Src->mayReadFromMemory() && Dst->mayReadFromMemory();
203}
204
205
206// Returns true if this is an output dependence.
207bool Dependence::isOutput() const {
208 return Src->mayWriteToMemory() && Dst->mayWriteToMemory();
209}
210
211
212// Returns true if this is an flow (aka true) dependence.
213bool Dependence::isFlow() const {
214 return Src->mayWriteToMemory() && Dst->mayReadFromMemory();
215}
216
217
218// Returns true if this is an anti dependence.
219bool Dependence::isAnti() const {
220 return Src->mayReadFromMemory() && Dst->mayWriteToMemory();
221}
222
223
224// Returns true if a particular level is scalar; that is,
225// if no subscript in the source or destination mention the induction
226// variable associated with the loop at this level.
227// Leave this out of line, so it will serve as a virtual method anchor
228bool Dependence::isScalar(unsigned level) const {
229 return false;
230}
231
232
233//===----------------------------------------------------------------------===//
234// FullDependence methods
235
NAKAMURA Takumi478559a2015-03-05 01:25:19 +0000236FullDependence::FullDependence(Instruction *Source, Instruction *Destination,
Sebastian Pop59b61b92012-10-11 07:32:34 +0000237 bool PossiblyLoopIndependent,
NAKAMURA Takumi478559a2015-03-05 01:25:19 +0000238 unsigned CommonLevels)
239 : Dependence(Source, Destination), Levels(CommonLevels),
240 LoopIndependent(PossiblyLoopIndependent) {
NAKAMURA Takumie110d642015-03-05 01:25:06 +0000241 Consistent = true;
David Blaikie47039dc2015-07-31 21:37:09 +0000242 if (CommonLevels)
243 DV = make_unique<DVEntry[]>(CommonLevels);
NAKAMURA Takumie110d642015-03-05 01:25:06 +0000244}
Sebastian Pop59b61b92012-10-11 07:32:34 +0000245
246// The rest are simple getters that hide the implementation.
247
248// getDirection - Returns the direction associated with a particular level.
249unsigned FullDependence::getDirection(unsigned Level) const {
250 assert(0 < Level && Level <= Levels && "Level out of range");
251 return DV[Level - 1].Direction;
252}
253
254
255// Returns the distance (or NULL) associated with a particular level.
256const SCEV *FullDependence::getDistance(unsigned Level) const {
257 assert(0 < Level && Level <= Levels && "Level out of range");
258 return DV[Level - 1].Distance;
259}
260
261
262// Returns true if a particular level is scalar; that is,
263// if no subscript in the source or destination mention the induction
264// variable associated with the loop at this level.
265bool FullDependence::isScalar(unsigned Level) const {
266 assert(0 < Level && Level <= Levels && "Level out of range");
267 return DV[Level - 1].Scalar;
268}
269
270
271// Returns true if peeling the first iteration from this loop
272// will break this dependence.
273bool FullDependence::isPeelFirst(unsigned Level) const {
274 assert(0 < Level && Level <= Levels && "Level out of range");
275 return DV[Level - 1].PeelFirst;
276}
277
278
279// Returns true if peeling the last iteration from this loop
280// will break this dependence.
281bool FullDependence::isPeelLast(unsigned Level) const {
282 assert(0 < Level && Level <= Levels && "Level out of range");
283 return DV[Level - 1].PeelLast;
284}
285
286
287// Returns true if splitting this loop will break the dependence.
288bool FullDependence::isSplitable(unsigned Level) const {
289 assert(0 < Level && Level <= Levels && "Level out of range");
290 return DV[Level - 1].Splitable;
291}
292
293
294//===----------------------------------------------------------------------===//
Chandler Carruth49c22192016-05-12 22:19:39 +0000295// DependenceInfo::Constraint methods
Sebastian Pop59b61b92012-10-11 07:32:34 +0000296
297// If constraint is a point <X, Y>, returns X.
298// Otherwise assert.
Chandler Carruth49c22192016-05-12 22:19:39 +0000299const SCEV *DependenceInfo::Constraint::getX() const {
Sebastian Pop59b61b92012-10-11 07:32:34 +0000300 assert(Kind == Point && "Kind should be Point");
301 return A;
302}
303
304
305// If constraint is a point <X, Y>, returns Y.
306// Otherwise assert.
Chandler Carruth49c22192016-05-12 22:19:39 +0000307const SCEV *DependenceInfo::Constraint::getY() const {
Sebastian Pop59b61b92012-10-11 07:32:34 +0000308 assert(Kind == Point && "Kind should be Point");
309 return B;
310}
311
312
313// If constraint is a line AX + BY = C, returns A.
314// Otherwise assert.
Chandler Carruth49c22192016-05-12 22:19:39 +0000315const SCEV *DependenceInfo::Constraint::getA() const {
Sebastian Pop59b61b92012-10-11 07:32:34 +0000316 assert((Kind == Line || Kind == Distance) &&
317 "Kind should be Line (or Distance)");
318 return A;
319}
320
321
322// If constraint is a line AX + BY = C, returns B.
323// Otherwise assert.
Chandler Carruth49c22192016-05-12 22:19:39 +0000324const SCEV *DependenceInfo::Constraint::getB() const {
Sebastian Pop59b61b92012-10-11 07:32:34 +0000325 assert((Kind == Line || Kind == Distance) &&
326 "Kind should be Line (or Distance)");
327 return B;
328}
329
330
331// If constraint is a line AX + BY = C, returns C.
332// Otherwise assert.
Chandler Carruth49c22192016-05-12 22:19:39 +0000333const SCEV *DependenceInfo::Constraint::getC() const {
Sebastian Pop59b61b92012-10-11 07:32:34 +0000334 assert((Kind == Line || Kind == Distance) &&
335 "Kind should be Line (or Distance)");
336 return C;
337}
338
339
340// If constraint is a distance, returns D.
341// Otherwise assert.
Chandler Carruth49c22192016-05-12 22:19:39 +0000342const SCEV *DependenceInfo::Constraint::getD() const {
Sebastian Pop59b61b92012-10-11 07:32:34 +0000343 assert(Kind == Distance && "Kind should be Distance");
344 return SE->getNegativeSCEV(C);
345}
346
347
348// Returns the loop associated with this constraint.
Chandler Carruth49c22192016-05-12 22:19:39 +0000349const Loop *DependenceInfo::Constraint::getAssociatedLoop() const {
Sebastian Pop59b61b92012-10-11 07:32:34 +0000350 assert((Kind == Distance || Kind == Line || Kind == Point) &&
351 "Kind should be Distance, Line, or Point");
352 return AssociatedLoop;
353}
354
Chandler Carruth49c22192016-05-12 22:19:39 +0000355void DependenceInfo::Constraint::setPoint(const SCEV *X, const SCEV *Y,
356 const Loop *CurLoop) {
Sebastian Pop59b61b92012-10-11 07:32:34 +0000357 Kind = Point;
358 A = X;
359 B = Y;
360 AssociatedLoop = CurLoop;
361}
362
Chandler Carruth49c22192016-05-12 22:19:39 +0000363void DependenceInfo::Constraint::setLine(const SCEV *AA, const SCEV *BB,
364 const SCEV *CC, const Loop *CurLoop) {
Sebastian Pop59b61b92012-10-11 07:32:34 +0000365 Kind = Line;
366 A = AA;
367 B = BB;
368 C = CC;
369 AssociatedLoop = CurLoop;
370}
371
Chandler Carruth49c22192016-05-12 22:19:39 +0000372void DependenceInfo::Constraint::setDistance(const SCEV *D,
373 const Loop *CurLoop) {
Sebastian Pop59b61b92012-10-11 07:32:34 +0000374 Kind = Distance;
Sanjoy Das2aacc0e2015-09-23 01:59:04 +0000375 A = SE->getOne(D->getType());
Sebastian Pop59b61b92012-10-11 07:32:34 +0000376 B = SE->getNegativeSCEV(A);
377 C = SE->getNegativeSCEV(D);
378 AssociatedLoop = CurLoop;
379}
380
Chandler Carruth49c22192016-05-12 22:19:39 +0000381void DependenceInfo::Constraint::setEmpty() { Kind = Empty; }
Sebastian Pop59b61b92012-10-11 07:32:34 +0000382
Chandler Carruth49c22192016-05-12 22:19:39 +0000383void DependenceInfo::Constraint::setAny(ScalarEvolution *NewSE) {
Sebastian Pop59b61b92012-10-11 07:32:34 +0000384 SE = NewSE;
385 Kind = Any;
386}
387
Aaron Ballman615eb472017-10-15 14:32:27 +0000388#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Sebastian Pop59b61b92012-10-11 07:32:34 +0000389// For debugging purposes. Dumps the constraint out to OS.
Matthias Braun8c209aa2017-01-28 02:02:38 +0000390LLVM_DUMP_METHOD void DependenceInfo::Constraint::dump(raw_ostream &OS) const {
Sebastian Pop59b61b92012-10-11 07:32:34 +0000391 if (isEmpty())
392 OS << " Empty\n";
393 else if (isAny())
394 OS << " Any\n";
395 else if (isPoint())
396 OS << " Point is <" << *getX() << ", " << *getY() << ">\n";
397 else if (isDistance())
398 OS << " Distance is " << *getD() <<
399 " (" << *getA() << "*X + " << *getB() << "*Y = " << *getC() << ")\n";
400 else if (isLine())
401 OS << " Line is " << *getA() << "*X + " <<
402 *getB() << "*Y = " << *getC() << "\n";
403 else
404 llvm_unreachable("unknown constraint type in Constraint::dump");
405}
Matthias Braun8c209aa2017-01-28 02:02:38 +0000406#endif
Sebastian Pop59b61b92012-10-11 07:32:34 +0000407
408
409// Updates X with the intersection
410// of the Constraints X and Y. Returns true if X has changed.
411// Corresponds to Figure 4 from the paper
412//
413// Practical Dependence Testing
414// Goff, Kennedy, Tseng
415// PLDI 1991
Chandler Carruth49c22192016-05-12 22:19:39 +0000416bool DependenceInfo::intersectConstraints(Constraint *X, const Constraint *Y) {
Sebastian Pop59b61b92012-10-11 07:32:34 +0000417 ++DeltaApplications;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000418 LLVM_DEBUG(dbgs() << "\tintersect constraints\n");
419 LLVM_DEBUG(dbgs() << "\t X ="; X->dump(dbgs()));
420 LLVM_DEBUG(dbgs() << "\t Y ="; Y->dump(dbgs()));
Sebastian Pop59b61b92012-10-11 07:32:34 +0000421 assert(!Y->isPoint() && "Y must not be a Point");
422 if (X->isAny()) {
423 if (Y->isAny())
424 return false;
425 *X = *Y;
426 return true;
427 }
428 if (X->isEmpty())
429 return false;
430 if (Y->isEmpty()) {
431 X->setEmpty();
432 return true;
433 }
434
435 if (X->isDistance() && Y->isDistance()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000436 LLVM_DEBUG(dbgs() << "\t intersect 2 distances\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +0000437 if (isKnownPredicate(CmpInst::ICMP_EQ, X->getD(), Y->getD()))
438 return false;
439 if (isKnownPredicate(CmpInst::ICMP_NE, X->getD(), Y->getD())) {
440 X->setEmpty();
441 ++DeltaSuccesses;
442 return true;
443 }
444 // Hmmm, interesting situation.
445 // I guess if either is constant, keep it and ignore the other.
446 if (isa<SCEVConstant>(Y->getD())) {
447 *X = *Y;
448 return true;
449 }
450 return false;
451 }
452
453 // At this point, the pseudo-code in Figure 4 of the paper
454 // checks if (X->isPoint() && Y->isPoint()).
455 // This case can't occur in our implementation,
456 // since a Point can only arise as the result of intersecting
457 // two Line constraints, and the right-hand value, Y, is never
458 // the result of an intersection.
459 assert(!(X->isPoint() && Y->isPoint()) &&
460 "We shouldn't ever see X->isPoint() && Y->isPoint()");
461
462 if (X->isLine() && Y->isLine()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000463 LLVM_DEBUG(dbgs() << "\t intersect 2 lines\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +0000464 const SCEV *Prod1 = SE->getMulExpr(X->getA(), Y->getB());
465 const SCEV *Prod2 = SE->getMulExpr(X->getB(), Y->getA());
466 if (isKnownPredicate(CmpInst::ICMP_EQ, Prod1, Prod2)) {
467 // slopes are equal, so lines are parallel
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000468 LLVM_DEBUG(dbgs() << "\t\tsame slope\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +0000469 Prod1 = SE->getMulExpr(X->getC(), Y->getB());
470 Prod2 = SE->getMulExpr(X->getB(), Y->getC());
471 if (isKnownPredicate(CmpInst::ICMP_EQ, Prod1, Prod2))
472 return false;
473 if (isKnownPredicate(CmpInst::ICMP_NE, Prod1, Prod2)) {
474 X->setEmpty();
475 ++DeltaSuccesses;
476 return true;
477 }
478 return false;
479 }
480 if (isKnownPredicate(CmpInst::ICMP_NE, Prod1, Prod2)) {
481 // slopes differ, so lines intersect
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000482 LLVM_DEBUG(dbgs() << "\t\tdifferent slopes\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +0000483 const SCEV *C1B2 = SE->getMulExpr(X->getC(), Y->getB());
484 const SCEV *C1A2 = SE->getMulExpr(X->getC(), Y->getA());
485 const SCEV *C2B1 = SE->getMulExpr(Y->getC(), X->getB());
486 const SCEV *C2A1 = SE->getMulExpr(Y->getC(), X->getA());
487 const SCEV *A1B2 = SE->getMulExpr(X->getA(), Y->getB());
488 const SCEV *A2B1 = SE->getMulExpr(Y->getA(), X->getB());
489 const SCEVConstant *C1A2_C2A1 =
490 dyn_cast<SCEVConstant>(SE->getMinusSCEV(C1A2, C2A1));
491 const SCEVConstant *C1B2_C2B1 =
492 dyn_cast<SCEVConstant>(SE->getMinusSCEV(C1B2, C2B1));
493 const SCEVConstant *A1B2_A2B1 =
494 dyn_cast<SCEVConstant>(SE->getMinusSCEV(A1B2, A2B1));
495 const SCEVConstant *A2B1_A1B2 =
496 dyn_cast<SCEVConstant>(SE->getMinusSCEV(A2B1, A1B2));
497 if (!C1B2_C2B1 || !C1A2_C2A1 ||
498 !A1B2_A2B1 || !A2B1_A1B2)
499 return false;
Sanjoy Das0de2fec2015-12-17 20:28:46 +0000500 APInt Xtop = C1B2_C2B1->getAPInt();
501 APInt Xbot = A1B2_A2B1->getAPInt();
502 APInt Ytop = C1A2_C2A1->getAPInt();
503 APInt Ybot = A2B1_A1B2->getAPInt();
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000504 LLVM_DEBUG(dbgs() << "\t\tXtop = " << Xtop << "\n");
505 LLVM_DEBUG(dbgs() << "\t\tXbot = " << Xbot << "\n");
506 LLVM_DEBUG(dbgs() << "\t\tYtop = " << Ytop << "\n");
507 LLVM_DEBUG(dbgs() << "\t\tYbot = " << Ybot << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +0000508 APInt Xq = Xtop; // these need to be initialized, even
509 APInt Xr = Xtop; // though they're just going to be overwritten
510 APInt::sdivrem(Xtop, Xbot, Xq, Xr);
511 APInt Yq = Ytop;
Jakub Staszak340c7802013-08-06 16:40:40 +0000512 APInt Yr = Ytop;
Sebastian Pop59b61b92012-10-11 07:32:34 +0000513 APInt::sdivrem(Ytop, Ybot, Yq, Yr);
514 if (Xr != 0 || Yr != 0) {
515 X->setEmpty();
516 ++DeltaSuccesses;
517 return true;
518 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000519 LLVM_DEBUG(dbgs() << "\t\tX = " << Xq << ", Y = " << Yq << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +0000520 if (Xq.slt(0) || Yq.slt(0)) {
521 X->setEmpty();
522 ++DeltaSuccesses;
523 return true;
524 }
525 if (const SCEVConstant *CUB =
526 collectConstantUpperBound(X->getAssociatedLoop(), Prod1->getType())) {
Benjamin Kramer46e38f32016-06-08 10:01:20 +0000527 const APInt &UpperBound = CUB->getAPInt();
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000528 LLVM_DEBUG(dbgs() << "\t\tupper bound = " << UpperBound << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +0000529 if (Xq.sgt(UpperBound) || Yq.sgt(UpperBound)) {
530 X->setEmpty();
531 ++DeltaSuccesses;
532 return true;
533 }
534 }
535 X->setPoint(SE->getConstant(Xq),
536 SE->getConstant(Yq),
537 X->getAssociatedLoop());
538 ++DeltaSuccesses;
539 return true;
540 }
541 return false;
542 }
543
544 // if (X->isLine() && Y->isPoint()) This case can't occur.
545 assert(!(X->isLine() && Y->isPoint()) && "This case should never occur");
546
547 if (X->isPoint() && Y->isLine()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000548 LLVM_DEBUG(dbgs() << "\t intersect Point and Line\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +0000549 const SCEV *A1X1 = SE->getMulExpr(Y->getA(), X->getX());
550 const SCEV *B1Y1 = SE->getMulExpr(Y->getB(), X->getY());
551 const SCEV *Sum = SE->getAddExpr(A1X1, B1Y1);
552 if (isKnownPredicate(CmpInst::ICMP_EQ, Sum, Y->getC()))
553 return false;
554 if (isKnownPredicate(CmpInst::ICMP_NE, Sum, Y->getC())) {
555 X->setEmpty();
556 ++DeltaSuccesses;
557 return true;
558 }
559 return false;
560 }
561
562 llvm_unreachable("shouldn't reach the end of Constraint intersection");
563 return false;
564}
565
566
567//===----------------------------------------------------------------------===//
Chandler Carruth49c22192016-05-12 22:19:39 +0000568// DependenceInfo methods
Sebastian Pop59b61b92012-10-11 07:32:34 +0000569
570// For debugging purposes. Dumps a dependence to OS.
571void Dependence::dump(raw_ostream &OS) const {
572 bool Splitable = false;
573 if (isConfused())
574 OS << "confused";
575 else {
576 if (isConsistent())
577 OS << "consistent ";
578 if (isFlow())
579 OS << "flow";
580 else if (isOutput())
581 OS << "output";
582 else if (isAnti())
583 OS << "anti";
584 else if (isInput())
585 OS << "input";
586 unsigned Levels = getLevels();
Preston Briggsfd0b5c82012-11-30 00:44:47 +0000587 OS << " [";
588 for (unsigned II = 1; II <= Levels; ++II) {
589 if (isSplitable(II))
590 Splitable = true;
591 if (isPeelFirst(II))
592 OS << 'p';
593 const SCEV *Distance = getDistance(II);
594 if (Distance)
595 OS << *Distance;
596 else if (isScalar(II))
597 OS << "S";
598 else {
599 unsigned Direction = getDirection(II);
600 if (Direction == DVEntry::ALL)
601 OS << "*";
Sebastian Pop59b61b92012-10-11 07:32:34 +0000602 else {
Preston Briggsfd0b5c82012-11-30 00:44:47 +0000603 if (Direction & DVEntry::LT)
604 OS << "<";
605 if (Direction & DVEntry::EQ)
606 OS << "=";
607 if (Direction & DVEntry::GT)
608 OS << ">";
Sebastian Pop59b61b92012-10-11 07:32:34 +0000609 }
Sebastian Pop59b61b92012-10-11 07:32:34 +0000610 }
Preston Briggsfd0b5c82012-11-30 00:44:47 +0000611 if (isPeelLast(II))
612 OS << 'p';
613 if (II < Levels)
614 OS << " ";
Sebastian Pop59b61b92012-10-11 07:32:34 +0000615 }
Preston Briggsfd0b5c82012-11-30 00:44:47 +0000616 if (isLoopIndependent())
617 OS << "|<";
618 OS << "]";
619 if (Splitable)
620 OS << " splitable";
Sebastian Pop59b61b92012-10-11 07:32:34 +0000621 }
622 OS << "!\n";
623}
624
David Green5ef933b2018-04-10 11:37:21 +0000625// Returns NoAlias/MayAliass/MustAlias for two memory locations based upon their
626// underlaying objects. If LocA and LocB are known to not alias (for any reason:
627// tbaa, non-overlapping regions etc), then it is known there is no dependecy.
628// Otherwise the underlying objects are checked to see if they point to
629// different identifiable objects.
Chandler Carruthc3f49eb2015-06-22 02:16:51 +0000630static AliasResult underlyingObjectsAlias(AliasAnalysis *AA,
David Green5ef933b2018-04-10 11:37:21 +0000631 const DataLayout &DL,
632 const MemoryLocation &LocA,
633 const MemoryLocation &LocB) {
634 // Check the original locations (minus size) for noalias, which can happen for
635 // tbaa, incompatible underlying object locations, etc.
636 MemoryLocation LocAS(LocA.Ptr, MemoryLocation::UnknownSize, LocA.AATags);
637 MemoryLocation LocBS(LocB.Ptr, MemoryLocation::UnknownSize, LocB.AATags);
638 if (AA->alias(LocAS, LocBS) == NoAlias)
639 return NoAlias;
640
641 // Check the underlying objects are the same
642 const Value *AObj = GetUnderlyingObject(LocA.Ptr, DL);
643 const Value *BObj = GetUnderlyingObject(LocB.Ptr, DL);
644
645 // If the underlying objects are the same, they must alias
646 if (AObj == BObj)
647 return MustAlias;
648
649 // We may have hit the recursion limit for underlying objects, or have
650 // underlying objects where we don't know they will alias.
651 if (!isIdentifiedObject(AObj) || !isIdentifiedObject(BObj))
652 return MayAlias;
653
654 // Otherwise we know the objects are different and both identified objects so
655 // must not alias.
656 return NoAlias;
Sebastian Pop59b61b92012-10-11 07:32:34 +0000657}
658
659
660// Returns true if the load or store can be analyzed. Atomic and volatile
661// operations have properties which this analysis does not understand.
662static
663bool isLoadOrStore(const Instruction *I) {
664 if (const LoadInst *LI = dyn_cast<LoadInst>(I))
665 return LI->isUnordered();
666 else if (const StoreInst *SI = dyn_cast<StoreInst>(I))
667 return SI->isUnordered();
668 return false;
669}
670
671
Sebastian Pop59b61b92012-10-11 07:32:34 +0000672// Examines the loop nesting of the Src and Dst
673// instructions and establishes their shared loops. Sets the variables
674// CommonLevels, SrcLevels, and MaxLevels.
675// The source and destination instructions needn't be contained in the same
676// loop. The routine establishNestingLevels finds the level of most deeply
677// nested loop that contains them both, CommonLevels. An instruction that's
678// not contained in a loop is at level = 0. MaxLevels is equal to the level
679// of the source plus the level of the destination, minus CommonLevels.
680// This lets us allocate vectors MaxLevels in length, with room for every
681// distinct loop referenced in both the source and destination subscripts.
682// The variable SrcLevels is the nesting depth of the source instruction.
683// It's used to help calculate distinct loops referenced by the destination.
684// Here's the map from loops to levels:
685// 0 - unused
686// 1 - outermost common loop
687// ... - other common loops
688// CommonLevels - innermost common loop
689// ... - loops containing Src but not Dst
690// SrcLevels - innermost loop containing Src but not Dst
691// ... - loops containing Dst but not Src
692// MaxLevels - innermost loops containing Dst but not Src
693// Consider the follow code fragment:
694// for (a = ...) {
695// for (b = ...) {
696// for (c = ...) {
697// for (d = ...) {
698// A[] = ...;
699// }
700// }
701// for (e = ...) {
702// for (f = ...) {
703// for (g = ...) {
704// ... = A[];
705// }
706// }
707// }
708// }
709// }
710// If we're looking at the possibility of a dependence between the store
711// to A (the Src) and the load from A (the Dst), we'll note that they
712// have 2 loops in common, so CommonLevels will equal 2 and the direction
713// vector for Result will have 2 entries. SrcLevels = 4 and MaxLevels = 7.
714// A map from loop names to loop numbers would look like
715// a - 1
716// b - 2 = CommonLevels
717// c - 3
718// d - 4 = SrcLevels
719// e - 5
720// f - 6
721// g - 7 = MaxLevels
Chandler Carruth49c22192016-05-12 22:19:39 +0000722void DependenceInfo::establishNestingLevels(const Instruction *Src,
723 const Instruction *Dst) {
Sebastian Pop59b61b92012-10-11 07:32:34 +0000724 const BasicBlock *SrcBlock = Src->getParent();
725 const BasicBlock *DstBlock = Dst->getParent();
726 unsigned SrcLevel = LI->getLoopDepth(SrcBlock);
727 unsigned DstLevel = LI->getLoopDepth(DstBlock);
728 const Loop *SrcLoop = LI->getLoopFor(SrcBlock);
729 const Loop *DstLoop = LI->getLoopFor(DstBlock);
730 SrcLevels = SrcLevel;
731 MaxLevels = SrcLevel + DstLevel;
732 while (SrcLevel > DstLevel) {
733 SrcLoop = SrcLoop->getParentLoop();
734 SrcLevel--;
735 }
736 while (DstLevel > SrcLevel) {
737 DstLoop = DstLoop->getParentLoop();
738 DstLevel--;
739 }
740 while (SrcLoop != DstLoop) {
741 SrcLoop = SrcLoop->getParentLoop();
742 DstLoop = DstLoop->getParentLoop();
743 SrcLevel--;
744 }
745 CommonLevels = SrcLevel;
746 MaxLevels -= CommonLevels;
747}
748
749
750// Given one of the loops containing the source, return
751// its level index in our numbering scheme.
Chandler Carruth49c22192016-05-12 22:19:39 +0000752unsigned DependenceInfo::mapSrcLoop(const Loop *SrcLoop) const {
Sebastian Pop59b61b92012-10-11 07:32:34 +0000753 return SrcLoop->getLoopDepth();
754}
755
756
757// Given one of the loops containing the destination,
758// return its level index in our numbering scheme.
Chandler Carruth49c22192016-05-12 22:19:39 +0000759unsigned DependenceInfo::mapDstLoop(const Loop *DstLoop) const {
Sebastian Pop59b61b92012-10-11 07:32:34 +0000760 unsigned D = DstLoop->getLoopDepth();
761 if (D > CommonLevels)
762 return D - CommonLevels + SrcLevels;
763 else
764 return D;
765}
766
767
768// Returns true if Expression is loop invariant in LoopNest.
Chandler Carruth49c22192016-05-12 22:19:39 +0000769bool DependenceInfo::isLoopInvariant(const SCEV *Expression,
770 const Loop *LoopNest) const {
Sebastian Pop59b61b92012-10-11 07:32:34 +0000771 if (!LoopNest)
772 return true;
773 return SE->isLoopInvariant(Expression, LoopNest) &&
774 isLoopInvariant(Expression, LoopNest->getParentLoop());
775}
776
777
778
779// Finds the set of loops from the LoopNest that
780// have a level <= CommonLevels and are referred to by the SCEV Expression.
Chandler Carruth49c22192016-05-12 22:19:39 +0000781void DependenceInfo::collectCommonLoops(const SCEV *Expression,
782 const Loop *LoopNest,
783 SmallBitVector &Loops) const {
Sebastian Pop59b61b92012-10-11 07:32:34 +0000784 while (LoopNest) {
785 unsigned Level = LoopNest->getLoopDepth();
786 if (Level <= CommonLevels && !SE->isLoopInvariant(Expression, LoopNest))
787 Loops.set(Level);
788 LoopNest = LoopNest->getParentLoop();
789 }
790}
791
Chandler Carruth49c22192016-05-12 22:19:39 +0000792void DependenceInfo::unifySubscriptType(ArrayRef<Subscript *> Pairs) {
Jingyue Wua84feb12015-05-29 16:58:08 +0000793
794 unsigned widestWidthSeen = 0;
795 Type *widestType;
796
797 // Go through each pair and find the widest bit to which we need
798 // to extend all of them.
Benjamin Krameraa209152016-06-26 17:27:42 +0000799 for (Subscript *Pair : Pairs) {
800 const SCEV *Src = Pair->Src;
801 const SCEV *Dst = Pair->Dst;
Jingyue Wua84feb12015-05-29 16:58:08 +0000802 IntegerType *SrcTy = dyn_cast<IntegerType>(Src->getType());
803 IntegerType *DstTy = dyn_cast<IntegerType>(Dst->getType());
804 if (SrcTy == nullptr || DstTy == nullptr) {
805 assert(SrcTy == DstTy && "This function only unify integer types and "
806 "expect Src and Dst share the same type "
807 "otherwise.");
808 continue;
809 }
810 if (SrcTy->getBitWidth() > widestWidthSeen) {
811 widestWidthSeen = SrcTy->getBitWidth();
812 widestType = SrcTy;
813 }
814 if (DstTy->getBitWidth() > widestWidthSeen) {
815 widestWidthSeen = DstTy->getBitWidth();
816 widestType = DstTy;
817 }
Jingyue Wu0fa125a2014-11-16 16:52:44 +0000818 }
Jingyue Wua84feb12015-05-29 16:58:08 +0000819
820
821 assert(widestWidthSeen > 0);
822
823 // Now extend each pair to the widest seen.
Benjamin Krameraa209152016-06-26 17:27:42 +0000824 for (Subscript *Pair : Pairs) {
825 const SCEV *Src = Pair->Src;
826 const SCEV *Dst = Pair->Dst;
Jingyue Wua84feb12015-05-29 16:58:08 +0000827 IntegerType *SrcTy = dyn_cast<IntegerType>(Src->getType());
828 IntegerType *DstTy = dyn_cast<IntegerType>(Dst->getType());
829 if (SrcTy == nullptr || DstTy == nullptr) {
830 assert(SrcTy == DstTy && "This function only unify integer types and "
831 "expect Src and Dst share the same type "
832 "otherwise.");
833 continue;
834 }
835 if (SrcTy->getBitWidth() < widestWidthSeen)
836 // Sign-extend Src to widestType
Benjamin Krameraa209152016-06-26 17:27:42 +0000837 Pair->Src = SE->getSignExtendExpr(Src, widestType);
Jingyue Wua84feb12015-05-29 16:58:08 +0000838 if (DstTy->getBitWidth() < widestWidthSeen) {
839 // Sign-extend Dst to widestType
Benjamin Krameraa209152016-06-26 17:27:42 +0000840 Pair->Dst = SE->getSignExtendExpr(Dst, widestType);
Jingyue Wua84feb12015-05-29 16:58:08 +0000841 }
Jingyue Wu0fa125a2014-11-16 16:52:44 +0000842 }
843}
Sebastian Pop59b61b92012-10-11 07:32:34 +0000844
845// removeMatchingExtensions - Examines a subscript pair.
846// If the source and destination are identically sign (or zero)
847// extended, it strips off the extension in an effect to simplify
848// the actual analysis.
Chandler Carruth49c22192016-05-12 22:19:39 +0000849void DependenceInfo::removeMatchingExtensions(Subscript *Pair) {
Sebastian Pop59b61b92012-10-11 07:32:34 +0000850 const SCEV *Src = Pair->Src;
851 const SCEV *Dst = Pair->Dst;
852 if ((isa<SCEVZeroExtendExpr>(Src) && isa<SCEVZeroExtendExpr>(Dst)) ||
853 (isa<SCEVSignExtendExpr>(Src) && isa<SCEVSignExtendExpr>(Dst))) {
854 const SCEVCastExpr *SrcCast = cast<SCEVCastExpr>(Src);
855 const SCEVCastExpr *DstCast = cast<SCEVCastExpr>(Dst);
Jingyue Wu0fa125a2014-11-16 16:52:44 +0000856 const SCEV *SrcCastOp = SrcCast->getOperand();
857 const SCEV *DstCastOp = DstCast->getOperand();
858 if (SrcCastOp->getType() == DstCastOp->getType()) {
859 Pair->Src = SrcCastOp;
860 Pair->Dst = DstCastOp;
Sebastian Pop59b61b92012-10-11 07:32:34 +0000861 }
862 }
863}
864
865
866// Examine the scev and return true iff it's linear.
867// Collect any loops mentioned in the set of "Loops".
Chandler Carruth49c22192016-05-12 22:19:39 +0000868bool DependenceInfo::checkSrcSubscript(const SCEV *Src, const Loop *LoopNest,
869 SmallBitVector &Loops) {
Sebastian Pop59b61b92012-10-11 07:32:34 +0000870 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Src);
871 if (!AddRec)
872 return isLoopInvariant(Src, LoopNest);
873 const SCEV *Start = AddRec->getStart();
874 const SCEV *Step = AddRec->getStepRecurrence(*SE);
James Molloyc0661ae2015-05-15 12:17:22 +0000875 const SCEV *UB = SE->getBackedgeTakenCount(AddRec->getLoop());
876 if (!isa<SCEVCouldNotCompute>(UB)) {
877 if (SE->getTypeSizeInBits(Start->getType()) <
878 SE->getTypeSizeInBits(UB->getType())) {
879 if (!AddRec->getNoWrapFlags())
880 return false;
881 }
882 }
Sebastian Pop59b61b92012-10-11 07:32:34 +0000883 if (!isLoopInvariant(Step, LoopNest))
884 return false;
885 Loops.set(mapSrcLoop(AddRec->getLoop()));
886 return checkSrcSubscript(Start, LoopNest, Loops);
887}
888
889
890
891// Examine the scev and return true iff it's linear.
892// Collect any loops mentioned in the set of "Loops".
Chandler Carruth49c22192016-05-12 22:19:39 +0000893bool DependenceInfo::checkDstSubscript(const SCEV *Dst, const Loop *LoopNest,
894 SmallBitVector &Loops) {
Sebastian Pop59b61b92012-10-11 07:32:34 +0000895 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Dst);
896 if (!AddRec)
897 return isLoopInvariant(Dst, LoopNest);
898 const SCEV *Start = AddRec->getStart();
899 const SCEV *Step = AddRec->getStepRecurrence(*SE);
James Molloyc0661ae2015-05-15 12:17:22 +0000900 const SCEV *UB = SE->getBackedgeTakenCount(AddRec->getLoop());
901 if (!isa<SCEVCouldNotCompute>(UB)) {
902 if (SE->getTypeSizeInBits(Start->getType()) <
903 SE->getTypeSizeInBits(UB->getType())) {
904 if (!AddRec->getNoWrapFlags())
905 return false;
906 }
907 }
Sebastian Pop59b61b92012-10-11 07:32:34 +0000908 if (!isLoopInvariant(Step, LoopNest))
909 return false;
910 Loops.set(mapDstLoop(AddRec->getLoop()));
911 return checkDstSubscript(Start, LoopNest, Loops);
912}
913
914
915// Examines the subscript pair (the Src and Dst SCEVs)
916// and classifies it as either ZIV, SIV, RDIV, MIV, or Nonlinear.
917// Collects the associated loops in a set.
Chandler Carruth49c22192016-05-12 22:19:39 +0000918DependenceInfo::Subscript::ClassificationKind
919DependenceInfo::classifyPair(const SCEV *Src, const Loop *SrcLoopNest,
920 const SCEV *Dst, const Loop *DstLoopNest,
921 SmallBitVector &Loops) {
Sebastian Pop59b61b92012-10-11 07:32:34 +0000922 SmallBitVector SrcLoops(MaxLevels + 1);
923 SmallBitVector DstLoops(MaxLevels + 1);
924 if (!checkSrcSubscript(Src, SrcLoopNest, SrcLoops))
925 return Subscript::NonLinear;
926 if (!checkDstSubscript(Dst, DstLoopNest, DstLoops))
927 return Subscript::NonLinear;
928 Loops = SrcLoops;
929 Loops |= DstLoops;
930 unsigned N = Loops.count();
931 if (N == 0)
932 return Subscript::ZIV;
933 if (N == 1)
934 return Subscript::SIV;
935 if (N == 2 && (SrcLoops.count() == 0 ||
936 DstLoops.count() == 0 ||
937 (SrcLoops.count() == 1 && DstLoops.count() == 1)))
938 return Subscript::RDIV;
939 return Subscript::MIV;
940}
941
942
943// A wrapper around SCEV::isKnownPredicate.
944// Looks for cases where we're interested in comparing for equality.
945// If both X and Y have been identically sign or zero extended,
946// it strips off the (confusing) extensions before invoking
947// SCEV::isKnownPredicate. Perhaps, someday, the ScalarEvolution package
948// will be similarly updated.
949//
950// If SCEV::isKnownPredicate can't prove the predicate,
951// we try simple subtraction, which seems to help in some cases
952// involving symbolics.
Chandler Carruth49c22192016-05-12 22:19:39 +0000953bool DependenceInfo::isKnownPredicate(ICmpInst::Predicate Pred, const SCEV *X,
954 const SCEV *Y) const {
Sebastian Pop59b61b92012-10-11 07:32:34 +0000955 if (Pred == CmpInst::ICMP_EQ ||
956 Pred == CmpInst::ICMP_NE) {
957 if ((isa<SCEVSignExtendExpr>(X) &&
958 isa<SCEVSignExtendExpr>(Y)) ||
959 (isa<SCEVZeroExtendExpr>(X) &&
960 isa<SCEVZeroExtendExpr>(Y))) {
961 const SCEVCastExpr *CX = cast<SCEVCastExpr>(X);
962 const SCEVCastExpr *CY = cast<SCEVCastExpr>(Y);
963 const SCEV *Xop = CX->getOperand();
964 const SCEV *Yop = CY->getOperand();
965 if (Xop->getType() == Yop->getType()) {
966 X = Xop;
967 Y = Yop;
968 }
969 }
970 }
971 if (SE->isKnownPredicate(Pred, X, Y))
972 return true;
973 // If SE->isKnownPredicate can't prove the condition,
974 // we try the brute-force approach of subtracting
975 // and testing the difference.
976 // By testing with SE->isKnownPredicate first, we avoid
977 // the possibility of overflow when the arguments are constants.
978 const SCEV *Delta = SE->getMinusSCEV(X, Y);
979 switch (Pred) {
980 case CmpInst::ICMP_EQ:
981 return Delta->isZero();
982 case CmpInst::ICMP_NE:
983 return SE->isKnownNonZero(Delta);
984 case CmpInst::ICMP_SGE:
985 return SE->isKnownNonNegative(Delta);
986 case CmpInst::ICMP_SLE:
987 return SE->isKnownNonPositive(Delta);
988 case CmpInst::ICMP_SGT:
989 return SE->isKnownPositive(Delta);
990 case CmpInst::ICMP_SLT:
991 return SE->isKnownNegative(Delta);
992 default:
993 llvm_unreachable("unexpected predicate in isKnownPredicate");
994 }
995}
996
David Greend143c652018-06-21 11:53:16 +0000997/// Compare to see if S is less than Size, using isKnownNegative(S - max(Size, 1))
998/// with some extra checking if S is an AddRec and we can prove less-than using
999/// the loop bounds.
1000bool DependenceInfo::isKnownLessThan(const SCEV *S, const SCEV *Size) const {
1001 // First unify to the same type
1002 auto *SType = dyn_cast<IntegerType>(S->getType());
1003 auto *SizeType = dyn_cast<IntegerType>(Size->getType());
1004 if (!SType || !SizeType)
1005 return false;
1006 Type *MaxType =
1007 (SType->getBitWidth() >= SizeType->getBitWidth()) ? SType : SizeType;
1008 S = SE->getTruncateOrZeroExtend(S, MaxType);
1009 Size = SE->getTruncateOrZeroExtend(Size, MaxType);
1010
1011 // Special check for addrecs using BE taken count
1012 const SCEV *Bound = SE->getMinusSCEV(S, Size);
1013 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Bound)) {
1014 if (AddRec->isAffine()) {
1015 const SCEV *BECount = SE->getBackedgeTakenCount(AddRec->getLoop());
1016 if (!isa<SCEVCouldNotCompute>(BECount)) {
1017 const SCEV *Limit = AddRec->evaluateAtIteration(BECount, *SE);
1018 if (SE->isKnownNegative(Limit))
1019 return true;
1020 }
1021 }
1022 }
1023
1024 // Check using normal isKnownNegative
1025 const SCEV *LimitedBound =
1026 SE->getMinusSCEV(S, SE->getSMaxExpr(Size, SE->getOne(Size->getType())));
1027 return SE->isKnownNegative(LimitedBound);
1028}
Sebastian Pop59b61b92012-10-11 07:32:34 +00001029
1030// All subscripts are all the same type.
1031// Loop bound may be smaller (e.g., a char).
1032// Should zero extend loop bound, since it's always >= 0.
James Molloyc0661ae2015-05-15 12:17:22 +00001033// This routine collects upper bound and extends or truncates if needed.
1034// Truncating is safe when subscripts are known not to wrap. Cases without
1035// nowrap flags should have been rejected earlier.
Sebastian Pop59b61b92012-10-11 07:32:34 +00001036// Return null if no bound available.
Chandler Carruth49c22192016-05-12 22:19:39 +00001037const SCEV *DependenceInfo::collectUpperBound(const Loop *L, Type *T) const {
Sebastian Pop59b61b92012-10-11 07:32:34 +00001038 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
1039 const SCEV *UB = SE->getBackedgeTakenCount(L);
James Molloyc0661ae2015-05-15 12:17:22 +00001040 return SE->getTruncateOrZeroExtend(UB, T);
Sebastian Pop59b61b92012-10-11 07:32:34 +00001041 }
Craig Topper9f008862014-04-15 04:59:12 +00001042 return nullptr;
Sebastian Pop59b61b92012-10-11 07:32:34 +00001043}
1044
1045
1046// Calls collectUpperBound(), then attempts to cast it to SCEVConstant.
1047// If the cast fails, returns NULL.
Chandler Carruth49c22192016-05-12 22:19:39 +00001048const SCEVConstant *DependenceInfo::collectConstantUpperBound(const Loop *L,
1049 Type *T) const {
Sebastian Pop59b61b92012-10-11 07:32:34 +00001050 if (const SCEV *UB = collectUpperBound(L, T))
1051 return dyn_cast<SCEVConstant>(UB);
Craig Topper9f008862014-04-15 04:59:12 +00001052 return nullptr;
Sebastian Pop59b61b92012-10-11 07:32:34 +00001053}
1054
1055
1056// testZIV -
1057// When we have a pair of subscripts of the form [c1] and [c2],
1058// where c1 and c2 are both loop invariant, we attack it using
1059// the ZIV test. Basically, we test by comparing the two values,
1060// but there are actually three possible results:
1061// 1) the values are equal, so there's a dependence
1062// 2) the values are different, so there's no dependence
1063// 3) the values might be equal, so we have to assume a dependence.
1064//
1065// Return true if dependence disproved.
Chandler Carruth49c22192016-05-12 22:19:39 +00001066bool DependenceInfo::testZIV(const SCEV *Src, const SCEV *Dst,
1067 FullDependence &Result) const {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001068 LLVM_DEBUG(dbgs() << " src = " << *Src << "\n");
1069 LLVM_DEBUG(dbgs() << " dst = " << *Dst << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001070 ++ZIVapplications;
1071 if (isKnownPredicate(CmpInst::ICMP_EQ, Src, Dst)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001072 LLVM_DEBUG(dbgs() << " provably dependent\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001073 return false; // provably dependent
1074 }
1075 if (isKnownPredicate(CmpInst::ICMP_NE, Src, Dst)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001076 LLVM_DEBUG(dbgs() << " provably independent\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001077 ++ZIVindependence;
1078 return true; // provably independent
1079 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001080 LLVM_DEBUG(dbgs() << " possibly dependent\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001081 Result.Consistent = false;
1082 return false; // possibly dependent
1083}
1084
1085
1086// strongSIVtest -
1087// From the paper, Practical Dependence Testing, Section 4.2.1
1088//
1089// When we have a pair of subscripts of the form [c1 + a*i] and [c2 + a*i],
1090// where i is an induction variable, c1 and c2 are loop invariant,
1091// and a is a constant, we can solve it exactly using the Strong SIV test.
1092//
1093// Can prove independence. Failing that, can compute distance (and direction).
1094// In the presence of symbolic terms, we can sometimes make progress.
1095//
1096// If there's a dependence,
1097//
1098// c1 + a*i = c2 + a*i'
1099//
1100// The dependence distance is
1101//
1102// d = i' - i = (c1 - c2)/a
1103//
1104// A dependence only exists if d is an integer and abs(d) <= U, where U is the
1105// loop's upper bound. If a dependence exists, the dependence direction is
1106// defined as
1107//
1108// { < if d > 0
1109// direction = { = if d = 0
1110// { > if d < 0
1111//
1112// Return true if dependence disproved.
Chandler Carruth49c22192016-05-12 22:19:39 +00001113bool DependenceInfo::strongSIVtest(const SCEV *Coeff, const SCEV *SrcConst,
1114 const SCEV *DstConst, const Loop *CurLoop,
1115 unsigned Level, FullDependence &Result,
1116 Constraint &NewConstraint) const {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001117 LLVM_DEBUG(dbgs() << "\tStrong SIV test\n");
1118 LLVM_DEBUG(dbgs() << "\t Coeff = " << *Coeff);
1119 LLVM_DEBUG(dbgs() << ", " << *Coeff->getType() << "\n");
1120 LLVM_DEBUG(dbgs() << "\t SrcConst = " << *SrcConst);
1121 LLVM_DEBUG(dbgs() << ", " << *SrcConst->getType() << "\n");
1122 LLVM_DEBUG(dbgs() << "\t DstConst = " << *DstConst);
1123 LLVM_DEBUG(dbgs() << ", " << *DstConst->getType() << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001124 ++StrongSIVapplications;
1125 assert(0 < Level && Level <= CommonLevels && "level out of range");
1126 Level--;
1127
1128 const SCEV *Delta = SE->getMinusSCEV(SrcConst, DstConst);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001129 LLVM_DEBUG(dbgs() << "\t Delta = " << *Delta);
1130 LLVM_DEBUG(dbgs() << ", " << *Delta->getType() << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001131
1132 // check that |Delta| < iteration count
1133 if (const SCEV *UpperBound = collectUpperBound(CurLoop, Delta->getType())) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001134 LLVM_DEBUG(dbgs() << "\t UpperBound = " << *UpperBound);
1135 LLVM_DEBUG(dbgs() << ", " << *UpperBound->getType() << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001136 const SCEV *AbsDelta =
1137 SE->isKnownNonNegative(Delta) ? Delta : SE->getNegativeSCEV(Delta);
1138 const SCEV *AbsCoeff =
1139 SE->isKnownNonNegative(Coeff) ? Coeff : SE->getNegativeSCEV(Coeff);
1140 const SCEV *Product = SE->getMulExpr(UpperBound, AbsCoeff);
1141 if (isKnownPredicate(CmpInst::ICMP_SGT, AbsDelta, Product)) {
1142 // Distance greater than trip count - no dependence
1143 ++StrongSIVindependence;
1144 ++StrongSIVsuccesses;
1145 return true;
1146 }
1147 }
1148
1149 // Can we compute distance?
1150 if (isa<SCEVConstant>(Delta) && isa<SCEVConstant>(Coeff)) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00001151 APInt ConstDelta = cast<SCEVConstant>(Delta)->getAPInt();
1152 APInt ConstCoeff = cast<SCEVConstant>(Coeff)->getAPInt();
Sebastian Pop59b61b92012-10-11 07:32:34 +00001153 APInt Distance = ConstDelta; // these need to be initialized
1154 APInt Remainder = ConstDelta;
1155 APInt::sdivrem(ConstDelta, ConstCoeff, Distance, Remainder);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001156 LLVM_DEBUG(dbgs() << "\t Distance = " << Distance << "\n");
1157 LLVM_DEBUG(dbgs() << "\t Remainder = " << Remainder << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001158 // Make sure Coeff divides Delta exactly
1159 if (Remainder != 0) {
1160 // Coeff doesn't divide Distance, no dependence
1161 ++StrongSIVindependence;
1162 ++StrongSIVsuccesses;
1163 return true;
1164 }
1165 Result.DV[Level].Distance = SE->getConstant(Distance);
1166 NewConstraint.setDistance(SE->getConstant(Distance), CurLoop);
1167 if (Distance.sgt(0))
1168 Result.DV[Level].Direction &= Dependence::DVEntry::LT;
1169 else if (Distance.slt(0))
1170 Result.DV[Level].Direction &= Dependence::DVEntry::GT;
1171 else
1172 Result.DV[Level].Direction &= Dependence::DVEntry::EQ;
1173 ++StrongSIVsuccesses;
1174 }
1175 else if (Delta->isZero()) {
1176 // since 0/X == 0
1177 Result.DV[Level].Distance = Delta;
1178 NewConstraint.setDistance(Delta, CurLoop);
1179 Result.DV[Level].Direction &= Dependence::DVEntry::EQ;
1180 ++StrongSIVsuccesses;
1181 }
1182 else {
1183 if (Coeff->isOne()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001184 LLVM_DEBUG(dbgs() << "\t Distance = " << *Delta << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001185 Result.DV[Level].Distance = Delta; // since X/1 == X
1186 NewConstraint.setDistance(Delta, CurLoop);
1187 }
1188 else {
1189 Result.Consistent = false;
1190 NewConstraint.setLine(Coeff,
1191 SE->getNegativeSCEV(Coeff),
1192 SE->getNegativeSCEV(Delta), CurLoop);
1193 }
1194
1195 // maybe we can get a useful direction
1196 bool DeltaMaybeZero = !SE->isKnownNonZero(Delta);
1197 bool DeltaMaybePositive = !SE->isKnownNonPositive(Delta);
1198 bool DeltaMaybeNegative = !SE->isKnownNonNegative(Delta);
1199 bool CoeffMaybePositive = !SE->isKnownNonPositive(Coeff);
1200 bool CoeffMaybeNegative = !SE->isKnownNonNegative(Coeff);
1201 // The double negatives above are confusing.
1202 // It helps to read !SE->isKnownNonZero(Delta)
1203 // as "Delta might be Zero"
1204 unsigned NewDirection = Dependence::DVEntry::NONE;
1205 if ((DeltaMaybePositive && CoeffMaybePositive) ||
1206 (DeltaMaybeNegative && CoeffMaybeNegative))
1207 NewDirection = Dependence::DVEntry::LT;
1208 if (DeltaMaybeZero)
1209 NewDirection |= Dependence::DVEntry::EQ;
1210 if ((DeltaMaybeNegative && CoeffMaybePositive) ||
1211 (DeltaMaybePositive && CoeffMaybeNegative))
1212 NewDirection |= Dependence::DVEntry::GT;
1213 if (NewDirection < Result.DV[Level].Direction)
1214 ++StrongSIVsuccesses;
1215 Result.DV[Level].Direction &= NewDirection;
1216 }
1217 return false;
1218}
1219
1220
1221// weakCrossingSIVtest -
1222// From the paper, Practical Dependence Testing, Section 4.2.2
1223//
1224// When we have a pair of subscripts of the form [c1 + a*i] and [c2 - a*i],
1225// where i is an induction variable, c1 and c2 are loop invariant,
1226// and a is a constant, we can solve it exactly using the
1227// Weak-Crossing SIV test.
1228//
1229// Given c1 + a*i = c2 - a*i', we can look for the intersection of
1230// the two lines, where i = i', yielding
1231//
1232// c1 + a*i = c2 - a*i
1233// 2a*i = c2 - c1
1234// i = (c2 - c1)/2a
1235//
1236// If i < 0, there is no dependence.
1237// If i > upperbound, there is no dependence.
1238// If i = 0 (i.e., if c1 = c2), there's a dependence with distance = 0.
1239// If i = upperbound, there's a dependence with distance = 0.
1240// If i is integral, there's a dependence (all directions).
1241// If the non-integer part = 1/2, there's a dependence (<> directions).
1242// Otherwise, there's no dependence.
1243//
1244// Can prove independence. Failing that,
1245// can sometimes refine the directions.
1246// Can determine iteration for splitting.
1247//
1248// Return true if dependence disproved.
Chandler Carruth49c22192016-05-12 22:19:39 +00001249bool DependenceInfo::weakCrossingSIVtest(
1250 const SCEV *Coeff, const SCEV *SrcConst, const SCEV *DstConst,
1251 const Loop *CurLoop, unsigned Level, FullDependence &Result,
1252 Constraint &NewConstraint, const SCEV *&SplitIter) const {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001253 LLVM_DEBUG(dbgs() << "\tWeak-Crossing SIV test\n");
1254 LLVM_DEBUG(dbgs() << "\t Coeff = " << *Coeff << "\n");
1255 LLVM_DEBUG(dbgs() << "\t SrcConst = " << *SrcConst << "\n");
1256 LLVM_DEBUG(dbgs() << "\t DstConst = " << *DstConst << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001257 ++WeakCrossingSIVapplications;
1258 assert(0 < Level && Level <= CommonLevels && "Level out of range");
1259 Level--;
1260 Result.Consistent = false;
1261 const SCEV *Delta = SE->getMinusSCEV(DstConst, SrcConst);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001262 LLVM_DEBUG(dbgs() << "\t Delta = " << *Delta << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001263 NewConstraint.setLine(Coeff, Coeff, Delta, CurLoop);
1264 if (Delta->isZero()) {
Sebastian Pope96232612012-10-12 02:04:32 +00001265 Result.DV[Level].Direction &= unsigned(~Dependence::DVEntry::LT);
1266 Result.DV[Level].Direction &= unsigned(~Dependence::DVEntry::GT);
Sebastian Pop59b61b92012-10-11 07:32:34 +00001267 ++WeakCrossingSIVsuccesses;
1268 if (!Result.DV[Level].Direction) {
1269 ++WeakCrossingSIVindependence;
1270 return true;
1271 }
1272 Result.DV[Level].Distance = Delta; // = 0
1273 return false;
1274 }
1275 const SCEVConstant *ConstCoeff = dyn_cast<SCEVConstant>(Coeff);
1276 if (!ConstCoeff)
1277 return false;
1278
1279 Result.DV[Level].Splitable = true;
1280 if (SE->isKnownNegative(ConstCoeff)) {
1281 ConstCoeff = dyn_cast<SCEVConstant>(SE->getNegativeSCEV(ConstCoeff));
1282 assert(ConstCoeff &&
1283 "dynamic cast of negative of ConstCoeff should yield constant");
1284 Delta = SE->getNegativeSCEV(Delta);
1285 }
1286 assert(SE->isKnownPositive(ConstCoeff) && "ConstCoeff should be positive");
1287
Chandler Carruth49c22192016-05-12 22:19:39 +00001288 // compute SplitIter for use by DependenceInfo::getSplitIteration()
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00001289 SplitIter = SE->getUDivExpr(
1290 SE->getSMaxExpr(SE->getZero(Delta->getType()), Delta),
1291 SE->getMulExpr(SE->getConstant(Delta->getType(), 2), ConstCoeff));
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001292 LLVM_DEBUG(dbgs() << "\t Split iter = " << *SplitIter << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001293
1294 const SCEVConstant *ConstDelta = dyn_cast<SCEVConstant>(Delta);
1295 if (!ConstDelta)
1296 return false;
1297
1298 // We're certain that ConstCoeff > 0; therefore,
1299 // if Delta < 0, then no dependence.
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001300 LLVM_DEBUG(dbgs() << "\t Delta = " << *Delta << "\n");
1301 LLVM_DEBUG(dbgs() << "\t ConstCoeff = " << *ConstCoeff << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001302 if (SE->isKnownNegative(Delta)) {
1303 // No dependence, Delta < 0
1304 ++WeakCrossingSIVindependence;
1305 ++WeakCrossingSIVsuccesses;
1306 return true;
1307 }
1308
1309 // We're certain that Delta > 0 and ConstCoeff > 0.
1310 // Check Delta/(2*ConstCoeff) against upper loop bound
1311 if (const SCEV *UpperBound = collectUpperBound(CurLoop, Delta->getType())) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001312 LLVM_DEBUG(dbgs() << "\t UpperBound = " << *UpperBound << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001313 const SCEV *ConstantTwo = SE->getConstant(UpperBound->getType(), 2);
1314 const SCEV *ML = SE->getMulExpr(SE->getMulExpr(ConstCoeff, UpperBound),
1315 ConstantTwo);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001316 LLVM_DEBUG(dbgs() << "\t ML = " << *ML << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001317 if (isKnownPredicate(CmpInst::ICMP_SGT, Delta, ML)) {
1318 // Delta too big, no dependence
1319 ++WeakCrossingSIVindependence;
1320 ++WeakCrossingSIVsuccesses;
1321 return true;
1322 }
1323 if (isKnownPredicate(CmpInst::ICMP_EQ, Delta, ML)) {
1324 // i = i' = UB
Sebastian Pope96232612012-10-12 02:04:32 +00001325 Result.DV[Level].Direction &= unsigned(~Dependence::DVEntry::LT);
1326 Result.DV[Level].Direction &= unsigned(~Dependence::DVEntry::GT);
Sebastian Pop59b61b92012-10-11 07:32:34 +00001327 ++WeakCrossingSIVsuccesses;
1328 if (!Result.DV[Level].Direction) {
1329 ++WeakCrossingSIVindependence;
1330 return true;
1331 }
1332 Result.DV[Level].Splitable = false;
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00001333 Result.DV[Level].Distance = SE->getZero(Delta->getType());
Sebastian Pop59b61b92012-10-11 07:32:34 +00001334 return false;
1335 }
1336 }
1337
1338 // check that Coeff divides Delta
Sanjoy Das0de2fec2015-12-17 20:28:46 +00001339 APInt APDelta = ConstDelta->getAPInt();
1340 APInt APCoeff = ConstCoeff->getAPInt();
Sebastian Pop59b61b92012-10-11 07:32:34 +00001341 APInt Distance = APDelta; // these need to be initialzed
1342 APInt Remainder = APDelta;
1343 APInt::sdivrem(APDelta, APCoeff, Distance, Remainder);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001344 LLVM_DEBUG(dbgs() << "\t Remainder = " << Remainder << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001345 if (Remainder != 0) {
1346 // Coeff doesn't divide Delta, no dependence
1347 ++WeakCrossingSIVindependence;
1348 ++WeakCrossingSIVsuccesses;
1349 return true;
1350 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001351 LLVM_DEBUG(dbgs() << "\t Distance = " << Distance << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001352
1353 // if 2*Coeff doesn't divide Delta, then the equal direction isn't possible
1354 APInt Two = APInt(Distance.getBitWidth(), 2, true);
1355 Remainder = Distance.srem(Two);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001356 LLVM_DEBUG(dbgs() << "\t Remainder = " << Remainder << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001357 if (Remainder != 0) {
1358 // Equal direction isn't possible
Sebastian Pope96232612012-10-12 02:04:32 +00001359 Result.DV[Level].Direction &= unsigned(~Dependence::DVEntry::EQ);
Sebastian Pop59b61b92012-10-11 07:32:34 +00001360 ++WeakCrossingSIVsuccesses;
1361 }
1362 return false;
1363}
1364
1365
1366// Kirch's algorithm, from
1367//
1368// Optimizing Supercompilers for Supercomputers
1369// Michael Wolfe
1370// MIT Press, 1989
1371//
1372// Program 2.1, page 29.
1373// Computes the GCD of AM and BM.
Mingjie Xing9deac1b2014-01-07 01:54:16 +00001374// Also finds a solution to the equation ax - by = gcd(a, b).
1375// Returns true if dependence disproved; i.e., gcd does not divide Delta.
Benjamin Kramerc321e532016-06-08 19:09:22 +00001376static bool findGCD(unsigned Bits, const APInt &AM, const APInt &BM,
1377 const APInt &Delta, APInt &G, APInt &X, APInt &Y) {
Sebastian Pop59b61b92012-10-11 07:32:34 +00001378 APInt A0(Bits, 1, true), A1(Bits, 0, true);
1379 APInt B0(Bits, 0, true), B1(Bits, 1, true);
1380 APInt G0 = AM.abs();
1381 APInt G1 = BM.abs();
1382 APInt Q = G0; // these need to be initialized
1383 APInt R = G0;
1384 APInt::sdivrem(G0, G1, Q, R);
1385 while (R != 0) {
1386 APInt A2 = A0 - Q*A1; A0 = A1; A1 = A2;
1387 APInt B2 = B0 - Q*B1; B0 = B1; B1 = B2;
1388 G0 = G1; G1 = R;
1389 APInt::sdivrem(G0, G1, Q, R);
1390 }
1391 G = G1;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001392 LLVM_DEBUG(dbgs() << "\t GCD = " << G << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001393 X = AM.slt(0) ? -A1 : A1;
1394 Y = BM.slt(0) ? B1 : -B1;
1395
1396 // make sure gcd divides Delta
1397 R = Delta.srem(G);
1398 if (R != 0)
1399 return true; // gcd doesn't divide Delta, no dependence
1400 Q = Delta.sdiv(G);
1401 X *= Q;
1402 Y *= Q;
1403 return false;
1404}
1405
Benjamin Kramerc321e532016-06-08 19:09:22 +00001406static APInt floorOfQuotient(const APInt &A, const APInt &B) {
Sebastian Pop59b61b92012-10-11 07:32:34 +00001407 APInt Q = A; // these need to be initialized
1408 APInt R = A;
1409 APInt::sdivrem(A, B, Q, R);
1410 if (R == 0)
1411 return Q;
1412 if ((A.sgt(0) && B.sgt(0)) ||
1413 (A.slt(0) && B.slt(0)))
1414 return Q;
1415 else
1416 return Q - 1;
1417}
1418
Benjamin Kramerc321e532016-06-08 19:09:22 +00001419static APInt ceilingOfQuotient(const APInt &A, const APInt &B) {
Sebastian Pop59b61b92012-10-11 07:32:34 +00001420 APInt Q = A; // these need to be initialized
1421 APInt R = A;
1422 APInt::sdivrem(A, B, Q, R);
1423 if (R == 0)
1424 return Q;
1425 if ((A.sgt(0) && B.sgt(0)) ||
1426 (A.slt(0) && B.slt(0)))
1427 return Q + 1;
1428 else
1429 return Q;
1430}
1431
1432
1433static
1434APInt maxAPInt(APInt A, APInt B) {
1435 return A.sgt(B) ? A : B;
1436}
1437
1438
1439static
1440APInt minAPInt(APInt A, APInt B) {
1441 return A.slt(B) ? A : B;
1442}
1443
1444
1445// exactSIVtest -
1446// When we have a pair of subscripts of the form [c1 + a1*i] and [c2 + a2*i],
1447// where i is an induction variable, c1 and c2 are loop invariant, and a1
1448// and a2 are constant, we can solve it exactly using an algorithm developed
1449// by Banerjee and Wolfe. See Section 2.5.3 in
1450//
1451// Optimizing Supercompilers for Supercomputers
1452// Michael Wolfe
1453// MIT Press, 1989
1454//
1455// It's slower than the specialized tests (strong SIV, weak-zero SIV, etc),
1456// so use them if possible. They're also a bit better with symbolics and,
1457// in the case of the strong SIV test, can compute Distances.
1458//
1459// Return true if dependence disproved.
Chandler Carruth49c22192016-05-12 22:19:39 +00001460bool DependenceInfo::exactSIVtest(const SCEV *SrcCoeff, const SCEV *DstCoeff,
1461 const SCEV *SrcConst, const SCEV *DstConst,
1462 const Loop *CurLoop, unsigned Level,
1463 FullDependence &Result,
1464 Constraint &NewConstraint) const {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001465 LLVM_DEBUG(dbgs() << "\tExact SIV test\n");
1466 LLVM_DEBUG(dbgs() << "\t SrcCoeff = " << *SrcCoeff << " = AM\n");
1467 LLVM_DEBUG(dbgs() << "\t DstCoeff = " << *DstCoeff << " = BM\n");
1468 LLVM_DEBUG(dbgs() << "\t SrcConst = " << *SrcConst << "\n");
1469 LLVM_DEBUG(dbgs() << "\t DstConst = " << *DstConst << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001470 ++ExactSIVapplications;
1471 assert(0 < Level && Level <= CommonLevels && "Level out of range");
1472 Level--;
1473 Result.Consistent = false;
1474 const SCEV *Delta = SE->getMinusSCEV(DstConst, SrcConst);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001475 LLVM_DEBUG(dbgs() << "\t Delta = " << *Delta << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001476 NewConstraint.setLine(SrcCoeff, SE->getNegativeSCEV(DstCoeff),
1477 Delta, CurLoop);
1478 const SCEVConstant *ConstDelta = dyn_cast<SCEVConstant>(Delta);
1479 const SCEVConstant *ConstSrcCoeff = dyn_cast<SCEVConstant>(SrcCoeff);
1480 const SCEVConstant *ConstDstCoeff = dyn_cast<SCEVConstant>(DstCoeff);
1481 if (!ConstDelta || !ConstSrcCoeff || !ConstDstCoeff)
1482 return false;
1483
1484 // find gcd
1485 APInt G, X, Y;
Sanjoy Das0de2fec2015-12-17 20:28:46 +00001486 APInt AM = ConstSrcCoeff->getAPInt();
1487 APInt BM = ConstDstCoeff->getAPInt();
Sebastian Pop59b61b92012-10-11 07:32:34 +00001488 unsigned Bits = AM.getBitWidth();
Sanjoy Das0de2fec2015-12-17 20:28:46 +00001489 if (findGCD(Bits, AM, BM, ConstDelta->getAPInt(), G, X, Y)) {
Sebastian Pop59b61b92012-10-11 07:32:34 +00001490 // gcd doesn't divide Delta, no dependence
1491 ++ExactSIVindependence;
1492 ++ExactSIVsuccesses;
1493 return true;
1494 }
1495
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001496 LLVM_DEBUG(dbgs() << "\t X = " << X << ", Y = " << Y << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001497
1498 // since SCEV construction normalizes, LM = 0
1499 APInt UM(Bits, 1, true);
1500 bool UMvalid = false;
1501 // UM is perhaps unavailable, let's check
1502 if (const SCEVConstant *CUB =
1503 collectConstantUpperBound(CurLoop, Delta->getType())) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00001504 UM = CUB->getAPInt();
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001505 LLVM_DEBUG(dbgs() << "\t UM = " << UM << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001506 UMvalid = true;
1507 }
1508
1509 APInt TU(APInt::getSignedMaxValue(Bits));
1510 APInt TL(APInt::getSignedMinValue(Bits));
1511
1512 // test(BM/G, LM-X) and test(-BM/G, X-UM)
1513 APInt TMUL = BM.sdiv(G);
1514 if (TMUL.sgt(0)) {
1515 TL = maxAPInt(TL, ceilingOfQuotient(-X, TMUL));
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001516 LLVM_DEBUG(dbgs() << "\t TL = " << TL << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001517 if (UMvalid) {
1518 TU = minAPInt(TU, floorOfQuotient(UM - X, TMUL));
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001519 LLVM_DEBUG(dbgs() << "\t TU = " << TU << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001520 }
1521 }
1522 else {
1523 TU = minAPInt(TU, floorOfQuotient(-X, TMUL));
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001524 LLVM_DEBUG(dbgs() << "\t TU = " << TU << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001525 if (UMvalid) {
1526 TL = maxAPInt(TL, ceilingOfQuotient(UM - X, TMUL));
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001527 LLVM_DEBUG(dbgs() << "\t TL = " << TL << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001528 }
1529 }
1530
1531 // test(AM/G, LM-Y) and test(-AM/G, Y-UM)
1532 TMUL = AM.sdiv(G);
1533 if (TMUL.sgt(0)) {
1534 TL = maxAPInt(TL, ceilingOfQuotient(-Y, TMUL));
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001535 LLVM_DEBUG(dbgs() << "\t TL = " << TL << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001536 if (UMvalid) {
1537 TU = minAPInt(TU, floorOfQuotient(UM - Y, TMUL));
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001538 LLVM_DEBUG(dbgs() << "\t TU = " << TU << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001539 }
1540 }
1541 else {
1542 TU = minAPInt(TU, floorOfQuotient(-Y, TMUL));
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001543 LLVM_DEBUG(dbgs() << "\t TU = " << TU << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001544 if (UMvalid) {
1545 TL = maxAPInt(TL, ceilingOfQuotient(UM - Y, TMUL));
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001546 LLVM_DEBUG(dbgs() << "\t TL = " << TL << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001547 }
1548 }
1549 if (TL.sgt(TU)) {
1550 ++ExactSIVindependence;
1551 ++ExactSIVsuccesses;
1552 return true;
1553 }
1554
1555 // explore directions
1556 unsigned NewDirection = Dependence::DVEntry::NONE;
1557
1558 // less than
1559 APInt SaveTU(TU); // save these
1560 APInt SaveTL(TL);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001561 LLVM_DEBUG(dbgs() << "\t exploring LT direction\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001562 TMUL = AM - BM;
1563 if (TMUL.sgt(0)) {
1564 TL = maxAPInt(TL, ceilingOfQuotient(X - Y + 1, TMUL));
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001565 LLVM_DEBUG(dbgs() << "\t\t TL = " << TL << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001566 }
1567 else {
1568 TU = minAPInt(TU, floorOfQuotient(X - Y + 1, TMUL));
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001569 LLVM_DEBUG(dbgs() << "\t\t TU = " << TU << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001570 }
1571 if (TL.sle(TU)) {
1572 NewDirection |= Dependence::DVEntry::LT;
1573 ++ExactSIVsuccesses;
1574 }
1575
1576 // equal
1577 TU = SaveTU; // restore
1578 TL = SaveTL;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001579 LLVM_DEBUG(dbgs() << "\t exploring EQ direction\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001580 if (TMUL.sgt(0)) {
1581 TL = maxAPInt(TL, ceilingOfQuotient(X - Y, TMUL));
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001582 LLVM_DEBUG(dbgs() << "\t\t TL = " << TL << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001583 }
1584 else {
1585 TU = minAPInt(TU, floorOfQuotient(X - Y, TMUL));
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001586 LLVM_DEBUG(dbgs() << "\t\t TU = " << TU << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001587 }
1588 TMUL = BM - AM;
1589 if (TMUL.sgt(0)) {
1590 TL = maxAPInt(TL, ceilingOfQuotient(Y - X, TMUL));
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001591 LLVM_DEBUG(dbgs() << "\t\t TL = " << TL << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001592 }
1593 else {
1594 TU = minAPInt(TU, floorOfQuotient(Y - X, TMUL));
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001595 LLVM_DEBUG(dbgs() << "\t\t TU = " << TU << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001596 }
1597 if (TL.sle(TU)) {
1598 NewDirection |= Dependence::DVEntry::EQ;
1599 ++ExactSIVsuccesses;
1600 }
1601
1602 // greater than
1603 TU = SaveTU; // restore
1604 TL = SaveTL;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001605 LLVM_DEBUG(dbgs() << "\t exploring GT direction\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001606 if (TMUL.sgt(0)) {
1607 TL = maxAPInt(TL, ceilingOfQuotient(Y - X + 1, TMUL));
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001608 LLVM_DEBUG(dbgs() << "\t\t TL = " << TL << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001609 }
1610 else {
1611 TU = minAPInt(TU, floorOfQuotient(Y - X + 1, TMUL));
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001612 LLVM_DEBUG(dbgs() << "\t\t TU = " << TU << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001613 }
1614 if (TL.sle(TU)) {
1615 NewDirection |= Dependence::DVEntry::GT;
1616 ++ExactSIVsuccesses;
1617 }
1618
1619 // finished
1620 Result.DV[Level].Direction &= NewDirection;
1621 if (Result.DV[Level].Direction == Dependence::DVEntry::NONE)
1622 ++ExactSIVindependence;
1623 return Result.DV[Level].Direction == Dependence::DVEntry::NONE;
1624}
1625
1626
1627
1628// Return true if the divisor evenly divides the dividend.
1629static
1630bool isRemainderZero(const SCEVConstant *Dividend,
1631 const SCEVConstant *Divisor) {
Benjamin Kramer46e38f32016-06-08 10:01:20 +00001632 const APInt &ConstDividend = Dividend->getAPInt();
1633 const APInt &ConstDivisor = Divisor->getAPInt();
Sebastian Pop59b61b92012-10-11 07:32:34 +00001634 return ConstDividend.srem(ConstDivisor) == 0;
1635}
1636
1637
1638// weakZeroSrcSIVtest -
1639// From the paper, Practical Dependence Testing, Section 4.2.2
1640//
1641// When we have a pair of subscripts of the form [c1] and [c2 + a*i],
1642// where i is an induction variable, c1 and c2 are loop invariant,
1643// and a is a constant, we can solve it exactly using the
1644// Weak-Zero SIV test.
1645//
1646// Given
1647//
1648// c1 = c2 + a*i
1649//
1650// we get
1651//
1652// (c1 - c2)/a = i
1653//
1654// If i is not an integer, there's no dependence.
1655// If i < 0 or > UB, there's no dependence.
David Green2911b3a2018-05-31 14:55:29 +00001656// If i = 0, the direction is >= and peeling the
Sebastian Pop59b61b92012-10-11 07:32:34 +00001657// 1st iteration will break the dependence.
David Green2911b3a2018-05-31 14:55:29 +00001658// If i = UB, the direction is <= and peeling the
Sebastian Pop59b61b92012-10-11 07:32:34 +00001659// last iteration will break the dependence.
1660// Otherwise, the direction is *.
1661//
1662// Can prove independence. Failing that, we can sometimes refine
1663// the directions. Can sometimes show that first or last
1664// iteration carries all the dependences (so worth peeling).
1665//
1666// (see also weakZeroDstSIVtest)
1667//
1668// Return true if dependence disproved.
Chandler Carruth49c22192016-05-12 22:19:39 +00001669bool DependenceInfo::weakZeroSrcSIVtest(const SCEV *DstCoeff,
1670 const SCEV *SrcConst,
1671 const SCEV *DstConst,
1672 const Loop *CurLoop, unsigned Level,
1673 FullDependence &Result,
1674 Constraint &NewConstraint) const {
Sebastian Pop59b61b92012-10-11 07:32:34 +00001675 // For the WeakSIV test, it's possible the loop isn't common to
1676 // the Src and Dst loops. If it isn't, then there's no need to
1677 // record a direction.
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001678 LLVM_DEBUG(dbgs() << "\tWeak-Zero (src) SIV test\n");
1679 LLVM_DEBUG(dbgs() << "\t DstCoeff = " << *DstCoeff << "\n");
1680 LLVM_DEBUG(dbgs() << "\t SrcConst = " << *SrcConst << "\n");
1681 LLVM_DEBUG(dbgs() << "\t DstConst = " << *DstConst << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001682 ++WeakZeroSIVapplications;
1683 assert(0 < Level && Level <= MaxLevels && "Level out of range");
1684 Level--;
1685 Result.Consistent = false;
1686 const SCEV *Delta = SE->getMinusSCEV(SrcConst, DstConst);
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00001687 NewConstraint.setLine(SE->getZero(Delta->getType()), DstCoeff, Delta,
1688 CurLoop);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001689 LLVM_DEBUG(dbgs() << "\t Delta = " << *Delta << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001690 if (isKnownPredicate(CmpInst::ICMP_EQ, SrcConst, DstConst)) {
1691 if (Level < CommonLevels) {
David Green2911b3a2018-05-31 14:55:29 +00001692 Result.DV[Level].Direction &= Dependence::DVEntry::GE;
Sebastian Pop59b61b92012-10-11 07:32:34 +00001693 Result.DV[Level].PeelFirst = true;
1694 ++WeakZeroSIVsuccesses;
1695 }
1696 return false; // dependences caused by first iteration
1697 }
1698 const SCEVConstant *ConstCoeff = dyn_cast<SCEVConstant>(DstCoeff);
1699 if (!ConstCoeff)
1700 return false;
1701 const SCEV *AbsCoeff =
1702 SE->isKnownNegative(ConstCoeff) ?
1703 SE->getNegativeSCEV(ConstCoeff) : ConstCoeff;
1704 const SCEV *NewDelta =
1705 SE->isKnownNegative(ConstCoeff) ? SE->getNegativeSCEV(Delta) : Delta;
1706
1707 // check that Delta/SrcCoeff < iteration count
1708 // really check NewDelta < count*AbsCoeff
1709 if (const SCEV *UpperBound = collectUpperBound(CurLoop, Delta->getType())) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001710 LLVM_DEBUG(dbgs() << "\t UpperBound = " << *UpperBound << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001711 const SCEV *Product = SE->getMulExpr(AbsCoeff, UpperBound);
1712 if (isKnownPredicate(CmpInst::ICMP_SGT, NewDelta, Product)) {
1713 ++WeakZeroSIVindependence;
1714 ++WeakZeroSIVsuccesses;
1715 return true;
1716 }
1717 if (isKnownPredicate(CmpInst::ICMP_EQ, NewDelta, Product)) {
1718 // dependences caused by last iteration
1719 if (Level < CommonLevels) {
David Green2911b3a2018-05-31 14:55:29 +00001720 Result.DV[Level].Direction &= Dependence::DVEntry::LE;
Sebastian Pop59b61b92012-10-11 07:32:34 +00001721 Result.DV[Level].PeelLast = true;
1722 ++WeakZeroSIVsuccesses;
1723 }
1724 return false;
1725 }
1726 }
1727
1728 // check that Delta/SrcCoeff >= 0
1729 // really check that NewDelta >= 0
1730 if (SE->isKnownNegative(NewDelta)) {
1731 // No dependence, newDelta < 0
1732 ++WeakZeroSIVindependence;
1733 ++WeakZeroSIVsuccesses;
1734 return true;
1735 }
1736
1737 // if SrcCoeff doesn't divide Delta, then no dependence
1738 if (isa<SCEVConstant>(Delta) &&
1739 !isRemainderZero(cast<SCEVConstant>(Delta), ConstCoeff)) {
1740 ++WeakZeroSIVindependence;
1741 ++WeakZeroSIVsuccesses;
1742 return true;
1743 }
1744 return false;
1745}
1746
1747
1748// weakZeroDstSIVtest -
1749// From the paper, Practical Dependence Testing, Section 4.2.2
1750//
1751// When we have a pair of subscripts of the form [c1 + a*i] and [c2],
1752// where i is an induction variable, c1 and c2 are loop invariant,
1753// and a is a constant, we can solve it exactly using the
1754// Weak-Zero SIV test.
1755//
1756// Given
1757//
1758// c1 + a*i = c2
1759//
1760// we get
1761//
1762// i = (c2 - c1)/a
1763//
1764// If i is not an integer, there's no dependence.
1765// If i < 0 or > UB, there's no dependence.
1766// If i = 0, the direction is <= and peeling the
1767// 1st iteration will break the dependence.
1768// If i = UB, the direction is >= and peeling the
1769// last iteration will break the dependence.
1770// Otherwise, the direction is *.
1771//
1772// Can prove independence. Failing that, we can sometimes refine
1773// the directions. Can sometimes show that first or last
1774// iteration carries all the dependences (so worth peeling).
1775//
1776// (see also weakZeroSrcSIVtest)
1777//
1778// Return true if dependence disproved.
Chandler Carruth49c22192016-05-12 22:19:39 +00001779bool DependenceInfo::weakZeroDstSIVtest(const SCEV *SrcCoeff,
1780 const SCEV *SrcConst,
1781 const SCEV *DstConst,
1782 const Loop *CurLoop, unsigned Level,
1783 FullDependence &Result,
1784 Constraint &NewConstraint) const {
Sebastian Pop59b61b92012-10-11 07:32:34 +00001785 // For the WeakSIV test, it's possible the loop isn't common to the
1786 // Src and Dst loops. If it isn't, then there's no need to record a direction.
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001787 LLVM_DEBUG(dbgs() << "\tWeak-Zero (dst) SIV test\n");
1788 LLVM_DEBUG(dbgs() << "\t SrcCoeff = " << *SrcCoeff << "\n");
1789 LLVM_DEBUG(dbgs() << "\t SrcConst = " << *SrcConst << "\n");
1790 LLVM_DEBUG(dbgs() << "\t DstConst = " << *DstConst << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001791 ++WeakZeroSIVapplications;
1792 assert(0 < Level && Level <= SrcLevels && "Level out of range");
1793 Level--;
1794 Result.Consistent = false;
1795 const SCEV *Delta = SE->getMinusSCEV(DstConst, SrcConst);
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00001796 NewConstraint.setLine(SrcCoeff, SE->getZero(Delta->getType()), Delta,
1797 CurLoop);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001798 LLVM_DEBUG(dbgs() << "\t Delta = " << *Delta << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001799 if (isKnownPredicate(CmpInst::ICMP_EQ, DstConst, SrcConst)) {
1800 if (Level < CommonLevels) {
1801 Result.DV[Level].Direction &= Dependence::DVEntry::LE;
1802 Result.DV[Level].PeelFirst = true;
1803 ++WeakZeroSIVsuccesses;
1804 }
1805 return false; // dependences caused by first iteration
1806 }
1807 const SCEVConstant *ConstCoeff = dyn_cast<SCEVConstant>(SrcCoeff);
1808 if (!ConstCoeff)
1809 return false;
1810 const SCEV *AbsCoeff =
1811 SE->isKnownNegative(ConstCoeff) ?
1812 SE->getNegativeSCEV(ConstCoeff) : ConstCoeff;
1813 const SCEV *NewDelta =
1814 SE->isKnownNegative(ConstCoeff) ? SE->getNegativeSCEV(Delta) : Delta;
1815
1816 // check that Delta/SrcCoeff < iteration count
1817 // really check NewDelta < count*AbsCoeff
1818 if (const SCEV *UpperBound = collectUpperBound(CurLoop, Delta->getType())) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001819 LLVM_DEBUG(dbgs() << "\t UpperBound = " << *UpperBound << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001820 const SCEV *Product = SE->getMulExpr(AbsCoeff, UpperBound);
1821 if (isKnownPredicate(CmpInst::ICMP_SGT, NewDelta, Product)) {
1822 ++WeakZeroSIVindependence;
1823 ++WeakZeroSIVsuccesses;
1824 return true;
1825 }
1826 if (isKnownPredicate(CmpInst::ICMP_EQ, NewDelta, Product)) {
1827 // dependences caused by last iteration
1828 if (Level < CommonLevels) {
1829 Result.DV[Level].Direction &= Dependence::DVEntry::GE;
1830 Result.DV[Level].PeelLast = true;
1831 ++WeakZeroSIVsuccesses;
1832 }
1833 return false;
1834 }
1835 }
1836
1837 // check that Delta/SrcCoeff >= 0
1838 // really check that NewDelta >= 0
1839 if (SE->isKnownNegative(NewDelta)) {
1840 // No dependence, newDelta < 0
1841 ++WeakZeroSIVindependence;
1842 ++WeakZeroSIVsuccesses;
1843 return true;
1844 }
1845
1846 // if SrcCoeff doesn't divide Delta, then no dependence
1847 if (isa<SCEVConstant>(Delta) &&
1848 !isRemainderZero(cast<SCEVConstant>(Delta), ConstCoeff)) {
1849 ++WeakZeroSIVindependence;
1850 ++WeakZeroSIVsuccesses;
1851 return true;
1852 }
1853 return false;
1854}
1855
1856
1857// exactRDIVtest - Tests the RDIV subscript pair for dependence.
1858// Things of the form [c1 + a*i] and [c2 + b*j],
1859// where i and j are induction variable, c1 and c2 are loop invariant,
1860// and a and b are constants.
1861// Returns true if any possible dependence is disproved.
Benjamin Kramerc914ab62012-10-31 11:25:32 +00001862// Marks the result as inconsistent.
Sebastian Pop59b61b92012-10-11 07:32:34 +00001863// Works in some cases that symbolicRDIVtest doesn't, and vice versa.
Chandler Carruth49c22192016-05-12 22:19:39 +00001864bool DependenceInfo::exactRDIVtest(const SCEV *SrcCoeff, const SCEV *DstCoeff,
1865 const SCEV *SrcConst, const SCEV *DstConst,
1866 const Loop *SrcLoop, const Loop *DstLoop,
1867 FullDependence &Result) const {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001868 LLVM_DEBUG(dbgs() << "\tExact RDIV test\n");
1869 LLVM_DEBUG(dbgs() << "\t SrcCoeff = " << *SrcCoeff << " = AM\n");
1870 LLVM_DEBUG(dbgs() << "\t DstCoeff = " << *DstCoeff << " = BM\n");
1871 LLVM_DEBUG(dbgs() << "\t SrcConst = " << *SrcConst << "\n");
1872 LLVM_DEBUG(dbgs() << "\t DstConst = " << *DstConst << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001873 ++ExactRDIVapplications;
1874 Result.Consistent = false;
1875 const SCEV *Delta = SE->getMinusSCEV(DstConst, SrcConst);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001876 LLVM_DEBUG(dbgs() << "\t Delta = " << *Delta << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001877 const SCEVConstant *ConstDelta = dyn_cast<SCEVConstant>(Delta);
1878 const SCEVConstant *ConstSrcCoeff = dyn_cast<SCEVConstant>(SrcCoeff);
1879 const SCEVConstant *ConstDstCoeff = dyn_cast<SCEVConstant>(DstCoeff);
1880 if (!ConstDelta || !ConstSrcCoeff || !ConstDstCoeff)
1881 return false;
1882
1883 // find gcd
1884 APInt G, X, Y;
Sanjoy Das0de2fec2015-12-17 20:28:46 +00001885 APInt AM = ConstSrcCoeff->getAPInt();
1886 APInt BM = ConstDstCoeff->getAPInt();
Sebastian Pop59b61b92012-10-11 07:32:34 +00001887 unsigned Bits = AM.getBitWidth();
Sanjoy Das0de2fec2015-12-17 20:28:46 +00001888 if (findGCD(Bits, AM, BM, ConstDelta->getAPInt(), G, X, Y)) {
Sebastian Pop59b61b92012-10-11 07:32:34 +00001889 // gcd doesn't divide Delta, no dependence
1890 ++ExactRDIVindependence;
1891 return true;
1892 }
1893
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001894 LLVM_DEBUG(dbgs() << "\t X = " << X << ", Y = " << Y << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001895
1896 // since SCEV construction seems to normalize, LM = 0
1897 APInt SrcUM(Bits, 1, true);
1898 bool SrcUMvalid = false;
1899 // SrcUM is perhaps unavailable, let's check
1900 if (const SCEVConstant *UpperBound =
1901 collectConstantUpperBound(SrcLoop, Delta->getType())) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00001902 SrcUM = UpperBound->getAPInt();
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001903 LLVM_DEBUG(dbgs() << "\t SrcUM = " << SrcUM << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001904 SrcUMvalid = true;
1905 }
1906
1907 APInt DstUM(Bits, 1, true);
1908 bool DstUMvalid = false;
1909 // UM is perhaps unavailable, let's check
1910 if (const SCEVConstant *UpperBound =
1911 collectConstantUpperBound(DstLoop, Delta->getType())) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00001912 DstUM = UpperBound->getAPInt();
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001913 LLVM_DEBUG(dbgs() << "\t DstUM = " << DstUM << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001914 DstUMvalid = true;
1915 }
1916
1917 APInt TU(APInt::getSignedMaxValue(Bits));
1918 APInt TL(APInt::getSignedMinValue(Bits));
1919
1920 // test(BM/G, LM-X) and test(-BM/G, X-UM)
1921 APInt TMUL = BM.sdiv(G);
1922 if (TMUL.sgt(0)) {
1923 TL = maxAPInt(TL, ceilingOfQuotient(-X, TMUL));
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001924 LLVM_DEBUG(dbgs() << "\t TL = " << TL << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001925 if (SrcUMvalid) {
1926 TU = minAPInt(TU, floorOfQuotient(SrcUM - X, TMUL));
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001927 LLVM_DEBUG(dbgs() << "\t TU = " << TU << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001928 }
1929 }
1930 else {
1931 TU = minAPInt(TU, floorOfQuotient(-X, TMUL));
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001932 LLVM_DEBUG(dbgs() << "\t TU = " << TU << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001933 if (SrcUMvalid) {
1934 TL = maxAPInt(TL, ceilingOfQuotient(SrcUM - X, TMUL));
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001935 LLVM_DEBUG(dbgs() << "\t TL = " << TL << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001936 }
1937 }
1938
1939 // test(AM/G, LM-Y) and test(-AM/G, Y-UM)
1940 TMUL = AM.sdiv(G);
1941 if (TMUL.sgt(0)) {
1942 TL = maxAPInt(TL, ceilingOfQuotient(-Y, TMUL));
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001943 LLVM_DEBUG(dbgs() << "\t TL = " << TL << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001944 if (DstUMvalid) {
1945 TU = minAPInt(TU, floorOfQuotient(DstUM - Y, TMUL));
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001946 LLVM_DEBUG(dbgs() << "\t TU = " << TU << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001947 }
1948 }
1949 else {
1950 TU = minAPInt(TU, floorOfQuotient(-Y, TMUL));
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001951 LLVM_DEBUG(dbgs() << "\t TU = " << TU << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001952 if (DstUMvalid) {
1953 TL = maxAPInt(TL, ceilingOfQuotient(DstUM - Y, TMUL));
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001954 LLVM_DEBUG(dbgs() << "\t TL = " << TL << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00001955 }
1956 }
1957 if (TL.sgt(TU))
1958 ++ExactRDIVindependence;
1959 return TL.sgt(TU);
1960}
1961
1962
1963// symbolicRDIVtest -
1964// In Section 4.5 of the Practical Dependence Testing paper,the authors
1965// introduce a special case of Banerjee's Inequalities (also called the
1966// Extreme-Value Test) that can handle some of the SIV and RDIV cases,
1967// particularly cases with symbolics. Since it's only able to disprove
1968// dependence (not compute distances or directions), we'll use it as a
1969// fall back for the other tests.
1970//
1971// When we have a pair of subscripts of the form [c1 + a1*i] and [c2 + a2*j]
1972// where i and j are induction variables and c1 and c2 are loop invariants,
1973// we can use the symbolic tests to disprove some dependences, serving as a
1974// backup for the RDIV test. Note that i and j can be the same variable,
1975// letting this test serve as a backup for the various SIV tests.
1976//
1977// For a dependence to exist, c1 + a1*i must equal c2 + a2*j for some
1978// 0 <= i <= N1 and some 0 <= j <= N2, where N1 and N2 are the (normalized)
1979// loop bounds for the i and j loops, respectively. So, ...
1980//
1981// c1 + a1*i = c2 + a2*j
1982// a1*i - a2*j = c2 - c1
1983//
1984// To test for a dependence, we compute c2 - c1 and make sure it's in the
1985// range of the maximum and minimum possible values of a1*i - a2*j.
1986// Considering the signs of a1 and a2, we have 4 possible cases:
1987//
1988// 1) If a1 >= 0 and a2 >= 0, then
1989// a1*0 - a2*N2 <= c2 - c1 <= a1*N1 - a2*0
1990// -a2*N2 <= c2 - c1 <= a1*N1
1991//
1992// 2) If a1 >= 0 and a2 <= 0, then
1993// a1*0 - a2*0 <= c2 - c1 <= a1*N1 - a2*N2
1994// 0 <= c2 - c1 <= a1*N1 - a2*N2
1995//
1996// 3) If a1 <= 0 and a2 >= 0, then
1997// a1*N1 - a2*N2 <= c2 - c1 <= a1*0 - a2*0
1998// a1*N1 - a2*N2 <= c2 - c1 <= 0
1999//
2000// 4) If a1 <= 0 and a2 <= 0, then
2001// a1*N1 - a2*0 <= c2 - c1 <= a1*0 - a2*N2
2002// a1*N1 <= c2 - c1 <= -a2*N2
2003//
2004// return true if dependence disproved
Chandler Carruth49c22192016-05-12 22:19:39 +00002005bool DependenceInfo::symbolicRDIVtest(const SCEV *A1, const SCEV *A2,
2006 const SCEV *C1, const SCEV *C2,
2007 const Loop *Loop1,
2008 const Loop *Loop2) const {
Sebastian Pop59b61b92012-10-11 07:32:34 +00002009 ++SymbolicRDIVapplications;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002010 LLVM_DEBUG(dbgs() << "\ttry symbolic RDIV test\n");
2011 LLVM_DEBUG(dbgs() << "\t A1 = " << *A1);
2012 LLVM_DEBUG(dbgs() << ", type = " << *A1->getType() << "\n");
2013 LLVM_DEBUG(dbgs() << "\t A2 = " << *A2 << "\n");
2014 LLVM_DEBUG(dbgs() << "\t C1 = " << *C1 << "\n");
2015 LLVM_DEBUG(dbgs() << "\t C2 = " << *C2 << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00002016 const SCEV *N1 = collectUpperBound(Loop1, A1->getType());
2017 const SCEV *N2 = collectUpperBound(Loop2, A1->getType());
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002018 LLVM_DEBUG(if (N1) dbgs() << "\t N1 = " << *N1 << "\n");
2019 LLVM_DEBUG(if (N2) dbgs() << "\t N2 = " << *N2 << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00002020 const SCEV *C2_C1 = SE->getMinusSCEV(C2, C1);
2021 const SCEV *C1_C2 = SE->getMinusSCEV(C1, C2);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002022 LLVM_DEBUG(dbgs() << "\t C2 - C1 = " << *C2_C1 << "\n");
2023 LLVM_DEBUG(dbgs() << "\t C1 - C2 = " << *C1_C2 << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00002024 if (SE->isKnownNonNegative(A1)) {
2025 if (SE->isKnownNonNegative(A2)) {
2026 // A1 >= 0 && A2 >= 0
2027 if (N1) {
2028 // make sure that c2 - c1 <= a1*N1
2029 const SCEV *A1N1 = SE->getMulExpr(A1, N1);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002030 LLVM_DEBUG(dbgs() << "\t A1*N1 = " << *A1N1 << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00002031 if (isKnownPredicate(CmpInst::ICMP_SGT, C2_C1, A1N1)) {
2032 ++SymbolicRDIVindependence;
2033 return true;
2034 }
2035 }
2036 if (N2) {
2037 // make sure that -a2*N2 <= c2 - c1, or a2*N2 >= c1 - c2
2038 const SCEV *A2N2 = SE->getMulExpr(A2, N2);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002039 LLVM_DEBUG(dbgs() << "\t A2*N2 = " << *A2N2 << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00002040 if (isKnownPredicate(CmpInst::ICMP_SLT, A2N2, C1_C2)) {
2041 ++SymbolicRDIVindependence;
2042 return true;
2043 }
2044 }
2045 }
2046 else if (SE->isKnownNonPositive(A2)) {
2047 // a1 >= 0 && a2 <= 0
2048 if (N1 && N2) {
2049 // make sure that c2 - c1 <= a1*N1 - a2*N2
2050 const SCEV *A1N1 = SE->getMulExpr(A1, N1);
2051 const SCEV *A2N2 = SE->getMulExpr(A2, N2);
2052 const SCEV *A1N1_A2N2 = SE->getMinusSCEV(A1N1, A2N2);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002053 LLVM_DEBUG(dbgs() << "\t A1*N1 - A2*N2 = " << *A1N1_A2N2 << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00002054 if (isKnownPredicate(CmpInst::ICMP_SGT, C2_C1, A1N1_A2N2)) {
2055 ++SymbolicRDIVindependence;
2056 return true;
2057 }
2058 }
2059 // make sure that 0 <= c2 - c1
2060 if (SE->isKnownNegative(C2_C1)) {
2061 ++SymbolicRDIVindependence;
2062 return true;
2063 }
2064 }
2065 }
2066 else if (SE->isKnownNonPositive(A1)) {
2067 if (SE->isKnownNonNegative(A2)) {
2068 // a1 <= 0 && a2 >= 0
2069 if (N1 && N2) {
2070 // make sure that a1*N1 - a2*N2 <= c2 - c1
2071 const SCEV *A1N1 = SE->getMulExpr(A1, N1);
2072 const SCEV *A2N2 = SE->getMulExpr(A2, N2);
2073 const SCEV *A1N1_A2N2 = SE->getMinusSCEV(A1N1, A2N2);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002074 LLVM_DEBUG(dbgs() << "\t A1*N1 - A2*N2 = " << *A1N1_A2N2 << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00002075 if (isKnownPredicate(CmpInst::ICMP_SGT, A1N1_A2N2, C2_C1)) {
2076 ++SymbolicRDIVindependence;
2077 return true;
2078 }
2079 }
2080 // make sure that c2 - c1 <= 0
2081 if (SE->isKnownPositive(C2_C1)) {
2082 ++SymbolicRDIVindependence;
2083 return true;
2084 }
2085 }
2086 else if (SE->isKnownNonPositive(A2)) {
2087 // a1 <= 0 && a2 <= 0
2088 if (N1) {
2089 // make sure that a1*N1 <= c2 - c1
2090 const SCEV *A1N1 = SE->getMulExpr(A1, N1);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002091 LLVM_DEBUG(dbgs() << "\t A1*N1 = " << *A1N1 << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00002092 if (isKnownPredicate(CmpInst::ICMP_SGT, A1N1, C2_C1)) {
2093 ++SymbolicRDIVindependence;
2094 return true;
2095 }
2096 }
2097 if (N2) {
2098 // make sure that c2 - c1 <= -a2*N2, or c1 - c2 >= a2*N2
2099 const SCEV *A2N2 = SE->getMulExpr(A2, N2);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002100 LLVM_DEBUG(dbgs() << "\t A2*N2 = " << *A2N2 << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00002101 if (isKnownPredicate(CmpInst::ICMP_SLT, C1_C2, A2N2)) {
2102 ++SymbolicRDIVindependence;
2103 return true;
2104 }
2105 }
2106 }
2107 }
2108 return false;
2109}
2110
2111
2112// testSIV -
2113// When we have a pair of subscripts of the form [c1 + a1*i] and [c2 - a2*i]
2114// where i is an induction variable, c1 and c2 are loop invariant, and a1 and
2115// a2 are constant, we attack it with an SIV test. While they can all be
2116// solved with the Exact SIV test, it's worthwhile to use simpler tests when
2117// they apply; they're cheaper and sometimes more precise.
2118//
2119// Return true if dependence disproved.
Chandler Carruth49c22192016-05-12 22:19:39 +00002120bool DependenceInfo::testSIV(const SCEV *Src, const SCEV *Dst, unsigned &Level,
2121 FullDependence &Result, Constraint &NewConstraint,
2122 const SCEV *&SplitIter) const {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002123 LLVM_DEBUG(dbgs() << " src = " << *Src << "\n");
2124 LLVM_DEBUG(dbgs() << " dst = " << *Dst << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00002125 const SCEVAddRecExpr *SrcAddRec = dyn_cast<SCEVAddRecExpr>(Src);
2126 const SCEVAddRecExpr *DstAddRec = dyn_cast<SCEVAddRecExpr>(Dst);
2127 if (SrcAddRec && DstAddRec) {
2128 const SCEV *SrcConst = SrcAddRec->getStart();
2129 const SCEV *DstConst = DstAddRec->getStart();
2130 const SCEV *SrcCoeff = SrcAddRec->getStepRecurrence(*SE);
2131 const SCEV *DstCoeff = DstAddRec->getStepRecurrence(*SE);
2132 const Loop *CurLoop = SrcAddRec->getLoop();
2133 assert(CurLoop == DstAddRec->getLoop() &&
2134 "both loops in SIV should be same");
2135 Level = mapSrcLoop(CurLoop);
2136 bool disproven;
2137 if (SrcCoeff == DstCoeff)
2138 disproven = strongSIVtest(SrcCoeff, SrcConst, DstConst, CurLoop,
2139 Level, Result, NewConstraint);
2140 else if (SrcCoeff == SE->getNegativeSCEV(DstCoeff))
2141 disproven = weakCrossingSIVtest(SrcCoeff, SrcConst, DstConst, CurLoop,
2142 Level, Result, NewConstraint, SplitIter);
2143 else
2144 disproven = exactSIVtest(SrcCoeff, DstCoeff, SrcConst, DstConst, CurLoop,
2145 Level, Result, NewConstraint);
2146 return disproven ||
2147 gcdMIVtest(Src, Dst, Result) ||
2148 symbolicRDIVtest(SrcCoeff, DstCoeff, SrcConst, DstConst, CurLoop, CurLoop);
2149 }
2150 if (SrcAddRec) {
2151 const SCEV *SrcConst = SrcAddRec->getStart();
2152 const SCEV *SrcCoeff = SrcAddRec->getStepRecurrence(*SE);
2153 const SCEV *DstConst = Dst;
2154 const Loop *CurLoop = SrcAddRec->getLoop();
2155 Level = mapSrcLoop(CurLoop);
2156 return weakZeroDstSIVtest(SrcCoeff, SrcConst, DstConst, CurLoop,
2157 Level, Result, NewConstraint) ||
2158 gcdMIVtest(Src, Dst, Result);
2159 }
2160 if (DstAddRec) {
2161 const SCEV *DstConst = DstAddRec->getStart();
2162 const SCEV *DstCoeff = DstAddRec->getStepRecurrence(*SE);
2163 const SCEV *SrcConst = Src;
2164 const Loop *CurLoop = DstAddRec->getLoop();
2165 Level = mapDstLoop(CurLoop);
2166 return weakZeroSrcSIVtest(DstCoeff, SrcConst, DstConst,
2167 CurLoop, Level, Result, NewConstraint) ||
2168 gcdMIVtest(Src, Dst, Result);
2169 }
2170 llvm_unreachable("SIV test expected at least one AddRec");
2171 return false;
2172}
2173
2174
2175// testRDIV -
2176// When we have a pair of subscripts of the form [c1 + a1*i] and [c2 + a2*j]
2177// where i and j are induction variables, c1 and c2 are loop invariant,
2178// and a1 and a2 are constant, we can solve it exactly with an easy adaptation
2179// of the Exact SIV test, the Restricted Double Index Variable (RDIV) test.
2180// It doesn't make sense to talk about distance or direction in this case,
2181// so there's no point in making special versions of the Strong SIV test or
2182// the Weak-crossing SIV test.
2183//
2184// With minor algebra, this test can also be used for things like
2185// [c1 + a1*i + a2*j][c2].
2186//
2187// Return true if dependence disproved.
Chandler Carruth49c22192016-05-12 22:19:39 +00002188bool DependenceInfo::testRDIV(const SCEV *Src, const SCEV *Dst,
2189 FullDependence &Result) const {
Sebastian Pop59b61b92012-10-11 07:32:34 +00002190 // we have 3 possible situations here:
2191 // 1) [a*i + b] and [c*j + d]
2192 // 2) [a*i + c*j + b] and [d]
2193 // 3) [b] and [a*i + c*j + d]
2194 // We need to find what we've got and get organized
2195
2196 const SCEV *SrcConst, *DstConst;
2197 const SCEV *SrcCoeff, *DstCoeff;
2198 const Loop *SrcLoop, *DstLoop;
2199
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002200 LLVM_DEBUG(dbgs() << " src = " << *Src << "\n");
2201 LLVM_DEBUG(dbgs() << " dst = " << *Dst << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00002202 const SCEVAddRecExpr *SrcAddRec = dyn_cast<SCEVAddRecExpr>(Src);
2203 const SCEVAddRecExpr *DstAddRec = dyn_cast<SCEVAddRecExpr>(Dst);
2204 if (SrcAddRec && DstAddRec) {
2205 SrcConst = SrcAddRec->getStart();
2206 SrcCoeff = SrcAddRec->getStepRecurrence(*SE);
2207 SrcLoop = SrcAddRec->getLoop();
2208 DstConst = DstAddRec->getStart();
2209 DstCoeff = DstAddRec->getStepRecurrence(*SE);
2210 DstLoop = DstAddRec->getLoop();
2211 }
2212 else if (SrcAddRec) {
2213 if (const SCEVAddRecExpr *tmpAddRec =
2214 dyn_cast<SCEVAddRecExpr>(SrcAddRec->getStart())) {
2215 SrcConst = tmpAddRec->getStart();
2216 SrcCoeff = tmpAddRec->getStepRecurrence(*SE);
2217 SrcLoop = tmpAddRec->getLoop();
2218 DstConst = Dst;
2219 DstCoeff = SE->getNegativeSCEV(SrcAddRec->getStepRecurrence(*SE));
2220 DstLoop = SrcAddRec->getLoop();
2221 }
2222 else
2223 llvm_unreachable("RDIV reached by surprising SCEVs");
2224 }
2225 else if (DstAddRec) {
2226 if (const SCEVAddRecExpr *tmpAddRec =
2227 dyn_cast<SCEVAddRecExpr>(DstAddRec->getStart())) {
2228 DstConst = tmpAddRec->getStart();
2229 DstCoeff = tmpAddRec->getStepRecurrence(*SE);
2230 DstLoop = tmpAddRec->getLoop();
2231 SrcConst = Src;
2232 SrcCoeff = SE->getNegativeSCEV(DstAddRec->getStepRecurrence(*SE));
2233 SrcLoop = DstAddRec->getLoop();
2234 }
2235 else
2236 llvm_unreachable("RDIV reached by surprising SCEVs");
2237 }
2238 else
2239 llvm_unreachable("RDIV expected at least one AddRec");
2240 return exactRDIVtest(SrcCoeff, DstCoeff,
2241 SrcConst, DstConst,
2242 SrcLoop, DstLoop,
2243 Result) ||
2244 gcdMIVtest(Src, Dst, Result) ||
2245 symbolicRDIVtest(SrcCoeff, DstCoeff,
2246 SrcConst, DstConst,
2247 SrcLoop, DstLoop);
2248}
2249
2250
2251// Tests the single-subscript MIV pair (Src and Dst) for dependence.
2252// Return true if dependence disproved.
2253// Can sometimes refine direction vectors.
Chandler Carruth49c22192016-05-12 22:19:39 +00002254bool DependenceInfo::testMIV(const SCEV *Src, const SCEV *Dst,
2255 const SmallBitVector &Loops,
2256 FullDependence &Result) const {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002257 LLVM_DEBUG(dbgs() << " src = " << *Src << "\n");
2258 LLVM_DEBUG(dbgs() << " dst = " << *Dst << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00002259 Result.Consistent = false;
2260 return gcdMIVtest(Src, Dst, Result) ||
2261 banerjeeMIVtest(Src, Dst, Loops, Result);
2262}
2263
2264
2265// Given a product, e.g., 10*X*Y, returns the first constant operand,
2266// in this case 10. If there is no constant part, returns NULL.
2267static
Brendon Cahoonbe2da822016-04-19 16:46:57 +00002268const SCEVConstant *getConstantPart(const SCEV *Expr) {
2269 if (const auto *Constant = dyn_cast<SCEVConstant>(Expr))
2270 return Constant;
2271 else if (const auto *Product = dyn_cast<SCEVMulExpr>(Expr))
2272 if (const auto *Constant = dyn_cast<SCEVConstant>(Product->getOperand(0)))
Sebastian Pop59b61b92012-10-11 07:32:34 +00002273 return Constant;
Craig Topper9f008862014-04-15 04:59:12 +00002274 return nullptr;
Sebastian Pop59b61b92012-10-11 07:32:34 +00002275}
2276
2277
2278//===----------------------------------------------------------------------===//
2279// gcdMIVtest -
2280// Tests an MIV subscript pair for dependence.
2281// Returns true if any possible dependence is disproved.
Benjamin Kramerc914ab62012-10-31 11:25:32 +00002282// Marks the result as inconsistent.
Sebastian Pop59b61b92012-10-11 07:32:34 +00002283// Can sometimes disprove the equal direction for 1 or more loops,
2284// as discussed in Michael Wolfe's book,
2285// High Performance Compilers for Parallel Computing, page 235.
2286//
2287// We spend some effort (code!) to handle cases like
2288// [10*i + 5*N*j + 15*M + 6], where i and j are induction variables,
2289// but M and N are just loop-invariant variables.
2290// This should help us handle linearized subscripts;
2291// also makes this test a useful backup to the various SIV tests.
2292//
2293// It occurs to me that the presence of loop-invariant variables
2294// changes the nature of the test from "greatest common divisor"
Preston Briggs4eb7ee52012-11-29 04:30:52 +00002295// to "a common divisor".
Chandler Carruth49c22192016-05-12 22:19:39 +00002296bool DependenceInfo::gcdMIVtest(const SCEV *Src, const SCEV *Dst,
2297 FullDependence &Result) const {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002298 LLVM_DEBUG(dbgs() << "starting gcd\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00002299 ++GCDapplications;
Preston Briggs3ad39492012-11-21 23:50:04 +00002300 unsigned BitWidth = SE->getTypeSizeInBits(Src->getType());
Sebastian Pop59b61b92012-10-11 07:32:34 +00002301 APInt RunningGCD = APInt::getNullValue(BitWidth);
2302
2303 // Examine Src coefficients.
2304 // Compute running GCD and record source constant.
2305 // Because we're looking for the constant at the end of the chain,
2306 // we can't quit the loop just because the GCD == 1.
2307 const SCEV *Coefficients = Src;
2308 while (const SCEVAddRecExpr *AddRec =
2309 dyn_cast<SCEVAddRecExpr>(Coefficients)) {
2310 const SCEV *Coeff = AddRec->getStepRecurrence(*SE);
Brendon Cahoonbe2da822016-04-19 16:46:57 +00002311 // If the coefficient is the product of a constant and other stuff,
2312 // we can use the constant in the GCD computation.
2313 const auto *Constant = getConstantPart(Coeff);
Sebastian Pop59b61b92012-10-11 07:32:34 +00002314 if (!Constant)
2315 return false;
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002316 APInt ConstCoeff = Constant->getAPInt();
Sebastian Pop59b61b92012-10-11 07:32:34 +00002317 RunningGCD = APIntOps::GreatestCommonDivisor(RunningGCD, ConstCoeff.abs());
2318 Coefficients = AddRec->getStart();
2319 }
2320 const SCEV *SrcConst = Coefficients;
2321
2322 // Examine Dst coefficients.
2323 // Compute running GCD and record destination constant.
2324 // Because we're looking for the constant at the end of the chain,
2325 // we can't quit the loop just because the GCD == 1.
2326 Coefficients = Dst;
2327 while (const SCEVAddRecExpr *AddRec =
2328 dyn_cast<SCEVAddRecExpr>(Coefficients)) {
2329 const SCEV *Coeff = AddRec->getStepRecurrence(*SE);
Brendon Cahoonbe2da822016-04-19 16:46:57 +00002330 // If the coefficient is the product of a constant and other stuff,
2331 // we can use the constant in the GCD computation.
2332 const auto *Constant = getConstantPart(Coeff);
Sebastian Pop59b61b92012-10-11 07:32:34 +00002333 if (!Constant)
2334 return false;
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002335 APInt ConstCoeff = Constant->getAPInt();
Sebastian Pop59b61b92012-10-11 07:32:34 +00002336 RunningGCD = APIntOps::GreatestCommonDivisor(RunningGCD, ConstCoeff.abs());
2337 Coefficients = AddRec->getStart();
2338 }
2339 const SCEV *DstConst = Coefficients;
2340
2341 APInt ExtraGCD = APInt::getNullValue(BitWidth);
2342 const SCEV *Delta = SE->getMinusSCEV(DstConst, SrcConst);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002343 LLVM_DEBUG(dbgs() << " Delta = " << *Delta << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00002344 const SCEVConstant *Constant = dyn_cast<SCEVConstant>(Delta);
2345 if (const SCEVAddExpr *Sum = dyn_cast<SCEVAddExpr>(Delta)) {
2346 // If Delta is a sum of products, we may be able to make further progress.
2347 for (unsigned Op = 0, Ops = Sum->getNumOperands(); Op < Ops; Op++) {
2348 const SCEV *Operand = Sum->getOperand(Op);
2349 if (isa<SCEVConstant>(Operand)) {
2350 assert(!Constant && "Surprised to find multiple constants");
2351 Constant = cast<SCEVConstant>(Operand);
2352 }
Benjamin Kramer24c643b2012-10-31 09:20:38 +00002353 else if (const SCEVMulExpr *Product = dyn_cast<SCEVMulExpr>(Operand)) {
Sebastian Pop59b61b92012-10-11 07:32:34 +00002354 // Search for constant operand to participate in GCD;
2355 // If none found; return false.
Benjamin Kramer24c643b2012-10-31 09:20:38 +00002356 const SCEVConstant *ConstOp = getConstantPart(Product);
2357 if (!ConstOp)
2358 return false;
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002359 APInt ConstOpValue = ConstOp->getAPInt();
Sebastian Pop59b61b92012-10-11 07:32:34 +00002360 ExtraGCD = APIntOps::GreatestCommonDivisor(ExtraGCD,
2361 ConstOpValue.abs());
2362 }
2363 else
2364 return false;
2365 }
2366 }
2367 if (!Constant)
2368 return false;
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002369 APInt ConstDelta = cast<SCEVConstant>(Constant)->getAPInt();
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002370 LLVM_DEBUG(dbgs() << " ConstDelta = " << ConstDelta << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00002371 if (ConstDelta == 0)
2372 return false;
2373 RunningGCD = APIntOps::GreatestCommonDivisor(RunningGCD, ExtraGCD);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002374 LLVM_DEBUG(dbgs() << " RunningGCD = " << RunningGCD << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00002375 APInt Remainder = ConstDelta.srem(RunningGCD);
2376 if (Remainder != 0) {
2377 ++GCDindependence;
2378 return true;
2379 }
2380
2381 // Try to disprove equal directions.
2382 // For example, given a subscript pair [3*i + 2*j] and [i' + 2*j' - 1],
2383 // the code above can't disprove the dependence because the GCD = 1.
2384 // So we consider what happen if i = i' and what happens if j = j'.
2385 // If i = i', we can simplify the subscript to [2*i + 2*j] and [2*j' - 1],
2386 // which is infeasible, so we can disallow the = direction for the i level.
2387 // Setting j = j' doesn't help matters, so we end up with a direction vector
2388 // of [<>, *]
2389 //
2390 // Given A[5*i + 10*j*M + 9*M*N] and A[15*i + 20*j*M - 21*N*M + 5],
2391 // we need to remember that the constant part is 5 and the RunningGCD should
2392 // be initialized to ExtraGCD = 30.
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002393 LLVM_DEBUG(dbgs() << " ExtraGCD = " << ExtraGCD << '\n');
Sebastian Pop59b61b92012-10-11 07:32:34 +00002394
2395 bool Improved = false;
2396 Coefficients = Src;
2397 while (const SCEVAddRecExpr *AddRec =
2398 dyn_cast<SCEVAddRecExpr>(Coefficients)) {
2399 Coefficients = AddRec->getStart();
2400 const Loop *CurLoop = AddRec->getLoop();
2401 RunningGCD = ExtraGCD;
2402 const SCEV *SrcCoeff = AddRec->getStepRecurrence(*SE);
2403 const SCEV *DstCoeff = SE->getMinusSCEV(SrcCoeff, SrcCoeff);
2404 const SCEV *Inner = Src;
2405 while (RunningGCD != 1 && isa<SCEVAddRecExpr>(Inner)) {
2406 AddRec = cast<SCEVAddRecExpr>(Inner);
2407 const SCEV *Coeff = AddRec->getStepRecurrence(*SE);
2408 if (CurLoop == AddRec->getLoop())
2409 ; // SrcCoeff == Coeff
2410 else {
Brendon Cahoonbe2da822016-04-19 16:46:57 +00002411 // If the coefficient is the product of a constant and other stuff,
2412 // we can use the constant in the GCD computation.
2413 Constant = getConstantPart(Coeff);
Brendon Cahoon86f783e2016-04-04 18:13:18 +00002414 if (!Constant)
2415 return false;
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002416 APInt ConstCoeff = Constant->getAPInt();
Sebastian Pop59b61b92012-10-11 07:32:34 +00002417 RunningGCD = APIntOps::GreatestCommonDivisor(RunningGCD, ConstCoeff.abs());
2418 }
2419 Inner = AddRec->getStart();
2420 }
2421 Inner = Dst;
2422 while (RunningGCD != 1 && isa<SCEVAddRecExpr>(Inner)) {
2423 AddRec = cast<SCEVAddRecExpr>(Inner);
2424 const SCEV *Coeff = AddRec->getStepRecurrence(*SE);
2425 if (CurLoop == AddRec->getLoop())
2426 DstCoeff = Coeff;
2427 else {
Brendon Cahoonbe2da822016-04-19 16:46:57 +00002428 // If the coefficient is the product of a constant and other stuff,
2429 // we can use the constant in the GCD computation.
2430 Constant = getConstantPart(Coeff);
Brendon Cahoon86f783e2016-04-04 18:13:18 +00002431 if (!Constant)
2432 return false;
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002433 APInt ConstCoeff = Constant->getAPInt();
Sebastian Pop59b61b92012-10-11 07:32:34 +00002434 RunningGCD = APIntOps::GreatestCommonDivisor(RunningGCD, ConstCoeff.abs());
2435 }
2436 Inner = AddRec->getStart();
2437 }
2438 Delta = SE->getMinusSCEV(SrcCoeff, DstCoeff);
Brendon Cahoonbe2da822016-04-19 16:46:57 +00002439 // If the coefficient is the product of a constant and other stuff,
2440 // we can use the constant in the GCD computation.
2441 Constant = getConstantPart(Delta);
2442 if (!Constant)
Sebastian Pop59b61b92012-10-11 07:32:34 +00002443 // The difference of the two coefficients might not be a product
2444 // or constant, in which case we give up on this direction.
2445 continue;
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002446 APInt ConstCoeff = Constant->getAPInt();
Sebastian Pop59b61b92012-10-11 07:32:34 +00002447 RunningGCD = APIntOps::GreatestCommonDivisor(RunningGCD, ConstCoeff.abs());
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002448 LLVM_DEBUG(dbgs() << "\tRunningGCD = " << RunningGCD << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00002449 if (RunningGCD != 0) {
2450 Remainder = ConstDelta.srem(RunningGCD);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002451 LLVM_DEBUG(dbgs() << "\tRemainder = " << Remainder << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00002452 if (Remainder != 0) {
2453 unsigned Level = mapSrcLoop(CurLoop);
Sebastian Pope96232612012-10-12 02:04:32 +00002454 Result.DV[Level - 1].Direction &= unsigned(~Dependence::DVEntry::EQ);
Sebastian Pop59b61b92012-10-11 07:32:34 +00002455 Improved = true;
2456 }
2457 }
2458 }
2459 if (Improved)
2460 ++GCDsuccesses;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002461 LLVM_DEBUG(dbgs() << "all done\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00002462 return false;
2463}
2464
2465
2466//===----------------------------------------------------------------------===//
2467// banerjeeMIVtest -
2468// Use Banerjee's Inequalities to test an MIV subscript pair.
2469// (Wolfe, in the race-car book, calls this the Extreme Value Test.)
2470// Generally follows the discussion in Section 2.5.2 of
2471//
2472// Optimizing Supercompilers for Supercomputers
2473// Michael Wolfe
2474//
2475// The inequalities given on page 25 are simplified in that loops are
2476// normalized so that the lower bound is always 0 and the stride is always 1.
2477// For example, Wolfe gives
2478//
2479// LB^<_k = (A^-_k - B_k)^- (U_k - L_k - N_k) + (A_k - B_k)L_k - B_k N_k
2480//
2481// where A_k is the coefficient of the kth index in the source subscript,
2482// B_k is the coefficient of the kth index in the destination subscript,
2483// U_k is the upper bound of the kth index, L_k is the lower bound of the Kth
2484// index, and N_k is the stride of the kth index. Since all loops are normalized
2485// by the SCEV package, N_k = 1 and L_k = 0, allowing us to simplify the
2486// equation to
2487//
2488// LB^<_k = (A^-_k - B_k)^- (U_k - 0 - 1) + (A_k - B_k)0 - B_k 1
2489// = (A^-_k - B_k)^- (U_k - 1) - B_k
2490//
2491// Similar simplifications are possible for the other equations.
2492//
2493// When we can't determine the number of iterations for a loop,
2494// we use NULL as an indicator for the worst case, infinity.
2495// When computing the upper bound, NULL denotes +inf;
2496// for the lower bound, NULL denotes -inf.
2497//
2498// Return true if dependence disproved.
Chandler Carruth49c22192016-05-12 22:19:39 +00002499bool DependenceInfo::banerjeeMIVtest(const SCEV *Src, const SCEV *Dst,
2500 const SmallBitVector &Loops,
2501 FullDependence &Result) const {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002502 LLVM_DEBUG(dbgs() << "starting Banerjee\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00002503 ++BanerjeeApplications;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002504 LLVM_DEBUG(dbgs() << " Src = " << *Src << '\n');
Sebastian Pop59b61b92012-10-11 07:32:34 +00002505 const SCEV *A0;
Dylan Noblesmith4ffafef2014-08-26 02:03:38 +00002506 CoefficientInfo *A = collectCoeffInfo(Src, true, A0);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002507 LLVM_DEBUG(dbgs() << " Dst = " << *Dst << '\n');
Sebastian Pop59b61b92012-10-11 07:32:34 +00002508 const SCEV *B0;
Dylan Noblesmith4ffafef2014-08-26 02:03:38 +00002509 CoefficientInfo *B = collectCoeffInfo(Dst, false, B0);
2510 BoundInfo *Bound = new BoundInfo[MaxLevels + 1];
Sebastian Pop59b61b92012-10-11 07:32:34 +00002511 const SCEV *Delta = SE->getMinusSCEV(B0, A0);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002512 LLVM_DEBUG(dbgs() << "\tDelta = " << *Delta << '\n');
Sebastian Pop59b61b92012-10-11 07:32:34 +00002513
2514 // Compute bounds for all the * directions.
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002515 LLVM_DEBUG(dbgs() << "\tBounds[*]\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00002516 for (unsigned K = 1; K <= MaxLevels; ++K) {
2517 Bound[K].Iterations = A[K].Iterations ? A[K].Iterations : B[K].Iterations;
2518 Bound[K].Direction = Dependence::DVEntry::ALL;
2519 Bound[K].DirSet = Dependence::DVEntry::NONE;
2520 findBoundsALL(A, B, Bound, K);
2521#ifndef NDEBUG
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002522 LLVM_DEBUG(dbgs() << "\t " << K << '\t');
Sebastian Pop59b61b92012-10-11 07:32:34 +00002523 if (Bound[K].Lower[Dependence::DVEntry::ALL])
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002524 LLVM_DEBUG(dbgs() << *Bound[K].Lower[Dependence::DVEntry::ALL] << '\t');
Sebastian Pop59b61b92012-10-11 07:32:34 +00002525 else
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002526 LLVM_DEBUG(dbgs() << "-inf\t");
Sebastian Pop59b61b92012-10-11 07:32:34 +00002527 if (Bound[K].Upper[Dependence::DVEntry::ALL])
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002528 LLVM_DEBUG(dbgs() << *Bound[K].Upper[Dependence::DVEntry::ALL] << '\n');
Sebastian Pop59b61b92012-10-11 07:32:34 +00002529 else
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002530 LLVM_DEBUG(dbgs() << "+inf\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00002531#endif
2532 }
2533
2534 // Test the *, *, *, ... case.
2535 bool Disproved = false;
2536 if (testBounds(Dependence::DVEntry::ALL, 0, Bound, Delta)) {
2537 // Explore the direction vector hierarchy.
2538 unsigned DepthExpanded = 0;
2539 unsigned NewDeps = exploreDirections(1, A, B, Bound,
2540 Loops, DepthExpanded, Delta);
2541 if (NewDeps > 0) {
2542 bool Improved = false;
2543 for (unsigned K = 1; K <= CommonLevels; ++K) {
2544 if (Loops[K]) {
2545 unsigned Old = Result.DV[K - 1].Direction;
2546 Result.DV[K - 1].Direction = Old & Bound[K].DirSet;
2547 Improved |= Old != Result.DV[K - 1].Direction;
2548 if (!Result.DV[K - 1].Direction) {
2549 Improved = false;
2550 Disproved = true;
2551 break;
2552 }
2553 }
2554 }
2555 if (Improved)
2556 ++BanerjeeSuccesses;
2557 }
2558 else {
2559 ++BanerjeeIndependence;
2560 Disproved = true;
2561 }
2562 }
2563 else {
2564 ++BanerjeeIndependence;
2565 Disproved = true;
2566 }
Dylan Noblesmith4ffafef2014-08-26 02:03:38 +00002567 delete [] Bound;
2568 delete [] A;
2569 delete [] B;
Sebastian Pop59b61b92012-10-11 07:32:34 +00002570 return Disproved;
2571}
2572
2573
2574// Hierarchically expands the direction vector
2575// search space, combining the directions of discovered dependences
2576// in the DirSet field of Bound. Returns the number of distinct
2577// dependences discovered. If the dependence is disproved,
2578// it will return 0.
Chandler Carruth49c22192016-05-12 22:19:39 +00002579unsigned DependenceInfo::exploreDirections(unsigned Level, CoefficientInfo *A,
2580 CoefficientInfo *B, BoundInfo *Bound,
2581 const SmallBitVector &Loops,
2582 unsigned &DepthExpanded,
2583 const SCEV *Delta) const {
Sebastian Pop59b61b92012-10-11 07:32:34 +00002584 if (Level > CommonLevels) {
2585 // record result
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002586 LLVM_DEBUG(dbgs() << "\t[");
Sebastian Pop59b61b92012-10-11 07:32:34 +00002587 for (unsigned K = 1; K <= CommonLevels; ++K) {
2588 if (Loops[K]) {
2589 Bound[K].DirSet |= Bound[K].Direction;
2590#ifndef NDEBUG
2591 switch (Bound[K].Direction) {
2592 case Dependence::DVEntry::LT:
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002593 LLVM_DEBUG(dbgs() << " <");
Sebastian Pop59b61b92012-10-11 07:32:34 +00002594 break;
2595 case Dependence::DVEntry::EQ:
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002596 LLVM_DEBUG(dbgs() << " =");
Sebastian Pop59b61b92012-10-11 07:32:34 +00002597 break;
2598 case Dependence::DVEntry::GT:
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002599 LLVM_DEBUG(dbgs() << " >");
Sebastian Pop59b61b92012-10-11 07:32:34 +00002600 break;
2601 case Dependence::DVEntry::ALL:
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002602 LLVM_DEBUG(dbgs() << " *");
Sebastian Pop59b61b92012-10-11 07:32:34 +00002603 break;
2604 default:
2605 llvm_unreachable("unexpected Bound[K].Direction");
2606 }
2607#endif
2608 }
2609 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002610 LLVM_DEBUG(dbgs() << " ]\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00002611 return 1;
2612 }
2613 if (Loops[Level]) {
2614 if (Level > DepthExpanded) {
2615 DepthExpanded = Level;
2616 // compute bounds for <, =, > at current level
2617 findBoundsLT(A, B, Bound, Level);
2618 findBoundsGT(A, B, Bound, Level);
2619 findBoundsEQ(A, B, Bound, Level);
2620#ifndef NDEBUG
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002621 LLVM_DEBUG(dbgs() << "\tBound for level = " << Level << '\n');
2622 LLVM_DEBUG(dbgs() << "\t <\t");
Sebastian Pop59b61b92012-10-11 07:32:34 +00002623 if (Bound[Level].Lower[Dependence::DVEntry::LT])
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002624 LLVM_DEBUG(dbgs() << *Bound[Level].Lower[Dependence::DVEntry::LT]
2625 << '\t');
Sebastian Pop59b61b92012-10-11 07:32:34 +00002626 else
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002627 LLVM_DEBUG(dbgs() << "-inf\t");
Sebastian Pop59b61b92012-10-11 07:32:34 +00002628 if (Bound[Level].Upper[Dependence::DVEntry::LT])
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002629 LLVM_DEBUG(dbgs() << *Bound[Level].Upper[Dependence::DVEntry::LT]
2630 << '\n');
Sebastian Pop59b61b92012-10-11 07:32:34 +00002631 else
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002632 LLVM_DEBUG(dbgs() << "+inf\n");
2633 LLVM_DEBUG(dbgs() << "\t =\t");
Sebastian Pop59b61b92012-10-11 07:32:34 +00002634 if (Bound[Level].Lower[Dependence::DVEntry::EQ])
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002635 LLVM_DEBUG(dbgs() << *Bound[Level].Lower[Dependence::DVEntry::EQ]
2636 << '\t');
Sebastian Pop59b61b92012-10-11 07:32:34 +00002637 else
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002638 LLVM_DEBUG(dbgs() << "-inf\t");
Sebastian Pop59b61b92012-10-11 07:32:34 +00002639 if (Bound[Level].Upper[Dependence::DVEntry::EQ])
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002640 LLVM_DEBUG(dbgs() << *Bound[Level].Upper[Dependence::DVEntry::EQ]
2641 << '\n');
Sebastian Pop59b61b92012-10-11 07:32:34 +00002642 else
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002643 LLVM_DEBUG(dbgs() << "+inf\n");
2644 LLVM_DEBUG(dbgs() << "\t >\t");
Sebastian Pop59b61b92012-10-11 07:32:34 +00002645 if (Bound[Level].Lower[Dependence::DVEntry::GT])
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002646 LLVM_DEBUG(dbgs() << *Bound[Level].Lower[Dependence::DVEntry::GT]
2647 << '\t');
Sebastian Pop59b61b92012-10-11 07:32:34 +00002648 else
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002649 LLVM_DEBUG(dbgs() << "-inf\t");
Sebastian Pop59b61b92012-10-11 07:32:34 +00002650 if (Bound[Level].Upper[Dependence::DVEntry::GT])
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002651 LLVM_DEBUG(dbgs() << *Bound[Level].Upper[Dependence::DVEntry::GT]
2652 << '\n');
Sebastian Pop59b61b92012-10-11 07:32:34 +00002653 else
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002654 LLVM_DEBUG(dbgs() << "+inf\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00002655#endif
2656 }
2657
2658 unsigned NewDeps = 0;
2659
2660 // test bounds for <, *, *, ...
2661 if (testBounds(Dependence::DVEntry::LT, Level, Bound, Delta))
2662 NewDeps += exploreDirections(Level + 1, A, B, Bound,
2663 Loops, DepthExpanded, Delta);
2664
2665 // Test bounds for =, *, *, ...
2666 if (testBounds(Dependence::DVEntry::EQ, Level, Bound, Delta))
2667 NewDeps += exploreDirections(Level + 1, A, B, Bound,
2668 Loops, DepthExpanded, Delta);
2669
2670 // test bounds for >, *, *, ...
2671 if (testBounds(Dependence::DVEntry::GT, Level, Bound, Delta))
2672 NewDeps += exploreDirections(Level + 1, A, B, Bound,
2673 Loops, DepthExpanded, Delta);
2674
2675 Bound[Level].Direction = Dependence::DVEntry::ALL;
2676 return NewDeps;
2677 }
2678 else
2679 return exploreDirections(Level + 1, A, B, Bound, Loops, DepthExpanded, Delta);
2680}
2681
2682
2683// Returns true iff the current bounds are plausible.
Chandler Carruth49c22192016-05-12 22:19:39 +00002684bool DependenceInfo::testBounds(unsigned char DirKind, unsigned Level,
2685 BoundInfo *Bound, const SCEV *Delta) const {
Sebastian Pop59b61b92012-10-11 07:32:34 +00002686 Bound[Level].Direction = DirKind;
2687 if (const SCEV *LowerBound = getLowerBound(Bound))
2688 if (isKnownPredicate(CmpInst::ICMP_SGT, LowerBound, Delta))
2689 return false;
2690 if (const SCEV *UpperBound = getUpperBound(Bound))
2691 if (isKnownPredicate(CmpInst::ICMP_SGT, Delta, UpperBound))
2692 return false;
2693 return true;
2694}
2695
2696
2697// Computes the upper and lower bounds for level K
2698// using the * direction. Records them in Bound.
2699// Wolfe gives the equations
2700//
2701// LB^*_k = (A^-_k - B^+_k)(U_k - L_k) + (A_k - B_k)L_k
2702// UB^*_k = (A^+_k - B^-_k)(U_k - L_k) + (A_k - B_k)L_k
2703//
2704// Since we normalize loops, we can simplify these equations to
2705//
2706// LB^*_k = (A^-_k - B^+_k)U_k
2707// UB^*_k = (A^+_k - B^-_k)U_k
2708//
2709// We must be careful to handle the case where the upper bound is unknown.
2710// Note that the lower bound is always <= 0
2711// and the upper bound is always >= 0.
Chandler Carruth49c22192016-05-12 22:19:39 +00002712void DependenceInfo::findBoundsALL(CoefficientInfo *A, CoefficientInfo *B,
2713 BoundInfo *Bound, unsigned K) const {
Craig Topper9f008862014-04-15 04:59:12 +00002714 Bound[K].Lower[Dependence::DVEntry::ALL] = nullptr; // Default value = -infinity.
2715 Bound[K].Upper[Dependence::DVEntry::ALL] = nullptr; // Default value = +infinity.
Sebastian Pop59b61b92012-10-11 07:32:34 +00002716 if (Bound[K].Iterations) {
2717 Bound[K].Lower[Dependence::DVEntry::ALL] =
2718 SE->getMulExpr(SE->getMinusSCEV(A[K].NegPart, B[K].PosPart),
2719 Bound[K].Iterations);
2720 Bound[K].Upper[Dependence::DVEntry::ALL] =
2721 SE->getMulExpr(SE->getMinusSCEV(A[K].PosPart, B[K].NegPart),
2722 Bound[K].Iterations);
2723 }
2724 else {
2725 // If the difference is 0, we won't need to know the number of iterations.
2726 if (isKnownPredicate(CmpInst::ICMP_EQ, A[K].NegPart, B[K].PosPart))
2727 Bound[K].Lower[Dependence::DVEntry::ALL] =
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00002728 SE->getZero(A[K].Coeff->getType());
Sebastian Pop59b61b92012-10-11 07:32:34 +00002729 if (isKnownPredicate(CmpInst::ICMP_EQ, A[K].PosPart, B[K].NegPart))
2730 Bound[K].Upper[Dependence::DVEntry::ALL] =
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00002731 SE->getZero(A[K].Coeff->getType());
Sebastian Pop59b61b92012-10-11 07:32:34 +00002732 }
2733}
2734
2735
2736// Computes the upper and lower bounds for level K
2737// using the = direction. Records them in Bound.
2738// Wolfe gives the equations
2739//
2740// LB^=_k = (A_k - B_k)^- (U_k - L_k) + (A_k - B_k)L_k
2741// UB^=_k = (A_k - B_k)^+ (U_k - L_k) + (A_k - B_k)L_k
2742//
2743// Since we normalize loops, we can simplify these equations to
2744//
2745// LB^=_k = (A_k - B_k)^- U_k
2746// UB^=_k = (A_k - B_k)^+ U_k
2747//
2748// We must be careful to handle the case where the upper bound is unknown.
2749// Note that the lower bound is always <= 0
2750// and the upper bound is always >= 0.
Chandler Carruth49c22192016-05-12 22:19:39 +00002751void DependenceInfo::findBoundsEQ(CoefficientInfo *A, CoefficientInfo *B,
2752 BoundInfo *Bound, unsigned K) const {
Craig Topper9f008862014-04-15 04:59:12 +00002753 Bound[K].Lower[Dependence::DVEntry::EQ] = nullptr; // Default value = -infinity.
2754 Bound[K].Upper[Dependence::DVEntry::EQ] = nullptr; // Default value = +infinity.
Sebastian Pop59b61b92012-10-11 07:32:34 +00002755 if (Bound[K].Iterations) {
2756 const SCEV *Delta = SE->getMinusSCEV(A[K].Coeff, B[K].Coeff);
2757 const SCEV *NegativePart = getNegativePart(Delta);
2758 Bound[K].Lower[Dependence::DVEntry::EQ] =
2759 SE->getMulExpr(NegativePart, Bound[K].Iterations);
2760 const SCEV *PositivePart = getPositivePart(Delta);
2761 Bound[K].Upper[Dependence::DVEntry::EQ] =
2762 SE->getMulExpr(PositivePart, Bound[K].Iterations);
2763 }
2764 else {
2765 // If the positive/negative part of the difference is 0,
2766 // we won't need to know the number of iterations.
2767 const SCEV *Delta = SE->getMinusSCEV(A[K].Coeff, B[K].Coeff);
2768 const SCEV *NegativePart = getNegativePart(Delta);
2769 if (NegativePart->isZero())
2770 Bound[K].Lower[Dependence::DVEntry::EQ] = NegativePart; // Zero
2771 const SCEV *PositivePart = getPositivePart(Delta);
2772 if (PositivePart->isZero())
2773 Bound[K].Upper[Dependence::DVEntry::EQ] = PositivePart; // Zero
2774 }
2775}
2776
2777
2778// Computes the upper and lower bounds for level K
2779// using the < direction. Records them in Bound.
2780// Wolfe gives the equations
2781//
2782// LB^<_k = (A^-_k - B_k)^- (U_k - L_k - N_k) + (A_k - B_k)L_k - B_k N_k
2783// UB^<_k = (A^+_k - B_k)^+ (U_k - L_k - N_k) + (A_k - B_k)L_k - B_k N_k
2784//
2785// Since we normalize loops, we can simplify these equations to
2786//
2787// LB^<_k = (A^-_k - B_k)^- (U_k - 1) - B_k
2788// UB^<_k = (A^+_k - B_k)^+ (U_k - 1) - B_k
2789//
2790// We must be careful to handle the case where the upper bound is unknown.
Chandler Carruth49c22192016-05-12 22:19:39 +00002791void DependenceInfo::findBoundsLT(CoefficientInfo *A, CoefficientInfo *B,
2792 BoundInfo *Bound, unsigned K) const {
Craig Topper9f008862014-04-15 04:59:12 +00002793 Bound[K].Lower[Dependence::DVEntry::LT] = nullptr; // Default value = -infinity.
2794 Bound[K].Upper[Dependence::DVEntry::LT] = nullptr; // Default value = +infinity.
Sebastian Pop59b61b92012-10-11 07:32:34 +00002795 if (Bound[K].Iterations) {
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00002796 const SCEV *Iter_1 = SE->getMinusSCEV(
2797 Bound[K].Iterations, SE->getOne(Bound[K].Iterations->getType()));
Sebastian Pop59b61b92012-10-11 07:32:34 +00002798 const SCEV *NegPart =
2799 getNegativePart(SE->getMinusSCEV(A[K].NegPart, B[K].Coeff));
2800 Bound[K].Lower[Dependence::DVEntry::LT] =
2801 SE->getMinusSCEV(SE->getMulExpr(NegPart, Iter_1), B[K].Coeff);
2802 const SCEV *PosPart =
2803 getPositivePart(SE->getMinusSCEV(A[K].PosPart, B[K].Coeff));
2804 Bound[K].Upper[Dependence::DVEntry::LT] =
2805 SE->getMinusSCEV(SE->getMulExpr(PosPart, Iter_1), B[K].Coeff);
2806 }
2807 else {
2808 // If the positive/negative part of the difference is 0,
2809 // we won't need to know the number of iterations.
2810 const SCEV *NegPart =
2811 getNegativePart(SE->getMinusSCEV(A[K].NegPart, B[K].Coeff));
2812 if (NegPart->isZero())
2813 Bound[K].Lower[Dependence::DVEntry::LT] = SE->getNegativeSCEV(B[K].Coeff);
2814 const SCEV *PosPart =
2815 getPositivePart(SE->getMinusSCEV(A[K].PosPart, B[K].Coeff));
2816 if (PosPart->isZero())
2817 Bound[K].Upper[Dependence::DVEntry::LT] = SE->getNegativeSCEV(B[K].Coeff);
2818 }
2819}
2820
2821
2822// Computes the upper and lower bounds for level K
2823// using the > direction. Records them in Bound.
2824// Wolfe gives the equations
2825//
2826// LB^>_k = (A_k - B^+_k)^- (U_k - L_k - N_k) + (A_k - B_k)L_k + A_k N_k
2827// UB^>_k = (A_k - B^-_k)^+ (U_k - L_k - N_k) + (A_k - B_k)L_k + A_k N_k
2828//
2829// Since we normalize loops, we can simplify these equations to
2830//
2831// LB^>_k = (A_k - B^+_k)^- (U_k - 1) + A_k
2832// UB^>_k = (A_k - B^-_k)^+ (U_k - 1) + A_k
2833//
2834// We must be careful to handle the case where the upper bound is unknown.
Chandler Carruth49c22192016-05-12 22:19:39 +00002835void DependenceInfo::findBoundsGT(CoefficientInfo *A, CoefficientInfo *B,
2836 BoundInfo *Bound, unsigned K) const {
Craig Topper9f008862014-04-15 04:59:12 +00002837 Bound[K].Lower[Dependence::DVEntry::GT] = nullptr; // Default value = -infinity.
2838 Bound[K].Upper[Dependence::DVEntry::GT] = nullptr; // Default value = +infinity.
Sebastian Pop59b61b92012-10-11 07:32:34 +00002839 if (Bound[K].Iterations) {
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00002840 const SCEV *Iter_1 = SE->getMinusSCEV(
2841 Bound[K].Iterations, SE->getOne(Bound[K].Iterations->getType()));
Sebastian Pop59b61b92012-10-11 07:32:34 +00002842 const SCEV *NegPart =
2843 getNegativePart(SE->getMinusSCEV(A[K].Coeff, B[K].PosPart));
2844 Bound[K].Lower[Dependence::DVEntry::GT] =
2845 SE->getAddExpr(SE->getMulExpr(NegPart, Iter_1), A[K].Coeff);
2846 const SCEV *PosPart =
2847 getPositivePart(SE->getMinusSCEV(A[K].Coeff, B[K].NegPart));
2848 Bound[K].Upper[Dependence::DVEntry::GT] =
2849 SE->getAddExpr(SE->getMulExpr(PosPart, Iter_1), A[K].Coeff);
2850 }
2851 else {
2852 // If the positive/negative part of the difference is 0,
2853 // we won't need to know the number of iterations.
2854 const SCEV *NegPart = getNegativePart(SE->getMinusSCEV(A[K].Coeff, B[K].PosPart));
2855 if (NegPart->isZero())
2856 Bound[K].Lower[Dependence::DVEntry::GT] = A[K].Coeff;
2857 const SCEV *PosPart = getPositivePart(SE->getMinusSCEV(A[K].Coeff, B[K].NegPart));
2858 if (PosPart->isZero())
2859 Bound[K].Upper[Dependence::DVEntry::GT] = A[K].Coeff;
2860 }
2861}
2862
2863
2864// X^+ = max(X, 0)
Chandler Carruth49c22192016-05-12 22:19:39 +00002865const SCEV *DependenceInfo::getPositivePart(const SCEV *X) const {
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00002866 return SE->getSMaxExpr(X, SE->getZero(X->getType()));
Sebastian Pop59b61b92012-10-11 07:32:34 +00002867}
2868
2869
2870// X^- = min(X, 0)
Chandler Carruth49c22192016-05-12 22:19:39 +00002871const SCEV *DependenceInfo::getNegativePart(const SCEV *X) const {
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00002872 return SE->getSMinExpr(X, SE->getZero(X->getType()));
Sebastian Pop59b61b92012-10-11 07:32:34 +00002873}
2874
2875
2876// Walks through the subscript,
2877// collecting each coefficient, the associated loop bounds,
2878// and recording its positive and negative parts for later use.
Chandler Carruth49c22192016-05-12 22:19:39 +00002879DependenceInfo::CoefficientInfo *
2880DependenceInfo::collectCoeffInfo(const SCEV *Subscript, bool SrcFlag,
2881 const SCEV *&Constant) const {
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00002882 const SCEV *Zero = SE->getZero(Subscript->getType());
Dylan Noblesmith4ffafef2014-08-26 02:03:38 +00002883 CoefficientInfo *CI = new CoefficientInfo[MaxLevels + 1];
Sebastian Pop59b61b92012-10-11 07:32:34 +00002884 for (unsigned K = 1; K <= MaxLevels; ++K) {
2885 CI[K].Coeff = Zero;
2886 CI[K].PosPart = Zero;
2887 CI[K].NegPart = Zero;
Craig Topper9f008862014-04-15 04:59:12 +00002888 CI[K].Iterations = nullptr;
Sebastian Pop59b61b92012-10-11 07:32:34 +00002889 }
2890 while (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Subscript)) {
2891 const Loop *L = AddRec->getLoop();
2892 unsigned K = SrcFlag ? mapSrcLoop(L) : mapDstLoop(L);
2893 CI[K].Coeff = AddRec->getStepRecurrence(*SE);
2894 CI[K].PosPart = getPositivePart(CI[K].Coeff);
2895 CI[K].NegPart = getNegativePart(CI[K].Coeff);
2896 CI[K].Iterations = collectUpperBound(L, Subscript->getType());
2897 Subscript = AddRec->getStart();
2898 }
2899 Constant = Subscript;
2900#ifndef NDEBUG
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002901 LLVM_DEBUG(dbgs() << "\tCoefficient Info\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00002902 for (unsigned K = 1; K <= MaxLevels; ++K) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002903 LLVM_DEBUG(dbgs() << "\t " << K << "\t" << *CI[K].Coeff);
2904 LLVM_DEBUG(dbgs() << "\tPos Part = ");
2905 LLVM_DEBUG(dbgs() << *CI[K].PosPart);
2906 LLVM_DEBUG(dbgs() << "\tNeg Part = ");
2907 LLVM_DEBUG(dbgs() << *CI[K].NegPart);
2908 LLVM_DEBUG(dbgs() << "\tUpper Bound = ");
Sebastian Pop59b61b92012-10-11 07:32:34 +00002909 if (CI[K].Iterations)
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002910 LLVM_DEBUG(dbgs() << *CI[K].Iterations);
Sebastian Pop59b61b92012-10-11 07:32:34 +00002911 else
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002912 LLVM_DEBUG(dbgs() << "+inf");
2913 LLVM_DEBUG(dbgs() << '\n');
Sebastian Pop59b61b92012-10-11 07:32:34 +00002914 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002915 LLVM_DEBUG(dbgs() << "\t Constant = " << *Subscript << '\n');
Sebastian Pop59b61b92012-10-11 07:32:34 +00002916#endif
2917 return CI;
2918}
2919
2920
2921// Looks through all the bounds info and
2922// computes the lower bound given the current direction settings
2923// at each level. If the lower bound for any level is -inf,
2924// the result is -inf.
Chandler Carruth49c22192016-05-12 22:19:39 +00002925const SCEV *DependenceInfo::getLowerBound(BoundInfo *Bound) const {
Sebastian Pop59b61b92012-10-11 07:32:34 +00002926 const SCEV *Sum = Bound[1].Lower[Bound[1].Direction];
2927 for (unsigned K = 2; Sum && K <= MaxLevels; ++K) {
2928 if (Bound[K].Lower[Bound[K].Direction])
2929 Sum = SE->getAddExpr(Sum, Bound[K].Lower[Bound[K].Direction]);
2930 else
Craig Topper9f008862014-04-15 04:59:12 +00002931 Sum = nullptr;
Sebastian Pop59b61b92012-10-11 07:32:34 +00002932 }
2933 return Sum;
2934}
2935
2936
2937// Looks through all the bounds info and
2938// computes the upper bound given the current direction settings
2939// at each level. If the upper bound at any level is +inf,
2940// the result is +inf.
Chandler Carruth49c22192016-05-12 22:19:39 +00002941const SCEV *DependenceInfo::getUpperBound(BoundInfo *Bound) const {
Sebastian Pop59b61b92012-10-11 07:32:34 +00002942 const SCEV *Sum = Bound[1].Upper[Bound[1].Direction];
2943 for (unsigned K = 2; Sum && K <= MaxLevels; ++K) {
2944 if (Bound[K].Upper[Bound[K].Direction])
2945 Sum = SE->getAddExpr(Sum, Bound[K].Upper[Bound[K].Direction]);
2946 else
Craig Topper9f008862014-04-15 04:59:12 +00002947 Sum = nullptr;
Sebastian Pop59b61b92012-10-11 07:32:34 +00002948 }
2949 return Sum;
2950}
2951
2952
2953//===----------------------------------------------------------------------===//
2954// Constraint manipulation for Delta test.
2955
2956// Given a linear SCEV,
2957// return the coefficient (the step)
2958// corresponding to the specified loop.
2959// If there isn't one, return 0.
Jingyue Wua84feb12015-05-29 16:58:08 +00002960// For example, given a*i + b*j + c*k, finding the coefficient
Sebastian Pop59b61b92012-10-11 07:32:34 +00002961// corresponding to the j loop would yield b.
Chandler Carruth49c22192016-05-12 22:19:39 +00002962const SCEV *DependenceInfo::findCoefficient(const SCEV *Expr,
2963 const Loop *TargetLoop) const {
Sebastian Pop59b61b92012-10-11 07:32:34 +00002964 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Expr);
2965 if (!AddRec)
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00002966 return SE->getZero(Expr->getType());
Sebastian Pop59b61b92012-10-11 07:32:34 +00002967 if (AddRec->getLoop() == TargetLoop)
2968 return AddRec->getStepRecurrence(*SE);
2969 return findCoefficient(AddRec->getStart(), TargetLoop);
2970}
2971
2972
2973// Given a linear SCEV,
2974// return the SCEV given by zeroing out the coefficient
2975// corresponding to the specified loop.
2976// For example, given a*i + b*j + c*k, zeroing the coefficient
2977// corresponding to the j loop would yield a*i + c*k.
Chandler Carruth49c22192016-05-12 22:19:39 +00002978const SCEV *DependenceInfo::zeroCoefficient(const SCEV *Expr,
2979 const Loop *TargetLoop) const {
Sebastian Pop59b61b92012-10-11 07:32:34 +00002980 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Expr);
2981 if (!AddRec)
2982 return Expr; // ignore
2983 if (AddRec->getLoop() == TargetLoop)
2984 return AddRec->getStart();
2985 return SE->getAddRecExpr(zeroCoefficient(AddRec->getStart(), TargetLoop),
2986 AddRec->getStepRecurrence(*SE),
2987 AddRec->getLoop(),
2988 AddRec->getNoWrapFlags());
2989}
2990
2991
2992// Given a linear SCEV Expr,
2993// return the SCEV given by adding some Value to the
2994// coefficient corresponding to the specified TargetLoop.
2995// For example, given a*i + b*j + c*k, adding 1 to the coefficient
2996// corresponding to the j loop would yield a*i + (b+1)*j + c*k.
Chandler Carruth49c22192016-05-12 22:19:39 +00002997const SCEV *DependenceInfo::addToCoefficient(const SCEV *Expr,
2998 const Loop *TargetLoop,
2999 const SCEV *Value) const {
Sebastian Pop59b61b92012-10-11 07:32:34 +00003000 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Expr);
3001 if (!AddRec) // create a new addRec
3002 return SE->getAddRecExpr(Expr,
3003 Value,
3004 TargetLoop,
3005 SCEV::FlagAnyWrap); // Worst case, with no info.
3006 if (AddRec->getLoop() == TargetLoop) {
3007 const SCEV *Sum = SE->getAddExpr(AddRec->getStepRecurrence(*SE), Value);
3008 if (Sum->isZero())
3009 return AddRec->getStart();
3010 return SE->getAddRecExpr(AddRec->getStart(),
3011 Sum,
3012 AddRec->getLoop(),
3013 AddRec->getNoWrapFlags());
3014 }
Preston Briggs6c286b62013-06-28 18:44:48 +00003015 if (SE->isLoopInvariant(AddRec, TargetLoop))
NAKAMURA Takumid0e13af2014-10-28 11:54:52 +00003016 return SE->getAddRecExpr(AddRec, Value, TargetLoop, SCEV::FlagAnyWrap);
3017 return SE->getAddRecExpr(
3018 addToCoefficient(AddRec->getStart(), TargetLoop, Value),
3019 AddRec->getStepRecurrence(*SE), AddRec->getLoop(),
3020 AddRec->getNoWrapFlags());
Sebastian Pop59b61b92012-10-11 07:32:34 +00003021}
3022
3023
3024// Review the constraints, looking for opportunities
3025// to simplify a subscript pair (Src and Dst).
3026// Return true if some simplification occurs.
3027// If the simplification isn't exact (that is, if it is conservative
3028// in terms of dependence), set consistent to false.
3029// Corresponds to Figure 5 from the paper
3030//
3031// Practical Dependence Testing
3032// Goff, Kennedy, Tseng
3033// PLDI 1991
Chandler Carruth49c22192016-05-12 22:19:39 +00003034bool DependenceInfo::propagate(const SCEV *&Src, const SCEV *&Dst,
3035 SmallBitVector &Loops,
3036 SmallVectorImpl<Constraint> &Constraints,
3037 bool &Consistent) {
Sebastian Pop59b61b92012-10-11 07:32:34 +00003038 bool Result = false;
Francis Visoiu Mistrihb52e0362017-05-17 01:07:53 +00003039 for (unsigned LI : Loops.set_bits()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003040 LLVM_DEBUG(dbgs() << "\t Constraint[" << LI << "] is");
3041 LLVM_DEBUG(Constraints[LI].dump(dbgs()));
Sebastian Pop59b61b92012-10-11 07:32:34 +00003042 if (Constraints[LI].isDistance())
3043 Result |= propagateDistance(Src, Dst, Constraints[LI], Consistent);
3044 else if (Constraints[LI].isLine())
3045 Result |= propagateLine(Src, Dst, Constraints[LI], Consistent);
3046 else if (Constraints[LI].isPoint())
3047 Result |= propagatePoint(Src, Dst, Constraints[LI]);
3048 }
3049 return Result;
3050}
3051
3052
3053// Attempt to propagate a distance
3054// constraint into a subscript pair (Src and Dst).
3055// Return true if some simplification occurs.
3056// If the simplification isn't exact (that is, if it is conservative
3057// in terms of dependence), set consistent to false.
Chandler Carruth49c22192016-05-12 22:19:39 +00003058bool DependenceInfo::propagateDistance(const SCEV *&Src, const SCEV *&Dst,
3059 Constraint &CurConstraint,
3060 bool &Consistent) {
Sebastian Pop59b61b92012-10-11 07:32:34 +00003061 const Loop *CurLoop = CurConstraint.getAssociatedLoop();
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003062 LLVM_DEBUG(dbgs() << "\t\tSrc is " << *Src << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00003063 const SCEV *A_K = findCoefficient(Src, CurLoop);
3064 if (A_K->isZero())
3065 return false;
3066 const SCEV *DA_K = SE->getMulExpr(A_K, CurConstraint.getD());
3067 Src = SE->getMinusSCEV(Src, DA_K);
3068 Src = zeroCoefficient(Src, CurLoop);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003069 LLVM_DEBUG(dbgs() << "\t\tnew Src is " << *Src << "\n");
3070 LLVM_DEBUG(dbgs() << "\t\tDst is " << *Dst << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00003071 Dst = addToCoefficient(Dst, CurLoop, SE->getNegativeSCEV(A_K));
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003072 LLVM_DEBUG(dbgs() << "\t\tnew Dst is " << *Dst << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00003073 if (!findCoefficient(Dst, CurLoop)->isZero())
3074 Consistent = false;
3075 return true;
3076}
3077
3078
3079// Attempt to propagate a line
3080// constraint into a subscript pair (Src and Dst).
3081// Return true if some simplification occurs.
3082// If the simplification isn't exact (that is, if it is conservative
3083// in terms of dependence), set consistent to false.
Chandler Carruth49c22192016-05-12 22:19:39 +00003084bool DependenceInfo::propagateLine(const SCEV *&Src, const SCEV *&Dst,
3085 Constraint &CurConstraint,
3086 bool &Consistent) {
Sebastian Pop59b61b92012-10-11 07:32:34 +00003087 const Loop *CurLoop = CurConstraint.getAssociatedLoop();
3088 const SCEV *A = CurConstraint.getA();
3089 const SCEV *B = CurConstraint.getB();
3090 const SCEV *C = CurConstraint.getC();
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003091 LLVM_DEBUG(dbgs() << "\t\tA = " << *A << ", B = " << *B << ", C = " << *C
3092 << "\n");
3093 LLVM_DEBUG(dbgs() << "\t\tSrc = " << *Src << "\n");
3094 LLVM_DEBUG(dbgs() << "\t\tDst = " << *Dst << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00003095 if (A->isZero()) {
3096 const SCEVConstant *Bconst = dyn_cast<SCEVConstant>(B);
3097 const SCEVConstant *Cconst = dyn_cast<SCEVConstant>(C);
3098 if (!Bconst || !Cconst) return false;
Sanjoy Das0de2fec2015-12-17 20:28:46 +00003099 APInt Beta = Bconst->getAPInt();
3100 APInt Charlie = Cconst->getAPInt();
Sebastian Pop59b61b92012-10-11 07:32:34 +00003101 APInt CdivB = Charlie.sdiv(Beta);
3102 assert(Charlie.srem(Beta) == 0 && "C should be evenly divisible by B");
3103 const SCEV *AP_K = findCoefficient(Dst, CurLoop);
3104 // Src = SE->getAddExpr(Src, SE->getMulExpr(AP_K, SE->getConstant(CdivB)));
3105 Src = SE->getMinusSCEV(Src, SE->getMulExpr(AP_K, SE->getConstant(CdivB)));
3106 Dst = zeroCoefficient(Dst, CurLoop);
3107 if (!findCoefficient(Src, CurLoop)->isZero())
3108 Consistent = false;
3109 }
3110 else if (B->isZero()) {
3111 const SCEVConstant *Aconst = dyn_cast<SCEVConstant>(A);
3112 const SCEVConstant *Cconst = dyn_cast<SCEVConstant>(C);
3113 if (!Aconst || !Cconst) return false;
Sanjoy Das0de2fec2015-12-17 20:28:46 +00003114 APInt Alpha = Aconst->getAPInt();
3115 APInt Charlie = Cconst->getAPInt();
Sebastian Pop59b61b92012-10-11 07:32:34 +00003116 APInt CdivA = Charlie.sdiv(Alpha);
3117 assert(Charlie.srem(Alpha) == 0 && "C should be evenly divisible by A");
3118 const SCEV *A_K = findCoefficient(Src, CurLoop);
3119 Src = SE->getAddExpr(Src, SE->getMulExpr(A_K, SE->getConstant(CdivA)));
3120 Src = zeroCoefficient(Src, CurLoop);
3121 if (!findCoefficient(Dst, CurLoop)->isZero())
3122 Consistent = false;
3123 }
3124 else if (isKnownPredicate(CmpInst::ICMP_EQ, A, B)) {
3125 const SCEVConstant *Aconst = dyn_cast<SCEVConstant>(A);
3126 const SCEVConstant *Cconst = dyn_cast<SCEVConstant>(C);
3127 if (!Aconst || !Cconst) return false;
Sanjoy Das0de2fec2015-12-17 20:28:46 +00003128 APInt Alpha = Aconst->getAPInt();
3129 APInt Charlie = Cconst->getAPInt();
Sebastian Pop59b61b92012-10-11 07:32:34 +00003130 APInt CdivA = Charlie.sdiv(Alpha);
3131 assert(Charlie.srem(Alpha) == 0 && "C should be evenly divisible by A");
3132 const SCEV *A_K = findCoefficient(Src, CurLoop);
3133 Src = SE->getAddExpr(Src, SE->getMulExpr(A_K, SE->getConstant(CdivA)));
3134 Src = zeroCoefficient(Src, CurLoop);
3135 Dst = addToCoefficient(Dst, CurLoop, A_K);
3136 if (!findCoefficient(Dst, CurLoop)->isZero())
3137 Consistent = false;
3138 }
3139 else {
3140 // paper is incorrect here, or perhaps just misleading
3141 const SCEV *A_K = findCoefficient(Src, CurLoop);
3142 Src = SE->getMulExpr(Src, A);
3143 Dst = SE->getMulExpr(Dst, A);
3144 Src = SE->getAddExpr(Src, SE->getMulExpr(A_K, C));
3145 Src = zeroCoefficient(Src, CurLoop);
3146 Dst = addToCoefficient(Dst, CurLoop, SE->getMulExpr(A_K, B));
3147 if (!findCoefficient(Dst, CurLoop)->isZero())
3148 Consistent = false;
3149 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003150 LLVM_DEBUG(dbgs() << "\t\tnew Src = " << *Src << "\n");
3151 LLVM_DEBUG(dbgs() << "\t\tnew Dst = " << *Dst << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00003152 return true;
3153}
3154
3155
3156// Attempt to propagate a point
3157// constraint into a subscript pair (Src and Dst).
3158// Return true if some simplification occurs.
Chandler Carruth49c22192016-05-12 22:19:39 +00003159bool DependenceInfo::propagatePoint(const SCEV *&Src, const SCEV *&Dst,
3160 Constraint &CurConstraint) {
Sebastian Pop59b61b92012-10-11 07:32:34 +00003161 const Loop *CurLoop = CurConstraint.getAssociatedLoop();
3162 const SCEV *A_K = findCoefficient(Src, CurLoop);
3163 const SCEV *AP_K = findCoefficient(Dst, CurLoop);
3164 const SCEV *XA_K = SE->getMulExpr(A_K, CurConstraint.getX());
3165 const SCEV *YAP_K = SE->getMulExpr(AP_K, CurConstraint.getY());
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003166 LLVM_DEBUG(dbgs() << "\t\tSrc is " << *Src << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00003167 Src = SE->getAddExpr(Src, SE->getMinusSCEV(XA_K, YAP_K));
3168 Src = zeroCoefficient(Src, CurLoop);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003169 LLVM_DEBUG(dbgs() << "\t\tnew Src is " << *Src << "\n");
3170 LLVM_DEBUG(dbgs() << "\t\tDst is " << *Dst << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00003171 Dst = zeroCoefficient(Dst, CurLoop);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003172 LLVM_DEBUG(dbgs() << "\t\tnew Dst is " << *Dst << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00003173 return true;
3174}
3175
3176
3177// Update direction vector entry based on the current constraint.
Chandler Carruth49c22192016-05-12 22:19:39 +00003178void DependenceInfo::updateDirection(Dependence::DVEntry &Level,
3179 const Constraint &CurConstraint) const {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003180 LLVM_DEBUG(dbgs() << "\tUpdate direction, constraint =");
3181 LLVM_DEBUG(CurConstraint.dump(dbgs()));
Sebastian Pop59b61b92012-10-11 07:32:34 +00003182 if (CurConstraint.isAny())
3183 ; // use defaults
3184 else if (CurConstraint.isDistance()) {
3185 // this one is consistent, the others aren't
3186 Level.Scalar = false;
3187 Level.Distance = CurConstraint.getD();
3188 unsigned NewDirection = Dependence::DVEntry::NONE;
3189 if (!SE->isKnownNonZero(Level.Distance)) // if may be zero
3190 NewDirection = Dependence::DVEntry::EQ;
3191 if (!SE->isKnownNonPositive(Level.Distance)) // if may be positive
3192 NewDirection |= Dependence::DVEntry::LT;
3193 if (!SE->isKnownNonNegative(Level.Distance)) // if may be negative
3194 NewDirection |= Dependence::DVEntry::GT;
3195 Level.Direction &= NewDirection;
3196 }
3197 else if (CurConstraint.isLine()) {
3198 Level.Scalar = false;
Craig Topper9f008862014-04-15 04:59:12 +00003199 Level.Distance = nullptr;
Sebastian Pop59b61b92012-10-11 07:32:34 +00003200 // direction should be accurate
3201 }
3202 else if (CurConstraint.isPoint()) {
3203 Level.Scalar = false;
Craig Topper9f008862014-04-15 04:59:12 +00003204 Level.Distance = nullptr;
Sebastian Pop59b61b92012-10-11 07:32:34 +00003205 unsigned NewDirection = Dependence::DVEntry::NONE;
3206 if (!isKnownPredicate(CmpInst::ICMP_NE,
3207 CurConstraint.getY(),
3208 CurConstraint.getX()))
3209 // if X may be = Y
3210 NewDirection |= Dependence::DVEntry::EQ;
3211 if (!isKnownPredicate(CmpInst::ICMP_SLE,
3212 CurConstraint.getY(),
3213 CurConstraint.getX()))
3214 // if Y may be > X
3215 NewDirection |= Dependence::DVEntry::LT;
3216 if (!isKnownPredicate(CmpInst::ICMP_SGE,
3217 CurConstraint.getY(),
3218 CurConstraint.getX()))
3219 // if Y may be < X
3220 NewDirection |= Dependence::DVEntry::GT;
3221 Level.Direction &= NewDirection;
3222 }
3223 else
3224 llvm_unreachable("constraint has unexpected kind");
3225}
3226
Sebastian Popc62c6792013-11-12 22:47:20 +00003227/// Check if we can delinearize the subscripts. If the SCEVs representing the
3228/// source and destination array references are recurrences on a nested loop,
Alp Tokercb402912014-01-24 17:20:08 +00003229/// this function flattens the nested recurrences into separate recurrences
Sebastian Popc62c6792013-11-12 22:47:20 +00003230/// for each loop level.
Chandler Carruth49c22192016-05-12 22:19:39 +00003231bool DependenceInfo::tryDelinearize(Instruction *Src, Instruction *Dst,
3232 SmallVectorImpl<Subscript> &Pair) {
Renato Golin038ede22018-03-09 21:05:58 +00003233 assert(isLoadOrStore(Src) && "instruction is not load or store");
3234 assert(isLoadOrStore(Dst) && "instruction is not load or store");
3235 Value *SrcPtr = getLoadStorePointerOperand(Src);
3236 Value *DstPtr = getLoadStorePointerOperand(Dst);
Hal Finkel0ef2b102015-08-19 02:56:36 +00003237
3238 Loop *SrcLoop = LI->getLoopFor(Src->getParent());
3239 Loop *DstLoop = LI->getLoopFor(Dst->getParent());
3240
3241 // Below code mimics the code in Delinearization.cpp
3242 const SCEV *SrcAccessFn =
3243 SE->getSCEVAtScope(SrcPtr, SrcLoop);
3244 const SCEV *DstAccessFn =
3245 SE->getSCEVAtScope(DstPtr, DstLoop);
3246
Sebastian Pop28e6b972014-05-27 22:41:51 +00003247 const SCEVUnknown *SrcBase =
Hal Finkel0ef2b102015-08-19 02:56:36 +00003248 dyn_cast<SCEVUnknown>(SE->getPointerBase(SrcAccessFn));
Sebastian Pop28e6b972014-05-27 22:41:51 +00003249 const SCEVUnknown *DstBase =
Hal Finkel0ef2b102015-08-19 02:56:36 +00003250 dyn_cast<SCEVUnknown>(SE->getPointerBase(DstAccessFn));
Sebastian Pop28e6b972014-05-27 22:41:51 +00003251
3252 if (!SrcBase || !DstBase || SrcBase != DstBase)
3253 return false;
3254
Hal Finkel0ef2b102015-08-19 02:56:36 +00003255 const SCEV *ElementSize = SE->getElementSize(Src);
3256 if (ElementSize != SE->getElementSize(Dst))
3257 return false;
3258
3259 const SCEV *SrcSCEV = SE->getMinusSCEV(SrcAccessFn, SrcBase);
3260 const SCEV *DstSCEV = SE->getMinusSCEV(DstAccessFn, DstBase);
Sebastian Pop28e6b972014-05-27 22:41:51 +00003261
Sebastian Popc62c6792013-11-12 22:47:20 +00003262 const SCEVAddRecExpr *SrcAR = dyn_cast<SCEVAddRecExpr>(SrcSCEV);
3263 const SCEVAddRecExpr *DstAR = dyn_cast<SCEVAddRecExpr>(DstSCEV);
3264 if (!SrcAR || !DstAR || !SrcAR->isAffine() || !DstAR->isAffine())
3265 return false;
3266
Sebastian Pop448712b2014-05-07 18:01:20 +00003267 // First step: collect parametric terms in both array references.
3268 SmallVector<const SCEV *, 4> Terms;
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00003269 SE->collectParametricTerms(SrcAR, Terms);
3270 SE->collectParametricTerms(DstAR, Terms);
Sebastian Popc62c6792013-11-12 22:47:20 +00003271
Sebastian Pop448712b2014-05-07 18:01:20 +00003272 // Second step: find subscript sizes.
3273 SmallVector<const SCEV *, 4> Sizes;
Sebastian Popa6e58602014-05-27 22:41:45 +00003274 SE->findArrayDimensions(Terms, Sizes, ElementSize);
Sebastian Pop448712b2014-05-07 18:01:20 +00003275
3276 // Third step: compute the access functions for each subscript.
3277 SmallVector<const SCEV *, 4> SrcSubscripts, DstSubscripts;
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00003278 SE->computeAccessFunctions(SrcAR, SrcSubscripts, Sizes);
3279 SE->computeAccessFunctions(DstAR, DstSubscripts, Sizes);
Sebastian Pop448712b2014-05-07 18:01:20 +00003280
Sebastian Pop5133d2e2014-02-21 18:15:07 +00003281 // Fail when there is only a subscript: that's a linearized access function.
Sebastian Pop448712b2014-05-07 18:01:20 +00003282 if (SrcSubscripts.size() < 2 || DstSubscripts.size() < 2 ||
3283 SrcSubscripts.size() != DstSubscripts.size())
Sebastian Popc62c6792013-11-12 22:47:20 +00003284 return false;
3285
Sebastian Pop448712b2014-05-07 18:01:20 +00003286 int size = SrcSubscripts.size();
Sebastian Pop29026d32014-02-21 18:15:11 +00003287
David Greend143c652018-06-21 11:53:16 +00003288 // Statically check that the array bounds are in-range. The first subscript we
3289 // don't have a size for and it cannot overflow into another subscript, so is
3290 // always safe. The others need to be 0 <= subscript[i] < bound, for both src
3291 // and dst.
3292 // FIXME: It may be better to record these sizes and add them as constraints
3293 // to the dependency checks.
3294 for (int i = 1; i < size; ++i) {
3295 if (!SE->isKnownNonNegative(SrcSubscripts[i]))
3296 return false;
3297
3298 if (!isKnownLessThan(SrcSubscripts[i], Sizes[i - 1]))
3299 return false;
3300
3301 if (!SE->isKnownNonNegative(DstSubscripts[i]))
3302 return false;
3303
3304 if (!isKnownLessThan(DstSubscripts[i], Sizes[i - 1]))
3305 return false;
3306 }
3307
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003308 LLVM_DEBUG({
3309 dbgs() << "\nSrcSubscripts: ";
Sebastian Pop448712b2014-05-07 18:01:20 +00003310 for (int i = 0; i < size; i++)
3311 dbgs() << *SrcSubscripts[i];
3312 dbgs() << "\nDstSubscripts: ";
3313 for (int i = 0; i < size; i++)
3314 dbgs() << *DstSubscripts[i];
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003315 });
Sebastian Popc62c6792013-11-12 22:47:20 +00003316
Sebastian Pop7ee14722013-11-13 22:37:58 +00003317 // The delinearization transforms a single-subscript MIV dependence test into
3318 // a multi-subscript SIV dependence test that is easier to compute. So we
3319 // resize Pair to contain as many pairs of subscripts as the delinearization
3320 // has found, and then initialize the pairs following the delinearization.
Sebastian Popc62c6792013-11-12 22:47:20 +00003321 Pair.resize(size);
3322 for (int i = 0; i < size; ++i) {
3323 Pair[i].Src = SrcSubscripts[i];
3324 Pair[i].Dst = DstSubscripts[i];
Jingyue Wu0fa125a2014-11-16 16:52:44 +00003325 unifySubscriptType(&Pair[i]);
Sebastian Popc62c6792013-11-12 22:47:20 +00003326 }
3327
3328 return true;
3329}
Sebastian Pop59b61b92012-10-11 07:32:34 +00003330
3331//===----------------------------------------------------------------------===//
3332
3333#ifndef NDEBUG
3334// For debugging purposes, dump a small bit vector to dbgs().
3335static void dumpSmallBitVector(SmallBitVector &BV) {
3336 dbgs() << "{";
Francis Visoiu Mistrihb52e0362017-05-17 01:07:53 +00003337 for (unsigned VI : BV.set_bits()) {
Sebastian Pop59b61b92012-10-11 07:32:34 +00003338 dbgs() << VI;
3339 if (BV.find_next(VI) >= 0)
3340 dbgs() << ' ';
3341 }
3342 dbgs() << "}\n";
3343}
3344#endif
3345
Sebastian Pop59b61b92012-10-11 07:32:34 +00003346// depends -
3347// Returns NULL if there is no dependence.
3348// Otherwise, return a Dependence with as many details as possible.
3349// Corresponds to Section 3.1 in the paper
3350//
3351// Practical Dependence Testing
3352// Goff, Kennedy, Tseng
3353// PLDI 1991
3354//
Preston Briggs3ad39492012-11-21 23:50:04 +00003355// Care is required to keep the routine below, getSplitIteration(),
3356// up to date with respect to this routine.
Dylan Noblesmith2cae60e2014-08-25 00:28:39 +00003357std::unique_ptr<Dependence>
Chandler Carruth49c22192016-05-12 22:19:39 +00003358DependenceInfo::depends(Instruction *Src, Instruction *Dst,
3359 bool PossiblyLoopIndependent) {
Preston Briggs1084fa22012-11-27 06:41:46 +00003360 if (Src == Dst)
3361 PossiblyLoopIndependent = false;
3362
Sebastian Pop59b61b92012-10-11 07:32:34 +00003363 if ((!Src->mayReadFromMemory() && !Src->mayWriteToMemory()) ||
3364 (!Dst->mayReadFromMemory() && !Dst->mayWriteToMemory()))
3365 // if both instructions don't reference memory, there's no dependence
Craig Topper9f008862014-04-15 04:59:12 +00003366 return nullptr;
Sebastian Pop59b61b92012-10-11 07:32:34 +00003367
Preston Briggs3ad39492012-11-21 23:50:04 +00003368 if (!isLoadOrStore(Src) || !isLoadOrStore(Dst)) {
Sebastian Pop59b61b92012-10-11 07:32:34 +00003369 // can only analyze simple loads and stores, i.e., no calls, invokes, etc.
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003370 LLVM_DEBUG(dbgs() << "can only handle simple loads and stores\n");
Dylan Noblesmith2cae60e2014-08-25 00:28:39 +00003371 return make_unique<Dependence>(Src, Dst);
Preston Briggs3ad39492012-11-21 23:50:04 +00003372 }
Sebastian Pop59b61b92012-10-11 07:32:34 +00003373
Renato Golin038ede22018-03-09 21:05:58 +00003374 assert(isLoadOrStore(Src) && "instruction is not load or store");
3375 assert(isLoadOrStore(Dst) && "instruction is not load or store");
3376 Value *SrcPtr = getLoadStorePointerOperand(Src);
3377 Value *DstPtr = getLoadStorePointerOperand(Dst);
Sebastian Pop59b61b92012-10-11 07:32:34 +00003378
David Green5ef933b2018-04-10 11:37:21 +00003379 switch (underlyingObjectsAlias(AA, F->getParent()->getDataLayout(),
3380 MemoryLocation::get(Dst),
3381 MemoryLocation::get(Src))) {
Chandler Carruthc3f49eb2015-06-22 02:16:51 +00003382 case MayAlias:
3383 case PartialAlias:
Sebastian Pop59b61b92012-10-11 07:32:34 +00003384 // cannot analyse objects if we don't understand their aliasing.
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003385 LLVM_DEBUG(dbgs() << "can't analyze may or partial alias\n");
Dylan Noblesmith2cae60e2014-08-25 00:28:39 +00003386 return make_unique<Dependence>(Src, Dst);
Chandler Carruthc3f49eb2015-06-22 02:16:51 +00003387 case NoAlias:
Sebastian Pop59b61b92012-10-11 07:32:34 +00003388 // If the objects noalias, they are distinct, accesses are independent.
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003389 LLVM_DEBUG(dbgs() << "no alias\n");
Craig Topper9f008862014-04-15 04:59:12 +00003390 return nullptr;
Chandler Carruthc3f49eb2015-06-22 02:16:51 +00003391 case MustAlias:
Sebastian Pop59b61b92012-10-11 07:32:34 +00003392 break; // The underlying objects alias; test accesses for dependence.
3393 }
3394
Sebastian Pop59b61b92012-10-11 07:32:34 +00003395 // establish loop nesting levels
3396 establishNestingLevels(Src, Dst);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003397 LLVM_DEBUG(dbgs() << " common nesting levels = " << CommonLevels << "\n");
3398 LLVM_DEBUG(dbgs() << " maximum nesting levels = " << MaxLevels << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00003399
NAKAMURA Takumid8422ce2015-03-05 01:25:12 +00003400 FullDependence Result(Src, Dst, PossiblyLoopIndependent, CommonLevels);
Sebastian Pop59b61b92012-10-11 07:32:34 +00003401 ++TotalArrayPairs;
3402
Sebastian Popbf6e1c22018-03-06 21:55:59 +00003403 unsigned Pairs = 1;
3404 SmallVector<Subscript, 2> Pair(Pairs);
3405 const SCEV *SrcSCEV = SE->getSCEV(SrcPtr);
3406 const SCEV *DstSCEV = SE->getSCEV(DstPtr);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003407 LLVM_DEBUG(dbgs() << " SrcSCEV = " << *SrcSCEV << "\n");
3408 LLVM_DEBUG(dbgs() << " DstSCEV = " << *DstSCEV << "\n");
Sebastian Popbf6e1c22018-03-06 21:55:59 +00003409 Pair[0].Src = SrcSCEV;
3410 Pair[0].Dst = DstSCEV;
Preston Briggs3ad39492012-11-21 23:50:04 +00003411
Sebastian Popbf6e1c22018-03-06 21:55:59 +00003412 if (Delinearize) {
Hal Finkel0ef2b102015-08-19 02:56:36 +00003413 if (tryDelinearize(Src, Dst, Pair)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003414 LLVM_DEBUG(dbgs() << " delinearized\n");
Hal Finkel0ef2b102015-08-19 02:56:36 +00003415 Pairs = Pair.size();
3416 }
Sebastian Popc62c6792013-11-12 22:47:20 +00003417 }
3418
Preston Briggs3ad39492012-11-21 23:50:04 +00003419 for (unsigned P = 0; P < Pairs; ++P) {
3420 Pair[P].Loops.resize(MaxLevels + 1);
3421 Pair[P].GroupLoops.resize(MaxLevels + 1);
3422 Pair[P].Group.resize(Pairs);
3423 removeMatchingExtensions(&Pair[P]);
3424 Pair[P].Classification =
3425 classifyPair(Pair[P].Src, LI->getLoopFor(Src->getParent()),
3426 Pair[P].Dst, LI->getLoopFor(Dst->getParent()),
3427 Pair[P].Loops);
3428 Pair[P].GroupLoops = Pair[P].Loops;
3429 Pair[P].Group.set(P);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003430 LLVM_DEBUG(dbgs() << " subscript " << P << "\n");
3431 LLVM_DEBUG(dbgs() << "\tsrc = " << *Pair[P].Src << "\n");
3432 LLVM_DEBUG(dbgs() << "\tdst = " << *Pair[P].Dst << "\n");
3433 LLVM_DEBUG(dbgs() << "\tclass = " << Pair[P].Classification << "\n");
3434 LLVM_DEBUG(dbgs() << "\tloops = ");
3435 LLVM_DEBUG(dumpSmallBitVector(Pair[P].Loops));
Sebastian Pop59b61b92012-10-11 07:32:34 +00003436 }
3437
3438 SmallBitVector Separable(Pairs);
3439 SmallBitVector Coupled(Pairs);
3440
3441 // Partition subscripts into separable and minimally-coupled groups
3442 // Algorithm in paper is algorithmically better;
3443 // this may be faster in practice. Check someday.
3444 //
3445 // Here's an example of how it works. Consider this code:
3446 //
3447 // for (i = ...) {
3448 // for (j = ...) {
3449 // for (k = ...) {
3450 // for (l = ...) {
3451 // for (m = ...) {
3452 // A[i][j][k][m] = ...;
3453 // ... = A[0][j][l][i + j];
3454 // }
3455 // }
3456 // }
3457 // }
3458 // }
3459 //
3460 // There are 4 subscripts here:
3461 // 0 [i] and [0]
3462 // 1 [j] and [j]
3463 // 2 [k] and [l]
3464 // 3 [m] and [i + j]
3465 //
3466 // We've already classified each subscript pair as ZIV, SIV, etc.,
3467 // and collected all the loops mentioned by pair P in Pair[P].Loops.
3468 // In addition, we've initialized Pair[P].GroupLoops to Pair[P].Loops
3469 // and set Pair[P].Group = {P}.
3470 //
3471 // Src Dst Classification Loops GroupLoops Group
3472 // 0 [i] [0] SIV {1} {1} {0}
3473 // 1 [j] [j] SIV {2} {2} {1}
3474 // 2 [k] [l] RDIV {3,4} {3,4} {2}
3475 // 3 [m] [i + j] MIV {1,2,5} {1,2,5} {3}
3476 //
3477 // For each subscript SI 0 .. 3, we consider each remaining subscript, SJ.
3478 // So, 0 is compared against 1, 2, and 3; 1 is compared against 2 and 3, etc.
3479 //
3480 // We begin by comparing 0 and 1. The intersection of the GroupLoops is empty.
3481 // Next, 0 and 2. Again, the intersection of their GroupLoops is empty.
3482 // Next 0 and 3. The intersection of their GroupLoop = {1}, not empty,
3483 // so Pair[3].Group = {0,3} and Done = false (that is, 0 will not be added
3484 // to either Separable or Coupled).
3485 //
3486 // Next, we consider 1 and 2. The intersection of the GroupLoops is empty.
3487 // Next, 1 and 3. The intersectionof their GroupLoops = {2}, not empty,
3488 // so Pair[3].Group = {0, 1, 3} and Done = false.
3489 //
3490 // Next, we compare 2 against 3. The intersection of the GroupLoops is empty.
3491 // Since Done remains true, we add 2 to the set of Separable pairs.
3492 //
3493 // Finally, we consider 3. There's nothing to compare it with,
3494 // so Done remains true and we add it to the Coupled set.
3495 // Pair[3].Group = {0, 1, 3} and GroupLoops = {1, 2, 5}.
3496 //
3497 // In the end, we've got 1 separable subscript and 1 coupled group.
3498 for (unsigned SI = 0; SI < Pairs; ++SI) {
3499 if (Pair[SI].Classification == Subscript::NonLinear) {
3500 // ignore these, but collect loops for later
3501 ++NonlinearSubscriptPairs;
3502 collectCommonLoops(Pair[SI].Src,
3503 LI->getLoopFor(Src->getParent()),
3504 Pair[SI].Loops);
3505 collectCommonLoops(Pair[SI].Dst,
3506 LI->getLoopFor(Dst->getParent()),
3507 Pair[SI].Loops);
NAKAMURA Takumid8422ce2015-03-05 01:25:12 +00003508 Result.Consistent = false;
NAKAMURA Takumi478559a2015-03-05 01:25:19 +00003509 } else if (Pair[SI].Classification == Subscript::ZIV) {
Sebastian Pop59b61b92012-10-11 07:32:34 +00003510 // always separable
3511 Separable.set(SI);
3512 }
3513 else {
3514 // SIV, RDIV, or MIV, so check for coupled group
3515 bool Done = true;
3516 for (unsigned SJ = SI + 1; SJ < Pairs; ++SJ) {
3517 SmallBitVector Intersection = Pair[SI].GroupLoops;
3518 Intersection &= Pair[SJ].GroupLoops;
3519 if (Intersection.any()) {
3520 // accumulate set of all the loops in group
3521 Pair[SJ].GroupLoops |= Pair[SI].GroupLoops;
3522 // accumulate set of all subscripts in group
3523 Pair[SJ].Group |= Pair[SI].Group;
3524 Done = false;
3525 }
3526 }
3527 if (Done) {
3528 if (Pair[SI].Group.count() == 1) {
3529 Separable.set(SI);
3530 ++SeparableSubscriptPairs;
3531 }
3532 else {
3533 Coupled.set(SI);
3534 ++CoupledSubscriptPairs;
3535 }
3536 }
3537 }
3538 }
3539
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003540 LLVM_DEBUG(dbgs() << " Separable = ");
3541 LLVM_DEBUG(dumpSmallBitVector(Separable));
3542 LLVM_DEBUG(dbgs() << " Coupled = ");
3543 LLVM_DEBUG(dumpSmallBitVector(Coupled));
Sebastian Pop59b61b92012-10-11 07:32:34 +00003544
3545 Constraint NewConstraint;
3546 NewConstraint.setAny(SE);
3547
3548 // test separable subscripts
Francis Visoiu Mistrihb52e0362017-05-17 01:07:53 +00003549 for (unsigned SI : Separable.set_bits()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003550 LLVM_DEBUG(dbgs() << "testing subscript " << SI);
Sebastian Pop59b61b92012-10-11 07:32:34 +00003551 switch (Pair[SI].Classification) {
3552 case Subscript::ZIV:
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003553 LLVM_DEBUG(dbgs() << ", ZIV\n");
NAKAMURA Takumid8422ce2015-03-05 01:25:12 +00003554 if (testZIV(Pair[SI].Src, Pair[SI].Dst, Result))
Craig Topper9f008862014-04-15 04:59:12 +00003555 return nullptr;
Sebastian Pop59b61b92012-10-11 07:32:34 +00003556 break;
3557 case Subscript::SIV: {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003558 LLVM_DEBUG(dbgs() << ", SIV\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00003559 unsigned Level;
Craig Topper9f008862014-04-15 04:59:12 +00003560 const SCEV *SplitIter = nullptr;
NAKAMURA Takumi478559a2015-03-05 01:25:19 +00003561 if (testSIV(Pair[SI].Src, Pair[SI].Dst, Level, Result, NewConstraint,
3562 SplitIter))
Craig Topper9f008862014-04-15 04:59:12 +00003563 return nullptr;
Sebastian Pop59b61b92012-10-11 07:32:34 +00003564 break;
3565 }
3566 case Subscript::RDIV:
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003567 LLVM_DEBUG(dbgs() << ", RDIV\n");
NAKAMURA Takumid8422ce2015-03-05 01:25:12 +00003568 if (testRDIV(Pair[SI].Src, Pair[SI].Dst, Result))
Craig Topper9f008862014-04-15 04:59:12 +00003569 return nullptr;
Sebastian Pop59b61b92012-10-11 07:32:34 +00003570 break;
3571 case Subscript::MIV:
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003572 LLVM_DEBUG(dbgs() << ", MIV\n");
NAKAMURA Takumid8422ce2015-03-05 01:25:12 +00003573 if (testMIV(Pair[SI].Src, Pair[SI].Dst, Pair[SI].Loops, Result))
Craig Topper9f008862014-04-15 04:59:12 +00003574 return nullptr;
Sebastian Pop59b61b92012-10-11 07:32:34 +00003575 break;
3576 default:
3577 llvm_unreachable("subscript has unexpected classification");
3578 }
3579 }
3580
3581 if (Coupled.count()) {
3582 // test coupled subscript groups
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003583 LLVM_DEBUG(dbgs() << "starting on coupled subscripts\n");
3584 LLVM_DEBUG(dbgs() << "MaxLevels + 1 = " << MaxLevels + 1 << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00003585 SmallVector<Constraint, 4> Constraints(MaxLevels + 1);
3586 for (unsigned II = 0; II <= MaxLevels; ++II)
3587 Constraints[II].setAny(SE);
Francis Visoiu Mistrihb52e0362017-05-17 01:07:53 +00003588 for (unsigned SI : Coupled.set_bits()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003589 LLVM_DEBUG(dbgs() << "testing subscript group " << SI << " { ");
Sebastian Pop59b61b92012-10-11 07:32:34 +00003590 SmallBitVector Group(Pair[SI].Group);
3591 SmallBitVector Sivs(Pairs);
3592 SmallBitVector Mivs(Pairs);
3593 SmallBitVector ConstrainedLevels(MaxLevels + 1);
Jingyue Wua84feb12015-05-29 16:58:08 +00003594 SmallVector<Subscript *, 4> PairsInGroup;
Francis Visoiu Mistrihb52e0362017-05-17 01:07:53 +00003595 for (unsigned SJ : Group.set_bits()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003596 LLVM_DEBUG(dbgs() << SJ << " ");
Sebastian Pop59b61b92012-10-11 07:32:34 +00003597 if (Pair[SJ].Classification == Subscript::SIV)
3598 Sivs.set(SJ);
3599 else
3600 Mivs.set(SJ);
Jingyue Wua84feb12015-05-29 16:58:08 +00003601 PairsInGroup.push_back(&Pair[SJ]);
Sebastian Pop59b61b92012-10-11 07:32:34 +00003602 }
Jingyue Wua84feb12015-05-29 16:58:08 +00003603 unifySubscriptType(PairsInGroup);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003604 LLVM_DEBUG(dbgs() << "}\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00003605 while (Sivs.any()) {
3606 bool Changed = false;
Francis Visoiu Mistrihb52e0362017-05-17 01:07:53 +00003607 for (unsigned SJ : Sivs.set_bits()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003608 LLVM_DEBUG(dbgs() << "testing subscript " << SJ << ", SIV\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00003609 // SJ is an SIV subscript that's part of the current coupled group
3610 unsigned Level;
Craig Topper9f008862014-04-15 04:59:12 +00003611 const SCEV *SplitIter = nullptr;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003612 LLVM_DEBUG(dbgs() << "SIV\n");
NAKAMURA Takumi478559a2015-03-05 01:25:19 +00003613 if (testSIV(Pair[SJ].Src, Pair[SJ].Dst, Level, Result, NewConstraint,
3614 SplitIter))
Craig Topper9f008862014-04-15 04:59:12 +00003615 return nullptr;
Sebastian Pop59b61b92012-10-11 07:32:34 +00003616 ConstrainedLevels.set(Level);
3617 if (intersectConstraints(&Constraints[Level], &NewConstraint)) {
3618 if (Constraints[Level].isEmpty()) {
3619 ++DeltaIndependence;
Craig Topper9f008862014-04-15 04:59:12 +00003620 return nullptr;
Sebastian Pop59b61b92012-10-11 07:32:34 +00003621 }
3622 Changed = true;
3623 }
3624 Sivs.reset(SJ);
3625 }
3626 if (Changed) {
3627 // propagate, possibly creating new SIVs and ZIVs
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003628 LLVM_DEBUG(dbgs() << " propagating\n");
3629 LLVM_DEBUG(dbgs() << "\tMivs = ");
3630 LLVM_DEBUG(dumpSmallBitVector(Mivs));
Francis Visoiu Mistrihb52e0362017-05-17 01:07:53 +00003631 for (unsigned SJ : Mivs.set_bits()) {
Sebastian Pop59b61b92012-10-11 07:32:34 +00003632 // SJ is an MIV subscript that's part of the current coupled group
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003633 LLVM_DEBUG(dbgs() << "\tSJ = " << SJ << "\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00003634 if (propagate(Pair[SJ].Src, Pair[SJ].Dst, Pair[SJ].Loops,
NAKAMURA Takumid8422ce2015-03-05 01:25:12 +00003635 Constraints, Result.Consistent)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003636 LLVM_DEBUG(dbgs() << "\t Changed\n");
Sebastian Pop59b61b92012-10-11 07:32:34 +00003637 ++DeltaPropagations;
3638 Pair[SJ].Classification =
3639 classifyPair(Pair[SJ].Src, LI->getLoopFor(Src->getParent()),
3640 Pair[SJ].Dst, LI->getLoopFor(Dst->getParent()),
3641 Pair[SJ].Loops);
3642 switch (Pair[SJ].Classification) {
3643 case Subscript::ZIV:
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003644 LLVM_DEBUG(dbgs() << "ZIV\n");
NAKAMURA Takumid8422ce2015-03-05 01:25:12 +00003645 if (testZIV(Pair[SJ].Src, Pair[SJ].Dst, Result))
Craig Topper9f008862014-04-15 04:59:12 +00003646 return nullptr;
Sebastian Pop59b61b92012-10-11 07:32:34 +00003647 Mivs.reset(SJ);
3648 break;
3649 case Subscript::SIV:
3650 Sivs.set(SJ);
3651 Mivs.reset(SJ);
3652 break;
3653 case Subscript::RDIV:
3654 case Subscript::MIV:
3655 break;
3656 default:
3657 llvm_unreachable("bad subscript classification");
3658 }
3659 }
3660 }
3661 }
3662 }
3663
3664 // test & propagate remaining RDIVs
Francis Visoiu Mistrihb52e0362017-05-17 01:07:53 +00003665 for (unsigned SJ : Mivs.set_bits()) {
Sebastian Pop59b61b92012-10-11 07:32:34 +00003666 if (Pair[SJ].Classification == Subscript::RDIV) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003667 LLVM_DEBUG(dbgs() << "RDIV test\n");
NAKAMURA Takumid8422ce2015-03-05 01:25:12 +00003668 if (testRDIV(Pair[SJ].Src, Pair[SJ].Dst, Result))
Craig Topper9f008862014-04-15 04:59:12 +00003669 return nullptr;
Sebastian Pop59b61b92012-10-11 07:32:34 +00003670 // I don't yet understand how to propagate RDIV results
3671 Mivs.reset(SJ);
3672 }
3673 }
3674
3675 // test remaining MIVs
3676 // This code is temporary.
3677 // Better to somehow test all remaining subscripts simultaneously.
Francis Visoiu Mistrihb52e0362017-05-17 01:07:53 +00003678 for (unsigned SJ : Mivs.set_bits()) {
Sebastian Pop59b61b92012-10-11 07:32:34 +00003679 if (Pair[SJ].Classification == Subscript::MIV) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003680 LLVM_DEBUG(dbgs() << "MIV test\n");
NAKAMURA Takumid8422ce2015-03-05 01:25:12 +00003681 if (testMIV(Pair[SJ].Src, Pair[SJ].Dst, Pair[SJ].Loops, Result))
Craig Topper9f008862014-04-15 04:59:12 +00003682 return nullptr;
Sebastian Pop59b61b92012-10-11 07:32:34 +00003683 }
3684 else
3685 llvm_unreachable("expected only MIV subscripts at this point");
3686 }
3687
NAKAMURA Takumid8422ce2015-03-05 01:25:12 +00003688 // update Result.DV from constraint vector
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003689 LLVM_DEBUG(dbgs() << " updating\n");
Francis Visoiu Mistrihb52e0362017-05-17 01:07:53 +00003690 for (unsigned SJ : ConstrainedLevels.set_bits()) {
3691 if (SJ > CommonLevels)
Karthik Bhat8d7f7ed2015-03-10 14:32:02 +00003692 break;
NAKAMURA Takumid8422ce2015-03-05 01:25:12 +00003693 updateDirection(Result.DV[SJ - 1], Constraints[SJ]);
3694 if (Result.DV[SJ - 1].Direction == Dependence::DVEntry::NONE)
Craig Topper9f008862014-04-15 04:59:12 +00003695 return nullptr;
Sebastian Pop59b61b92012-10-11 07:32:34 +00003696 }
3697 }
3698 }
3699
Preston Briggs4eb7ee52012-11-29 04:30:52 +00003700 // Make sure the Scalar flags are set correctly.
Sebastian Pop59b61b92012-10-11 07:32:34 +00003701 SmallBitVector CompleteLoops(MaxLevels + 1);
3702 for (unsigned SI = 0; SI < Pairs; ++SI)
3703 CompleteLoops |= Pair[SI].Loops;
3704 for (unsigned II = 1; II <= CommonLevels; ++II)
3705 if (CompleteLoops[II])
NAKAMURA Takumid8422ce2015-03-05 01:25:12 +00003706 Result.DV[II - 1].Scalar = false;
Sebastian Pop59b61b92012-10-11 07:32:34 +00003707
Sebastian Pop59b61b92012-10-11 07:32:34 +00003708 if (PossiblyLoopIndependent) {
Preston Briggs5cb8cfa2012-11-27 19:12:26 +00003709 // Make sure the LoopIndependent flag is set correctly.
3710 // All directions must include equal, otherwise no
3711 // loop-independent dependence is possible.
Sebastian Pop59b61b92012-10-11 07:32:34 +00003712 for (unsigned II = 1; II <= CommonLevels; ++II) {
NAKAMURA Takumid8422ce2015-03-05 01:25:12 +00003713 if (!(Result.getDirection(II) & Dependence::DVEntry::EQ)) {
3714 Result.LoopIndependent = false;
Sebastian Pop59b61b92012-10-11 07:32:34 +00003715 break;
3716 }
3717 }
3718 }
Preston Briggs5cb8cfa2012-11-27 19:12:26 +00003719 else {
3720 // On the other hand, if all directions are equal and there's no
3721 // loop-independent dependence possible, then no dependence exists.
3722 bool AllEqual = true;
3723 for (unsigned II = 1; II <= CommonLevels; ++II) {
NAKAMURA Takumid8422ce2015-03-05 01:25:12 +00003724 if (Result.getDirection(II) != Dependence::DVEntry::EQ) {
Preston Briggs4eb7ee52012-11-29 04:30:52 +00003725 AllEqual = false;
3726 break;
Preston Briggs5cb8cfa2012-11-27 19:12:26 +00003727 }
3728 }
3729 if (AllEqual)
Craig Topper9f008862014-04-15 04:59:12 +00003730 return nullptr;
Preston Briggs5cb8cfa2012-11-27 19:12:26 +00003731 }
Sebastian Pop59b61b92012-10-11 07:32:34 +00003732
David Blaikie47039dc2015-07-31 21:37:09 +00003733 return make_unique<FullDependence>(std::move(Result));
Sebastian Pop59b61b92012-10-11 07:32:34 +00003734}
3735
3736
3737
3738//===----------------------------------------------------------------------===//
3739// getSplitIteration -
3740// Rather than spend rarely-used space recording the splitting iteration
3741// during the Weak-Crossing SIV test, we re-compute it on demand.
3742// The re-computation is basically a repeat of the entire dependence test,
3743// though simplified since we know that the dependence exists.
3744// It's tedious, since we must go through all propagations, etc.
3745//
Preston Briggs3ad39492012-11-21 23:50:04 +00003746// Care is required to keep this code up to date with respect to the routine
3747// above, depends().
Sebastian Pop59b61b92012-10-11 07:32:34 +00003748//
3749// Generally, the dependence analyzer will be used to build
3750// a dependence graph for a function (basically a map from instructions
3751// to dependences). Looking for cycles in the graph shows us loops
3752// that cannot be trivially vectorized/parallelized.
3753//
3754// We can try to improve the situation by examining all the dependences
3755// that make up the cycle, looking for ones we can break.
3756// Sometimes, peeling the first or last iteration of a loop will break
3757// dependences, and we've got flags for those possibilities.
3758// Sometimes, splitting a loop at some other iteration will do the trick,
3759// and we've got a flag for that case. Rather than waste the space to
3760// record the exact iteration (since we rarely know), we provide
3761// a method that calculates the iteration. It's a drag that it must work
3762// from scratch, but wonderful in that it's possible.
3763//
3764// Here's an example:
3765//
3766// for (i = 0; i < 10; i++)
3767// A[i] = ...
3768// ... = A[11 - i]
3769//
3770// There's a loop-carried flow dependence from the store to the load,
3771// found by the weak-crossing SIV test. The dependence will have a flag,
3772// indicating that the dependence can be broken by splitting the loop.
3773// Calling getSplitIteration will return 5.
3774// Splitting the loop breaks the dependence, like so:
3775//
3776// for (i = 0; i <= 5; i++)
3777// A[i] = ...
3778// ... = A[11 - i]
3779// for (i = 6; i < 10; i++)
3780// A[i] = ...
3781// ... = A[11 - i]
3782//
3783// breaks the dependence and allows us to vectorize/parallelize
3784// both loops.
Chandler Carruth49c22192016-05-12 22:19:39 +00003785const SCEV *DependenceInfo::getSplitIteration(const Dependence &Dep,
3786 unsigned SplitLevel) {
Dylan Noblesmithd96ce662014-08-25 00:28:35 +00003787 assert(Dep.isSplitable(SplitLevel) &&
Sebastian Pop59b61b92012-10-11 07:32:34 +00003788 "Dep should be splitable at SplitLevel");
Dylan Noblesmithd96ce662014-08-25 00:28:35 +00003789 Instruction *Src = Dep.getSrc();
3790 Instruction *Dst = Dep.getDst();
Sebastian Pop59b61b92012-10-11 07:32:34 +00003791 assert(Src->mayReadFromMemory() || Src->mayWriteToMemory());
3792 assert(Dst->mayReadFromMemory() || Dst->mayWriteToMemory());
3793 assert(isLoadOrStore(Src));
3794 assert(isLoadOrStore(Dst));
Renato Golin038ede22018-03-09 21:05:58 +00003795 Value *SrcPtr = getLoadStorePointerOperand(Src);
3796 Value *DstPtr = getLoadStorePointerOperand(Dst);
David Green5ef933b2018-04-10 11:37:21 +00003797 assert(underlyingObjectsAlias(AA, F->getParent()->getDataLayout(),
3798 MemoryLocation::get(Dst),
3799 MemoryLocation::get(Src)) == MustAlias);
Sebastian Pop59b61b92012-10-11 07:32:34 +00003800
3801 // establish loop nesting levels
3802 establishNestingLevels(Src, Dst);
3803
3804 FullDependence Result(Src, Dst, false, CommonLevels);
3805
Sebastian Popbf6e1c22018-03-06 21:55:59 +00003806 unsigned Pairs = 1;
3807 SmallVector<Subscript, 2> Pair(Pairs);
3808 const SCEV *SrcSCEV = SE->getSCEV(SrcPtr);
3809 const SCEV *DstSCEV = SE->getSCEV(DstPtr);
3810 Pair[0].Src = SrcSCEV;
3811 Pair[0].Dst = DstSCEV;
Preston Briggs3ad39492012-11-21 23:50:04 +00003812
Sebastian Popbf6e1c22018-03-06 21:55:59 +00003813 if (Delinearize) {
Hal Finkel0ef2b102015-08-19 02:56:36 +00003814 if (tryDelinearize(Src, Dst, Pair)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003815 LLVM_DEBUG(dbgs() << " delinearized\n");
Hal Finkel0ef2b102015-08-19 02:56:36 +00003816 Pairs = Pair.size();
3817 }
Sebastian Popc62c6792013-11-12 22:47:20 +00003818 }
3819
Preston Briggs3ad39492012-11-21 23:50:04 +00003820 for (unsigned P = 0; P < Pairs; ++P) {
3821 Pair[P].Loops.resize(MaxLevels + 1);
3822 Pair[P].GroupLoops.resize(MaxLevels + 1);
3823 Pair[P].Group.resize(Pairs);
3824 removeMatchingExtensions(&Pair[P]);
3825 Pair[P].Classification =
3826 classifyPair(Pair[P].Src, LI->getLoopFor(Src->getParent()),
3827 Pair[P].Dst, LI->getLoopFor(Dst->getParent()),
3828 Pair[P].Loops);
3829 Pair[P].GroupLoops = Pair[P].Loops;
3830 Pair[P].Group.set(P);
Sebastian Pop59b61b92012-10-11 07:32:34 +00003831 }
3832
3833 SmallBitVector Separable(Pairs);
3834 SmallBitVector Coupled(Pairs);
3835
3836 // partition subscripts into separable and minimally-coupled groups
3837 for (unsigned SI = 0; SI < Pairs; ++SI) {
3838 if (Pair[SI].Classification == Subscript::NonLinear) {
3839 // ignore these, but collect loops for later
3840 collectCommonLoops(Pair[SI].Src,
3841 LI->getLoopFor(Src->getParent()),
3842 Pair[SI].Loops);
3843 collectCommonLoops(Pair[SI].Dst,
3844 LI->getLoopFor(Dst->getParent()),
3845 Pair[SI].Loops);
3846 Result.Consistent = false;
3847 }
3848 else if (Pair[SI].Classification == Subscript::ZIV)
3849 Separable.set(SI);
3850 else {
3851 // SIV, RDIV, or MIV, so check for coupled group
3852 bool Done = true;
3853 for (unsigned SJ = SI + 1; SJ < Pairs; ++SJ) {
3854 SmallBitVector Intersection = Pair[SI].GroupLoops;
3855 Intersection &= Pair[SJ].GroupLoops;
3856 if (Intersection.any()) {
3857 // accumulate set of all the loops in group
3858 Pair[SJ].GroupLoops |= Pair[SI].GroupLoops;
3859 // accumulate set of all subscripts in group
3860 Pair[SJ].Group |= Pair[SI].Group;
3861 Done = false;
3862 }
3863 }
3864 if (Done) {
3865 if (Pair[SI].Group.count() == 1)
3866 Separable.set(SI);
3867 else
3868 Coupled.set(SI);
3869 }
3870 }
3871 }
3872
3873 Constraint NewConstraint;
3874 NewConstraint.setAny(SE);
3875
3876 // test separable subscripts
Francis Visoiu Mistrihb52e0362017-05-17 01:07:53 +00003877 for (unsigned SI : Separable.set_bits()) {
Sebastian Pop59b61b92012-10-11 07:32:34 +00003878 switch (Pair[SI].Classification) {
3879 case Subscript::SIV: {
3880 unsigned Level;
Craig Topper9f008862014-04-15 04:59:12 +00003881 const SCEV *SplitIter = nullptr;
Sebastian Pop59b61b92012-10-11 07:32:34 +00003882 (void) testSIV(Pair[SI].Src, Pair[SI].Dst, Level,
3883 Result, NewConstraint, SplitIter);
3884 if (Level == SplitLevel) {
Craig Topper9f008862014-04-15 04:59:12 +00003885 assert(SplitIter != nullptr);
Sebastian Pop59b61b92012-10-11 07:32:34 +00003886 return SplitIter;
3887 }
3888 break;
3889 }
3890 case Subscript::ZIV:
3891 case Subscript::RDIV:
3892 case Subscript::MIV:
3893 break;
3894 default:
3895 llvm_unreachable("subscript has unexpected classification");
3896 }
3897 }
3898
3899 if (Coupled.count()) {
3900 // test coupled subscript groups
3901 SmallVector<Constraint, 4> Constraints(MaxLevels + 1);
3902 for (unsigned II = 0; II <= MaxLevels; ++II)
3903 Constraints[II].setAny(SE);
Francis Visoiu Mistrihb52e0362017-05-17 01:07:53 +00003904 for (unsigned SI : Coupled.set_bits()) {
Sebastian Pop59b61b92012-10-11 07:32:34 +00003905 SmallBitVector Group(Pair[SI].Group);
3906 SmallBitVector Sivs(Pairs);
3907 SmallBitVector Mivs(Pairs);
3908 SmallBitVector ConstrainedLevels(MaxLevels + 1);
Francis Visoiu Mistrihb52e0362017-05-17 01:07:53 +00003909 for (unsigned SJ : Group.set_bits()) {
Sebastian Pop59b61b92012-10-11 07:32:34 +00003910 if (Pair[SJ].Classification == Subscript::SIV)
3911 Sivs.set(SJ);
3912 else
3913 Mivs.set(SJ);
3914 }
3915 while (Sivs.any()) {
3916 bool Changed = false;
Francis Visoiu Mistrihb52e0362017-05-17 01:07:53 +00003917 for (unsigned SJ : Sivs.set_bits()) {
Sebastian Pop59b61b92012-10-11 07:32:34 +00003918 // SJ is an SIV subscript that's part of the current coupled group
3919 unsigned Level;
Craig Topper9f008862014-04-15 04:59:12 +00003920 const SCEV *SplitIter = nullptr;
Sebastian Pop59b61b92012-10-11 07:32:34 +00003921 (void) testSIV(Pair[SJ].Src, Pair[SJ].Dst, Level,
3922 Result, NewConstraint, SplitIter);
3923 if (Level == SplitLevel && SplitIter)
3924 return SplitIter;
3925 ConstrainedLevels.set(Level);
3926 if (intersectConstraints(&Constraints[Level], &NewConstraint))
3927 Changed = true;
3928 Sivs.reset(SJ);
3929 }
3930 if (Changed) {
3931 // propagate, possibly creating new SIVs and ZIVs
Francis Visoiu Mistrihb52e0362017-05-17 01:07:53 +00003932 for (unsigned SJ : Mivs.set_bits()) {
Sebastian Pop59b61b92012-10-11 07:32:34 +00003933 // SJ is an MIV subscript that's part of the current coupled group
3934 if (propagate(Pair[SJ].Src, Pair[SJ].Dst,
3935 Pair[SJ].Loops, Constraints, Result.Consistent)) {
3936 Pair[SJ].Classification =
3937 classifyPair(Pair[SJ].Src, LI->getLoopFor(Src->getParent()),
3938 Pair[SJ].Dst, LI->getLoopFor(Dst->getParent()),
3939 Pair[SJ].Loops);
3940 switch (Pair[SJ].Classification) {
3941 case Subscript::ZIV:
3942 Mivs.reset(SJ);
3943 break;
3944 case Subscript::SIV:
3945 Sivs.set(SJ);
3946 Mivs.reset(SJ);
3947 break;
3948 case Subscript::RDIV:
3949 case Subscript::MIV:
3950 break;
3951 default:
3952 llvm_unreachable("bad subscript classification");
3953 }
3954 }
3955 }
3956 }
3957 }
3958 }
3959 }
3960 llvm_unreachable("somehow reached end of routine");
Craig Topper9f008862014-04-15 04:59:12 +00003961 return nullptr;
Sebastian Pop59b61b92012-10-11 07:32:34 +00003962}