Start with a contract, then earn the rewrite
This tutorial follows the shipped fma-fuse stage in
passes/fma.cpp. It is a useful small transformation with substantial
safety obligations: replace an admitted FMUL/FADD pair with an FFMA while keeping
the instruction slots, SSA graph, physical operands, and encoding consistent.
Complete the quickstart first. You need an MLIR-enabled source checkout to edit and rebuild the pass. The source is not yet public; the filenames and function names below are navigation landmarks using the launch layout. C++ excerpts are taken from existing code and are not standalone implementations.
The practical sequence is admit → prove dependencies → prepare → verify → commit → publish → validate on the device. Refusal is a supported outcome at every stage where the required evidence is missing.
Choose a narrow semantic and numerical policy
FMA contraction is not an exact floating-point identity. Multiplication followed
by addition rounds twice; FFMA rounds the fused result once. Results can differ
even for finite inputs. The existing pipeline therefore requires explicit
--passes fma-fuse; it does not enable this policy by default.
The first gate is deliberately narrow. This is the existing fma_product
predicate, an illustrative excerpt from fma.cpp:
return inst.mnemonic == "FMUL" && inst.modifiers.empty() && !inst.has_guard &&
inst.operands.size() == 3 && fma_plain(inst.operands[0]) &&
fma_register(inst.operands[0], product);fma_consumer then requires an unguarded, modifier-free FADD with the product
in exactly one plain source slot. In-place products have additional plain-register
restrictions. Other source forms still have to pass the actual encoder checks;
this is not permission to contract every instruction spelling containing FMUL
and FADD.
For your own pass, write its contract before broadening a matcher: supported SMs, operand families, modifiers, predicates, aliasing, and numerical policy. If the claim is exactness, preserve signed zero, subnormal behavior, NaNs, infinities, rounding, and exceptions relevant to the application. If it permits approximation or contraction, make the permission explicit and define the comparison tolerance before measuring performance.
Follow actual SSA values and physical effects
The current machine dialect represents instructions as sass.inst operations.
A structured operands attribute describes physical register fields, memory
operands, decorations, and back-references to the op’s SSA sources/results.
Editing a mnemonic or a printed register number alone cannot update all of that
meaning.
Use sass::project_register_bindings to obtain a checked sass_op_refs. Its
occs map structured register occurrences to actual mlir::Values; old_srcs
holds retained destination values for guarded writes. Failed projection means
the partial result cannot be consumed. See SassDialect.h, SassOps.cpp, and
docs/development/instruction-register-bindings.md.
The existing fma_replace checks both projections and confirms that the FADD
consumes this particular multiply result. This excerpt is a dependency check,
not merely a physical-register-name match:
if (mlir::failed(sass::project_register_bindings(multiply, mul_refs)) ||
mlir::failed(sass::project_register_bindings(add, add_refs)) ||
multiply->getNumResults() != 1 || add->getNumResults() != 1 ||
fma_source(add_refs, slot) != multiply->getResult(0))
return "invalid-pair-ssa";SSA bindings and physical effects answer different questions. The shared
sass::sass_inst_defuse query with sass_effect_kind::physical_registers
includes modeled physical spans and implicit dependencies that are not extra
exact SSA operands. Its possible writes and definite kills are distinct. A
guarded write may update a register, but cannot kill its old value on the
false-predicate path.
That distinction matters even though FMA itself rejects predicated pairs. The pass must still prove that a later predicated overwrite does not hide a surviving use of the product. It uses physical liveness, including loops and successor blocks, and refuses reachable instructions with unmodeled effects before a definite product kill. An empty explicit operand list is not proof of no effects.
Read the compiler contracts and the analysis guide before changing these gates. In particular, do not manufacture exact SSA followers from a conservative physical register span.
Prove the whole instruction window
fma_func collects current instructions from the MLIR function, verifies their
bindings, and classifies control transfers using the shared branch machinery.
Its candidate scan stays in one block and stops at control or synchronization
barriers, unknown effects, a rewritten product, or a clobbered multiplicand.
Symbol- and relocation-pinned offsets also block the rewrite window.
When the add writes a different register, the pass proves the product is dead
after the consumer. In-place cases additionally protect the addend and destination
against intervening writes. Refusal counters name the failed proof, for example
fmul-src-rewritten-in-window, product-live-after-consumer, or
symbol-or-reloc-in-window.
For a new optimization, use this same discipline: prove what may change between producer and consumer, including predicates, implicit register groups, memory effects, and control flow. Treat an unsupported effect or unresolved transfer conservatively. Do not infer that two arithmetic instructions can be moved across a call or barrier because their printed R registers look independent.
Prepare both replacements before committing either
FMA keeps both instruction slots. In an ordinary admitted pair, the multiply slot becomes a MOV of zero and the add slot becomes FFMA. If the product aliases a multiplicand, the first slot becomes NOP and the original multiplicand SSA value is retained. The pass does not shorten the section merely because one arithmetic operation disappeared.
fma_replace constructs the new AST operands, collects sources from the checked
occurrences, and calls sass::make_inst. The builder takes actual source values,
result types, and the decoded replacement schedule; it can refuse an inconsistent
source count. The pass verifies both new instruction ops before replacing result
uses and erasing the originals. If preparation or verification fails, it removes
the temporary replacements and keeps the pair.
This is the edit boundary to copy: prepare first, commit only a complete valid replacement. When editing a guarded operation in another pass, preserve its guard and retained old destination inputs too. Keeping its explicit sources while dropping its old value silently changes the false-predicate behavior.
Remove stale raw authority, or install checked new words
#sass.raw is authoritative encoding evidence. In
lib/pepesilvia/emit.cpp, emit_inst returns RAW immediately when has_raw
is set. A changed operand with the old raw word still attached can therefore
emit the old instruction.
The ordinary semantic-edit API is sass::mark_edited(op), declared in
SassLower.h and defined in SassLower.cpp. It removes the raw attribute so
the shared emitter must regenerate the instruction. uniform.cpp demonstrates
the pattern: prepare candidate encodings, update structured operands and result
types, handle reuse changes, then call mark_edited in commit.
The following is the complete existing marker implementation, not an automatic listener attached to arbitrary attribute writes:
void mark_edited(Operation* op)
{
if (op != nullptr)
op->removeAttr("raw");
}FMA deliberately uses a more specialized route. fma_word first checks that the
original raw word decodes to the current structured instruction. It encodes the
wanted replacement, merges the intended owned fields, and independently decodes
the result to check the requested instruction. Only then does fma_replace
attach new verified raw words and their decoded schedules to the new ops.
It never leaves the old raw encoding authoritative for a changed instruction.
Do not turn this special case into a general instruction to write raw bits.
Use the shared encoder and its ownership rules. Semantic changes normally use
mark_edited; a new checked-raw path needs its own justification and tests.
Preserving control fields is an obligation, not a proof
Stalls, yield, read/write barrier posts, wait masks, and operand reuse are machine state. Replacing or moving instructions can change which accesses are pending even when the visible values look correct.
FMA preserves its original slot-control mask
0xc3fffe0000000000 while generating reuse from the new operands. The replacement
schedule is decoded from the checked word. This preserves the implementation’s
specific encoding policy; it does not establish that a MOV or NOP posts and
waits on scoreboards exactly as the removed FMUL did on every GPU.
sass::set_sched updates the schedule and patches retained raw through the
shared scheduling mask, preserving other bits. This low-level API does not
validate the joint form-specific issue encoding or establish schedule legality. The ordinary semantic marker is still required when instruction
content changes. Do not guess a control-code layout from another architecture
or zero barrier fields merely to make encoding succeed.
Read Scheduling codes and their challenges before adding a scheduling transform. Keep unknown dependencies conservative, and validate forward progress on the target device as well as numerical output.
Make each proof refer to the current IR
An analysis computed before a rewrite describes the old program. FMA recomputes physical liveness when checking subsequent pairs, so an earlier contraction can change the next admission decision. Uniformization gathers and preflights its candidate web before its commit phase instead of mutating underneath the same selection proof.
Discard or recompute liveness, uniformity, allocation plans, and schedule
projections after relevant edits. SassLower.h explicitly says that any function
mutation invalidates a sass_schedule_projection, including schedule-only
changes. Do not retain pointers to erased operations in a later analysis.
Symbolic memoization has an explicit owner. If a live sass::sym_resolver must
survive an in-place semantic edit, use sass::edit_sym(resolver, op, edit) as
documented in SassSymAddr.h. Its callback may edit only the named live operation;
it may not erase it, mutate other nodes, or run during a resolver query.
Structural changes require the documented broader invalidation. Otherwise end
the analysis phase and create a fresh resolver for the changed region. There is
no global listener that repairs every copied proof or cached result for you.
Extend the shared MLIR pipeline
The normal stages are C++ transformations over MLIR, selected by the shared
sass_rewrite_kernel_image_mlir driver in dialect/lib/SassPasses.cpp. They
are not one runtime .so per optimization, and internal.h is not a stable
public plugin API.
For an extension to FMA, edit fma.cpp and use the existing focused checks. If the transformation
needs a separate stage, follow the existing wiring rather than inventing a
registration mechanism:
- Add the bounded implementation under
passes/, reusing the existing instruction, analysis, and emission APIs. Put only declarations or shared records needed by other translation units ininternal.h. - Add the stage to
mlrw_pass, the correspondingmlrw_pass_namesentry, and the execution/report switches inSassPasses.cpp. Preserve supplied order, repeated stages, and failure propagation. - Update
exe/sass-mlir.cpppass listing/help,docs/cli.md, and relevant CLI/pipeline checks. Include the implementation in the shared MLIR build source list forpasses/; a new optimization does not need a separate runtime plugin target. - Use the existing checks for the affected behavior. A new case should expose a distinct failure or unsupported boundary; duplicating the matcher in a test adds no independent evidence.
The CLI and the preload-facing mlircore/mlircore.cpp forward to the same rewrite
entry. The runtime kernel-rewrite plugin is the application adapter; it can
select FMA with SASS2MLIR_PASS=fma-fuse and an explicit SASS2MLIR_KERNEL
filter. A shared-pipeline implementation keeps offline and runtime behavior on
the same path without introducing another FMA plugin or parser.
If a pass resizes or reorders code, use sass_code_edit and the existing
stage-layout protocol. Each stage repairs its current branch/schedule coordinates
before the next stage; cumulative origins are retained for publication and
metadata. Final emission derives resolved direct branch targets from MLIR edges.
Do not update raw section bytes or ELF metadata independently.
The shared emitter classifies unencodable instructions as UNREGENERABLE; the
driver refuses those results. The cubin writer validates origins, pins, tails,
and metadata ownership before publishing text and metadata together. A failure
returns no transformed image and retains the original input. That publication
guarantee does not replace the pass’s semantic proof.
Check the changed contract
Start with the existing focused FMA check:
make -C build -j1 fma-test
ctest --test-dir build --output-on-failure -j1 -R '^host-fma$'Read tests/host/fma_test.cpp to understand what that check establishes. Its
verify_case helper verifies lifted and transformed MLIR, compares literal
expected section bytes, exercises complete-image publication, and checks that
the original image was not mutated. Those are separate properties of the
rewrite; passing them does not establish device arithmetic or forward progress.
Choose validation from the actual change. If admission changes, demonstrate the newly supported input and the nearest input that must still be refused. If encoding changes, inspect independently decoded output. If layout changes, check branch targets and metadata in the published cubin. Use existing coverage where it already answers the question.
The goal is a small, discriminating check with an independent expected result. Do not add fixture variants just because their instruction spelling differs, or manufacture an expected answer by running the transformation under test.
Prove behavior and progress before timing
Keep the original, make a separate candidate, and record the selected kernel, pass order, architecture, build revision, input bytes, and output bytes:
build/sass-mlir inspect kernel.cubin
build/sass-mlir verify kernel.cubin --threads 1
build/sass-mlir optimize kernel.cubin --passes fma-fuse \
--kernel KERNEL_SUBSTRING --out candidate.cubin
build/sass-mlir verify candidate.cubin --threads 1Replace KERNEL_SUBSTRING with a name from inspect. There is no universal
numerical-test CLI: use a workload-specific launcher that preserves the kernel’s
ABI and compares original and candidate results on the target GPU. Check boundary
sizes, predicates, aliases, adversarial numerical inputs, and repeated execution;
use a timeout to catch lost forward progress. For FMA, test against the agreed
fused-rounding policy rather than demanding separate-rounding bit identity.
Only after those checks should you time the same validated artifact with warmup, repeated measurements, synchronized completion, and an unchanged baseline. Serialize jobs on the device and keep loaded binaries fixed during a run. Report the GPU, driver/toolkit, launch and input contract, correctness criteria, and measurement spread alongside any speedup.
Continue with the analysis guide, scheduling, or the CLI reference.