36#include "llvm/ADT/STLExtras.h"
37#include "llvm/ADT/SetVector.h"
38#include "llvm/ADT/SmallBitVector.h"
39#include "llvm/ADT/TypeSwitch.h"
40#include "llvm/Support/InterleavedRange.h"
42#include "llvm/Support/DebugLog.h"
46#define DEBUG_TYPE "parallel-loop-fusion"
49#define GEN_PASS_DEF_SCFPARALLELLOOPFUSION
50#include "mlir/Dialect/SCF/Transforms/Passes.h.inc"
60 return walkResult.wasInterrupted();
65 ParallelOp secondPloop) {
66 if (firstPloop.getNumLoops() != secondPloop.getNumLoops() ||
67 firstPloop.getUnsignedCmp() != secondPloop.getUnsignedCmp())
77 return std::equal(lhs.begin(), lhs.end(), rhs.begin(),
79 if (lhsValue == rhsValue)
81 std::optional<int64_t> lhsConst =
82 getConstantIntValue(lhsValue);
83 std::optional<int64_t> rhsConst =
84 getConstantIntValue(rhsValue);
85 return lhsConst && rhsConst && *lhsConst == *rhsConst;
88 return matchOperands(firstPloop.getLowerBound(),
89 secondPloop.getLowerBound()) &&
90 matchOperands(firstPloop.getUpperBound(),
91 secondPloop.getUpperBound()) &&
92 matchOperands(firstPloop.getStep(), secondPloop.getStep());
103 if (!isa<memref::StoreOp, vector::TransferWriteOp, vector::StoreOp>(op1))
105 bool opsAreIdentical =
107 .Case([&](memref::StoreOp storeOp1) {
108 auto storeOp2 = cast<memref::StoreOp>(op2);
109 return (storeOp1.getMemRef() == storeOp2.getMemRef()) &&
110 (storeOp1.getIndices() == storeOp2.getIndices());
112 .Case([&](vector::TransferWriteOp writeOp1) {
113 auto writeOp2 = cast<vector::TransferWriteOp>(op2);
114 return (writeOp1.getBase() == writeOp2.getBase()) &&
115 (writeOp1.getIndices() == writeOp2.getIndices()) &&
116 (writeOp1.getMask() == writeOp2.getMask()) &&
117 (writeOp1.getValueToStore().
getType() ==
118 writeOp2.getValueToStore().getType()) &&
119 (writeOp1.getInBounds() == writeOp2.getInBounds());
121 .Case([&](vector::StoreOp vecStoreOp1) {
122 auto vecStoreOp2 = cast<vector::StoreOp>(op2);
123 return (vecStoreOp1.getBase() == vecStoreOp2.getBase()) &&
124 (vecStoreOp1.getIndices() == vecStoreOp2.getIndices()) &&
125 (vecStoreOp1.getValueToStore().
getType() ==
126 vecStoreOp2.getValueToStore().getType()) &&
127 (vecStoreOp1.getAlignment() == vecStoreOp2.getAlignment()) &&
128 (vecStoreOp1.getNontemporal() ==
129 vecStoreOp2.getNontemporal());
131 .Default([](
Operation *) {
return false; });
132 return opsAreIdentical;
145 if (!val1DefOp || !val2DefOp)
150 val1DefOp, val2DefOp,
165 return constOp.value();
168 return constOp.value();
175 return constOp.value();
178 return constOp.value();
182 if (
auto applyOp = expr.
getDefiningOp<affine::AffineApplyOp>()) {
190 auto bin = dyn_cast<AffineBinaryOpExpr>(
result);
193 auto lhsDim = dyn_cast<AffineDimExpr>(bin.getLHS());
194 auto rhsDim = dyn_cast<AffineDimExpr>(bin.getRHS());
195 auto lhsConst = dyn_cast<AffineConstantExpr>(bin.getLHS());
196 auto rhsConst = dyn_cast<AffineConstantExpr>(bin.getRHS());
197 if (lhsConst && rhsDim)
198 return lhsConst.getValue();
199 if (rhsConst && lhsDim)
200 return rhsConst.getValue();
236 auto getConstLoopBoundsForIV =
237 [](
Value index) -> std::optional<std::tuple<int64_t, int64_t, int64_t>> {
238 auto blockArg = dyn_cast<BlockArgument>(
index);
241 auto *parentOp = blockArg.getOwner()->getParentOp();
242 auto loopLike = dyn_cast<LoopLikeOpInterface>(parentOp);
249 auto ivs = loopLike.getLoopInductionVars();
252 auto it = llvm::find(*ivs, blockArg);
253 if (it == ivs->end())
255 unsigned pos = std::distance(ivs->begin(), it);
256 if (pos >= ranges.size())
258 auto [lb,
ub, step] = ranges[pos];
259 return std::make_tuple(lb,
ub, step);
263 std::optional<int64_t> writeConst =
265 if (!writeConst && writeIndex) {
267 if (
auto bounds = getConstLoopBoundsForIV(writeIndex)) {
268 auto [lb,
ub, step] = *bounds;
269 if (step > 0 &&
ub == lb + step)
277 if (rangeExtent <= 0 || step <= 0)
281 int64_t rangeEnd = rangeStart + rangeExtent;
282 return lb >= rangeStart &&
ub <= rangeEnd;
285 if (offsetConst && writeConst) {
287 int64_t start = *offsetConst + *writeConst;
289 return (*loadConst >= start && *loadConst < start + extent);
290 if (
auto bounds = getConstLoopBoundsForIV(loadIndex)) {
291 auto [lb,
ub, step] = *bounds;
292 return loopIVWithinRange(lb,
ub, step, start, extent);
298 if (offsetConst && *offsetConst == 0 &&
301 if (
auto addConst =
getAddConstant(loadIndex, writeIndex, loopsIVsMap)) {
305 return (*addConst >= start && *addConst < start + extent);
311 if (
auto offsetVal = dyn_cast<Value>(offset)) {
324 .Case([&](memref::LoadOp
load) {
return load.getMemRef(); })
325 .Case([&](memref::StoreOp store) {
return store.getMemRef(); })
326 .Case([&](vector::TransferReadOp read) {
return read.getBase(); })
327 .Case([&](vector::TransferWriteOp write) {
return write.getBase(); })
328 .Case([&](vector::LoadOp
load) {
return load.getBase(); })
329 .Case([&](vector::StoreOp store) {
return store.getBase(); })
352 Value base = writeBase;
356 llvm::SmallBitVector droppedDims;
357 bool hasSubview =
false;
358 auto *ctx = loadOp.getContext();
359 if (
auto subView = base.
getDefiningOp<memref::SubViewOp>()) {
360 if (!subView.hasUnitStride())
362 baseMemref = cast<MemrefValue>(subView.getSource());
363 offsets = llvm::to_vector(subView.getMixedOffsets());
364 droppedDims = subView.getDroppedDims();
367 baseMemref = dyn_cast<MemrefValue>(base);
372 auto loadIndices = loadOp.getIndices();
373 unsigned baseRank = baseMemref.getType().getRank();
374 if ((loadOp.getMemref() != baseMemref) || (loadIndices.size() != baseRank))
377 unsigned writeRank = writeIndices.size();
378 if ((!hasSubview && writeRank != baseRank) ||
379 (hasSubview && offsets.size() != baseRank) ||
380 (vectorDimForWriteDim.size() != writeRank))
383 auto zeroAttr = IntegerAttr::get(IndexType::get(ctx), 0);
384 unsigned writeMemrefDim = 0;
385 for (
unsigned baseDim : llvm::seq(baseRank)) {
386 bool wasDropped = (hasSubview && droppedDims.test(baseDim));
387 int64_t vectorDim = !wasDropped ? vectorDimForWriteDim[writeMemrefDim] : -1;
389 if (vectorDim >= 0) {
390 int64_t dimSize = vecTy.getDimSize(vectorDim);
391 if (dimSize == ShapedType::kDynamic)
395 Value writeIndex = !wasDropped ? writeIndices[writeMemrefDim] :
Value();
411 vector::TransferWriteOp writeOp,
413 auto vecTy = dyn_cast<VectorType>(writeOp.getVector().getType());
418 if (writeOp.getMask() || writeOp.isMasked())
421 unsigned writeRank = writeOp.getIndices().size();
429 for (
unsigned vecDim = 0; vecDim < permutationMap.
getNumResults(); ++vecDim) {
430 auto dimExpr = dyn_cast<AffineDimExpr>(permutationMap.
getResult(vecDim));
433 unsigned writeDim = dimExpr.getPosition();
434 if (writeDim >= writeRank || vectorDimForWriteDim[writeDim] != -1)
436 vectorDimForWriteDim[writeDim] = vecDim;
440 vecTy, vectorDimForWriteDim, ivsMap);
445 vector::StoreOp storeOp,
447 auto vecTy = dyn_cast<VectorType>(storeOp.getValueToStore().getType());
451 unsigned writeRank = storeOp.getIndices().size();
452 if (vecTy.getRank() > writeRank)
456 unsigned vecRank = vecTy.getRank();
457 for (
unsigned i = 0; i < vecRank; ++i) {
458 unsigned writeDim = writeRank - vecRank + i;
459 vectorDimForWriteDim[writeDim] = i;
463 vecTy, vectorDimForWriteDim, ivsMap);
473template <
typename OpTy1,
typename OpTy2>
475 OpTy1 op1, OpTy2 op2,
const IRMapping &firstToSecondPloopIVsMap,
479 if (!base1 || !base2)
482 auto accessThroughTrivialSubviewIsSame =
483 [&
b](memref::SubViewOp subView,
ValueRange subViewAccess,
486 LogicalResult resolved = resolveSourceIndicesRankReducingSubview(
487 subView.getLoc(),
b, subView, subViewAccess, resolvedSubviewAccess);
488 if (failed(resolved) ||
489 (resolvedSubviewAccess.size() != sourceAccess.size()))
491 for (
auto [dimIdx, resolvedIndex] :
492 llvm::enumerate(resolvedSubviewAccess)) {
501 if (
auto subView = base1.template getDefiningOp<memref::SubViewOp>();
504 base2, cast<MemrefValue>(subView.getSource())) &&
505 accessThroughTrivialSubviewIsSame(subView, op1.getIndices(),
507 firstToSecondPloopIVsMap))
511 if (
auto subView = base2.template getDefiningOp<memref::SubViewOp>();
514 base1, cast<MemrefValue>(subView.getSource())) &&
515 accessThroughTrivialSubviewIsSame(subView, op2.getIndices(),
517 firstToSecondPloopIVsMap))
526template <
typename OpTy1,
typename OpTy2>
529 auto indices1 = op1.getIndices();
530 auto indices2 = op2.getIndices();
531 if (indices1.size() != indices2.size())
533 for (
auto [idx1, idx2] : llvm::zip(indices1, indices2)) {
544 const IRMapping &firstToSecondPloopIVsMap,
546 if (!loadOp || !storeOp)
549 if (!isa<memref::LoadOp, vector::TransferReadOp, vector::LoadOp>(loadOp))
551 bool accessSameMemory =
553 .Case([&](memref::LoadOp memLoadOp) {
554 if (
auto memStoreOp = dyn_cast<memref::StoreOp>(storeOp))
556 firstToSecondPloopIVsMap,
b);
557 if (
auto vecWriteOp = dyn_cast<vector::TransferWriteOp>(storeOp))
559 firstToSecondPloopIVsMap);
560 if (
auto vecStoreOp = dyn_cast<vector::StoreOp>(storeOp))
562 firstToSecondPloopIVsMap);
565 .Case([&](vector::TransferReadOp vecReadOp) {
566 auto vecWriteOp = dyn_cast<vector::TransferWriteOp>(storeOp);
572 firstToSecondPloopIVsMap,
b) &&
573 (vecReadOp.getVectorType() == vecWriteOp.getVectorType()) &&
574 (vecReadOp.getPermutationMap() ==
575 vecWriteOp.getPermutationMap()) &&
576 (vecReadOp.getMask() == vecWriteOp.getMask()) &&
577 !vecWriteOp.isMasked() &&
578 (vecReadOp.getInBounds() == vecWriteOp.getInBounds());
580 .Case([&](vector::LoadOp vecLoadOp) {
581 auto vecStoreOp = dyn_cast<vector::StoreOp>(storeOp);
585 firstToSecondPloopIVsMap,
b) &&
586 (vecLoadOp.getVectorType() == vecStoreOp.getVectorType()) &&
587 (vecLoadOp.getAlignment() == vecStoreOp.getAlignment());
589 .Default([](
Operation *) {
return false; });
590 return accessSameMemory;
595 .Case([&](memref::StoreOp storeOp) {
return storeOp.getMemRef(); })
596 .Case([&](vector::TransferWriteOp writeOp) {
return writeOp.getBase(); })
597 .Case([&](vector::StoreOp vecStoreOp) {
return vecStoreOp.getBase(); })
606 if (
auto transfWriteOp = dyn_cast<vector::TransferWriteOp>(storeOp);
607 transfWriteOp && isa<memref::LoadOp>(loadOp))
610 if (
auto vecStoreOp = dyn_cast<vector::StoreOp>(storeOp);
611 vecStoreOp && isa<memref::LoadOp>(loadOp))
621 ParallelOp firstPloop, ParallelOp secondPloop,
622 const IRMapping &firstToSecondPloopIndices,
627 llvm::SmallSetVector<Value, 4> buffersWrittenInFirstPloop;
629 auto collectStoreOpsInWalk = [&](
Operation *op) {
630 auto memOpInterf = dyn_cast_if_present<MemoryEffectOpInterface>(op);
643 MemrefValue storeOpBaseMemref = dyn_cast<MemrefValue>(storeOpBase);
644 if (!storeOpBaseMemref)
648 bufferStoresInFirstPloop[buffer].push_back(op);
649 buffersWrittenInFirstPloop.insert(buffer);
655 if (firstPloop.getBody()->walk(collectStoreOpsInWalk).wasInterrupted())
664 auto checkLoadInWalkHasNoIncompatibleDataDeps = [&](
Operation *loadOp) {
665 auto memOpInterf = dyn_cast_if_present<MemoryEffectOpInterface>(loadOp);
681 if (!isa<memref::LoadOp, vector::TransferReadOp, vector::LoadOp>(loadOp) ||
682 !isa<MemrefValue>(loadOp->getOperand(0)))
685 MemrefValue loadOpBase = cast<MemrefValue>(loadOp->getOperand(0));
688 for (
Value storedMem : buffersWrittenInFirstPloop)
689 if ((storedMem != loadedOrigBuf) &&
mayAlias(storedMem, loadedOrigBuf) &&
690 !llvm::all_of(bufferStoresInFirstPloop[storedMem],
693 firstToSecondPloopIndices);
698 auto writeOpsIt = bufferStoresInFirstPloop.find(loadedOrigBuf);
699 if (writeOpsIt == bufferStoresInFirstPloop.end())
705 if (writeOps.empty())
712 if (!llvm::all_of(writeOps, [&](
Operation *otherWriteOp) {
721 firstToSecondPloopIndices,
b)) {
730 return !secondPloop.getBody()
731 ->walk(checkLoadInWalkHasNoIncompatibleDataDeps)
740 const IRMapping &firstToSecondPloopIndices,
744 firstPloop, secondPloop, firstToSecondPloopIndices,
mayAlias,
b))
748 secondToFirstPloopIndices.
map(secondPloop.getBody()->getArguments(),
749 firstPloop.getBody()->getArguments());
751 secondPloop, firstPloop, secondToFirstPloopIndices,
mayAlias,
b);
758 const IRMapping &firstToSecondPloopIndices,
779static std::optional<ParallelOp>
782 assert(loop.getNumLoops() ==
indices.size());
783 if (loop.getNumLoops() < 2)
795 ParallelOp::create(builder, loop.getLoc(), newLB, newUB, newStep,
796 loop.getInitVals(),
nullptr, loop.getUnsignedCmp());
797 auto ivs = loop.getInductionVars();
801 for (
auto [iv, riv] : llvm::zip(ivs, newIvs)) {
802 mapping.
map(iv, riv);
807 for (
auto &o : loop.getNumReductions()
808 ? loop.getBodyRegion().front()
809 : loop.getBodyRegion().front().without_terminator()) {
831 return llvm::hash_combine(
844 ParallelOp &secondPloop,
845 int permBudget = 120) {
847 if (firstPloop.getNumLoops() < 2 ||
848 firstPloop.getNumLoops() != secondPloop.getNumLoops())
853 llvm::SmallSetVector<LoopIV, 6> unique;
854 for (
unsigned index : llvm::seq(firstPloop.getNumLoops())) {
855 firstIVs[
index].lBound = firstPloop.getLowerBound()[
index];
856 firstIVs[
index].uBound = firstPloop.getUpperBound()[
index];
857 firstIVs[
index].step = firstPloop.getStep()[
index];
858 secondIVs[
index].lBound = secondPloop.getLowerBound()[
index];
859 secondIVs[
index].uBound = secondPloop.getUpperBound()[
index];
860 secondIVs[
index].step = secondPloop.getStep()[
index];
861 unique.insert(firstIVs[
index]);
866 llvm::zip(firstIVs, secondIVs), diffIVs.begin(),
867 [](
auto const &pair) { return std::get<0>(pair) != std::get<1>(pair); });
870 for (
auto [idx, val] : enumerate(diffIVs))
880 std::iota(basic.begin(), basic.end(), 0);
882 if (
indices.empty() && unique.size() == firstIVs.size())
892 if (fIdx != sIdx && firstIVs[fIdx] == secondIVs[sIdx] &&
893 remaps.end() == std::find(remaps.begin(), remaps.end(), sIdx)) {
894 remaps.push_back(sIdx);
901 if (
indices.size() != remaps.size())
905 for (
auto [from, to] : zip(
indices, remaps)) {
909 LDBG() <<
"Collected basic permutations: "
910 << llvm::interleaved_array(basic);
913 if (unique.size() == firstIVs.size()) {
920 assert(unique.size() != firstIVs.size() &&
921 "Expected at least two equal axes");
926 for (
auto iv : unique) {
928 for (
unsigned index : llvm::seq(firstIVs.size())) {
929 if (firstIVs[
index] == iv)
930 group.push_back(
index);
932 if (group.size() > 1)
933 groups.push_back(std::move(group));
939 while (repeat && permBudget) {
941 for (
auto const &[group, groupRemaps] : zip(groups, rmpdGroups)) {
942 repeat |= std::next_permutation(groupRemaps.begin(), groupRemaps.end());
949 for (
auto const &[group, groupRemaps] : zip(groups, rmpdGroups)) {
950 for (
auto [from, to] : zip(group, groupRemaps))
951 extra[from] = basic[to];
953 if (basic != extra) {
954 LDBG() <<
"Collected extra permutations: "
955 << llvm::interleaved_array(extra);
957 extraResults.push_back(std::move(extra));
970 Block *block1 = firstPloop.getBody();
971 Block *block2 = secondPloop.getBody();
973 ValueRange inits2 = secondPloop.getInitVals();
976 newInitVars.append(inits2.begin(), inits2.end());
979 b.setInsertionPoint(secondPloop);
980 auto newSecondPloop =
981 ParallelOp::create(
b, secondPloop.getLoc(), secondPloop.getLowerBound(),
982 secondPloop.getUpperBound(), secondPloop.getStep(),
983 newInitVars,
nullptr, secondPloop.getUnsignedCmp());
985 Block *newBlock = newSecondPloop.getBody();
989 b.inlineBlockBefore(block2, newBlock, newBlock->
begin(),
991 b.inlineBlockBefore(block1, newBlock, newBlock->
begin(),
994 ValueRange results = newSecondPloop.getResults();
995 if (!results.empty()) {
996 b.setInsertionPointToEnd(newBlock);
1001 newReduceArgs.append(reduceArgs2.begin(), reduceArgs2.end());
1003 auto newReduceOp = scf::ReduceOp::create(
b, term2.getLoc(), newReduceArgs);
1005 for (
auto &&[i, reg] : llvm::enumerate(llvm::concat<Region>(
1006 term1.getReductions(), term2.getReductions()))) {
1008 Block &newRedBlock = newReduceOp.getReductions()[i].
front();
1009 b.inlineBlockBefore(&oldRedBlock, &newRedBlock, newRedBlock.
begin(),
1013 firstPloop.replaceAllUsesWith(results.take_front(inits1.size()));
1014 secondPloop.replaceAllUsesWith(results.take_back(inits2.size()));
1019 secondPloop.erase();
1020 secondPloop = newSecondPloop;
1024static void fuseIfLegal(ParallelOp firstPloop, ParallelOp &secondPloop,
1027 Block *block1 = firstPloop.getBody();
1028 Block *block2 = secondPloop.getBody();
1032 if (
isFusionLegal(firstPloop, secondPloop, firstToSecondPloopIndices,
1044 LDBG() <<
"Applied permutation: " << llvm::interleaved_array(perms);
1047 firstToSecondPloopIndices.
clear();
1049 newLoop->getBody()->getArguments());
1050 if (!
isFusionLegal(firstPloop, *newLoop, firstToSecondPloopIndices,
1052 LDBG() <<
"Rejected: " << newLoop;
1058 secondPloop.replaceAllUsesWith(newLoop->getResults());
1059 secondPloop->erase();
1060 secondPloop = *newLoop;
1071 for (
auto &block : region) {
1072 ploopChains.clear();
1073 ploopChains.push_back({});
1078 bool noSideEffects =
true;
1079 for (
auto &op : block) {
1080 if (
auto ploop = dyn_cast<ParallelOp>(op)) {
1081 if (noSideEffects) {
1082 ploopChains.back().push_back(ploop);
1084 ploopChains.push_back({ploop});
1085 noSideEffects =
true;
1093 for (
int i = 0, e = ploops.size(); i + 1 < e; ++i)
1100struct ParallelLoopFusion
1101 :
public impl::SCFParallelLoopFusionBase<ParallelLoopFusion> {
1102 void runOnOperation()
override {
1103 auto &aa = getAnalysis<AliasAnalysis>();
1110 auto val2Def = val2.getDefiningOp();
1114 val2Def ? val2Def->getParentOfType<ParallelOp>() :
nullptr;
1115 if (val1Loop != val2Loop)
1118 return !aa.alias(val1, val2).isNo();
1121 getOperation()->walk([&](
Operation *child) {
1130 return std::make_unique<ParallelLoopFusion>();
static bool mayAlias(Value first, Value second)
Returns true if two values may be referencing aliasing memory.
static bool canResolveAlias(Operation *loadOp, Operation *storeOp, const IRMapping &loopsIVsMap)
To be called when mayAlias(val1, val2) is true.
static std::optional< ParallelOp > interchangeLoops(OpBuilder &builder, ParallelOp &loop, const ArrayRef< int64_t > &indices)
static bool equalIterationSpaces(ParallelOp firstPloop, ParallelOp secondPloop)
Verify equal iteration spaces.
static bool isLoadOnWrittenVector(memref::LoadOp loadOp, Value writeBase, ValueRange writeIndices, VectorType vecTy, ArrayRef< int64_t > vectorDimForWriteDim, const IRMapping &ivsMap)
Recognize scalar memref.load of an element produced by a vector write (vector.transfer_write or vecto...
static bool loadMatchesVectorWrite(memref::LoadOp loadOp, vector::TransferWriteOp writeOp, const IRMapping &ivsMap)
Recognize scalar memref.load of an element produced by a vector.transfer_write.
static std::optional< int64_t > getAddConstant(Value expr, Value base, const IRMapping &loopsIVsMap)
If the expr value is the result of an integer addition of base and a constant, return the constant.
static bool opsAccessSameIndices(OpTy1 op1, OpTy2 op2, const IRMapping &loopsIVsMap, OpBuilder &b)
Check if both memory read/write operations access the same indices (considering also the mapping of i...
static Value getStoreOpTargetBuffer(Operation *op)
static void applyLoopFusion(ParallelOp &firstPloop, ParallelOp &secondPloop, OpBuilder &builder)
Prepend operations of firstPloop's body into secondPloop's body.
static bool haveNoDataDependenciesExceptSameIndex(ParallelOp firstPloop, ParallelOp secondPloop, const IRMapping &firstToSecondPloopIndices, llvm::function_ref< bool(Value, Value)> mayAlias, OpBuilder &b)
Check that the parallel loops have no mixed access to the same buffers.
static Value getBaseMemref(Operation *op)
Return the base memref value used by the given memory op.
static bool loadsFromSameMemoryLocationWrittenBy(Operation *loadOp, Operation *storeOp, const IRMapping &firstToSecondPloopIVsMap, OpBuilder &b)
Check if the loadOp reads from the same memory location (same buffer, same indices and same propertie...
static SmallVector< SmallVector< int64_t > > computeCandidateInterchangePermutations(ParallelOp &firstPloop, ParallelOp &secondPloop, int permBudget=120)
static bool loadIndexWithinWriteRange(Value loadIndex, OpFoldResult offset, Value writeIndex, int64_t extent, const IRMapping &loopsIVsMap)
static bool opsWriteSameMemLocation(Operation *op1, Operation *op2)
Check if both operations are the same type of memory write op and write to the same memory location (...
static bool noIncompatibleDataDependencies(ParallelOp firstPloop, ParallelOp secondPloop, const IRMapping &firstToSecondPloopIndices, llvm::function_ref< bool(Value, Value)> mayAlias, OpBuilder &b)
Check that in each loop there are no read ops on the buffers written by the other loop,...
static bool valsAreEquivalent(Value val1, Value val2, const IRMapping &loopsIVsMap)
Check if val1 (from the first parallel loop) and val2 (from the second) are equivalent,...
static bool isFusionLegal(ParallelOp firstPloop, ParallelOp secondPloop, const IRMapping &firstToSecondPloopIndices, llvm::function_ref< bool(Value, Value)> mayAlias, OpBuilder &b)
Check if fusion of the two parallel loops is legal: i.e.
static bool opsAccessSameIndicesViaRankReducingSubview(OpTy1 op1, OpTy2 op2, const IRMapping &firstToSecondPloopIVsMap, OpBuilder &b)
Check if both operations access the same positions of the same buffer, but one of the two does it thr...
static bool loadMatchesVectorStore(memref::LoadOp loadOp, vector::StoreOp storeOp, const IRMapping &ivsMap)
Recognize scalar memref.load of an element produced by a vector.store.
static bool hasNestedParallelOp(ParallelOp ploop)
Verify there are no nested ParallelOps.
static void fuseIfLegal(ParallelOp firstPloop, ParallelOp &secondPloop, OpBuilder builder, llvm::function_ref< bool(Value, Value)> mayAlias)
Check fusion pre-conditions and call fusion if it is possible.
Base type for affine expression.
A multi-dimensional affine map Affine map's are immutable like Type's, and they are uniqued.
bool isProjectedPermutation(bool allowZeroInResults=false) const
Returns true if the AffineMap represents a subset (i.e.
unsigned getNumSymbols() const
unsigned getNumDims() const
unsigned getNumResults() const
AffineExpr getResult(unsigned idx) const
static AffineMap getPermutationMap(ArrayRef< unsigned > permutation, MLIRContext *context)
Returns an AffineMap representing a permutation.
Block represents an ordered list of Operations.
Operation * getTerminator()
Get the terminator operation of this block.
BlockArgListType getArguments()
A class for computing basic dominance information.
bool properlyDominates(Operation *a, Operation *b, bool enclosingOpOk=true) const
Return true if operation A properly dominates operation B, i.e.
This is a utility class for mapping one set of IR entities to another.
auto lookupOrDefault(T from) const
Lookup a mapped value within the map.
void clear()
Clears all mappings held by the mapper.
void map(Value from, Value to)
Inserts a new mapping for 'from' to 'to'.
This class coordinates rewriting a piece of IR outside of a pattern rewrite, providing a way to keep ...
RAII guard to reset the insertion point of the builder when destroyed.
This class helps build Operations.
static OpBuilder atBlockBegin(Block *block, Listener *listener=nullptr)
Create a builder and set the insertion point to before the first operation in the block but still ins...
void setInsertionPoint(Block *block, Block::iterator insertPoint)
Set the insertion point to the specified location.
This class represents a single result from folding an operation.
This trait indicates that the memory effects of an operation includes the effects of operations neste...
This class implements the operand iterators for the Operation class.
Operation is the basic unit of execution within MLIR.
OpTy getParentOfType()
Return the closest surrounding parent operation that is of type 'OpTy'.
OperationName getName()
The name of an operation is the key identifier for it.
MutableArrayRef< Region > getRegions()
Returns the regions held by this operation.
user_range getUsers()
Returns a range of all users.
This class contains a list of basic blocks and a link to the parent operation it is attached to.
This class provides an abstraction over the different types of ranges over Values.
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Operation * getDefiningOp() const
If this value is the result of an operation, return the operation that defines it.
static WalkResult advance()
static WalkResult interrupt()
MemrefValue skipFullyAliasingOperations(MemrefValue source)
Walk up the source chain until an operation that changes/defines the view of memory is found (i....
bool isSameViewOrTrivialAlias(MemrefValue a, MemrefValue b)
Checks if two (memref) values are the same or statically known to alias the same region of memory.
void naivelyFuseParallelOps(Region ®ion, llvm::function_ref< bool(Value, Value)> mayAlias)
Fuses all adjacent scf.parallel operations with identical bounds and step into one scf....
Include the generated interface declarations.
bool matchPattern(Value value, const Pattern &pattern)
Entry point for matching a pattern over a Value.
std::optional< int64_t > getConstantIntValue(OpFoldResult ofr)
If ofr is a constant integer or an IntegerAttr, return the integer.
Type getType(OpFoldResult ofr)
Returns the int type of the integer in ofr.
SmallVector< T > applyPermutation(ArrayRef< T > input, ArrayRef< int64_t > permutation)
bool isMemoryEffectFree(Operation *op)
Returns true if the given operation is free of memory effects.
llvm::SmallVector< std::tuple< int64_t, int64_t, int64_t > > getConstLoopBounds(mlir::LoopLikeOpInterface loopOp)
Get constant loop bounds and steps for each of the induction variables of the given loop operation,...
detail::constant_int_predicate_matcher m_Zero()
Matches a constant scalar / vector splat / tensor splat integer zero.
TypedValue< BaseMemRefType > MemrefValue
A value with a memref type.
llvm::DenseMap< KeyT, ValueT, KeyInfoT, BucketT > DenseMap
std::unique_ptr< Pass > createParallelLoopFusionPass()
Creates a loop fusion pass which fuses parallel loops.
SmallVector< int64_t > invertPermutationVector(ArrayRef< int64_t > permutation)
Helper method to apply to inverse a permutation.
bool operator==(LoopIV const &other) const
bool operator!=(LoopIV const &other) const
static bool isEqual(const LoopIV &lhs, const LoopIV &rhs)
static unsigned getHashValue(const LoopIV &val)
The following effect indicates that the operation frees some resource that has been allocated.
The following effect indicates that the operation reads from some resource.
The following effect indicates that the operation writes to some resource.
static bool isEquivalentTo(Operation *lhs, Operation *rhs, function_ref< LogicalResult(Value, Value)> checkEquivalent, function_ref< void(Value, Value)> markEquivalent=nullptr, Flags flags=Flags::None, function_ref< LogicalResult(ValueRange, ValueRange)> checkCommutativeEquivalent=nullptr)
Compare two operations (including their regions) and return if they are equivalent.