clang 24.0.0git
CallConvLoweringPass.cpp
Go to the documentation of this file.
1//===- CallConvLoweringPass.cpp - Lower CIR to ABI calling convention ----===//
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 pass walks every cir.func and cir.call in the module, computes a
10// FunctionClassification for it (via either an ABI target or a pre-built
11// classification injected as a function attribute), and dispatches to
12// CIRABIRewriteContext to perform the actual IR rewriting.
13//
14// Two driver modes (mutually exclusive):
15//
16// target=test
17// Use the MLIR test ABI target (mlir/lib/ABI/Targets/Test/) to classify
18// each function. Predictable rules that approximate x86_64 SysV. Real
19// targets (x86_64, AArch64) will be added once the LLVM ABI library
20// ships them.
21//
22// classification-attr=<name>
23// Read a DictionaryAttr named <name> from each cir.func and parse it via
24// mlir::abi::test::parseClassificationAttr. Used by tests to inject any
25// classification (including shapes the test target itself does not
26// produce) without depending on a real ABI target.
27//
28// The pass requires a `dlti.dl_spec` attribute on the module so the
29// classifier can query type sizes and alignments.
30//
31//===----------------------------------------------------------------------===//
32
33#include "CIRABIClassifier.h"
34#include "PassDetail.h"
36
37#include "mlir/ABI/ABIRewriteContext.h"
38#include "mlir/Dialect/DLTI/DLTI.h"
39#include "mlir/IR/Builders.h"
40#include "mlir/IR/BuiltinOps.h"
41#include "mlir/IR/SymbolTable.h"
42#include "mlir/Interfaces/DataLayoutInterfaces.h"
43#include "mlir/Pass/Pass.h"
46#include "llvm/ABI/TargetInfo.h"
47#include "llvm/ADT/ScopeExit.h"
48
49#include <algorithm>
50
51using namespace mlir;
52using namespace mlir::abi;
53using namespace cir;
54
55namespace mlir {
56#define GEN_PASS_DEF_CALLCONVLOWERING
57#include "clang/CIR/Dialect/Passes.h.inc"
58} // namespace mlir
59
60/// Whether \p ty, or an aggregate member/element reached by value (never
61/// through a pointer), is an incomplete record. Such a record has no known
62/// layout, so no classification can be built for it.
63static bool hasIncompleteRecordByValue(mlir::Type ty) {
64 if (auto recTy = dyn_cast<cir::RecordType>(ty))
65 return !recTy.isComplete() ||
66 llvm::any_of(recTy.getMembers(), hasIncompleteRecordByValue);
67 if (auto arrTy = dyn_cast<cir::ArrayType>(ty))
68 return hasIncompleteRecordByValue(arrTy.getElementType());
69 return false;
70}
71
72/// Whether \p fc gives the callee access to memory through a pointer the ABI
73/// introduced: an sret slot for an indirect return, or an indirect or byref
74/// argument.
75static bool hasIndirectSlot(const FunctionClassification &fc) {
76 if (fc.returnInfo.kind == ArgKind::Indirect)
77 return true;
78 return llvm::any_of(fc.argInfos, [](const ArgClassification &ac) {
79 return ac.kind == ArgKind::Indirect || ac.kind == ArgKind::IndirectAliased;
80 });
81}
82
83/// Record on \p op that the memory its pointer arguments address may be read
84/// and written. Absent effects already allow that, since an absent attribute
85/// means the effects are unknown, so they are left absent.
86template <typename OpTy> static void widenForArgMemory(OpTy op) {
87 cir::MemoryEffectsAttr effects = op.getMemoryEffectsAttr();
88 if (!effects)
89 return;
90 op.setMemoryEffectsAttr(cir::MemoryEffectsAttr::get(
91 effects.getContext(), effects.getOther(), cir::ModRefInfo::ModRef,
92 effects.getInaccessibleMem(), effects.getErrnoMem(),
93 effects.getTargetMem0(), effects.getTargetMem1()));
94}
95
96#ifndef NDEBUG
97/// Whether \p callFc classifies a call's leading arguments and its return
98/// exactly as \p calleeFc classifies the callee's declared parameters and
99/// return. A function definition and its call sites are rewritten from
100/// separate classifications, so the two would silently disagree on the wire
101/// format if an ellipsis argument could ever change how a declared parameter
102/// is passed.
103static bool classifiesSamePrefix(const FunctionClassification &calleeFc,
104 const FunctionClassification &callFc) {
105 if (callFc.argInfos.size() < calleeFc.argInfos.size())
106 return false;
107 return calleeFc.returnInfo == callFc.returnInfo &&
108 std::equal(calleeFc.argInfos.begin(), calleeFc.argInfos.end(),
109 callFc.argInfos.begin());
110}
111#endif
112
113namespace {
114
115struct CallConvLoweringPass
116 : public impl::CallConvLoweringBase<CallConvLoweringPass> {
117 using CallConvLoweringBase::CallConvLoweringBase;
118
119 CallConvLoweringPass(const CallConvLoweringOptions &options,
120 const llvm::abi::X86ABICompatInfo &x86AbiCompat)
121 : CallConvLoweringBase(options), x86AbiCompat(x86AbiCompat) {}
122
123 void runOnOperation() override;
124
125 /// The x86_64 flags whose value depends on the target and the requested ABI
126 /// compatibility version. Carried outside the pass options because the
127 /// struct has no command-line parser, so a cir-opt run gets the library
128 /// defaults rather than a target's values.
129 llvm::abi::X86ABICompatInfo x86AbiCompat;
130};
131
132} // namespace
133
134/// Build the classifier the pass options select. Exactly one of \p target
135/// and \p classificationAttrName is set, which runOnOperation checks before
136/// calling.
137static std::unique_ptr<CIRABIClassifier>
139 StringRef classificationAttrName, const DataLayout &dl,
140 ModuleOp modOp, const ABIClassifierOptions &options) {
141 if (!classificationAttrName.empty())
142 return createInjectedABIClassifier(dl, classificationAttrName);
143
144 switch (target) {
148 return createX86_64ABIClassifier(dl, modOp, options);
150 return createAMDGPUABIClassifier(dl, modOp);
152 break;
153 }
154 llvm_unreachable("an unset driver mode is rejected before this point");
155}
156
157namespace {
158
159/// Find the cir.func declaration matching a direct cir.call / cir.try_call
160/// callee, if any. Returns nullptr if the callee is indirect or the symbol
161/// cannot be resolved. Takes a SymbolTable instead of a ModuleOp so the
162/// symbol lookup is amortized across all the call sites the driver walks
163/// (ModuleOp::lookupSymbol is linear per call).
164cir::FuncOp lookupCallee(Operation *callOp, SymbolTable &symbolTable) {
165 FlatSymbolRefAttr callee;
166 if (auto call = dyn_cast<cir::CallOp>(callOp))
167 callee = call.getCalleeAttr();
168 else if (auto tryCall = dyn_cast<cir::TryCallOp>(callOp))
169 callee = tryCall.getCalleeAttr();
170 else
171 return nullptr;
172 if (!callee)
173 return nullptr;
174 return symbolTable.lookup<cir::FuncOp>(callee.getValue());
175}
176
177void CallConvLoweringPass::runOnOperation() {
178 ModuleOp moduleOp = getOperation();
179 MLIRContext *ctx = &getContext();
180
181 bool haveTarget = target != cir::CallConvTarget::None;
182 bool haveAttr = !classificationAttr.empty();
183 if (haveTarget == haveAttr) {
184 moduleOp.emitOpError() << "CallConvLowering requires exactly one of "
185 "'target' or 'classification-attr' pass options";
186 signalPassFailure();
187 return;
188 }
189
190 if (!moduleOp->hasAttr(DLTIDialect::kDataLayoutAttrName)) {
191 moduleOp.emitOpError()
192 << "CallConvLowering requires a DataLayout (dlti.dl_spec attribute "
193 "on the module)";
194 signalPassFailure();
195 return;
196 }
197
198 // A module without #cir.lowering_options gets the CodeGenOptions
199 // default, which marks arguments noundef.
200 auto loweringOpts = moduleOp->getAttrOfType<cir::LoweringOptionsAttr>(
201 cir::CIRDialect::getLoweringOptionsAttrName());
202 bool enableNoundefAttrs =
203 !loweringOpts || loweringOpts.getEnableNoundefAttrs();
204
205 DataLayout dl(moduleOp);
206 CIRABIRewriteContext rewriteCtx(moduleOp, dl, enableNoundefAttrs);
207 // A non-byval indirect parameter's slot outlives the rewrite that retypes
208 // the parameter, so that a call forwarding the parameter can still recognize
209 // it. Draining on scope exit collapses those slots whichever way this
210 // function returns.
211 llvm::scope_exit drainParamSlots(
212 [&] { rewriteCtx.finalizeParameterSlots(); });
213 SymbolTable symbolTable(moduleOp);
214
215 cir::ABIClassifierOptions classifierOptions;
216 classifierOptions.x86AvxAbiLevel = x86AvxAbiLevel;
218 classifierOptions.x86AbiCompat = x86AbiCompat;
219 std::unique_ptr<cir::CIRABIClassifier> classifier = createABIClassifier(
220 target, classificationAttr, dl, moduleOp, classifierOptions);
221
222 // Classify every cir.func up front. No IR mutation happens here, so
223 // later walks can consult any function's classification regardless of
224 // visitation order.
225 llvm::MapVector<cir::FuncOp, FunctionClassification> classifications;
226 bool anyFailed = false;
227 moduleOp.walk([&](cir::FuncOp f) {
228 // A lowered signature uses ordinary CIR types and cannot be told apart
229 // from one that still needs lowering, so only a function that says it
230 // needs lowering is lowered.
231 if (!f.getRequiresCallConvLowering())
232 return;
233 // A complete type is required at any call or definition, so only a
234 // declaration can carry an incomplete-by-value parameter or return type,
235 // and no translation unit can ever call or define it with real argument
236 // data. Leave it unclassified.
237 cir::FuncType fnTy = f.getFunctionType();
238 if (f.isDeclaration() &&
239 (hasIncompleteRecordByValue(fnTy.getReturnType()) ||
240 llvm::any_of(fnTy.getInputs(), hasIncompleteRecordByValue)))
241 return;
242 std::optional<FunctionClassification> fc = classifier->classifyFunction(f);
243 if (!fc) {
244 anyFailed = true;
245 return;
246 }
247 classifications.insert({f, std::move(*fc)});
248 });
249 if (anyFailed) {
250 signalPassFailure();
251 return;
252 }
253
254 // Build a callee-to-callers index. One module walk collects every direct
255 // cir.call / cir.try_call to each cir.func; the loop below rewrites a
256 // function and all of its call sites together. Indirect or unresolved
257 // callees are skipped here; rewriteCallSite errors on those at the end.
258 //
259 // A call that passes arguments through an ellipsis gets its own
260 // classification, recorded here while every signature is still in its
261 // original form. The callee's classification covers only its declared
262 // parameters and cannot describe those extra arguments.
263 llvm::DenseMap<cir::FuncOp, SmallVector<Operation *>> callers;
264 // Keyed on the call op collected below, looked up once when that same op is
265 // rewritten. A key must never come from an op created during the rewrite:
266 // a recycled address could match an unrelated entry.
267 llvm::DenseMap<Operation *, FunctionClassification> variadicCallSites;
268 moduleOp.walk([&](Operation *op) {
269 auto call = dyn_cast<cir::CIRCallOpInterface>(op);
270 if (!call)
271 return;
272 cir::FuncOp callee = lookupCallee(op, symbolTable);
273 if (!callee || !callee.getRequiresCallConvLowering())
274 return;
275 callers[callee].push_back(op);
276
277 cir::FuncType calleeTy = callee.getFunctionType();
278 if (call.getNumArgOperands() <= calleeTy.getNumInputs())
279 return;
280 // A callee declared without a prototype also takes more operands than it
281 // declares, and the verifier allows it. Those extra arguments are named
282 // rather than passed through an ellipsis, so the accounting below does not
283 // describe them.
284 if (!calleeTy.isVarArg()) {
285 op->emitOpError() << "extra arguments to a callee without a prototype "
286 "not yet implemented in CallConvLowering";
287 anyFailed = true;
288 return;
289 }
290 std::optional<FunctionClassification> fc =
291 classifier->classifyVariadicCall(call, callee);
292 if (!fc) {
293 anyFailed = true;
294 return;
295 }
296 variadicCallSites.insert({op, std::move(*fc)});
297 });
298 if (anyFailed) {
299 signalPassFailure();
300 return;
301 }
302
303 // A cir.get_global holding a function's address carries the signature the
304 // source wrote, which the verifier ties to the callee, so it goes stale when
305 // that callee is rewritten. A function address in a global initializer is a
306 // GlobalViewAttr instead, whose recorded type the verifier does not tie to
307 // the callee and which is dropped at opaque-pointer lowering, so it needs no
308 // counterpart.
309 llvm::DenseMap<cir::FuncOp, SmallVector<cir::GetGlobalOp>> addressTakers;
310 moduleOp.walk([&](cir::GetGlobalOp getGlobal) {
311 auto ptrTy = cast<cir::PointerType>(getGlobal.getAddr().getType());
312 if (!isa<cir::FuncType>(ptrTy.getPointee()))
313 return;
314 // A get_global's pointee must equal the named symbol's type, and the
315 // GlobalOp verifier rejects a function type there, so this names a
316 // cir.func.
317 auto callee = cast<cir::FuncOp>(symbolTable.lookup(getGlobal.getName()));
318 addressTakers[callee].push_back(getGlobal);
319 });
320
321 // Restate every non-byval indirect parameter's slot alignment and route any
322 // use of such a parameter as a call argument through a load of that slot,
323 // before any definition or call site is rewritten. Doing this up front
324 // makes the forwarding decision independent of the order the callee and its
325 // caller were declared in.
326 for (auto &kv : classifications) {
327 if (failed(rewriteCtx.prepareNonByvalParameters(kv.first, kv.second))) {
328 signalPassFailure();
329 return;
330 }
331 }
332
333 // An sret slot or an indirect argument is a pointer the source never
334 // wrote, and an ellipsis can carry one the declared parameters do not
335 // describe. The callee reads and writes that memory whatever const or
336 // pure recorded about it, so the recorded effects have to widen.
337 for (auto &kv : classifications) {
338 cir::FuncOp func = kv.first;
339 if (hasIndirectSlot(kv.second) || func.getFunctionType().isVarArg())
340 widenForArgMemory(func);
341 }
342
343 // Rewrite each function together with every direct call to it and every op
344 // holding its address. By the time we move on to function F+1, F's
345 // signature and every reference to F have already been brought into
346 // alignment, and F+1..FN are still in their original (mutually consistent)
347 // form, so the IR is verifier-clean at every outer-iteration boundary.
348 //
349 // There is still a brief inner window where F's signature has been
350 // rewritten but its references have not yet caught up -- we have no way to
351 // mutate both sides of a call atomically. No verifier runs inside the
352 // pass, and at pass exit the module is verifier-clean. Fusing the inner
353 // loops here keeps the invalid window per-function rather than module-wide.
354 OpBuilder builder(ctx);
355 for (auto &kv : classifications) {
356 cir::FuncOp func = kv.first;
357 const FunctionClassification &fc = kv.second;
358 if (failed(rewriteCtx.rewriteFunctionDefinition(func, fc, builder))) {
359 signalPassFailure();
360 return;
361 }
362 for (Operation *callOp : callers.lookup(func)) {
363 const FunctionClassification *callFc = &fc;
364 if (auto it = variadicCallSites.find(callOp);
365 it != variadicCallSites.end()) {
366 callFc = &it->second;
367 assert(classifiesSamePrefix(fc, *callFc) &&
368 "a call site's declared parameters must be classified the same "
369 "way as the callee's");
370 }
371 if (hasIndirectSlot(*callFc))
372 widenForArgMemory(cast<cir::CIRCallOpInterface>(callOp));
373 if (failed(rewriteCtx.rewriteCallSite(callOp, *callFc, builder))) {
374 signalPassFailure();
375 return;
376 }
377 }
378 for (cir::GetGlobalOp addrOp : addressTakers.lookup(func))
379 rewriteCtx.rewriteFunctionAddress(addrOp, func, builder);
380 }
381
382 // Rewrite indirect call sites. The callee is opaque, so classify from the
383 // function pointer's pointee FuncType and let rewriteCallSite retype the
384 // callee pointer to match the coerced signature. Collect the calls first:
385 // when an sret rewrite reuses a single-use store's destination as the return
386 // slot it erases that store, which is the operation a live walk has already
387 // cached as the next one to visit.
388 SmallVector<cir::CIRCallOpInterface> indirectCalls;
389 // An indirect call has no callee to say whether it is lowered, but it is
390 // lowered together with the function it is in.
391 auto inFunctionToLower = [](Operation *op) {
392 auto func = op->getParentOfType<cir::FuncOp>();
393 return func && func.getRequiresCallConvLowering();
394 };
395 moduleOp.walk([&](cir::CIRCallOpInterface c) {
396 if (c.isIndirect() && inFunctionToLower(c))
397 indirectCalls.push_back(c);
398 });
399 for (cir::CIRCallOpInterface c : indirectCalls) {
400 std::optional<FunctionClassification> fc =
401 classifier->classifyIndirectCall(c);
402 if (!fc) {
403 signalPassFailure();
404 return;
405 }
406 if (hasIndirectSlot(*fc))
408 if (failed(rewriteCtx.rewriteCallSite(c.getOperation(), *fc, builder))) {
409 signalPassFailure();
410 return;
411 }
412 }
413
414 // Collect the fetches before rewriting any, because rewriting one erases
415 // it, and a live walk holds the op it is about to visit next.
416 SmallVector<cir::VAArgOp> vaArgs;
417 moduleOp.walk([&](cir::VAArgOp v) {
418 if (inFunctionToLower(v))
419 vaArgs.push_back(v);
420 });
421 for (cir::VAArgOp v : vaArgs) {
422 std::optional<ArgClassification> ac = classifier->classifyVAArg(v);
423 if (!ac) {
424 signalPassFailure();
425 return;
426 }
427 if (failed(rewriteCtx.rewriteVAArg(v.getOperation(), *ac, builder))) {
428 signalPassFailure();
429 return;
430 }
431 }
432
433 // Everything in and around these functions now uses the target ABI.
434 for (auto &kv : classifications)
435 kv.first.setRequiresCallConvLowering(false);
436}
437
438} // namespace
439
440std::unique_ptr<Pass> mlir::createCallConvLoweringPass() {
441 return std::make_unique<CallConvLoweringPass>();
442}
443
445 cir::CallConvTarget target, llvm::abi::X86AVXABILevel x86AvxAbiLevel,
447 const llvm::abi::X86ABICompatInfo &x86AbiCompat) {
448 CallConvLoweringOptions options;
449 options.target = target;
450 options.x86AvxAbiLevel = x86AvxAbiLevel;
451 options.allowsX86TargetAttrAvx = allowsX86TargetAttrAvx;
452 return std::make_unique<CallConvLoweringPass>(options, x86AbiCompat);
453}
static bool hasIndirectSlot(const FunctionClassification &fc)
Whether fc gives the callee access to memory through a pointer the ABI introduced: an sret slot for a...
static bool classifiesSamePrefix(const FunctionClassification &calleeFc, const FunctionClassification &callFc)
Whether callFc classifies a call's leading arguments and its return exactly as calleeFc classifies th...
static bool hasIncompleteRecordByValue(mlir::Type ty)
Whether ty, or an aggregate member/element reached by value (never through a pointer),...
static void widenForArgMemory(OpTy op)
Record on op that the memory its pointer arguments address may be read and written.
static std::unique_ptr< CIRABIClassifier > createABIClassifier(cir::CallConvTarget target, StringRef classificationAttrName, const DataLayout &dl, ModuleOp modOp, const ABIClassifierOptions &options)
Build the classifier the pass options select.
static bool allowsX86TargetAttrAvx(const llvm::Triple &triple, clang::LangOptions::ClangABI compat)
Whether __attribute__((target(...))) on a function may raise its AVX ABI level above the command line...
Definition CIRPasses.cpp:45
std::unique_ptr< CIRABIClassifier > createAMDGPUABIClassifier(const mlir::DataLayout &dl, mlir::ModuleOp modOp)
The AMDGPU classifier.
std::unique_ptr< CIRABIClassifier > createX86_64ABIClassifier(const mlir::DataLayout &dl, mlir::ModuleOp modOp, const ABIClassifierOptions &options)
The x86_64 System V classifier.
std::unique_ptr< CIRABIClassifier > createInjectedABIClassifier(const mlir::DataLayout &dl, llvm::StringRef attrName)
A classifier that reads each function's classification from the DictionaryAttr named attrName.
std::unique_ptr< CIRABIClassifier > createTestTargetABIClassifier(const mlir::DataLayout &dl)
The MLIR test ABI target's classifier, whose predictable rules approximate x86_64 SysV.
CallConvTarget
The ABI target whose calling-convention rules drive CallConvLowering.
Definition Passes.h:23
std::unique_ptr< Pass > createCallConvLoweringPass()
The target-specific settings a classifier needs beyond what it can read from the module.
bool allowsX86TargetAttrAvx
Whether a function's own recorded target features may raise its x86_64 AVX level above x86AvxAbiLevel...
llvm::abi::X86ABICompatInfo x86AbiCompat
The x86_64 flags whose value depends on the target and the requested ABI compatibility version.
llvm::abi::X86AVXABILevel x86AvxAbiLevel
The AVX level the x86_64 classifier sizes a native vector at.