1 //===- AffineAnalysis.cpp - Affine structures analysis routines -----------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements miscellaneous analysis routines for affine structures
10 // (expressions, maps, sets), and other utilities relying on such analysis.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "mlir/Dialect/Affine/Analysis/AffineAnalysis.h"
15 #include "mlir/Analysis/SliceAnalysis.h"
16 #include "mlir/Dialect/Affine/Analysis/LoopAnalysis.h"
17 #include "mlir/Dialect/Affine/Analysis/Utils.h"
18 #include "mlir/Dialect/Affine/IR/AffineOps.h"
19 #include "mlir/Dialect/Affine/IR/AffineValueMap.h"
20 #include "mlir/Dialect/Func/IR/FuncOps.h"
21 #include "mlir/IR/AffineExprVisitor.h"
22 #include "mlir/IR/BuiltinOps.h"
23 #include "mlir/IR/IntegerSet.h"
24 #include "mlir/Interfaces/ViewLikeInterface.h"
25 #include "llvm/ADT/TypeSwitch.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/raw_ostream.h"
28 
29 #define DEBUG_TYPE "affine-analysis"
30 
31 using namespace mlir;
32 using namespace presburger;
33 
34 /// Get the value that is being reduced by `pos`-th reduction in the loop if
35 /// such a reduction can be performed by affine parallel loops. This assumes
36 /// floating-point operations are commutative. On success, `kind` will be the
37 /// reduction kind suitable for use in affine parallel loop builder. If the
38 /// reduction is not supported, returns null.
39 static Value getSupportedReduction(AffineForOp forOp, unsigned pos,
40                                    arith::AtomicRMWKind &kind) {
41   SmallVector<Operation *> combinerOps;
42   Value reducedVal =
43       matchReduction(forOp.getRegionIterArgs(), pos, combinerOps);
44   if (!reducedVal)
45     return nullptr;
46 
47   // Expected only one combiner operation.
48   if (combinerOps.size() > 1)
49     return nullptr;
50 
51   Operation *combinerOp = combinerOps.back();
52   Optional<arith::AtomicRMWKind> maybeKind =
53       TypeSwitch<Operation *, Optional<arith::AtomicRMWKind>>(combinerOp)
54           .Case([](arith::AddFOp) { return arith::AtomicRMWKind::addf; })
55           .Case([](arith::MulFOp) { return arith::AtomicRMWKind::mulf; })
56           .Case([](arith::AddIOp) { return arith::AtomicRMWKind::addi; })
57           .Case([](arith::AndIOp) { return arith::AtomicRMWKind::andi; })
58           .Case([](arith::OrIOp) { return arith::AtomicRMWKind::ori; })
59           .Case([](arith::MulIOp) { return arith::AtomicRMWKind::muli; })
60           .Case([](arith::MinFOp) { return arith::AtomicRMWKind::minf; })
61           .Case([](arith::MaxFOp) { return arith::AtomicRMWKind::maxf; })
62           .Case([](arith::MinSIOp) { return arith::AtomicRMWKind::mins; })
63           .Case([](arith::MaxSIOp) { return arith::AtomicRMWKind::maxs; })
64           .Case([](arith::MinUIOp) { return arith::AtomicRMWKind::minu; })
65           .Case([](arith::MaxUIOp) { return arith::AtomicRMWKind::maxu; })
66           .Default([](Operation *) -> Optional<arith::AtomicRMWKind> {
67             // TODO: AtomicRMW supports other kinds of reductions this is
68             // currently not detecting, add those when the need arises.
69             return llvm::None;
70           });
71   if (!maybeKind)
72     return nullptr;
73 
74   kind = *maybeKind;
75   return reducedVal;
76 }
77 
78 /// Populate `supportedReductions` with descriptors of the supported reductions.
79 void mlir::getSupportedReductions(
80     AffineForOp forOp, SmallVectorImpl<LoopReduction> &supportedReductions) {
81   unsigned numIterArgs = forOp.getNumIterOperands();
82   if (numIterArgs == 0)
83     return;
84   supportedReductions.reserve(numIterArgs);
85   for (unsigned i = 0; i < numIterArgs; ++i) {
86     arith::AtomicRMWKind kind;
87     if (Value value = getSupportedReduction(forOp, i, kind))
88       supportedReductions.emplace_back(LoopReduction{kind, i, value});
89   }
90 }
91 
92 /// Returns true if `forOp' is a parallel loop. If `parallelReductions` is
93 /// provided, populates it with descriptors of the parallelizable reductions and
94 /// treats them as not preventing parallelization.
95 bool mlir::isLoopParallel(AffineForOp forOp,
96                           SmallVectorImpl<LoopReduction> *parallelReductions) {
97   unsigned numIterArgs = forOp.getNumIterOperands();
98 
99   // Loop is not parallel if it has SSA loop-carried dependences and reduction
100   // detection is not requested.
101   if (numIterArgs > 0 && !parallelReductions)
102     return false;
103 
104   // Find supported reductions of requested.
105   if (parallelReductions) {
106     getSupportedReductions(forOp, *parallelReductions);
107     // Return later to allow for identifying all parallel reductions even if the
108     // loop is not parallel.
109     if (parallelReductions->size() != numIterArgs)
110       return false;
111   }
112 
113   // Check memory dependences.
114   return isLoopMemoryParallel(forOp);
115 }
116 
117 /// Returns true if `op` is an alloc-like op, i.e., one allocating memrefs.
118 static bool isAllocLikeOp(Operation *op) {
119   auto memEffects = dyn_cast<MemoryEffectOpInterface>(op);
120   return memEffects && memEffects.hasEffect<MemoryEffects::Allocate>();
121 }
122 
123 /// Returns true if `v` is allocated locally to `enclosingOp` -- i.e., it is
124 /// allocated by an operation nested within `enclosingOp`.
125 static bool isLocallyDefined(Value v, Operation *enclosingOp) {
126   Operation *defOp = v.getDefiningOp();
127   if (!defOp)
128     return false;
129 
130   if (isAllocLikeOp(defOp) && enclosingOp->isProperAncestor(defOp))
131     return true;
132 
133   // Aliasing ops.
134   auto viewOp = dyn_cast<ViewLikeOpInterface>(defOp);
135   return viewOp && isLocallyDefined(viewOp.getViewSource(), enclosingOp);
136 }
137 
138 bool mlir::isLoopMemoryParallel(AffineForOp forOp) {
139   // Any memref-typed iteration arguments are treated as serializing.
140   if (llvm::any_of(forOp.getResultTypes(),
141                    [](Type type) { return type.isa<BaseMemRefType>(); }))
142     return false;
143 
144   // Collect all load and store ops in loop nest rooted at 'forOp'.
145   SmallVector<Operation *, 8> loadAndStoreOps;
146   auto walkResult = forOp.walk([&](Operation *op) -> WalkResult {
147     if (auto readOp = dyn_cast<AffineReadOpInterface>(op)) {
148       // Memrefs that are allocated inside `forOp` need not be considered.
149       if (!isLocallyDefined(readOp.getMemRef(), forOp))
150         loadAndStoreOps.push_back(op);
151     } else if (auto writeOp = dyn_cast<AffineWriteOpInterface>(op)) {
152       // Filter out stores the same way as above.
153       if (!isLocallyDefined(writeOp.getMemRef(), forOp))
154         loadAndStoreOps.push_back(op);
155     } else if (!isa<AffineForOp, AffineYieldOp, AffineIfOp>(op) &&
156                !isAllocLikeOp(op) &&
157                !MemoryEffectOpInterface::hasNoEffect(op)) {
158       // Alloc-like ops inside `forOp` are fine (they don't impact parallelism)
159       // as long as they don't escape the loop (which has been checked above).
160       return WalkResult::interrupt();
161     }
162 
163     return WalkResult::advance();
164   });
165 
166   // Stop early if the loop has unknown ops with side effects.
167   if (walkResult.wasInterrupted())
168     return false;
169 
170   // Dep check depth would be number of enclosing loops + 1.
171   unsigned depth = getNestingDepth(forOp) + 1;
172 
173   // Check dependences between all pairs of ops in 'loadAndStoreOps'.
174   for (auto *srcOp : loadAndStoreOps) {
175     MemRefAccess srcAccess(srcOp);
176     for (auto *dstOp : loadAndStoreOps) {
177       MemRefAccess dstAccess(dstOp);
178       FlatAffineValueConstraints dependenceConstraints;
179       DependenceResult result = checkMemrefAccessDependence(
180           srcAccess, dstAccess, depth, &dependenceConstraints,
181           /*dependenceComponents=*/nullptr);
182       if (result.value != DependenceResult::NoDependence)
183         return false;
184     }
185   }
186   return true;
187 }
188 
189 /// Returns the sequence of AffineApplyOp Operations operation in
190 /// 'affineApplyOps', which are reachable via a search starting from 'operands',
191 /// and ending at operands which are not defined by AffineApplyOps.
192 // TODO: Add a method to AffineApplyOp which forward substitutes the
193 // AffineApplyOp into any user AffineApplyOps.
194 void mlir::getReachableAffineApplyOps(
195     ArrayRef<Value> operands, SmallVectorImpl<Operation *> &affineApplyOps) {
196   struct State {
197     // The ssa value for this node in the DFS traversal.
198     Value value;
199     // The operand index of 'value' to explore next during DFS traversal.
200     unsigned operandIndex;
201   };
202   SmallVector<State, 4> worklist;
203   for (auto operand : operands) {
204     worklist.push_back({operand, 0});
205   }
206 
207   while (!worklist.empty()) {
208     State &state = worklist.back();
209     auto *opInst = state.value.getDefiningOp();
210     // Note: getDefiningOp will return nullptr if the operand is not an
211     // Operation (i.e. block argument), which is a terminator for the search.
212     if (!isa_and_nonnull<AffineApplyOp>(opInst)) {
213       worklist.pop_back();
214       continue;
215     }
216 
217     if (state.operandIndex == 0) {
218       // Pre-Visit: Add 'opInst' to reachable sequence.
219       affineApplyOps.push_back(opInst);
220     }
221     if (state.operandIndex < opInst->getNumOperands()) {
222       // Visit: Add next 'affineApplyOp' operand to worklist.
223       // Get next operand to visit at 'operandIndex'.
224       auto nextOperand = opInst->getOperand(state.operandIndex);
225       // Increment 'operandIndex' in 'state'.
226       ++state.operandIndex;
227       // Add 'nextOperand' to worklist.
228       worklist.push_back({nextOperand, 0});
229     } else {
230       // Post-visit: done visiting operands AffineApplyOp, pop off stack.
231       worklist.pop_back();
232     }
233   }
234 }
235 
236 // Builds a system of constraints with dimensional variables corresponding to
237 // the loop IVs of the forOps appearing in that order. Any symbols founds in
238 // the bound operands are added as symbols in the system. Returns failure for
239 // the yet unimplemented cases.
240 // TODO: Handle non-unit steps through local variables or stride information in
241 // FlatAffineValueConstraints. (For eg., by using iv - lb % step = 0 and/or by
242 // introducing a method in FlatAffineValueConstraints
243 // setExprStride(ArrayRef<int64_t> expr, int64_t stride)
244 LogicalResult mlir::getIndexSet(MutableArrayRef<Operation *> ops,
245                                 FlatAffineValueConstraints *domain) {
246   SmallVector<Value, 4> indices;
247   SmallVector<AffineForOp, 8> forOps;
248 
249   for (Operation *op : ops) {
250     assert((isa<AffineForOp, AffineIfOp>(op)) &&
251            "ops should have either AffineForOp or AffineIfOp");
252     if (AffineForOp forOp = dyn_cast<AffineForOp>(op))
253       forOps.push_back(forOp);
254   }
255   extractForInductionVars(forOps, &indices);
256   // Reset while associated Values in 'indices' to the domain.
257   domain->reset(forOps.size(), /*numSymbols=*/0, /*numLocals=*/0, indices);
258   for (Operation *op : ops) {
259     // Add constraints from forOp's bounds.
260     if (AffineForOp forOp = dyn_cast<AffineForOp>(op)) {
261       if (failed(domain->addAffineForOpDomain(forOp)))
262         return failure();
263     } else if (AffineIfOp ifOp = dyn_cast<AffineIfOp>(op)) {
264       domain->addAffineIfOpDomain(ifOp);
265     }
266   }
267   return success();
268 }
269 
270 /// Computes the iteration domain for 'op' and populates 'indexSet', which
271 /// encapsulates the constraints involving loops surrounding 'op' and
272 /// potentially involving any Function symbols. The dimensional variables in
273 /// 'indexSet' correspond to the loops surrounding 'op' from outermost to
274 /// innermost.
275 static LogicalResult getOpIndexSet(Operation *op,
276                                    FlatAffineValueConstraints *indexSet) {
277   SmallVector<Operation *, 4> ops;
278   getEnclosingAffineForAndIfOps(*op, &ops);
279   return getIndexSet(ops, indexSet);
280 }
281 
282 // Returns the number of outer loop common to 'src/dstDomain'.
283 // Loops common to 'src/dst' domains are added to 'commonLoops' if non-null.
284 static unsigned
285 getNumCommonLoops(const FlatAffineValueConstraints &srcDomain,
286                   const FlatAffineValueConstraints &dstDomain,
287                   SmallVectorImpl<AffineForOp> *commonLoops = nullptr) {
288   // Find the number of common loops shared by src and dst accesses.
289   unsigned minNumLoops =
290       std::min(srcDomain.getNumDimVars(), dstDomain.getNumDimVars());
291   unsigned numCommonLoops = 0;
292   for (unsigned i = 0; i < minNumLoops; ++i) {
293     if (!isForInductionVar(srcDomain.getValue(i)) ||
294         !isForInductionVar(dstDomain.getValue(i)) ||
295         srcDomain.getValue(i) != dstDomain.getValue(i))
296       break;
297     if (commonLoops != nullptr)
298       commonLoops->push_back(getForInductionVarOwner(srcDomain.getValue(i)));
299     ++numCommonLoops;
300   }
301   if (commonLoops != nullptr)
302     assert(commonLoops->size() == numCommonLoops);
303   return numCommonLoops;
304 }
305 
306 /// Returns Block common to 'srcAccess.opInst' and 'dstAccess.opInst'.
307 static Block *getCommonBlock(const MemRefAccess &srcAccess,
308                              const MemRefAccess &dstAccess,
309                              const FlatAffineValueConstraints &srcDomain,
310                              unsigned numCommonLoops) {
311   // Get the chain of ancestor blocks to the given `MemRefAccess` instance. The
312   // search terminates when either an op with the `AffineScope` trait or
313   // `endBlock` is reached.
314   auto getChainOfAncestorBlocks = [&](const MemRefAccess &access,
315                                       SmallVector<Block *, 4> &ancestorBlocks,
316                                       Block *endBlock = nullptr) {
317     Block *currBlock = access.opInst->getBlock();
318     // Loop terminates when the currBlock is nullptr or equals to the endBlock,
319     // or its parent operation holds an affine scope.
320     while (currBlock && currBlock != endBlock &&
321            !currBlock->getParentOp()->hasTrait<OpTrait::AffineScope>()) {
322       ancestorBlocks.push_back(currBlock);
323       currBlock = currBlock->getParentOp()->getBlock();
324     }
325   };
326 
327   if (numCommonLoops == 0) {
328     Block *block = srcAccess.opInst->getBlock();
329     while (!llvm::isa<func::FuncOp>(block->getParentOp())) {
330       block = block->getParentOp()->getBlock();
331     }
332     return block;
333   }
334   Value commonForIV = srcDomain.getValue(numCommonLoops - 1);
335   AffineForOp forOp = getForInductionVarOwner(commonForIV);
336   assert(forOp && "commonForValue was not an induction variable");
337 
338   // Find the closest common block including those in AffineIf.
339   SmallVector<Block *, 4> srcAncestorBlocks, dstAncestorBlocks;
340   getChainOfAncestorBlocks(srcAccess, srcAncestorBlocks, forOp.getBody());
341   getChainOfAncestorBlocks(dstAccess, dstAncestorBlocks, forOp.getBody());
342 
343   Block *commonBlock = forOp.getBody();
344   for (int i = srcAncestorBlocks.size() - 1, j = dstAncestorBlocks.size() - 1;
345        i >= 0 && j >= 0 && srcAncestorBlocks[i] == dstAncestorBlocks[j];
346        i--, j--)
347     commonBlock = srcAncestorBlocks[i];
348 
349   return commonBlock;
350 }
351 
352 // Returns true if the ancestor operation of 'srcAccess' appears before the
353 // ancestor operation of 'dstAccess' in the common ancestral block. Returns
354 // false otherwise.
355 // Note that because 'srcAccess' or 'dstAccess' may be nested in conditionals,
356 // the function is named 'srcAppearsBeforeDstInCommonBlock'. Note that
357 // 'numCommonLoops' is the number of contiguous surrounding outer loops.
358 static bool srcAppearsBeforeDstInAncestralBlock(
359     const MemRefAccess &srcAccess, const MemRefAccess &dstAccess,
360     const FlatAffineValueConstraints &srcDomain, unsigned numCommonLoops) {
361   // Get Block common to 'srcAccess.opInst' and 'dstAccess.opInst'.
362   auto *commonBlock =
363       getCommonBlock(srcAccess, dstAccess, srcDomain, numCommonLoops);
364   // Check the dominance relationship between the respective ancestors of the
365   // src and dst in the Block of the innermost among the common loops.
366   auto *srcInst = commonBlock->findAncestorOpInBlock(*srcAccess.opInst);
367   assert(srcInst != nullptr);
368   auto *dstInst = commonBlock->findAncestorOpInBlock(*dstAccess.opInst);
369   assert(dstInst != nullptr);
370 
371   // Determine whether dstInst comes after srcInst.
372   return srcInst->isBeforeInBlock(dstInst);
373 }
374 
375 // Adds ordering constraints to 'dependenceDomain' based on number of loops
376 // common to 'src/dstDomain' and requested 'loopDepth'.
377 // Note that 'loopDepth' cannot exceed the number of common loops plus one.
378 // EX: Given a loop nest of depth 2 with IVs 'i' and 'j':
379 // *) If 'loopDepth == 1' then one constraint is added: i' >= i + 1
380 // *) If 'loopDepth == 2' then two constraints are added: i == i' and j' > j + 1
381 // *) If 'loopDepth == 3' then two constraints are added: i == i' and j == j'
382 static void
383 addOrderingConstraints(const FlatAffineValueConstraints &srcDomain,
384                        const FlatAffineValueConstraints &dstDomain,
385                        unsigned loopDepth,
386                        FlatAffineValueConstraints *dependenceDomain) {
387   unsigned numCols = dependenceDomain->getNumCols();
388   SmallVector<int64_t, 4> eq(numCols);
389   unsigned numSrcDims = srcDomain.getNumDimVars();
390   unsigned numCommonLoops = getNumCommonLoops(srcDomain, dstDomain);
391   unsigned numCommonLoopConstraints = std::min(numCommonLoops, loopDepth);
392   for (unsigned i = 0; i < numCommonLoopConstraints; ++i) {
393     std::fill(eq.begin(), eq.end(), 0);
394     eq[i] = -1;
395     eq[i + numSrcDims] = 1;
396     if (i == loopDepth - 1) {
397       eq[numCols - 1] = -1;
398       dependenceDomain->addInequality(eq);
399     } else {
400       dependenceDomain->addEquality(eq);
401     }
402   }
403 }
404 
405 // Computes distance and direction vectors in 'dependences', by adding
406 // variables to 'dependenceDomain' which represent the difference of the IVs,
407 // eliminating all other variables, and reading off distance vectors from
408 // equality constraints (if possible), and direction vectors from inequalities.
409 static void computeDirectionVector(
410     const FlatAffineValueConstraints &srcDomain,
411     const FlatAffineValueConstraints &dstDomain, unsigned loopDepth,
412     FlatAffineValueConstraints *dependenceDomain,
413     SmallVector<DependenceComponent, 2> *dependenceComponents) {
414   // Find the number of common loops shared by src and dst accesses.
415   SmallVector<AffineForOp, 4> commonLoops;
416   unsigned numCommonLoops =
417       getNumCommonLoops(srcDomain, dstDomain, &commonLoops);
418   if (numCommonLoops == 0)
419     return;
420   // Compute direction vectors for requested loop depth.
421   unsigned numIdsToEliminate = dependenceDomain->getNumVars();
422   // Add new variables to 'dependenceDomain' to represent the direction
423   // constraints for each shared loop.
424   dependenceDomain->insertDimVar(/*pos=*/0, /*num=*/numCommonLoops);
425 
426   // Add equality constraints for each common loop, setting newly introduced
427   // variable at column 'j' to the 'dst' IV minus the 'src IV.
428   SmallVector<int64_t, 4> eq;
429   eq.resize(dependenceDomain->getNumCols());
430   unsigned numSrcDims = srcDomain.getNumDimVars();
431   // Constraint variables format:
432   // [num-common-loops][num-src-dim-ids][num-dst-dim-ids][num-symbols][constant]
433   for (unsigned j = 0; j < numCommonLoops; ++j) {
434     std::fill(eq.begin(), eq.end(), 0);
435     eq[j] = 1;
436     eq[j + numCommonLoops] = 1;
437     eq[j + numCommonLoops + numSrcDims] = -1;
438     dependenceDomain->addEquality(eq);
439   }
440 
441   // Eliminate all variables other than the direction variables just added.
442   dependenceDomain->projectOut(numCommonLoops, numIdsToEliminate);
443 
444   // Scan each common loop variable column and set direction vectors based
445   // on eliminated constraint system.
446   dependenceComponents->resize(numCommonLoops);
447   for (unsigned j = 0; j < numCommonLoops; ++j) {
448     (*dependenceComponents)[j].op = commonLoops[j].getOperation();
449     auto lbConst = dependenceDomain->getConstantBound(IntegerPolyhedron::LB, j);
450     (*dependenceComponents)[j].lb =
451         lbConst.value_or(std::numeric_limits<int64_t>::min());
452     auto ubConst = dependenceDomain->getConstantBound(IntegerPolyhedron::UB, j);
453     (*dependenceComponents)[j].ub =
454         ubConst.value_or(std::numeric_limits<int64_t>::max());
455   }
456 }
457 
458 LogicalResult MemRefAccess::getAccessRelation(FlatAffineRelation &rel) const {
459   // Create set corresponding to domain of access.
460   FlatAffineValueConstraints domain;
461   if (failed(getOpIndexSet(opInst, &domain)))
462     return failure();
463 
464   // Get access relation from access map.
465   AffineValueMap accessValueMap;
466   getAccessMap(&accessValueMap);
467   if (failed(getRelationFromMap(accessValueMap, rel)))
468     return failure();
469 
470   FlatAffineRelation domainRel(rel.getNumDomainDims(), /*numRangeDims=*/0,
471                                domain);
472 
473   // Merge and align domain ids of `ret` and ids of `domain`. Since the domain
474   // of the access map is a subset of the domain of access, the domain ids of
475   // `ret` are guranteed to be a subset of ids of `domain`.
476   for (unsigned i = 0, e = domain.getNumDimVars(); i < e; ++i) {
477     unsigned loc;
478     if (rel.findVar(domain.getValue(i), &loc)) {
479       rel.swapVar(i, loc);
480     } else {
481       rel.insertDomainVar(i);
482       rel.setValue(i, domain.getValue(i));
483     }
484   }
485 
486   // Append domain constraints to `rel`.
487   domainRel.appendRangeVar(rel.getNumRangeDims());
488   domainRel.mergeSymbolVars(rel);
489   domainRel.mergeLocalVars(rel);
490   rel.append(domainRel);
491 
492   return success();
493 }
494 
495 // Populates 'accessMap' with composition of AffineApplyOps reachable from
496 // indices of MemRefAccess.
497 void MemRefAccess::getAccessMap(AffineValueMap *accessMap) const {
498   // Get affine map from AffineLoad/Store.
499   AffineMap map;
500   if (auto loadOp = dyn_cast<AffineReadOpInterface>(opInst))
501     map = loadOp.getAffineMap();
502   else
503     map = cast<AffineWriteOpInterface>(opInst).getAffineMap();
504 
505   SmallVector<Value, 8> operands(indices.begin(), indices.end());
506   fullyComposeAffineMapAndOperands(&map, &operands);
507   map = simplifyAffineMap(map);
508   canonicalizeMapAndOperands(&map, &operands);
509   accessMap->reset(map, operands);
510 }
511 
512 // Builds a flat affine constraint system to check if there exists a dependence
513 // between memref accesses 'srcAccess' and 'dstAccess'.
514 // Returns 'NoDependence' if the accesses can be definitively shown not to
515 // access the same element.
516 // Returns 'HasDependence' if the accesses do access the same element.
517 // Returns 'Failure' if an error or unsupported case was encountered.
518 // If a dependence exists, returns in 'dependenceComponents' a direction
519 // vector for the dependence, with a component for each loop IV in loops
520 // common to both accesses (see Dependence in AffineAnalysis.h for details).
521 //
522 // The memref access dependence check is comprised of the following steps:
523 // *) Build access relation for each access. An access relation maps elements
524 //    of an iteration domain to the element(s) of an array domain accessed by
525 //    that iteration of the associated statement through some array reference.
526 // *) Compute the dependence relation by composing access relation of
527 //    `srcAccess` with the inverse of access relation of `dstAccess`.
528 //    Doing this builds a relation between iteration domain of `srcAccess`
529 //    to the iteration domain of `dstAccess` which access the same memory
530 //    location.
531 // *) Add ordering constraints for `srcAccess` to be accessed before
532 //    `dstAccess`.
533 //
534 // This method builds a constraint system with the following column format:
535 //
536 //  [src-dim-variables, dst-dim-variables, symbols, constant]
537 //
538 // For example, given the following MLIR code with "source" and "destination"
539 // accesses to the same memref label, and symbols %M, %N, %K:
540 //
541 //   affine.for %i0 = 0 to 100 {
542 //     affine.for %i1 = 0 to 50 {
543 //       %a0 = affine.apply
544 //         (d0, d1) -> (d0 * 2 - d1 * 4 + s1, d1 * 3 - s0) (%i0, %i1)[%M, %N]
545 //       // Source memref access.
546 //       store %v0, %m[%a0#0, %a0#1] : memref<4x4xf32>
547 //     }
548 //   }
549 //
550 //   affine.for %i2 = 0 to 100 {
551 //     affine.for %i3 = 0 to 50 {
552 //       %a1 = affine.apply
553 //         (d0, d1) -> (d0 * 7 + d1 * 9 - s1, d1 * 11 + s0) (%i2, %i3)[%K, %M]
554 //       // Destination memref access.
555 //       %v1 = load %m[%a1#0, %a1#1] : memref<4x4xf32>
556 //     }
557 //   }
558 //
559 // The access relation for `srcAccess` would be the following:
560 //
561 //   [src_dim0, src_dim1, mem_dim0, mem_dim1,  %N,   %M,  const]
562 //       2        -4       -1         0         1     0     0     = 0
563 //       0         3        0        -1         0    -1     0     = 0
564 //       1         0        0         0         0     0     0    >= 0
565 //      -1         0        0         0         0     0     100  >= 0
566 //       0         1        0         0         0     0     0    >= 0
567 //       0        -1        0         0         0     0     50   >= 0
568 //
569 //  The access relation for `dstAccess` would be the following:
570 //
571 //   [dst_dim0, dst_dim1, mem_dim0, mem_dim1,  %M,   %K,  const]
572 //       7         9       -1         0        -1     0     0     = 0
573 //       0         11       0        -1         0    -1     0     = 0
574 //       1         0        0         0         0     0     0    >= 0
575 //      -1         0        0         0         0     0     100  >= 0
576 //       0         1        0         0         0     0     0    >= 0
577 //       0        -1        0         0         0     0     50   >= 0
578 //
579 //  The equalities in the above relations correspond to the access maps while
580 //  the inequalities corresspond to the iteration domain constraints.
581 //
582 // The dependence relation formed:
583 //
584 //   [src_dim0, src_dim1, dst_dim0, dst_dim1,  %M,   %N,   %K,  const]
585 //      2         -4        -7        -9        1     1     0     0    = 0
586 //      0          3         0        -11      -1     0     1     0    = 0
587 //       1         0         0         0        0     0     0     0    >= 0
588 //      -1         0         0         0        0     0     0     100  >= 0
589 //       0         1         0         0        0     0     0     0    >= 0
590 //       0        -1         0         0        0     0     0     50   >= 0
591 //       0         0         1         0        0     0     0     0    >= 0
592 //       0         0        -1         0        0     0     0     100  >= 0
593 //       0         0         0         1        0     0     0     0    >= 0
594 //       0         0         0        -1        0     0     0     50   >= 0
595 //
596 //
597 // TODO: Support AffineExprs mod/floordiv/ceildiv.
598 DependenceResult mlir::checkMemrefAccessDependence(
599     const MemRefAccess &srcAccess, const MemRefAccess &dstAccess,
600     unsigned loopDepth, FlatAffineValueConstraints *dependenceConstraints,
601     SmallVector<DependenceComponent, 2> *dependenceComponents, bool allowRAR) {
602   LLVM_DEBUG(llvm::dbgs() << "Checking for dependence at depth: "
603                           << Twine(loopDepth) << " between:\n";);
604   LLVM_DEBUG(srcAccess.opInst->dump(););
605   LLVM_DEBUG(dstAccess.opInst->dump(););
606 
607   // Return 'NoDependence' if these accesses do not access the same memref.
608   if (srcAccess.memref != dstAccess.memref)
609     return DependenceResult::NoDependence;
610 
611   // Return 'NoDependence' if one of these accesses is not an
612   // AffineWriteOpInterface.
613   if (!allowRAR && !isa<AffineWriteOpInterface>(srcAccess.opInst) &&
614       !isa<AffineWriteOpInterface>(dstAccess.opInst))
615     return DependenceResult::NoDependence;
616 
617   // Create access relation from each MemRefAccess.
618   FlatAffineRelation srcRel, dstRel;
619   if (failed(srcAccess.getAccessRelation(srcRel)))
620     return DependenceResult::Failure;
621   if (failed(dstAccess.getAccessRelation(dstRel)))
622     return DependenceResult::Failure;
623 
624   FlatAffineValueConstraints srcDomain = srcRel.getDomainSet();
625   FlatAffineValueConstraints dstDomain = dstRel.getDomainSet();
626 
627   // Return 'NoDependence' if loopDepth > numCommonLoops and if the ancestor
628   // operation of 'srcAccess' does not properly dominate the ancestor
629   // operation of 'dstAccess' in the same common operation block.
630   // Note: this check is skipped if 'allowRAR' is true, because because RAR
631   // deps can exist irrespective of lexicographic ordering b/w src and dst.
632   unsigned numCommonLoops = getNumCommonLoops(srcDomain, dstDomain);
633   assert(loopDepth <= numCommonLoops + 1);
634   if (!allowRAR && loopDepth > numCommonLoops &&
635       !srcAppearsBeforeDstInAncestralBlock(srcAccess, dstAccess, srcDomain,
636                                            numCommonLoops)) {
637     return DependenceResult::NoDependence;
638   }
639 
640   // Compute the dependence relation by composing `srcRel` with the inverse of
641   // `dstRel`. Doing this builds a relation between iteration domain of
642   // `srcAccess` to the iteration domain of `dstAccess` which access the same
643   // memory locations.
644   dstRel.inverse();
645   dstRel.compose(srcRel);
646   *dependenceConstraints = dstRel;
647 
648   // Add 'src' happens before 'dst' ordering constraints.
649   addOrderingConstraints(srcDomain, dstDomain, loopDepth,
650                          dependenceConstraints);
651 
652   // Return 'NoDependence' if the solution space is empty: no dependence.
653   if (dependenceConstraints->isEmpty())
654     return DependenceResult::NoDependence;
655 
656   // Compute dependence direction vector and return true.
657   if (dependenceComponents != nullptr)
658     computeDirectionVector(srcDomain, dstDomain, loopDepth,
659                            dependenceConstraints, dependenceComponents);
660 
661   LLVM_DEBUG(llvm::dbgs() << "Dependence polyhedron:\n");
662   LLVM_DEBUG(dependenceConstraints->dump());
663   return DependenceResult::HasDependence;
664 }
665 
666 /// Gathers dependence components for dependences between all ops in loop nest
667 /// rooted at 'forOp' at loop depths in range [1, maxLoopDepth].
668 void mlir::getDependenceComponents(
669     AffineForOp forOp, unsigned maxLoopDepth,
670     std::vector<SmallVector<DependenceComponent, 2>> *depCompsVec) {
671   // Collect all load and store ops in loop nest rooted at 'forOp'.
672   SmallVector<Operation *, 8> loadAndStoreOps;
673   forOp->walk([&](Operation *op) {
674     if (isa<AffineReadOpInterface, AffineWriteOpInterface>(op))
675       loadAndStoreOps.push_back(op);
676   });
677 
678   unsigned numOps = loadAndStoreOps.size();
679   for (unsigned d = 1; d <= maxLoopDepth; ++d) {
680     for (unsigned i = 0; i < numOps; ++i) {
681       auto *srcOp = loadAndStoreOps[i];
682       MemRefAccess srcAccess(srcOp);
683       for (unsigned j = 0; j < numOps; ++j) {
684         auto *dstOp = loadAndStoreOps[j];
685         MemRefAccess dstAccess(dstOp);
686 
687         FlatAffineValueConstraints dependenceConstraints;
688         SmallVector<DependenceComponent, 2> depComps;
689         // TODO: Explore whether it would be profitable to pre-compute and store
690         // deps instead of repeatedly checking.
691         DependenceResult result = checkMemrefAccessDependence(
692             srcAccess, dstAccess, d, &dependenceConstraints, &depComps);
693         if (hasDependence(result))
694           depCompsVec->push_back(depComps);
695       }
696     }
697   }
698 }
699