MLIR 24.0.0git
ABIRewriteContext.h
Go to the documentation of this file.
1//===- ABIRewriteContext.h - Dialect-specific ABI rewriting -----*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines ABIRewriteContext, the abstract interface for dialect-
10// specific ABI lowering rewrites. Each MLIR dialect that wants ABI lowering
11// (CIR, FIR, etc.) provides a concrete subclass.
12//
13// ABIRewriteContext consumes ABI classification results and drives the
14// creation of lowered function signatures, argument coercions, and call
15// site rewrites using dialect-specific operations.
16//
17//===----------------------------------------------------------------------===//
18
19#ifndef MLIR_ABI_ABIREWRITECONTEXT_H
20#define MLIR_ABI_ABIREWRITECONTEXT_H
21
22#include "mlir/IR/Builders.h"
23#include "mlir/IR/Operation.h"
24#include "mlir/IR/Types.h"
25#include "mlir/IR/Value.h"
27#include "llvm/ADT/STLExtras.h"
28#include "llvm/Support/Alignment.h"
29
30#include <cassert>
31
32namespace mlir {
33namespace abi {
34
35/// Classification of how a single argument or return value should be
36/// passed at the ABI level.
37///
38/// This is a dialect-agnostic representation. It mirrors the kinds
39/// found in the LLVM ABI library and in CIR's ABIArgInfo, but does
40/// not depend on either.
41enum class ArgKind : uint8_t {
42 /// Pass directly in registers, possibly coerced to a different type.
44
45 /// Like Direct, but with a sign/zero extension attribute.
47
48 /// Pass indirectly via a pointer (sret for returns, byval for args).
50
51 /// Pass a pointer to the caller's object with no copy implied (byref). The
52 /// callee must not write through it. Arguments only.
54
55 /// Ignore (void return, empty struct).
57
58 /// Expand an aggregate into its constituent scalar fields.
60};
61
62/// Describes how a single argument or return value is passed after ABI
63/// lowering.
66
67 /// The ABI-coerced type, if different from the original. Null means
68 /// use the original type.
69 Type coercedType = nullptr;
70
71 /// For Indirect and IndirectAliased: alignment of the pointed-to object.
72 llvm::Align indirectAlign = llvm::Align(1);
73
74 /// For Extend: whether to sign-extend (true) or zero-extend (false).
75 bool signExtend = false;
76
77 /// For Extend: Whether the extension is conservative, i.e. the sender
78 /// extends, but the receiver does not assume the extension. Currently only
79 /// supported for arguments, i.e. caller extends, but callee does not assume
80 /// extension.
81 bool conservative = false;
82
83 /// For Direct: whether a struct coercion can be flattened into
84 /// individual register-width arguments.
85 bool canFlatten = true;
86
87 /// For Indirect: whether the callee gets ownership (byval).
88 bool byVal = false;
89
90 /// For Indirect and IndirectAliased: target address space of the pointer
91 /// passed in place of the value. Zero is the default address space.
92 unsigned indirectAddrSpace = 0;
93
94 /// For Direct with coercion: the byte offset within the original aggregate
95 /// at which the coerced value lives. Non-zero when the low eightbyte is
96 /// NO_CLASS and the value is carried in a later eightbyte (x86-64 SysV).
97 unsigned directOffset = 0;
98
99 /// For Direct: the alignment of the argument's stack slot when the value
100 /// is passed in memory, if the ABI sets one apart from the type's.
101 llvm::MaybeAlign directAlign;
102
103 /// How many integer and vector argument registers the value occupies. Both
104 /// zero means it travels in memory, which is also what a target whose
105 /// classifier does not record the demand reports.
106 unsigned neededIntRegs = 0;
107 unsigned neededSseRegs = 0;
108
109 /// Whether the value is passed as-is, so a rewriter can leave it alone.
110 /// Only an uncoerced Direct with no stack-slot alignment qualifies.
111 /// Extend counts as needing a rewrite even though it only adds an
112 /// attribute, because the attribute changes observable behavior, and a
113 /// Direct with a stack-slot alignment does too because it needs
114 /// llvm.alignstack.
115 bool isPassThrough() const {
117 }
118
119 /// Whether two classifications describe the same wire format. Every field
120 /// participates, so a field added above must be added here as well.
121 bool operator==(const ArgClassification &other) const {
122 return kind == other.kind && coercedType == other.coercedType &&
123 indirectAlign == other.indirectAlign &&
124 signExtend == other.signExtend &&
125 conservative == other.conservative &&
126 canFlatten == other.canFlatten && byVal == other.byVal &&
128 directOffset == other.directOffset &&
129 directAlign == other.directAlign &&
130 neededIntRegs == other.neededIntRegs &&
132 }
133
135 return getDirect(/*coerced=*/nullptr, /*offset=*/0);
136 }
137
138 static ArgClassification getDirect(Type coerced, unsigned offset,
139 llvm::MaybeAlign align = std::nullopt) {
140 // isPassThrough ignores directOffset, so an offset with no coerced
141 // type to read at it would be silently ignored.
142 assert((!offset || coerced) &&
143 "a direct offset needs a coerced type to read at it");
146 c.coercedType = coerced;
147 c.directOffset = offset;
148 c.directAlign = align;
149 return c;
150 }
151
155 return c;
156 }
157
158 static ArgClassification getIndirect(llvm::Align align, bool byVal,
159 unsigned addrSpace) {
162 c.indirectAlign = align;
163 c.byVal = byVal;
164 c.indirectAddrSpace = addrSpace;
165 return c;
166 }
167
168 static ArgClassification getIndirectAliased(llvm::Align align,
169 unsigned addrSpace) {
172 c.indirectAlign = align;
173 c.indirectAddrSpace = addrSpace;
174 return c;
175 }
176
177 static ArgClassification getExtend(Type coerced, bool signExt,
178 bool conservative = false) {
181 c.coercedType = coerced;
182 c.signExtend = signExt;
184 return c;
185 }
186};
187
188/// Holds the full ABI classification for a function: return type and
189/// all arguments.
193
194 /// Whether the classified return type was the source language's void.
195 ///
196 /// A void return classifies as Ignore, and so does a return the ABI drops,
197 /// such as an empty record. The two need opposite treatment: void is
198 /// already its own wire form, while a dropped record return has to be
199 /// rewritten to one. returnInfo alone cannot tell them apart, so whoever
200 /// produces the classification records it here, next to the return type it
201 /// came from. A consumer that re-derived it from something else could pair
202 /// a classification with the wrong answer, and reading a dropped return as
203 /// void means silently skipping the rewrite it needs.
204 ///
205 /// Left false when unknown, which costs a needless rewrite rather than a
206 /// skipped one.
207 bool returnsVoid = false;
208
209 /// Whether any value in the signature is passed differently from how it is
210 /// written, so a rewriter has work to do.
211 bool needsRewrite() const {
212 if (!returnsVoid && !returnInfo.isPassThrough())
213 return true;
214 return !llvm::all_of(argInfos, [](const ArgClassification &ac) {
215 return ac.isPassThrough();
216 });
217 }
218};
219
220/// ABIRewriteContext is the abstract interface that each dialect
221/// implements to perform ABI-specific rewrites on its operations.
222///
223/// The pass orchestrator calls these methods after ABI classification
224/// to rewrite function definitions and call sites.
226public:
227 virtual ~ABIRewriteContext() = default;
228
229 /// Rewrite a function definition to use ABI-lowered types.
230 ///
231 /// This creates a new function with the lowered signature, rewrites
232 /// the function body to adapt between the ABI types and the
233 /// original high-level types, and replaces the original function.
234 ///
235 /// \param funcOp The function to rewrite (via FunctionOpInterface).
236 /// \param fc The ABI classification for this function.
237 /// \param builder The OpBuilder to use for modifications.
238 /// \returns success() if the function was rewritten.
239 virtual LogicalResult
240 rewriteFunctionDefinition(FunctionOpInterface funcOp,
241 const FunctionClassification &fc,
242 OpBuilder &builder) = 0;
243
244 /// Rewrite a call operation to match the callee's ABI-lowered
245 /// signature.
246 ///
247 /// This coerces arguments, handles indirect returns (sret), and
248 /// adapts the call result back to the original high-level type.
249 ///
250 /// \param callOp The call operation to rewrite.
251 /// \param fc The ABI classification for the callee.
252 /// \param builder The OpBuilder to use for modifications.
253 /// \returns success() if the call was rewritten.
254 virtual LogicalResult rewriteCallSite(Operation *callOp,
255 const FunctionClassification &fc,
256 OpBuilder &builder) = 0;
257
258 /// Rewrite a single "fetch the next vararg" operation (e.g. C `va_arg`) to
259 /// match how \p ac says the fetched type is passed at the ABI level.
260 ///
261 /// \p ac classifies only the one type being fetched, in isolation, with the
262 /// whole register budget available. A vararg fetch advances a runtime
263 /// cursor (the platform va_list) through registers and then memory, so
264 /// whether a given fetch lands in a register depends on how much of the
265 /// budget earlier variadic arguments already consumed at run time, not on
266 /// the fetch's static position.
267 ///
268 /// An implementation may erase \p vaArgOp and replace its result, so a
269 /// caller walking the IR must collect the fetches before rewriting any of
270 /// them.
271 ///
272 /// The default implementation reports failure, so a dialect that has not
273 /// implemented vararg fetches does not need to override this. An overrider
274 /// that fails is responsible for emitting its own diagnostic.
275 ///
276 /// \param vaArgOp The fetch to rewrite. May be erased.
277 /// \param ac The ABI classification of the fetched type.
278 /// \param builder The OpBuilder to use for modifications.
279 /// \returns success() if the operation was rewritten.
280 virtual LogicalResult rewriteVAArg(Operation *vaArgOp,
281 const ArgClassification &ac,
282 OpBuilder &builder) {
283 return failure();
284 }
285
286 /// Return the dialect namespace this context handles (e.g. "cir").
287 virtual StringRef getDialectNamespace() const = 0;
288};
289
290} // namespace abi
291} // namespace mlir
292
293#endif // MLIR_ABI_ABIREWRITECONTEXT_H
This class helps build Operations.
Definition Builders.h:210
Operation is the basic unit of execution within MLIR.
Definition Operation.h:87
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
Definition Types.h:74
ABIRewriteContext is the abstract interface that each dialect implements to perform ABI-specific rewr...
virtual StringRef getDialectNamespace() const =0
Return the dialect namespace this context handles (e.g. "cir").
virtual LogicalResult rewriteVAArg(Operation *vaArgOp, const ArgClassification &ac, OpBuilder &builder)
Rewrite a single "fetch the next vararg" operation (e.g.
virtual ~ABIRewriteContext()=default
virtual LogicalResult rewriteFunctionDefinition(FunctionOpInterface funcOp, const FunctionClassification &fc, OpBuilder &builder)=0
Rewrite a function definition to use ABI-lowered types.
virtual LogicalResult rewriteCallSite(Operation *callOp, const FunctionClassification &fc, OpBuilder &builder)=0
Rewrite a call operation to match the callee's ABI-lowered signature.
ArgKind
Classification of how a single argument or return value should be passed at the ABI level.
@ Indirect
Pass indirectly via a pointer (sret for returns, byval for args).
@ IndirectAliased
Pass a pointer to the caller's object with no copy implied (byref).
@ Extend
Like Direct, but with a sign/zero extension attribute.
@ Expand
Expand an aggregate into its constituent scalar fields.
@ Ignore
Ignore (void return, empty struct).
@ Direct
Pass directly in registers, possibly coerced to a different type.
Include the generated interface declarations.
Describes how a single argument or return value is passed after ABI lowering.
static ArgClassification getIgnore()
bool canFlatten
For Direct: whether a struct coercion can be flattened into individual register-width arguments.
bool signExtend
For Extend: whether to sign-extend (true) or zero-extend (false).
bool isPassThrough() const
Whether the value is passed as-is, so a rewriter can leave it alone.
bool conservative
For Extend: Whether the extension is conservative, i.e.
unsigned indirectAddrSpace
For Indirect and IndirectAliased: target address space of the pointer passed in place of the value.
llvm::MaybeAlign directAlign
For Direct: the alignment of the argument's stack slot when the value is passed in memory,...
static ArgClassification getDirect()
bool operator==(const ArgClassification &other) const
Whether two classifications describe the same wire format.
static ArgClassification getIndirect(llvm::Align align, bool byVal, unsigned addrSpace)
Type coercedType
The ABI-coerced type, if different from the original.
static ArgClassification getExtend(Type coerced, bool signExt, bool conservative=false)
unsigned directOffset
For Direct with coercion: the byte offset within the original aggregate at which the coerced value li...
bool byVal
For Indirect: whether the callee gets ownership (byval).
static ArgClassification getIndirectAliased(llvm::Align align, unsigned addrSpace)
unsigned neededIntRegs
How many integer and vector argument registers the value occupies.
llvm::Align indirectAlign
For Indirect and IndirectAliased: alignment of the pointed-to object.
static ArgClassification getDirect(Type coerced, unsigned offset, llvm::MaybeAlign align=std::nullopt)
Holds the full ABI classification for a function: return type and all arguments.
bool returnsVoid
Whether the classified return type was the source language's void.
bool needsRewrite() const
Whether any value in the signature is passed differently from how it is written, so a rewriter has wo...
SmallVector< ArgClassification > argInfos