MLIR 的一个特殊优势(以及与 LLVM、GCC、XLA、TensorFlow 等其他编译器基础架构的主要区别)是它使用单个编译器 IR 来表示多个抽象级别的代码:MLIR 操作可以是“TensorFlow operation”、“XLA HLO”、仿射循环嵌套、LLVM IR 指令(可传递地包括 X86、Lanai、PTX 和其他目标特定指令)或 MLIR 算子系统可以合理表达的任何其它内容。 鉴于 MLIR 跨越了如此广泛的不同问题范围,用于执行图到图重写的单一基础架构可以帮助解决许多不同的领域挑战。
像 MLIR 这样的基于静态单赋值 (SSA) 的IR可以轻松访问Op的操作数和“users”。因此,这些图到图重写的自然抽象是 DAG Pattern匹配的抽象:客户端定义 DAG tile模式(其中tile是定义 DAG 子图的一系列Op),并且每个Pattern都包含一个产生的结果 DAG 和产生它的成本(或者相反,叫作进行替换的好处(benifit))。一个通用的基础设施可以有效地找到并执行重写。
DAG 到 DAG Pattern匹配的一个退化但常见的情况是常量折叠:操作数包含常量的Op通常可以折叠为结果常量值。
MLIR 的Op可能会覆盖fold来实现,与一般的 DAG 到 DAG Pattern匹配器相比,它暴露了一个更简单的 API,并适用于通用的匹配器不适用的情况。例如,DAG 重写可以删除当前函数中的任意节点,这可能会使迭代器无效。作为 API 的常量折叠则不会删除任何节点,它只是提供一个常量值(列表)并允许客户端根据需要更新其数据结构。
这是与给定根操作匹配并执行 IR 重写的代码块。RewritePattern 可以通过单独的 match 和 rewrite 方法或通过组合的 matchAndRewrite 方法来指定此实现。使用组合 matchAndRewrite 方法时,在匹配成功之前不应发生 IR 突变。当匹配和重写阶段需要non-trivially的可重计算信息时,组合的 matchAndRewrite 很有用。请参阅下面的示例:
classMyPattern :public RewritePattern { public: /// This overload constructs a pattern that only matches operations with the /// root name of `MyOp`. MyPattern(PatternBenefit benefit, MLIRContext *context) : RewritePattern(MyOp::getOperationName(), benefit, context) {} /// This overload constructs a pattern that matches any operation type. MyPattern(PatternBenefit benefit) : RewritePattern(benefit, MatchAnyOpTypeTag()) {}
/// In this section, the `match` and `rewrite` implementation is specified /// using the separate hooks. LogicalResult match(Operation *op)constoverride{ // The `match` method returns `success()` if the pattern is a match, failure // otherwise. // ... } voidrewrite(Operation *op, PatternRewriter &rewriter){ // The `rewrite` method performs mutations on the IR rooted at `op` using // the provided rewriter. All mutations must go through the provided // rewriter. }
/// In this section, the `match` and `rewrite` implementation is specified /// using a single hook. LogicalResult matchAndRewrite(Operation *op, PatternRewriter &rewriter){ // The `matchAndRewrite` method performs both the matching and the mutation. // Note that the match must reach a successful point before IR mutation may // take place. } };
限制
在Pattern的match部分中,应用以下约束:
不允许IR突变。
在Pattern的rewrite部分中,应用以下约束:
所有 IR 突变,包括创建,都必须由给定的 PatternRewriter 执行。此类提供了用于执行Pattern中可能发生的所有可能突变的钩子。例如,这意味着不应通过其erase方法来删除操作。要删除操作,应使用适当的 PatternRewriter 钩子(在本例中为 eraseOp)。
voidpopulateMyPatterns(RewritePatternSet &patterns, MLIRContext *ctx){ // Debug labels may also be attached to patterns during insertion. This allows // for easily attaching common labels to groups of patterns. patterns.addWithLabel("MyRewritePatterns", ctx); }
PatternRewriter 是一个特殊的类,它允许Pattern与Pattern应用程序的驱动程序进行通信。如上所述,所有 IR 突变,包括创建,都需要通过 PatternRewriter 类执行。这是必需的,因为底层Pattern驱动程序可能具有在发生突变时会失效的状态。 下面显示了一些更流行的 PatternRewriter API 的示例,请参阅类文档(https://github.com/llvm/llvm-project/blob/main/mlir/include/mlir/IR/PatternMatch.h#L235)以获取可用 API 的更新列表:
/// Define a custom PatternRewriter for use by the driver. classMyPatternRewriter :public PatternRewriter { public: MyPatternRewriter(MLIRContext *ctx) : PatternRewriter(ctx) {}
/// Override the necessary PatternRewriter hooks here. };
/// Apply the custom driver to `op`. voidapplyMyPatternDriver(Operation *op, const RewritePatternSet &patterns){ // Initialize the custom PatternRewriter. MyPatternRewriter rewriter(op->getContext());
// Create the applicator and apply our cost model. PatternApplicator applicator(patterns); applicator.applyCostModel([](const Pattern &pattern) { // Apply a default cost model. // Note: This is just for demonstration, if the default cost model is truly // desired `applicator.applyDefaultCostModel()` should be used // instead. return pattern.getBenefit(); });
// Try to match and apply a pattern. LogicalResult result = applicator.matchAndRewrite(op, rewriter); if (failed(result)) { // ... No patterns were applied. } // ... A pattern was successfully applied. }
voidMyPass::initialize(MLIRContext *context){ // No patterns are explicitly disabled. SmallVector<std::string> disabledPatterns; // Enable only patterns with a debug name or label of `MyRewritePatterns`. SmallVector<std::string> enabledPatterns(1, "MyRewritePatterns");
ListOption<"disabledPatterns", "disable-patterns", "std::string", "Labels of patterns that should be filtered out during application", "llvm::cl::MiscFlags::CommaSeparated">, ListOption<"enabledPatterns", "enable-patterns", "std::string", "Labels of patterns that should be used during application, all " "other patterns are filtered out", "llvm::cl::MiscFlags::CommaSeparated">,
// When constructing the `FrozenRewritePatternSet`, we provide the filter // list options. frozenPatterns = FrozenRewritePatternSet(rewritePatterns, disabledPatterns, enabledPatterns); }
0x4. Operation Canonicalization(操作规范化)
规范化是编译器 IR 设计的重要组成部分:它使实现可靠的编译器转换和推理代码中的优劣变得更加容易,并引发了有关特定 IR 级别目标的有趣讨论。Dan Gohman 写了一篇文章探讨这些问题;如果你不熟悉这些概念,则值得一读。文章地址为:https://sunfishcode.github.io/blog/2018/10/22/Canonicalization.html 。
def MyOp : ... { // I want to define a fully general set of patterns for this op. let hasCanonicalizer = 1; }
def OtherOp : ... {
// A single "matchAndRewrite" style RewritePattern implemented as a method // is good enough for me. let hasCanonicalizeMethod = 1; }
/// Implementations of this hook can only perform the following changes to the /// operation: /// /// 1. They can leave the operation alone and without changing the IR, and /// return nullptr. /// 2. They can mutate the operation in place, without changing anything else /// in the IR. In this case, return the operation itself. /// 3. They can return an existing value or attribute that can be used instead /// of the operation. The caller will remove the operation and use that /// result instead. /// OpFoldResult MyOp::fold(ArrayRef operands){ ... }
否则将生成下面的内容:
/// Implementations of this hook can only perform the following changes to the /// operation: /// /// 1. They can leave the operation alone and without changing the IR, and /// return failure. /// 2. They can mutate the operation in place, without changing anything else /// in the IR. In this case, return success. /// 3. They can return a list of existing values or attribute that can be used /// instead of the operation. In this case, fill in the results list and /// return success. The results list must correspond 1-1 with the results of /// the operation, partial folding is not supported. The caller will remove /// the operation and use those results instead. /// /// Note that this mechanism cannot be used to remove 0-result operations.
LogicalResult MyOp::fold(ArrayRef operands, SmallVectorImpl &results){ ... }
def MyDialect_Dialect : ... { let hasConstantMaterializer = 1; }
然后可以在源文件中具体化常量:
/// Hook to materialize a single constant operation from a given attribute value /// with the desired resultant type. This method should use the provided builder /// to create the operation without changing the insertion position. The /// generated operation is expected to be constant-like. On success, this hook /// should return the value generated to represent the constant value. /// Otherwise, it should return nullptr on failure. Operation *MyDialect::materializeConstant(OpBuilder &builder, Attribute value, Type type, Location loc){ ... }