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