Pre-lowering hook for targets with custom dialects (TargetLowering)

I’m exploring a Mojo target that has its own MLIR dialect and I’d like to check whether a small extension point would be welcome before I open an issue.

Problem

  • TargetLowering already has addPostLowerToLLVMPasses, which runs on LLVM-dialect IR just before translation to LLVM IR.
  • A target-specific dialect can’t be lowered there. By then, the module is LLVM dialect, and KGEN/POP lowering has already seen (and may have rejected) ops and types it doesn’t know.
  • There is no slot on post-elaboration KGEN IR, before LowerKGENToLLVM,where a target can lower its own ops (for example ones written with__mlir_op).

Proposal

  • Add TargetLowering::addPreLowerToLLVMPasses(OpPassManager&), default no-op, next to the post hook.
  • Give target-specific-llvm-lowering a pre-lowering option. Default behavior is unchanged.
  • Run the pass in pre mode at the start of buildLowerToLLVMPipeline.
  • Dispatch is through TargetLoweringRegistry by triple, exactly like the post hook, so only the claiming target is affected. For other targets the pass is a no-op.

Why not use the existing hook? It runs too late: after the generic lowering has consumed the IR.

Questions

  1. Is there an existing mechanism I missed?
  2. Would the team accept this as a PR? I understand compiler changes need an accepted issue first, and that changes to the pipeline may be out of scope for external PRs. If so, is this better handled internally?
  3. Preference between a pass option and a separate pass?

I have a working branch with a unit test (a mock target, three cases - AI assisted coding). I’ll share it once there’s interest.

Is you dialect for the host or for the device ? For the host we indeed don’t have anything yet, but for the device you should be able to use lowerAndEmitOffload and construct your own custom pipeline there. The way it works now is backend tells that it “fully owns lowering” after our optimizations and transformations.

However, there are certain cases where this is not sufficient and I am working on adding another hook buildPostElaborationPipeline that will let target backend to fully own MLIR pipeline.

That is, we will have

buildPostElaborationPipeline - to let target to have own MLIR pipeline after IR becomes concrete. This should be also possible to use it for host targets

lowerAndEmitOffload - to let target to lower KGEN/POP/HLCF to custom dialect(s) and return target’s executable.

As for your proposal, for now I’d prefer to avoid allowing targets to inject passes into our pipeline. Mainly because it’s not clear whether it’s going to be widely used. For now better to let target to fully own some big logical chunk of pipeline. With more and more targets, we can come back to your proposal.

Thanks @npanchen, this is very helpful, and I’m happy to drop the pass-injection proposal. Owning a whole logical chunk of the pipeline seems like a cleaner solution than adding injection points.

To answer your first question: my dialect is for the host path, not an offload device. It’s compiled to an object file for a freestanding target, so lowerAndEmitOffload doesn’t apply. That matches your point that host targets have nothing yet.

I have a few questions about buildPostElaborationPipeline so I can plan around it:

  1. Will it be a hook on the target (for example on TargetBackend), chosen by the module’s target triple?
  2. Will it work on the host object path (lowerAllFuncsToLLVM), and not only on the offload path?
  3. Where does it sit relative to the existing stages? Today buildPostElaborationPipeline is the optimization stage, andbuildLowerToLLVMPipeline (starting with LowerKGENToLLVM) runs afterwards. Does the new hook replace only the first, or both? Can a target compose it from the stock pieces (call the first/late opt pipelines, add its own passes, then still use the stock LowerKGENToLLVM)? My case needs a few target passes after the optimizations and just before LowerKGENToLLVM.
  4. Is there a rough timeline, or a PR or issue I can follow?

I’d be glad to try it against a host-style target with its own dialect and report back.

Will it be a hook on the target (for example on TargetBackend), chosen by the module’s target triple?

My current idea is it will belong to TargetBackend and populateElaborateModulePasses will have something like

if (auto target = TargetBackendRegistry::get().lookup(triple); target && target->buildPostElaborationPipeline(pm...))
  return;

buildPostElaborationPipeline(pm, ...); // default

There might be some inconvenience to replicate our pipeline, because Pipeline.h is not in Mojo/include. Maybe team will be ok to move that header file to Mojo/include

Will it work on the host object path (lowerAllFuncsToLLVM), and not only on the offload path?

It suppose to work because populateElaborateModulePasses is used by the host (I assume you plan to override isBaseTarget for you)

Where does it sit relative to the existing stages? Today buildPostElaborationPipeline is the optimization stage, andbuildLowerToLLVMPipeline (starting with LowerKGENToLLVM) runs afterwards. Does the new hook replace only the first, or both? Can a target compose it from the stock pieces (call the first/late opt pipelines, add its own passes, then still use the stock LowerKGENToLLVM)? My case needs a few target passes after the optimizations and just before LowerKGENToLLVM.

It’s only meant to be used before any lowering.

In high-level, our pipeline can be seen as

parser -> elaborator -> MLIR optimizations -> MLIR lowering to target
                             ^                        ^
                 buildPostElaborationPipeline   buildLowerToLLVMPipeline/lowerAndEmitOffload 

That’s true for both host and device with some nuances that are not relevant here.

Is there a rough timeline, or a PR or issue I can follow?

It’s a bit complicated, but for internal repo I will open PR later today. Then review process, which may still change some things I have. And that’s a good time to remind that our plugin APIs are not stable (yet), so things might come and go away, so please be patient and raise concerns if something isn’t working for you.

Please see our AI usage policy (quoting below for reference). In the future, please make sure that if you’re using AI to help write replies, those replies still read as human-written, and there’s value in the reply beyond what AI has generated.

Don’t post AI-generated technical solutions without disclosing the source.
If you feel that an AI-generated code snippet or technical solution would add value to a discussion, be sure to disclose that the content is AI-generated (e.g. “I asked ChatGPT this question, and this is what it said: …”).
Otherwise, you’re welcome to use AI to edit or supplement your posts, but posts that are obviously AI-generated, don’t include a disclosure, and don’t add value to a discussion will be removed. Repeatedly violating this guidelines may result in removal of your account.

Thanks, this is very clear, and it fits what I need better than my proposal did.

I assume you plan to override isBaseTarget for you

Yes, I do plan to override isBaseTarget for a host-style target with its own dialect, so populateElaborateModulePasses is the right place.

There might be some inconvenience to replicate our pipeline, because Pipeline.h is not in Mojo/include. Maybe team will be ok to move that header file to Mojo/include

Two comments on the design, based on how I’d use it:

  1. Pipeline.h visibility. To build a custom pipeline, a target would call buildFirstOptPipeline and buildLateOptPipeline from Pipeline.h and then add its own passes. That is the pattern I’d use (optimizations first, then a few target passes that lower the target’s own ops, ahead of buildLowerToLLVMPipeline). Moving at least those functions to Mojo/include would make that possible without copying the pipeline. It would be nice to have that in the PR.
  2. Replace vs. extend. As per your design, the hook replaces the default pipeline. Targets that want “the default plus a few passes” would have to copy the sequence and deal with drift when it changes. Would it be reasonable for the hook to receive the default builder (or for there to be a variant that only adds passes)? Not essential, but just a thought.

Thanks for the note about plugin APIs being unstable. I’ll keep that in mind and raise anything that breaks. When the PR is available, I’d be happy to try it on a host-style target and report back.

Alrighty. I’ve merged my changes. Because next sync of our internal repo with external will happen tomorrow, to unblock you, use this patch

diff --git a/Mojo/include/Mojo/Compiler/Pipeline.h b/Mojo/include/Mojo/Compiler/Pipeline.h
new file mode 100644
index 00000000000..9f5842d786f
--- /dev/null
+++ b/Mojo/include/Mojo/Compiler/Pipeline.h
@@ -0,0 +1,42 @@
+//===----------------------------------------------------------------------===//
+// Copyright (c) 2026, Modular Inc. All rights reserved.
+//
+// Licensed under the Apache License v2.0 with LLVM Exceptions:
+// https://llvm.org/LICENSE.txt
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//===----------------------------------------------------------------------===//
+
+#ifndef KGEN_COMPILER_OPTPIPELINE_H
+#define KGEN_COMPILER_OPTPIPELINE_H
+
+namespace mlir {
+class PassManager;
+} // namespace mlir
+
+namespace M::KGEN {
+
+class CompilationOptions;
+
+/// The optimization and simplification passes that run right after the
+/// elaborator.
+void buildPostElaborationPipeline(mlir::PassManager &pm,
+                                  const CompilationOptions &options);
+
+/// Convention lowering, inlining and the optimizations that run at every
+/// level.
+void buildFirstOptPipeline(mlir::PassManager &pm,
+                           const CompilationOptions &options);
+
+/// The `-O1` and `-O2` optimization rounds, then loop, closure and async
+/// lowering.
+void buildLateOptPipeline(mlir::PassManager &pm,
+                          const CompilationOptions &options);
+
+} // namespace M::KGEN
+
+#endif // KGEN_COMPILER_OPTPIPELINE_H
diff --git a/Mojo/include/Mojo/Compiler/Target/TargetBackend.h b/Mojo/include/Mojo/Compiler/Target/TargetBackend.h
index 92cdce1da6e..4a0a63027df 100644
--- a/Mojo/include/Mojo/Compiler/Target/TargetBackend.h
+++ b/Mojo/include/Mojo/Compiler/Target/TargetBackend.h
@@ -54,6 +54,7 @@ struct object_creator;
 
 namespace mlir {
 class Operation;
+class PassManager;
 } // namespace mlir
 
 namespace M::KGEN {
@@ -179,6 +180,16 @@ public:
                                    FuncSymbolAttr symbol,
                                    mlir::ModuleOp module) const;
 
+  /// Appends the target's whole post-elaboration pipeline to `pm` and returns
+  /// true. A target that returns false gets the default pipeline instead. A
+  /// target pipeline replaces the default entirely, so it must include the
+  /// generic optimizations.
+  virtual bool
+  buildPostElaborationPipeline(mlir::PassManager &pm,
+                               const CompilationOptions &options) const {
+    return false;
+  }
+
   virtual SplitStrategy
   splitStrategy(const CompilationOptions &options) const = 0;
   /// Inter-procedural codegen disables parallel/per-function llc.
diff --git a/Mojo/lib/Compiler/KGENCompiler.cpp b/Mojo/lib/Compiler/KGENCompiler.cpp
index 95702e1ff62..5d04e73e820 100644
--- a/Mojo/lib/Compiler/KGENCompiler.cpp
+++ b/Mojo/lib/Compiler/KGENCompiler.cpp
@@ -171,6 +171,19 @@ generateInstantiateStub(GeneratorOp func, FuncSymbolAttr symbol,
   ReturnOp::create(b, call.getResults());
 }
 
+// Appends the target's post-elaboration pipeline, or the default one when the
+// target has none.
+static void buildPostElaborationPipeline(mlir::PassManager &pm,
+                                         TargetInfoAttr target,
+                                         const CompilationOptions &options) {
+  ErrorOr<const TargetBackend *> backendOr =
+      TargetBackendRegistry::get().lookup(target.getTriple());
+  if (!backendOr.isError() &&
+      (*backendOr)->buildPostElaborationPipeline(pm, options))
+    return;
+  buildPostElaborationPipeline(pm, options);
+}
+
 /// Find a FuncOp in the module by its kgen.offload.kernelid LLVM metadata.
 /// Returns nullptr if no function with the given kernel ID is found.
 static FuncOp findFuncByKernelId(ModuleOp module, uint64_t kernelId) {
@@ -346,7 +359,7 @@ static ErrorOr<StringAttr> compileStandaloneKernel(
   pm.addPass(createElaborateGenerators(target, elaboratorOptions,
                                        compilationOptions, compileElaboratorAsm,
                                        compileOffloads));
-  buildPostElaborationPipeline(pm, compilationOptions);
+  ::buildPostElaborationPipeline(pm, target, compilationOptions);
 
   if (failed(pm.run(*module)))
     return Error("failed to run the pass manager");
@@ -756,7 +769,7 @@ static ElaboratorCompileOffloadRetType compileOffloads(
           createElaborateGenerators(target, elabOptions, compilationOptions,
                                     compileElaboratorAsm, compileOffloads));
 
-      buildPostElaborationPipeline(pm, compilationOptions);
+      ::buildPostElaborationPipeline(pm, target, compilationOptions);
 
       if (failed(pm.run(*module)))
         return Error("failed to run the pass manager for offload functions");
@@ -966,7 +979,7 @@ void KGEN::populateElaborateModulePasses(mlir::PassManager &pm,
                                          const CompilationOptions &options) {
   buildElaborateModulePipeline(pm, target, options, compileElaboratorAsm,
                                compileOffloads);
-  buildPostElaborationPipeline(pm, options);
+  ::buildPostElaborationPipeline(pm, target, options);
 }
 
 //===----------------------------------------------------------------------===//
diff --git a/Mojo/lib/Compiler/Pipeline/Pipeline.h b/Mojo/lib/Compiler/Pipeline/Pipeline.h
index 64f9a489124..f15c281c042 100644
--- a/Mojo/lib/Compiler/Pipeline/Pipeline.h
+++ b/Mojo/lib/Compiler/Pipeline/Pipeline.h
@@ -14,6 +14,7 @@
 #define KGEN_COMPILER_PIPELINE_PIPELINE_H
 
 #include "Mojo/Compiler/KGENCompiler.h"
+#include "Mojo/Compiler/Pipeline.h"
 #include "Mojo/ToolCommon/KGENPasses.h"
 #include "Support/LLVMForwardDecls.h"
 
@@ -60,19 +61,6 @@ void buildElaborateModulePipeline(mlir::PassManager &pm, TargetInfoAttr target,
 void populateElaborateModulePasses(mlir::PassManager &pm, TargetInfoAttr target,
                                    const CompilationOptions &options);
 
-//===----------------------------------------------------------------------===//
-// PostElaborationPipeline
-//===----------------------------------------------------------------------===//
-
-/// This populates the post-elaboration optimization and simplification passes.
-/// These passes are intended to run immediately after the elaborator.
-void buildPostElaborationPipeline(mlir::PassManager &pm,
-                                  const CompilationOptions &options);
-void buildFirstOptPipeline(mlir::PassManager &pm,
-                           const CompilationOptions &options);
-void buildLateOptPipeline(mlir::PassManager &pm,
-                          const CompilationOptions &options);
-
 } // namespace KGEN
 } // namespace M
 

Let me know if you need any other help

Thanks @npanchen for the patch. I tried it on a host-style target that has its own dialect, and it works well for my case.

What I did => I applied the patch, made a TargetBackend that derives from HostBackend and overrides buildPostElaborationPipeline. It calls buildFirstOptPipeline, then buildLateOptPipeline, then adds a few target passes. The build and the Mojo unit and lit tests pass, and my end-to-end flow produces the same LLVM IR as my earlier approach. The public Pipeline.h is exactly what made this easy.

Some feedback, in order of importance:

  1. Registry precedence. To make my backend win over HostBackend for the same triple, I registered a dispatcher whose matches() is false and whose resolve() returns my backend. This works because lookup prefers a resolve() result that differs from the queried backend, and otherwise takes the first direct match in static-init order. Could that be documented? Two delegating backends would still race, so a priority or a documented tie-break might help.
  2. Subclassing HostBackend. Is this a supported pattern? It needed isBaseTarget, splitStrategy and the emit overrides, plus Bazel deps on the HostBackend, Pipeline and compiler headers targets. A short doc note, or a smaller base class for “host-like” targets, would help.
  3. Public pipeline functions. Composing with buildFirstOptPipeline and buildLateOptPipeline is what made this easy, since the hook replaces the default pipeline. Please keep them in the public header and treat them as the supported way to extend the default.
  4. Extend vs. replace. Still a minor point: a variant that adds passes around the default would avoid targets copying the sequence.

nice

t calls buildFirstOptPipeline, then buildLateOptPipeline, then adds a few target passes.

I think you should be able to avoid this by calling KGEN::buildPostElaborationPipeline then add your own passes

Registry precedence. To make my backend win over HostBackend for the same triple, I registered a dispatcher whose matches() is false and whose resolve() returns my backend. This works because lookup prefers a resolve() result that differs from the queried backend, and otherwise takes the first direct match in static-init order. Could that be documented? Two delegating backends would still race, so a priority or a documented tie-break might help.

Subclassing HostBackend. Is this a supported pattern? It needed isBaseTarget, splitStrategy and the emit overrides, plus Bazel deps on the HostBackend, Pipeline and compiler headers targets. A short doc note, or a smaller base class for “host-like” targets, would help

Ideally for host targets that should not be that hard. It should be possible to extend HostBackend, but we haven’t looked at this yet, but I’m excited to see you’re looking at this. That said, if you can write doc on how to add host targets or propose extending HostBackend, that will be awesome.

Thanks, calling KGEN::buildPostElaborationPipeline and then adding my own passes works well. It also means I pick up the whole default pipeline (fast-math, verifier, materialization) and follow it as it changes. I’ve switched to that, and things still work as expected.

On HostBackend, I’d be glad to help. Subclassing it was straightforward: my backend only overrides name, matches and the new pipeline hook. The awkward part was the registry: the stock HostBackend registration and my backend both match the same triple, and registering mine directly would make the winner depend on static-init order. I fixed that with a small “dispatcher backend” whose matches() is false and whose resolve() returns my backend. It works because lookup prefers a resolve() result that differs from the queried backend.

I can do either of these:

  1. Write a short doc on adding a host-like target. It would cover subclassing HostBackend, the registry precedence pattern above, and the Bazel deps. I’d write it from what I encountered while building one.
  2. Propose a priority or tie-break in TargetBackendRegistry, so a host-like backend can register directly without the dispatcher.

Which do you prefer, and where should the doc live (for example under Mojo/docs/, or next to TargetBackend.h)? I’m also happy to wait until your PR is mainlined.