15#include "mlir/Config/mlir-config.h"
27#include "llvm/ADT/BitVector.h"
28#include "llvm/ADT/DenseMap.h"
29#include "llvm/ADT/ScopeExit.h"
30#include "llvm/ADT/SetVector.h"
31#include "llvm/ADT/SmallPtrSet.h"
32#include "llvm/Support/DebugLog.h"
33#include "llvm/Support/ScopedPrinter.h"
34#include "llvm/Support/raw_ostream.h"
36#ifdef MLIR_GREEDY_REWRITE_RANDOMIZER_SEED
42#define DEBUG_TYPE "greedy-rewriter"
50#if MLIR_ENABLE_EXPENSIVE_PATTERN_API_CHECKS
65 void computeFingerPrints(
Operation *topLevel) {
66 this->topLevel = topLevel;
67 this->topLevelFingerPrint.emplace(topLevel);
69 fingerprints.try_emplace(op, op,
false);
76 topLevelFingerPrint.reset();
80 void notifyRewriteSuccess() {
85 if (failed(
verify(topLevel)))
86 llvm::report_fatal_error(
"IR failed to verify after pattern application");
90 if (*topLevelFingerPrint == afterFingerPrint) {
92 llvm::report_fatal_error(
93 "pattern returned success but IR did not change");
95 for (
const auto &it : fingerprints) {
97 if (it.first == topLevel)
108 llvm::report_fatal_error(
"operation finger print changed");
113 void notifyRewriteFailure() {
119 if (*topLevelFingerPrint != afterFingerPrint) {
121 llvm::report_fatal_error(
"pattern returned failure but IR did change");
125 void notifyFoldingSuccess() {
130 if (failed(
verify(topLevel)))
131 llvm::report_fatal_error(
"IR failed to verify after folding");
136 void invalidateFingerPrint(
Operation *op) { fingerprints.erase(op); }
169 invalidateFingerPrint(op);
174 op->
walk([
this](
Operation *op) { invalidateFingerPrint(op); });
186 std::optional<OperationFingerPrint> topLevelFingerPrint;
198static void logSuccessfulFolding(
Operation *op) {
199 LDBG() <<
"// *** IR Dump After Successful Folding ***\n"
240 std::vector<Operation *> list;
246Worklist::Worklist() { list.reserve(64); }
248void Worklist::clear() {
253bool Worklist::empty()
const {
255 return !llvm::any_of(list,
256 [](
Operation *op) {
return static_cast<bool>(op); });
260 assert(op &&
"cannot push nullptr to worklist");
262 if (!map.insert({op, list.size()}).second)
268 assert(!empty() &&
"cannot pop from empty worklist");
276 while (!list.empty() && !list.back())
282 assert(op &&
"cannot remove nullptr from worklist");
283 auto it = map.find(op);
284 if (it != map.end()) {
285 assert(list[it->second] == op &&
"malformed worklist data structure");
286 list[it->second] =
nullptr;
291void Worklist::reverse() {
292 std::reverse(list.begin(), list.end());
293 for (
size_t i = 0, e = list.size(); i != e; ++i)
297#ifdef MLIR_GREEDY_REWRITE_RANDOMIZER_SEED
302class RandomizedWorklist :
public Worklist {
304 RandomizedWorklist() : Worklist() {
305 generator.seed(MLIR_GREEDY_REWRITE_RANDOMIZER_SEED);
312 assert(!list.empty() &&
"cannot pop from empty worklist");
315 list.
erase(list.begin() + pos);
316 for (
int64_t i = pos, e = list.size(); i < e; ++i)
350 void clear() { regionStates.clear(); }
352 void notifyBlockInserted(
Block *block,
Region *previous,
354 void notifyBlockErased(
Block *block)
override;
355 void notifyOperationInserted(
Operation *op,
357 void notifyOperationModified(
Operation *op)
override;
358 void notifyOperationErased(
Operation *op)
override;
365 Block *entry =
nullptr;
377 llvm::SmallDenseSet<Block *, 4> uncertain;
380 llvm::SmallSetVector<Block *, 4> changedBlocks;
383 llvm::SmallDenseSet<Block *, 4> removedBlocks;
386 void traverse(
Region *region);
391 void markUncertain(
Block *block);
394 LogicalResult applyChanges();
399 void markChanged(
Block *block) {
402 auto it = regionStates.find(block->
getParent());
403 if (it != regionStates.end())
404 it->second.changedBlocks.insert(block);
408 auto it = regionStates.find(region);
409 if (it != regionStates.end())
410 it->second.removedBlocks.insert(block);
412 bool isBlockReachable(
Block *block);
432 void notifyBlockInserted(
Block *block,
Region *previous,
438 ForwardingListener::notifyBlockInserted(block, previous, previousIt);
441 void notifyBlockErased(
Block *block)
override {
443 ForwardingListener::notifyBlockErased(block);
446 void notifyOperationInserted(
Operation *op,
451 if (previous.
isSet())
455 ForwardingListener::notifyOperationInserted(op, previous);
458 void notifyOperationModified(
Operation *op)
override {
460 ForwardingListener::notifyOperationModified(op);
463 void notifyOperationErased(
Operation *op)
override {
465 ForwardingListener::notifyOperationErased(op);
480 explicit GreedyPatternRewriteDriver(
MLIRContext *ctx,
485 void addSingleOpToWorklist(
Operation *op);
492 void notifyOperationModified(
Operation *op)
override;
497 void notifyOperationInserted(
Operation *op,
503 void notifyOperationErased(
Operation *op)
override;
512 bool processWorklist();
520#ifdef MLIR_GREEDY_REWRITE_RANDOMIZER_SEED
521 RandomizedWorklist worklist;
533 llvm::SmallDenseSet<Operation *, 4> strictModeFilteredOps;
537 ReachabilityListener reachabilityListener;
544 void addOperandsToWorklist(
Operation *op);
547 void notifyBlockInserted(
Block *block,
Region *previous,
551 void notifyBlockErased(
Block *block)
override;
561 llvm::impl::raw_ldbg_ostream os{(Twine(
"[") +
DEBUG_TYPE +
":1] ").str(),
564 llvm::ScopedPrinter logger{os};
570 DeadnessListener deadnessListener;
572#if MLIR_ENABLE_EXPENSIVE_PATTERN_API_CHECKS
573 ExpensiveChecks expensiveChecks;
590 if (successor->getParent() == block->
getParent())
591 successors.insert(successor);
595void ReachabilityListener::RegionState::traverse(Region *region) {
600 changedBlocks.clear();
601 removedBlocks.clear();
602 entry = ®ion->
front();
603 addReachable({entry},
false);
606void ReachabilityListener::RegionState::addReachable(SmallVector<Block *> roots,
608 while (!roots.empty()) {
609 auto [it,
inserted] = reachable.try_emplace(roots.pop_back_val());
613 it->second.append(successors.begin(), successors.end());
615 uncertain.insert(it->first);
616 roots.append(it->second);
620void ReachabilityListener::RegionState::markUncertain(
Block *block) {
621 SmallVector<Block *> worklist{block};
622 while (!worklist.empty()) {
623 Block *current = worklist.pop_back_val();
624 auto it = reachable.find(current);
625 if (it == reachable.end() || !uncertain.insert(current).second)
627 worklist.append(it->second);
631LogicalResult ReachabilityListener::RegionState::applyChanges() {
632 if (changedBlocks.empty() && removedBlocks.empty())
636 SmallVector<Block *> unreachable;
637 for (
Block *changed : changedBlocks) {
640 if (removedBlocks.contains(changed))
642 auto it = reachable.find(changed);
643 if (it == reachable.end())
648 if (changed != entry && changed->hasNoPredecessors())
649 markUncertain(changed);
652 const auto &old = it->second;
654 for (
Block *lost : old) {
655 if (current.contains(lost))
660 auto lostIt = reachable.find(lost);
661 if (lostIt == reachable.end())
670 bool isGone = removedBlocks.contains(lost) || lost->hasNoPredecessors();
671 if (isGone && llvm::all_of(lostIt->second, [&](
Block *successor) {
672 return current.contains(successor);
674 unreachable.push_back(lost);
681 SmallVector<Block *> roots;
682 for (
Block *successor : current)
683 if (!reachable.contains(successor))
684 roots.push_back(successor);
686 it->second.assign(current.begin(), current.end());
687 addReachable(std::move(roots), uncertain.contains(changed));
691 unreachable.append(removedBlocks.begin(), removedBlocks.end());
692 for (
Block *block : unreachable) {
693 reachable.erase(block);
694 uncertain.erase(block);
696 changedBlocks.clear();
697 removedBlocks.clear();
701bool ReachabilityListener::isBlockReachable(
Block *block) {
704 if (!region || block == ®ion->
front())
708 auto [it,
inserted] = regionStates.try_emplace(region);
709 RegionState &state = it->second;
711 if (isStale ||
failed(state.applyChanges()) ||
712 state.uncertain.contains(block))
713 state.traverse(region);
714 bool result = state.reachable.contains(block);
715#if MLIR_ENABLE_EXPENSIVE_PATTERN_API_CHECKS
717 "reachability cache disagrees with a traversal");
722bool ReachabilityListener::isReachable(Operation *op) {
726 if (!isBlockReachable(block))
729 if (!region || region == scope)
736void ReachabilityListener::notifyBlockInserted(
Block *block, Region *previous,
743 if (previous != region) {
745 markRemoved(previous, block);
746 auto it = regionStates.find(region);
747 if (it != regionStates.end() && (it->second.removedBlocks.contains(block) ||
748 it->second.reachable.contains(block)))
749 regionStates.erase(it);
755void ReachabilityListener::notifyBlockErased(
Block *block) {
760void ReachabilityListener::notifyOperationInserted(
761 Operation *op, OpBuilder::InsertPoint previous) {
764 if (previous.
isSet())
770void ReachabilityListener::notifyOperationModified(Operation *op) {
776void ReachabilityListener::notifyOperationErased(Operation *op) {
781 regionStates.erase(®ion);
785GreedyPatternRewriteDriver::GreedyPatternRewriteDriver(
786 MLIRContext *ctx,
const FrozenRewritePatternSet &patterns,
787 const GreedyRewriteConfig &config)
788 : rewriter(ctx), config(config),
789 reachabilityListener(
this, config.getScope()), matcher(patterns),
790 deadnessListener(&reachabilityListener)
791#
if MLIR_ENABLE_EXPENSIVE_PATTERN_API_CHECKS
795 config.getScope() ? config.getScope()->getParentOp()
801 matcher.applyDefaultCostModel();
804#if MLIR_ENABLE_EXPENSIVE_PATTERN_API_CHECKS
813bool GreedyPatternRewriteDriver::processWorklist() {
817 llvm::scope_exit clearReachability([&] { reachabilityListener.clear(); });
820 const char *logLineComment =
821 "//===-------------------------------------------===//\n";
824 auto logResult = [&](StringRef
result,
const llvm::Twine &msg = {}) {
826 logger.startLine() <<
"} -> " <<
result;
827 if (!msg.isTriviallyEmpty())
828 logger.getOStream() <<
" : " << msg;
829 logger.getOStream() <<
"\n";
831 auto logResultWithLine = [&](StringRef
result,
const llvm::Twine &msg = {}) {
833 logger.startLine() << logLineComment;
837 bool changed =
false;
838 int64_t numRewrites = 0;
839 while (!worklist.empty() &&
842 auto *op = worklist.pop();
843 if (!reachabilityListener.isReachable(op)) {
844 LLVM_DEBUG(logger.startLine() <<
"Skipping unreachable operation : '"
845 << op->
getName() <<
"'(" << op <<
")\n");
850 logger.getOStream() <<
"\n";
851 logger.startLine() << logLineComment;
852 logger.startLine() <<
"Processing operation : '" << op->
getName() <<
"'("
860 OpPrintingFlags().printGenericOpForm().elideLargeElementsAttrs());
861 logger.getOStream() <<
"\n\n";
866 if (deadnessListener.isOpTriviallyDead(op)) {
870 LLVM_DEBUG(logResultWithLine(
"success",
"operation is trivially dead"));
879 SmallVector<OpFoldResult> foldResults;
880 if (succeeded(op->
fold(foldResults))) {
881 LLVM_DEBUG(logResultWithLine(
"success",
"operation was folded"));
885 if (foldResults.empty()) {
888 deadnessListener.notifyOperationModified(op);
890 LLVM_DEBUG(logSuccessfulFolding(dumpRootOp));
891#if MLIR_ENABLE_EXPENSIVE_PATTERN_API_CHECKS
892 expensiveChecks.notifyFoldingSuccess();
899 "folder produced incorrect number of results");
900 OpBuilder::InsertionGuard g(rewriter);
902 SmallVector<Value> replacements;
903 bool materializationSucceeded =
true;
904 for (
auto [ofr, resultType] :
906 if (
auto value = dyn_cast<Value>(ofr)) {
907 assert(value.getType() == resultType &&
908 "folder produced value of incorrect type");
909 replacements.push_back(value);
914 rewriter, cast<Attribute>(ofr), resultType, op->
getLoc());
919 llvm::SmallDenseSet<Operation *> replacementOps;
922 "folder reused existing op for one result but constant "
923 "materialization failed for another result");
924 replacementOps.insert(
replacement.getDefiningOp());
926 for (Operation *op : replacementOps) {
930 materializationSucceeded =
false;
934 assert(constOp->
hasTrait<OpTrait::ConstantLike>() &&
935 "materializeConstant produced op that is not a ConstantLike");
937 "materializeConstant produced incorrect result type");
938 replacements.push_back(constOp->
getResult(0));
941 if (materializationSucceeded) {
944 LLVM_DEBUG(logSuccessfulFolding(dumpRootOp));
945#if MLIR_ENABLE_EXPENSIVE_PATTERN_API_CHECKS
946 expensiveChecks.notifyFoldingSuccess();
956 auto canApplyCallback = [&](
const Pattern &pattern) {
958 logger.getOStream() <<
"\n";
959 logger.startLine() <<
"* Pattern " << pattern.getDebugName() <<
" : '"
961 llvm::interleaveComma(pattern.getGeneratedOps(), logger.getOStream());
962 logger.getOStream() <<
")' {\n";
965 if (RewriterBase::Listener *listener = config.
getListener())
966 listener->notifyPatternBegin(pattern, op);
969 function_ref<bool(
const Pattern &)> canApply = canApplyCallback;
970 auto onFailureCallback = [&](
const Pattern &pattern) {
971 LLVM_DEBUG(logResult(
"failure",
"pattern failed to match"));
972 if (RewriterBase::Listener *listener = config.
getListener())
973 listener->notifyPatternEnd(pattern, failure());
975 function_ref<void(
const Pattern &)> onFailure = onFailureCallback;
976 auto onSuccessCallback = [&](
const Pattern &pattern) {
977 LLVM_DEBUG(logResult(
"success",
"pattern applied successfully"));
978 if (RewriterBase::Listener *listener = config.
getListener())
979 listener->notifyPatternEnd(pattern,
success());
982 function_ref<LogicalResult(
const Pattern &)> onSuccess = onSuccessCallback;
994#if MLIR_ENABLE_EXPENSIVE_PATTERN_API_CHECKS
998 llvm::scope_exit clearFingerprints([&]() { expensiveChecks.clear(); });
1001 LogicalResult matchResult =
1002 matcher.
matchAndRewrite(op, rewriter, canApply, onFailure, onSuccess);
1004 if (succeeded(matchResult)) {
1005 LLVM_DEBUG(logResultWithLine(
"success",
"at least one pattern matched"));
1006#if MLIR_ENABLE_EXPENSIVE_PATTERN_API_CHECKS
1007 expensiveChecks.notifyRewriteSuccess();
1012 LLVM_DEBUG(logResultWithLine(
"failure",
"all patterns failed to match"));
1013#if MLIR_ENABLE_EXPENSIVE_PATTERN_API_CHECKS
1014 expensiveChecks.notifyRewriteFailure();
1022void GreedyPatternRewriteDriver::addToWorklist(Operation *op) {
1023 assert(op &&
"expected valid op");
1025 SmallVector<Operation *, 8> ancestors;
1026 Region *region =
nullptr;
1028 ancestors.push_back(op);
1032 for (Operation *op : ancestors)
1033 addSingleOpToWorklist(op);
1036 if (region ==
nullptr)
1041void GreedyPatternRewriteDriver::addSingleOpToWorklist(Operation *op) {
1042 if (config.
getStrictness() == GreedyRewriteStrictness::AnyOp ||
1043 strictModeFilteredOps.contains(op))
1047void GreedyPatternRewriteDriver::notifyBlockInserted(
1049 if (RewriterBase::Listener *listener = config.
getListener())
1050 listener->notifyBlockInserted(block, previous, previousIt);
1053void GreedyPatternRewriteDriver::notifyBlockErased(
Block *block) {
1054 if (RewriterBase::Listener *listener = config.
getListener())
1055 listener->notifyBlockErased(block);
1058void GreedyPatternRewriteDriver::notifyOperationInserted(
1059 Operation *op, OpBuilder::InsertPoint previous) {
1061 logger.startLine() <<
"** Insert : '" << op->
getName() <<
"'(" << op
1064 if (RewriterBase::Listener *listener = config.
getListener())
1065 listener->notifyOperationInserted(op, previous);
1066 if (config.
getStrictness() == GreedyRewriteStrictness::ExistingAndNewOps)
1067 strictModeFilteredOps.insert(op);
1071void GreedyPatternRewriteDriver::notifyOperationModified(Operation *op) {
1073 logger.startLine() <<
"** Modified: '" << op->
getName() <<
"'(" << op
1076 if (RewriterBase::Listener *listener = config.
getListener())
1077 listener->notifyOperationModified(op);
1081void GreedyPatternRewriteDriver::addOperandsToWorklist(Operation *op) {
1091 auto *defOp = operand.getDefiningOp();
1095 Operation *otherUser =
nullptr;
1096 bool hasMoreThanTwoUses =
false;
1097 for (
auto *user : operand.getUsers()) {
1098 if (user == op || user == otherUser)
1104 hasMoreThanTwoUses =
true;
1107 if (hasMoreThanTwoUses)
1110 addToWorklist(defOp);
1114void GreedyPatternRewriteDriver::notifyOperationErased(Operation *op) {
1116 logger.startLine() <<
"** Erase : '" << op->
getName() <<
"'(" << op
1128 "scope region must not be erased during greedy pattern rewrite");
1131 if (RewriterBase::Listener *listener = config.
getListener())
1132 listener->notifyOperationErased(op);
1134 addOperandsToWorklist(op);
1135 worklist.remove(op);
1137 if (config.
getStrictness() != GreedyRewriteStrictness::AnyOp)
1138 strictModeFilteredOps.erase(op);
1141void GreedyPatternRewriteDriver::notifyOperationReplaced(
1144 logger.startLine() <<
"** Replace : '" << op->
getName() <<
"'(" << op
1147 if (RewriterBase::Listener *listener = config.
getListener())
1148 listener->notifyOperationReplaced(op,
replacement);
1151void GreedyPatternRewriteDriver::notifyMatchFailure(
1152 Location loc,
function_ref<
void(Diagnostic &)> reasonCallback) {
1154 Diagnostic diag(loc, DiagnosticSeverity::Remark);
1155 reasonCallback(diag);
1156 logger.startLine() <<
"** Match Failure : " << diag.str() <<
"\n";
1158 if (RewriterBase::Listener *listener = config.
getListener())
1159 listener->notifyMatchFailure(loc, reasonCallback);
1169class RegionPatternRewriteDriver :
public GreedyPatternRewriteDriver {
1171 explicit RegionPatternRewriteDriver(MLIRContext *ctx,
1172 const FrozenRewritePatternSet &patterns,
1173 const GreedyRewriteConfig &config,
1178 LogicalResult simplify(
bool *changed) &&;
1186RegionPatternRewriteDriver::RegionPatternRewriteDriver(
1187 MLIRContext *ctx,
const FrozenRewritePatternSet &patterns,
1188 const GreedyRewriteConfig &config, Region ®ion)
1189 : GreedyPatternRewriteDriver(ctx, patterns, config), region(region) {
1192 region.walk([&](Operation *op) { strictModeFilteredOps.insert(op); });
1197 Region *r = ®ion;
1198 while (r && r != scope)
1199 r = r->getParentRegion();
1200 assert(r &&
"provided region is not within the config scope");
1206class GreedyPatternRewriteIteration
1210 GreedyPatternRewriteIteration(ArrayRef<IRUnit> units, int64_t iteration)
1211 : tracing::ActionImpl<GreedyPatternRewriteIteration>(units),
1212 iteration(iteration) {}
1213 static constexpr StringLiteral tag =
"GreedyPatternRewriteIteration";
1214 void print(raw_ostream &os)
const override {
1215 os <<
"GreedyPatternRewriteIteration(" << iteration <<
")";
1219 int64_t iteration = 0;
1223LogicalResult RegionPatternRewriteDriver::simplify(
bool *changed) && {
1224 bool continueRewrites =
false;
1225 bool anyChanged =
false;
1240 auto insertKnownConstant = [&](
Operation *op) {
1246 auto result = folder.insertKnownConstant(op, constValue);
1274 continueRewrites =
false;
1288 continueRewrites |= processWorklist();
1304 bool cseChanged =
false;
1307 continueRewrites |= cseChanged;
1310 {®ion}, iteration);
1311 anyChanged |= continueRewrites;
1312 }
while (continueRewrites);
1315 *changed = anyChanged;
1318 return success(!continueRewrites);
1329 "patterns can only be applied to operations IsolatedFromAbove");
1335#if MLIR_ENABLE_EXPENSIVE_PATTERN_API_CHECKS
1337 llvm::report_fatal_error(
1338 "greedy pattern rewriter input IR failed to verify");
1341#ifdef EXPENSIVE_CHECKS
1344 bool rewriteChanged =
false;
1347 RegionPatternRewriteDriver driver(region.
getContext(), patterns, config,
1349 LogicalResult converged = std::move(driver).simplify(&rewriteChanged);
1350#ifdef EXPENSIVE_CHECKS
1351 if (rewriteChanged !=
1353 llvm::report_fatal_error(
1354 "greedy pattern rewriter changed flag does not match the IR");
1357 *changed = rewriteChanged;
1358 if (failed(converged))
1359 LDBG() <<
"The pattern rewrite did not converge after scanning "
1370class MultiOpPatternRewriteDriver :
public GreedyPatternRewriteDriver {
1372 explicit MultiOpPatternRewriteDriver(
1375 llvm::SmallDenseSet<Operation *, 4> *survivingOps =
nullptr);
1381 void notifyOperationErased(
Operation *op)
override {
1382 GreedyPatternRewriteDriver::notifyOperationErased(op);
1384 survivingOps->erase(op);
1390 llvm::SmallDenseSet<Operation *, 4> *
const survivingOps =
nullptr;
1394MultiOpPatternRewriteDriver::MultiOpPatternRewriteDriver(
1397 llvm::SmallDenseSet<Operation *, 4> *survivingOps)
1398 : GreedyPatternRewriteDriver(ctx, patterns, config),
1399 survivingOps(survivingOps) {
1401 strictModeFilteredOps.insert_range(ops);
1404 survivingOps->clear();
1405 survivingOps->insert_range(ops);
1413 addSingleOpToWorklist(op);
1416 bool result = processWorklist();
1420 return success(worklist.empty());
1428 assert(!ops.empty() &&
"expected at least one op");
1430 if (ops.size() == 1)
1431 return ops.front()->getParentRegion();
1433 Region *region = ops.front()->getParentRegion();
1434 ops = ops.drop_front();
1435 int sz = ops.size();
1436 llvm::BitVector remainingOps(sz,
true);
1440 while ((pos = remainingOps.find_first_in(pos + 1, sz)) != -1) {
1443 remainingOps.reset(pos);
1445 if (remainingOps.none())
1471 bool allOpsInScope = llvm::all_of(ops, [&](
Operation *op) {
1474 assert(allOpsInScope &&
"ops must be within the specified scope");
1478#if MLIR_ENABLE_EXPENSIVE_PATTERN_API_CHECKS
1480 llvm::report_fatal_error(
1481 "greedy pattern rewriter input IR failed to verify");
1484#ifdef EXPENSIVE_CHECKS
1485 std::optional<OperationFingerPrint> before;
1489 bool rewriteChanged =
false;
1492 llvm::SmallDenseSet<Operation *, 4> surviving;
1493 MultiOpPatternRewriteDriver driver(ops.front()->getContext(), patterns,
1495 allErased ? &surviving :
nullptr);
1496 LogicalResult converged = std::move(driver).simplify(ops, &rewriteChanged);
1497#ifdef EXPENSIVE_CHECKS
1501 llvm::report_fatal_error(
1502 "greedy pattern rewriter changed flag does not match the IR");
1505 *changed = rewriteChanged;
1507 *allErased = surviving.empty();
1508 if (failed(converged))
1509 LDBG() <<
"The pattern rewrite did not converge after "
return MutableOperandRange * this
static bool mayDefineSuccessors(Operation *op)
Return whether op may define successors of its block.
static Region * findCommonAncestor(ArrayRef< Operation * > ops)
Find the region that is the closest common ancestor of all given ops.
static SmallPtrSet< Block *, 2 > getRegionSuccessors(Block *block)
Collect the distinct successors of block that are in the same region.
*if copies could not be generated due to yet unimplemented cases *copyInPlacementStart and copyOutPlacementStart in copyPlacementBlock *specify the insertion points where the incoming copies and outgoing should be inserted(the insertion happens right before the *insertion point). Since `begin` can itself be invalidated due to the memref *rewriting done from this method
*if copies could not be generated due to yet unimplemented cases *copyInPlacementStart and copyOutPlacementStart in copyPlacementBlock *specify the insertion points where the incoming copies and outgoing should be the output argument nBegin is set to its * replacement(set to `begin` if no invalidation happens). Since outgoing *copies could have been inserted at `end`
static const mlir::GenInfo * generator
static Operation * getDumpRootOp(Operation *op)
Log IR after pattern application.
static void print(spirv::VerCapExtAttr triple, DialectAsmPrinter &printer)
#define MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(CLASS_NAME)
Attributes are known-constant values of operations.
Block represents an ordered list of Operations.
Region * getParent() const
Provide a 'getParent' method for ilist_node_with_parent methods.
SuccessorRange getSuccessors()
bool isReachable(Block *other, SmallPtrSet< Block *, 16 > &&except={})
Return "true" if there is a path from this block to the given block (according to the successors rela...
bool hasNoPredecessors()
Return true if this block has no predecessors.
Operation * getParentOp()
Returns the closest surrounding operation that contains this block.
A cache for repeated deadness queries on nested operations.
void scheduleBlockInvalidation(Block *block)
Report a change to a block and its contents.
bool isOpTriviallyDead(Operation *op)
Return true if the operation is unused and can be erased.
void scheduleAncestorInvalidation(Operation *op)
Invalidate the cached effects of this operation and its ancestors.
void notifyOperationErased(Operation *op)
Call once for each erased operation before it is detached or destroyed.
void scheduleInvalidation(Operation *op)
Report a change to this operation or its nested IR.
void notifyBlockErased(Block *block)
Call before an empty block is detached and destroyed.
This class contains all of the information necessary to report a diagnostic to the DiagnosticEngine.
virtual Operation * materializeConstant(OpBuilder &builder, Attribute value, Type type, Location loc)
Registered hook to materialize a single constant operation from a given attribute value with the desi...
A class for computing basic dominance information.
This class represents a frozen set of patterns that can be processed by a pattern applicator.
This class allows control over how the GreedyPatternRewriteDriver works.
static constexpr int64_t kNoLimit
bool isFoldingEnabled() const
Whether this should fold while greedily rewriting.
RewriterBase::Listener * getListener() const
An optional listener that should be notified about IR modifications.
bool isConstantCSEEnabled() const
If set to "true", constants are CSE'd (even across multiple regions that are in a parent-ancestor rel...
Region * getScope() const
Only ops within the scope are added to the worklist.
GreedyRewriteStrictness getStrictness() const
Strict mode can restrict the ops that are added to the worklist during the rewrite.
bool isCSEBetweenIterationsEnabled() const
If set to "true", full common-subexpression elimination is run on the scoped region between each patt...
bool getUseTopDownTraversal() const
This specifies the order of initial traversal that populates the rewriters worklist.
GreedyRewriteConfig & setScope(Region *scope)
GreedyRewriteConfig & setListener(RewriterBase::Listener *listener)
int64_t getMaxNumRewrites() const
This specifies the maximum number of rewrites within an iteration.
int64_t getMaxIterations() const
This specifies the maximum number of times the rewriter will iterate between applying patterns and si...
GreedySimplifyRegionLevel getRegionSimplificationLevel() const
Perform control flow optimizations to the region tree after applying all patterns.
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
MLIRContext is the top-level object for a collection of MLIR operations.
void executeAction(function_ref< void()> actionFn, const tracing::Action &action)
Dispatch the provided action to the handler if any, or just execute it.
This class represents a saved insertion point.
bool isSet() const
Returns true if this insert point is set.
void setInsertionPoint(Block *block, Block::iterator insertPoint)
Set the insertion point to the specified location.
Set of flags used to control the behavior of the various IR print methods (e.g.
This class provides the API for ops that are known to be isolated from above.
This class provides the API for ops that are known to be terminators.
A wrapper class that allows for printing an operation with a set of flags, useful to act as a "stream...
A unique fingerprint for a specific operation, and all of it's internal operations (if includeNested ...
A utility class for folding operations, and unifying duplicated constants generated along the way.
@ Unchanged
The operation was retained without modifying the IR.
@ Replaced
The operation was replaced with an existing constant and erased.
Operation is the basic unit of execution within MLIR.
Dialect * getDialect()
Return the dialect this operation is associated with, or nullptr if the associated dialect is not loa...
LogicalResult fold(ArrayRef< Attribute > operands, SmallVectorImpl< OpFoldResult > &results)
Attempt to fold this operation with the specified constant operand values.
bool hasTrait()
Returns true if the operation was registered with a particular trait, e.g.
unsigned getNumSuccessors()
bool mightHaveTrait()
Returns true if the operation might have the provided trait.
Block * getBlock()
Returns the operation block that contains this operation.
OpResult getResult(unsigned idx)
Get the 'idx'th result of this operation.
unsigned getNumRegions()
Returns the number of regions held by this operation.
Location getLoc()
The source location the operation was defined or derived from.
Operation * getParentOp()
Returns the closest surrounding operation that contains this operation or nullptr if this is a top-le...
OperationName getName()
The name of an operation is the key identifier for it.
void print(raw_ostream &os, const OpPrintingFlags &flags={})
MutableArrayRef< Region > getRegions()
Returns the regions held by this operation.
result_type_range getResultTypes()
operand_range getOperands()
Returns an iterator on the underlying Value's.
std::enable_if_t< llvm::function_traits< std::decay_t< FnT > >::num_args==1, RetT > walk(FnT &&callback)
Walk the operation by calling the callback for each nested operation (including this one),...
Region * getParentRegion()
Returns the region to which the instruction belongs.
void erase()
Remove this operation from its parent block and delete it.
unsigned getNumResults()
Return the number of results held by this operation.
This class manages the application of a group of rewrite patterns, with a user-provided cost model.
LogicalResult matchAndRewrite(Operation *op, PatternRewriter &rewriter, function_ref< bool(const Pattern &)> canApply={}, function_ref< void(const Pattern &)> onFailure={}, function_ref< LogicalResult(const Pattern &)> onSuccess={})
Attempt to match and rewrite the given op with any pattern, allowing a predicate to decide if a patte...
A special type of RewriterBase that coordinates the application of a rewrite pattern on the current I...
This class contains a list of basic blocks and a link to the parent operation it is attached to.
Region * getParentRegion()
Return the region containing this region or nullptr if the region is attached to a top-level operatio...
Operation * findAncestorOpInRegion(Operation &op)
Returns 'op' if 'op' lies in this region, or otherwise finds the ancestor of 'op' that lies in this r...
Operation * getParentOp()
Return the parent operation this region is attached to.
MLIRContext * getContext()
Return the context this region is inserted in.
BlockListType::iterator iterator
RetT walk(FnT &&callback)
Walk all nested operations, blocks or regions (including this region), depending on the type of callb...
virtual void replaceOp(Operation *op, ValueRange newValues)
Replace the results of the given (original) operation with the specified list of values (replacements...
virtual void eraseOp(Operation *op)
This method erases an operation that is known to have no uses.
This class provides an abstraction over the different types of ranges over Values.
static WalkResult advance()
CRTP Implementation of an action.
Include the generated interface declarations.
bool matchPattern(Value value, const Pattern &pattern)
Entry point for matching a pattern over a Value.
void eliminateCommonSubExpressions(RewriterBase &rewriter, DominanceInfo &domInfo, Operation *op, bool *changed=nullptr, int64_t *numCSE=nullptr, int64_t *numDCE=nullptr)
Eliminate common subexpressions within the given operation.
LogicalResult eraseUnreachableBlocks(RewriterBase &rewriter, MutableArrayRef< Region > regions, bool recurse=true)
Erase the unreachable blocks within the provided regions.
@ Aggressive
Run extra simplificiations (e.g.
@ Disabled
Disable region control-flow simplification.
LogicalResult applyPatternsGreedily(Region ®ion, const FrozenRewritePatternSet &patterns, GreedyRewriteConfig config=GreedyRewriteConfig(), bool *changed=nullptr)
Rewrite ops in the given region, which must be isolated from above, by repeatedly applying the highes...
LogicalResult applyOpPatternsGreedily(ArrayRef< Operation * > ops, const FrozenRewritePatternSet &patterns, GreedyRewriteConfig config=GreedyRewriteConfig(), bool *changed=nullptr, bool *allErased=nullptr)
Rewrite the specified ops by repeatedly applying the highest benefit patterns in a greedy worklist dr...
bool isOpTriviallyDead(Operation *op)
Return true if the given operation is unused, and has no side effects on memory that prevent erasing.
llvm::DenseMap< KeyT, ValueT, KeyInfoT, BucketT > DenseMap
@ AnyOp
No restrictions wrt. which ops are processed.
LogicalResult simplifyRegions(RewriterBase &rewriter, MutableArrayRef< Region > regions, bool mergeBlocks=true)
Run a set of structural simplifications over the given regions.
detail::constant_op_matcher m_Constant()
Matches a constant foldable operation.
LogicalResult verify(Operation *op, bool verifyRecursively=true)
Perform (potentially expensive) checks of invariants, used to detect compiler bugs,...
llvm::function_ref< Fn > function_ref
A listener that forwards all notifications to another listener.
void notifyOperationInserted(Operation *op, InsertPoint previous) override
Notify the listener that the specified operation was inserted.
void notifyOperationModified(Operation *op) override
Notify the listener that the specified operation was modified in-place.
void notifyOperationErased(Operation *op) override
Notify the listener that the specified operation is about to be erased.
void notifyBlockErased(Block *block) override
Notify the listener that the specified block is about to be erased.
void notifyBlockInserted(Block *block, Region *previous, Region::iterator previousIt) override
Notify the listener that the specified block was inserted.