clang 24.0.0git
CIRABIRewriteContext.cpp
Go to the documentation of this file.
1//===- CIRABIRewriteContext.cpp - CIR ABI rewrite context ----------------===//
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
10#include "mlir/Dialect/LLVMIR/LLVMDialectDecl.h"
11#include "mlir/IR/Builders.h"
12#include "mlir/IR/Dominance.h"
19#include "llvm/ADT/STLExtras.h"
20#include "llvm/IR/Attributes.h"
21#include "llvm/Support/MathExtras.h"
22#include <algorithm>
23#include <array>
24#include <utility>
25
26using namespace cir;
27using namespace mlir;
28using namespace mlir::abi;
29
30// This rewrite context supports the Direct (with or without coercion),
31// Extend, Ignore, Indirect-return (sret), Indirect-argument (byval and
32// non-byval), IndirectAliased-argument (byref), and Expand (struct
33// flattening) classifications.
34//
35// An Indirect argument is byval or not, following its classification's
36// byVal flag. byval is a by-value parameter the ABI passes in memory rather
37// than registers, usually for its size. Non-byval is a by-value parameter
38// whose type cannot be copied freely, because it has a non-trivial copy
39// constructor, move constructor, or destructor, so the callee works on the
40// caller's own object rather than a copy.
41//
42// At the call site both forward the caller's storage, since byval is copied
43// on the caller's side of the call. byval falls back to a slot of its own
44// when the operand's storage cannot be handed on. At the callee, byval fills
45// the CIRGen param slot with a copy of the incoming object, while non-byval
46// rewires that slot to the incoming pointer so the body mutates the caller's
47// storage in place.
48//
49// A byref argument is lowered like byval, apart from its attribute and the
50// address space of its pointer. The callee must not write through that
51// pointer, so it fills the CIRGen param slot with a copy just as byval does.
52//
53// For Expand, the single struct argument is replaced by N scalar arguments
54// (one per field). At the callee, the N field block arguments are stored
55// directly into the parameter's own alloca (the CIRGen spill slot). At the
56// call site, the struct operand is decomposed into its fields by reading
57// each member from the source alloca (get_member + load) when the operand is
58// a load of an alloca, or via cir.extract_member otherwise.
59//
60// For Direct + canFlatten (where the coerced type is a multi-field struct), the
61// coerced struct is similarly passed as N separate arguments, one per field.
62// The callee stores the N scalar block args into one slot sized and aligned for
63// both the coerced struct and the original argument type, which the body reads.
64// The call site reads each field of the coerced struct out of memory holding
65// the operand as a separate call argument.
66
67namespace {
68
69/// A pointer to \p pointee in target address space \p addrSpace. Zero is the
70/// default address space, which carries no attribute.
71cir::PointerType getPtrTyInAddrSpace(mlir::Type pointee, unsigned addrSpace) {
72 mlir::ptr::MemorySpaceAttrInterface asAttr;
73 if (addrSpace)
74 asAttr = cir::TargetAddressSpaceAttr::get(pointee.getContext(), addrSpace);
75 return cir::PointerType::get(pointee, asAttr);
76}
77
78/// The pointer passed in place of an Indirect or byref value, or an sret
79/// return, of type \p pointee.
80cir::PointerType getIndirectPtrTy(mlir::Type pointee,
81 const ArgClassification &ac) {
82 assert(
83 (ac.kind == ArgKind::Indirect || ac.kind == ArgKind::IndirectAliased) &&
84 "expected an indirect classification");
85 return getPtrTyInAddrSpace(pointee, ac.indirectAddrSpace);
86}
87
88/// The struct a union is flattened as: its storage member, then its tail
89/// padding if it has any. This matches the union's LLVM type.
90cir::StructType getUnionFlattenType(cir::UnionType unionTy,
91 const mlir::DataLayout &dl) {
93 if (mlir::Type storage = unionTy.getUnionStorageType(dl))
94 fields.push_back(storage);
95 if (mlir::Type padding = unionTy.getPadding())
96 fields.push_back(padding);
97 return cir::StructType::get(unionTy.getContext(), fields, unionTy.getPacked(),
98 /*is_class=*/false,
100}
101
102/// Return the coerced RecordType for a Direct classification that should be
103/// flattened into individual scalar arguments, or a null type if the
104/// classification does not call for flattening.
105///
106/// Flattening applies when all four conditions hold:
107/// 1. The classification is Direct with a non-null coercedType.
108/// 2. canFlatten is set.
109/// 3. The coercedType is a struct, or a union, which is flattened as the
110/// struct getUnionFlattenType returns.
111/// 4. The struct has at least one field. A struct of one field is passed as
112/// that field.
113cir::RecordType getFlattenedCoercedType(const ArgClassification &ac,
114 const mlir::DataLayout &dl) {
115 if (ac.kind != ArgKind::Direct || !ac.coercedType || !ac.canFlatten)
116 return {};
117 auto recTy = dyn_cast<cir::RecordType>(ac.coercedType);
118 if (auto unionTy = dyn_cast_if_present<cir::UnionType>(recTy))
119 recTy = getUnionFlattenType(unionTy, dl);
120 if (!recTy || !recTy.isStruct() || recTy.getMembers().empty())
121 return {};
122 return recTy;
123}
124
125/// Whether \p ac is an Extend of a record argument of type \p origTy. Such an
126/// argument is a transparent union, passed as its first member, which
127/// \p ac.coercedType holds.
128bool isRecordExtend(const ArgClassification &ac, mlir::Type origTy) {
129 if (ac.kind != ArgKind::Extend || !mlir::isa<cir::RecordType>(origTy))
130 return false;
131 assert(ac.coercedType && "an Extend of a record names its first member type");
132 return true;
133}
134
135/// Build the new argument-type list for a function whose ABI classification
136/// is \p fc. Handles Direct (with or without coercion), Extend, Ignore,
137/// Indirect (byval and non-byval), IndirectAliased (byref), and Expand
138/// (struct flattening) arguments.
139/// The sret return pointer, when present, is prepended by
140/// rewriteFunctionDefinition rather than here.
141mlir::LogicalResult buildNewArgTypes(
142 ArrayRef<mlir::Type> oldArgTypes, const FunctionClassification &fc,
143 SmallVectorImpl<mlir::Type> &newArgTypes, const mlir::DataLayout &dl,
144 function_ref<mlir::InFlightDiagnostic()> emitError) {
145 assert(newArgTypes.empty() && "expected an empty output vector");
146 newArgTypes.reserve(oldArgTypes.size());
147 for (auto [idx, ac] : llvm::enumerate(fc.argInfos)) {
148 mlir::Type origTy = oldArgTypes[idx];
149 switch (ac.kind) {
150 case ArgKind::Direct:
151 // Direct with canFlatten and a struct coerced type: push one wire type
152 // per field of the coerced struct rather than the struct itself.
153 if (cir::RecordType flatTy = getFlattenedCoercedType(ac, dl)) {
154 llvm::append_range(newArgTypes, flatTy.getMembers());
155 } else {
156 // Direct with a coerced type: the lowered signature uses the coerced
157 // type; the body still expects origTy and insertArgCoercion recovers it
158 // from a coercion slot. Direct without coercion is a pass-through.
159 newArgTypes.push_back(ac.coercedType ? ac.coercedType : origTy);
160 }
161 break;
162 case ArgKind::Ignore:
163 break;
164 case ArgKind::Expand: {
165 // Flatten the struct into one wire argument per field. The
166 // reassembly in the callee body and the decomposition at the call
167 // site are handled by insertArgCoercion and rewriteCallSite.
168 auto recTy = cast<cir::RecordType>(origTy);
169 assert(recTy.isStruct() &&
170 "Expand classification requires a struct type, not a union");
171 assert(!recTy.getMembers().empty() &&
172 "Expand classification requires at least one struct field");
173 llvm::append_range(newArgTypes, recTy.getMembers());
174 break;
175 }
176 case ArgKind::Extend:
177 // Extend keeps the original (narrow) type in the signature; the
178 // sign/zero extension is communicated to LLVM via the llvm.signext /
179 // llvm.zeroext arg attribute, attached separately below. For an integer
180 // the coercedType the classifier set is informational (typically the
181 // register-width type the value gets extended to in registers) and does
182 // not change the CIR signature. A transparent union is passed as the
183 // type of its first member, which coercedType holds.
184 newArgTypes.push_back(isRecordExtend(ac, origTy) ? ac.coercedType
185 : origTy);
186 break;
187 case ArgKind::Indirect:
188 case ArgKind::IndirectAliased:
189 newArgTypes.push_back(getIndirectPtrTy(origTy, ac));
190 break;
191 }
192 }
193 return mlir::success();
194}
195
196/// Compute the new return type for a function whose return classification
197/// is \p retInfo. Direct returns keep (or coerce to) their type, Ignore and
198/// Indirect (sret) returns become void, Extend keeps its type; Expand and
199/// IndirectAliased emit an error.
200mlir::Type
201computeNewReturnType(mlir::Type origRetTy, const ArgClassification &retInfo,
202 mlir::MLIRContext *ctx,
203 function_ref<mlir::InFlightDiagnostic()> emitError) {
204 switch (retInfo.kind) {
205 case ArgKind::Direct:
206 // Direct return with a coerced type uses the coerced type on the wire;
207 // the rewriter inserts a coercion before each cir.return.
208 return retInfo.coercedType ? retInfo.coercedType : origRetTy;
209 case ArgKind::Ignore:
210 return cir::VoidType::get(ctx);
211 case ArgKind::Expand:
212 emitError() << "Expand return is not allowed (classic codegen rejects "
213 << "it in EmitFunctionEpilog)";
214 return nullptr;
215 case ArgKind::IndirectAliased:
216 emitError() << "IndirectAliased return is not supported";
217 return nullptr;
218 case ArgKind::Extend:
219 // Same convention as Extend args: keep the original return type in the
220 // signature; the sign/zero extension is communicated via the
221 // llvm.signext / llvm.zeroext res attribute attached separately below.
222 return origRetTy;
223 case ArgKind::Indirect:
224 // sret: the value is returned through a pointer argument that the ABI
225 // synthesizes (rewriteFunctionDefinition prepends it to the argument
226 // list); it is not part of the source-level signature, so the wire
227 // return type becomes void.
228 return cir::VoidType::get(ctx);
229 }
230 llvm_unreachable("all ArgKind cases handled");
231}
232
233/// Create a typed poison constant to stand in for a value the body of a
234/// function (or the result of a call) still references but whose ABI
235/// classification is Ignore. Using poison is honest -- the value is
236/// genuinely unused at the ABI boundary -- and avoids a fake alloca+load
237/// pattern that would suggest we have a value when we don't.
238mlir::Value createIgnoredValue(mlir::OpBuilder &builder, mlir::Location loc,
239 mlir::Type ty) {
240 return cir::ConstantOp::create(builder, loc, ty, cir::PoisonAttr::get(ty));
241}
242
243/// Whether \p coercedTy is wider than the type a value of type \p origTy has
244/// in memory, so the coerced value passes bits the value does not define and
245/// cannot be noundef. This is the comparison classic CodeGen makes. A bool
246/// vector's memory type is its storage integer, one bit per element and at
247/// least a byte wide, not its power-of-two size.
248static bool isCoercionWiderThanMemory(mlir::Type origTy, mlir::Type coercedTy,
249 const mlir::DataLayout &dl) {
250 uint64_t memoryBits = dl.getTypeSizeInBits(origTy).getFixedValue();
251 if (auto vecTy = mlir::dyn_cast<cir::VectorType>(origTy);
252 vecTy && mlir::isa<cir::BoolType>(vecTy.getElementType()))
253 memoryBits = vecTy.getBoolStorageWidth();
254 return dl.getTypeSizeInBits(coercedTy).getFixedValue() > memoryBits;
255}
256
257/// Whether updateArgAttrs has anything to change: an arg that is Ignore (its
258/// slot is dropped), Extend (needs llvm.signext / llvm.zeroext), Indirect or
259/// IndirectAliased (needs the pointer attributes), Expand (changes the argument
260/// count), or a coerced Direct, which may be flattened or may lose
261/// llvm.noundef, or that has a stack-slot alignment, which needs
262/// llvm.alignstack.
263static bool needsArgAttrUpdate(const FunctionClassification &fc) {
264 return llvm::any_of(fc.argInfos, [](const ArgClassification &ac) {
265 return ac.kind == ArgKind::Ignore || ac.kind == ArgKind::Extend ||
266 ac.kind == ArgKind::Indirect ||
267 ac.kind == ArgKind::IndirectAliased || ac.kind == ArgKind::Expand ||
268 (ac.kind == ArgKind::Direct && (ac.coercedType || ac.directAlign));
269 });
270}
271
272/// Build an updated arg_attrs ArrayAttr that drops Ignore'd args, adds
273/// llvm.signext / llvm.zeroext on Extend args, adds the pointer attributes
274/// for Indirect and IndirectAliased args in place of llvm.nofpclass, drops
275/// llvm.noundef from a coerced Direct arg that passes undefined bits,
276/// adds llvm.alignstack on a Direct arg with a stack-slot alignment, gives each
277/// field of a Direct+canFlatten argument the argument's attributes, and gives
278/// each field of an Expand argument an empty dict. When \p enableNoundefAttrs
279/// is set, Extend, Indirect and IndirectAliased args are also marked
280/// llvm.noundef. Direct and Extend slots keep their other existing attributes.
281/// \p origArgTypes provides the pre-rewrite type for each arg slot.
282mlir::ArrayAttr updateArgAttrs(mlir::MLIRContext *ctx, mlir::ModuleOp module,
283 ArrayRef<mlir::Type> origArgTypes,
284 mlir::ArrayAttr existingArgAttrs,
285 const FunctionClassification &fc,
286 const mlir::DataLayout &dl,
287 bool enableNoundefAttrs, bool isCallSite) {
288 mlir::Builder builder(ctx);
290 newArgAttrs.reserve(fc.argInfos.size());
291 for (auto [oldIdx, ac] : llvm::enumerate(fc.argInfos)) {
292 if (ac.kind == ArgKind::Ignore)
293 continue;
294 mlir::DictionaryAttr existing = builder.getDictionaryAttr({});
295 if (existingArgAttrs && oldIdx < existingArgAttrs.size())
296 existing = mlir::cast<mlir::DictionaryAttr>(existingArgAttrs[oldIdx]);
297 if (ac.kind == ArgKind::Direct && ac.coercedType &&
298 isCoercionWiderThanMemory(origArgTypes[oldIdx], ac.coercedType, dl)) {
299 mlir::NamedAttrList attrs(existing);
300 attrs.erase(mlir::LLVM::LLVMDialect::getNoUndefAttrName());
301 existing = attrs.getDictionary(ctx);
302 }
303 if (ac.kind == ArgKind::Direct && ac.directAlign) {
304 mlir::NamedAttrList attrs(existing);
305 attrs.set(mlir::LLVM::LLVMDialect::getStackAlignmentAttrName(),
306 builder.getI64IntegerAttr(ac.directAlign->value()));
307 existing = attrs.getDictionary(ctx);
308 }
309 if (cir::RecordType flatTy = getFlattenedCoercedType(ac, dl)) {
310 // Direct + canFlatten: as in classic CodeGen, each flattened field
311 // carries the attributes of the argument it came from.
312 newArgAttrs.append(flatTy.getNumElements(), existing);
313 } else if (ac.kind == ArgKind::Expand) {
314 // An expanded record has no attributes classic CodeGen would copy to its
315 // fields, so each field gets an empty dict.
316 auto recTy = cast<cir::RecordType>(origArgTypes[oldIdx]);
317 newArgAttrs.append(recTy.getNumElements(), builder.getDictionaryAttr({}));
318 } else if (ac.kind == ArgKind::Extend) {
319 // An extended value has no undefined bits. This covers a transparent
320 // union passed as its extended first member, which CIRGen does not
321 // mark noundef because it is a record.
322 StringRef attrName = ac.signExtend
323 ? mlir::LLVM::LLVMDialect::getSExtAttrName()
324 : mlir::LLVM::LLVMDialect::getZExtAttrName();
325 mlir::NamedAttrList attrs(existing);
326 // Conservative argument extends apply only at the call-site.
327 if (isCallSite || !ac.conservative)
328 attrs.set(attrName, builder.getUnitAttr());
329 if (enableNoundefAttrs)
330 attrs.set(mlir::LLVM::LLVMDialect::getNoUndefAttrName(),
331 builder.getUnitAttr());
332 newArgAttrs.push_back(attrs.getDictionary(ctx));
333 } else if (ac.kind == ArgKind::Indirect) {
334 // Indirect lowering hands the callee a pointer. llvm.align and
335 // llvm.noundef describe that pointer, not the bytes it points to, and
336 // llvm.nofpclass, which describes the value, does not apply to a
337 // pointer. Without byval the pointer points to the caller's own object.
338 // With byval the backend copies the pointee on the caller's side of the
339 // call, so the callee gets an object of its own even when the pointer
340 // points to the caller's own object.
341 mlir::Type pointeeTy = origArgTypes[oldIdx];
342 mlir::NamedAttrList attrs(existing);
343 attrs.erase(mlir::LLVM::LLVMDialect::getNoFPClassAttrName());
344 attrs.set(mlir::LLVM::LLVMDialect::getAlignAttrName(),
345 builder.getI64IntegerAttr(ac.indirectAlign.value()));
346 if (enableNoundefAttrs)
347 attrs.set(mlir::LLVM::LLVMDialect::getNoUndefAttrName(),
348 builder.getUnitAttr());
349 if (ac.byVal) {
350 // llvm.byval(T) records the pre-rewrite arg type because the opaque
351 // LLVM pointer cannot carry it. Classic adds llvm.noalias under
352 // -fpass-by-value-is-noalias, which CIR does not plumb through.
354 attrs.set(mlir::LLVM::LLVMDialect::getByValAttrName(),
355 mlir::TypeAttr::get(pointeeTy));
356 } else {
357 // llvm.nofreeobj says the object cannot be freed while the callee
358 // runs, which holds because the caller owns it across the call.
359 attrs.set(mlir::LLVM::LLVMDialect::getNoFreeObjAttrName(),
360 builder.getUnitAttr());
361 // llvm.dead_on_return says the object's lifetime ends in the callee,
362 // which holds unless the caller still has a destructor to run on it.
363 // A record with no layout entry has no destructor.
364 auto recTy = mlir::dyn_cast<cir::RecordType>(pointeeTy);
365 cir::RecordLayoutAttr layout =
366 recTy ? cir::tryGetRecordLayout(module, recTy.getName())
367 : cir::RecordLayoutAttr();
368 if (!layout || layout.getHasTrivialDtor())
369 attrs.set(mlir::LLVM::LLVMDialect::getDeadOnReturnAttrName(),
370 builder.getI64IntegerAttr(static_cast<int64_t>(
371 llvm::DeadOnReturnInfo().toIntValue())));
372 attrs.set(mlir::LLVM::LLVMDialect::getDereferenceableAttrName(),
373 builder.getI64IntegerAttr(
374 dl.getTypeAllocSize(pointeeTy).getFixedValue()));
375 }
376 newArgAttrs.push_back(attrs.getDictionary(ctx));
377 } else if (ac.kind == ArgKind::IndirectAliased) {
378 // llvm.byref(T) records the pre-rewrite arg type, as llvm.byval does.
379 // llvm.nofpclass describes the value and does not apply to a pointer.
380 mlir::NamedAttrList attrs(existing);
381 attrs.erase(mlir::LLVM::LLVMDialect::getNoFPClassAttrName());
382 attrs.set(mlir::LLVM::LLVMDialect::getAlignAttrName(),
383 builder.getI64IntegerAttr(ac.indirectAlign.value()));
384 if (enableNoundefAttrs)
385 attrs.set(mlir::LLVM::LLVMDialect::getNoUndefAttrName(),
386 builder.getUnitAttr());
387 attrs.set(mlir::LLVM::LLVMDialect::getByRefAttrName(),
388 mlir::TypeAttr::get(origArgTypes[oldIdx]));
389 newArgAttrs.push_back(attrs.getDictionary(ctx));
390 } else {
391 newArgAttrs.push_back(existing);
392 }
393 }
394 return builder.getArrayAttr(newArgAttrs);
395}
396
397/// Build an updated res_attrs ArrayAttr (single entry, since CIR funcs have
398/// at most one result) that adds llvm.signext / llvm.zeroext on an Extend
399/// return and drops llvm.noundef from a coerced return that passes undefined
400/// bits. Preserves any other existing res attributes. Returns
401/// \p existingResAttrs unchanged, which may be null, when there is nothing to
402/// add or drop.
403mlir::ArrayAttr updateResAttrs(mlir::MLIRContext *ctx,
404 mlir::ArrayAttr existingResAttrs,
405 const ArgClassification &retInfo,
406 mlir::Type origRetTy,
407 const mlir::DataLayout &dl) {
408 bool needsNoUndefDrop =
409 retInfo.kind == ArgKind::Direct && retInfo.coercedType &&
410 isCoercionWiderThanMemory(origRetTy, retInfo.coercedType, dl);
411 if (retInfo.kind != ArgKind::Extend && !needsNoUndefDrop)
412 return existingResAttrs;
413
414 mlir::NamedAttrList attrs;
415 if (existingResAttrs && !existingResAttrs.empty())
416 attrs.append(
417 mlir::cast<mlir::DictionaryAttr>(existingResAttrs[0]).getValue());
418 if (retInfo.kind == ArgKind::Extend)
419 attrs.set(retInfo.signExtend ? "llvm.signext" : "llvm.zeroext",
420 mlir::UnitAttr::get(ctx));
421 if (needsNoUndefDrop)
422 attrs.erase(mlir::LLVM::LLVMDialect::getNoUndefAttrName());
423 return mlir::ArrayAttr::get(ctx, {attrs.getDictionary(ctx)});
424}
425
426/// The number of bytes a coercion memory slot needs to hold a value of type
427/// \p ty without truncating it. For most types this is the ordinary storage
428/// size. For a _BitInt it is deliberately the value's own literal byte
429/// footprint (ceil(width/8)) rather than the wider, ABI-alignment-padded
430/// footprint a _BitInt gets as a record member (see
431/// cir::IntType::getStorageTypeWidth): this coercion is about how many bytes
432/// the *value* needs to round-trip, not how a record would lay it out, and
433/// those are genuinely different questions for a _BitInt (e.g. _BitInt(33)
434/// only needs 5 bytes here, even though it occupies 8 padded bytes as a
435/// record member).
436static uint64_t coercionByteSize(mlir::Type ty, const mlir::DataLayout &dl) {
437 if (auto intTy = mlir::dyn_cast<cir::IntType>(ty))
438 return llvm::divideCeil(intTy.getWidth(), 8);
439 return dl.getTypeSize(ty);
440}
441
442/// A \p wantTy-typed view of the storage \p base points at. When \p wantTy is
443/// \p base's own pointee type, \p base is returned unchanged and \p offset must
444/// be 0. Any other type is reached by a bitcast, preceded by a byte stride
445/// of \p offset bytes when \p offset is nonzero. The view keeps \p base's
446/// address space. Any operations created are added to \p createdOps.
447static mlir::Value
448emitViewAtOffset(mlir::OpBuilder &builder, mlir::Location loc,
449 mlir::Type wantTy, mlir::Value base,
450 SmallPtrSetImpl<mlir::Operation *> &createdOps,
451 unsigned offset) {
452 auto basePtrTy = mlir::cast<cir::PointerType>(base.getType());
453 if (wantTy == basePtrTy.getPointee()) {
454 assert(offset == 0 && "a view of the storage's own type has no offset");
455 return base;
456 }
457 mlir::ptr::MemorySpaceAttrInterface addrSpace = basePtrTy.getAddrSpace();
458 mlir::Value view = base;
459 if (offset != 0) {
460 auto u8Ty = cir::IntType::get(builder.getContext(), 8, /*isSigned=*/false);
461 auto u8PtrTy = cir::PointerType::get(u8Ty, addrSpace);
462 auto u8Base = cir::CastOp::create(builder, loc, u8PtrTy,
463 cir::CastKind::bitcast, base);
464 createdOps.insert(u8Base);
465 auto strideTy =
466 cir::IntType::get(builder.getContext(), 64, /*isSigned=*/true);
467 auto strideVal = cir::ConstantOp::create(
468 builder, loc, cir::IntAttr::get(strideTy, offset));
469 createdOps.insert(strideVal);
470 view = cir::PtrStrideOp::create(builder, loc, u8PtrTy, u8Base, strideVal);
471 createdOps.insert(view.getDefiningOp());
472 }
473 auto typedView = cir::CastOp::create(builder, loc,
474 cir::PointerType::get(wantTy, addrSpace),
475 cir::CastKind::bitcast, view);
476 createdOps.insert(typedView);
477 return typedView;
478}
479
480/// A pointer to \p pointee in the target's alloca address space, which every
481/// temporary this pass allocates has to live in.
482static cir::PointerType getAllocaPtrTy(mlir::Type pointee,
483 const mlir::DataLayout &dl) {
484 mlir::ptr::MemorySpaceAttrInterface addrSpace;
485 if (auto asAttr = mlir::dyn_cast_if_present<mlir::IntegerAttr>(
486 dl.getAllocaMemorySpace()))
487 addrSpace = cir::TargetAddressSpaceAttr::get(pointee.getContext(),
488 asAttr.getUInt());
489 return cir::PointerType::get(pointee, addrSpace);
490}
491
492/// A coercion slot for \p srcTy and \p dstTy, which must differ. It is typed
493/// as \p srcTy unless coercionByteSize says \p dstTy is larger, aligned for
494/// both, and placed at the start of \p slotBlock. \p offset, where the
495/// coerced side sits within the slot, is only checked by assertions. The
496/// alloca is added to \p createdOps.
497static cir::AllocaOp createCoercionSlot(
498 mlir::OpBuilder &builder, mlir::Location loc, mlir::Type srcTy,
499 mlir::Type dstTy, mlir::Block *slotBlock, const mlir::DataLayout &dl,
500 SmallPtrSetImpl<mlir::Operation *> &createdOps, unsigned offset) {
501 assert(srcTy != dstTy && "callers must pre-check that the types differ");
502
503 cir::CIRDataLayout cirDataLayout(
504 slotBlock->getParentOp()->getParentOfType<mlir::ModuleOp>());
505 uint64_t srcAlign = cirDataLayout.getTypeLanguageAlignment(srcTy);
506 uint64_t dstAlign = cirDataLayout.getTypeLanguageAlignment(dstTy);
507 uint64_t allocaAlign = std::max(srcAlign, dstAlign);
508 mlir::Type slotTy = coercionByteSize(srcTy, dl) >= coercionByteSize(dstTy, dl)
509 ? srcTy
510 : dstTy;
511
512 // Sizes are compared two ways on purpose: relative size in
513 // coercionByteSize terms, which is how slotTy was picked, and capacity in
514 // getTypeSize terms, which is what the alloca is given.
515 [[maybe_unused]] mlir::Type coercedTy = ((slotTy == srcTy) ? dstTy : srcTy);
516 assert((offset == 0 ||
517 coercionByteSize(coercedTy, dl) < coercionByteSize(slotTy, dl)) &&
518 "a direct offset must land on the coerced side, the smaller one");
519 assert((offset == 0 ||
520 offset + dl.getTypeSize(coercedTy) <= dl.getTypeSize(slotTy)) &&
521 "coerce slot too small for offset access");
522 assert((offset == 0 ||
523 offset % cirDataLayout.getTypeLanguageAlignment(coercedTy) == 0) &&
524 "a direct offset must be aligned for the coerced access");
525
526 mlir::OpBuilder::InsertionGuard guard(builder);
527 builder.setInsertionPointToStart(slotBlock);
528 auto alloca = cir::AllocaOp::create(builder, loc, getAllocaPtrTy(slotTy, dl),
529 builder.getStringAttr("coerce"),
530 builder.getI64IntegerAttr(allocaAlign));
531 createdOps.insert(alloca);
532 return alloca;
533}
534
535/// Coerce \p src into a temporary memory slot typed for \p dstTy at the
536/// current builder insertion point, and return the destination-typed pointer
537/// to that slot without loading the value back out. This is the shared
538/// memory half of emitCoercion: callers that want the whole coerced value use
539/// emitCoercion (below); callers that want to read individual members of a
540/// coerced struct (the call-site struct flattening) take the returned pointer
541/// and emit their own cir.get_member + cir.load per field. Lowers uniformly
542/// for scalar, vector, and record types.
543///
544/// The slot is sized to the larger of the two types so that neither the store
545/// nor a later load ever runs past it: the coerced ABI type can be larger
546/// than the original (e.g. a 12-byte aggregate passed as `{i64, i64}`), so
547/// accessing the destination through a source-sized slot would over-read.
548/// Alignment is max(srcAlign, dstAlign) to satisfy both accesses. The slot
549/// is written through a source-typed view and returned as a destination-typed
550/// view.
551///
552/// The temporary alloca is placed at the start of \p slotBlock, which must
553/// dominate every use of the coerced value and must be a block that ends up
554/// inside the enclosing function's entry block after any later outlining.
555///
556/// \p offset is where the coerced value sits within the larger of the two
557/// types, non-zero when the ABI passes a value in a register read from
558/// partway into its storage. The coerced type must be the smaller of the
559/// two, so one that can exceed the value it coerces, such as a multi-field
560/// register tuple, must not be given an offset.
561///
562/// Any operations the helper creates are appended to \p createdOps so the
563/// caller can leave them out when it later rewires the source value's uses,
564/// which would otherwise clobber the store's value operand.
565mlir::Value emitCoercionToMemory(mlir::OpBuilder &builder, mlir::Location loc,
566 mlir::Type dstTy, mlir::Value src,
567 mlir::Block *slotBlock,
568 const mlir::DataLayout &dl,
569 SmallPtrSetImpl<mlir::Operation *> &createdOps,
570 unsigned offset) {
571 mlir::Type srcTy = src.getType();
572 cir::AllocaOp alloca = createCoercionSlot(builder, loc, srcTy, dstTy,
573 slotBlock, dl, createdOps, offset);
574 mlir::Type slotTy = alloca.getAllocaType();
575
576 // Store through a source-typed view of the slot.
577 mlir::Value srcSlot = emitViewAtOffset(
578 builder, loc, srcTy, alloca, createdOps, srcTy == slotTy ? 0 : offset);
579 auto store = cir::StoreOp::create(builder, loc, src, srcSlot);
580 createdOps.insert(store);
581
582 // Return a destination-typed view of the slot.
583 return emitViewAtOffset(builder, loc, dstTy, alloca, createdOps,
584 dstTy == slotTy ? 0 : offset);
585}
586
587/// Cast \p src to \p dstTy when both are pointers to the same pointee, so only
588/// the address space changes. Returns null when a real coercion is needed.
589static mlir::Value
590emitAddrSpaceCoercion(mlir::OpBuilder &builder, mlir::Location loc,
591 mlir::Type dstTy, mlir::Value src,
592 SmallPtrSetImpl<mlir::Operation *> &createdOps,
593 unsigned offset) {
594 auto srcPtrTy = dyn_cast<cir::PointerType>(src.getType());
595 auto dstPtrTy = dyn_cast<cir::PointerType>(dstTy);
596 if (offset || !srcPtrTy || !dstPtrTy ||
597 srcPtrTy.getPointee() != dstPtrTy.getPointee())
598 return {};
599 assert(srcPtrTy.getAddrSpace() != dstPtrTy.getAddrSpace() &&
600 "pointers to the same pointee must differ in address space");
601 auto cast = cir::CastOp::create(builder, loc, dstTy,
602 cir::CastKind::address_space, src);
603 createdOps.insert(cast);
604 return cast;
605}
606
607/// Coerce \p src to type \p dstTy by going through memory and load the whole
608/// coerced value back out. Builds on emitCoercionToMemory, adding the final
609/// load of the destination-typed view. A pointer that only changes address
610/// space is cast instead.
611mlir::Value emitCoercion(mlir::OpBuilder &builder, mlir::Location loc,
612 mlir::Type dstTy, mlir::Value src,
613 mlir::Block *slotBlock, const mlir::DataLayout &dl,
614 SmallPtrSetImpl<mlir::Operation *> &createdOps,
615 unsigned offset) {
616 if (mlir::Value cast =
617 emitAddrSpaceCoercion(builder, loc, dstTy, src, createdOps, offset))
618 return cast;
619
620 mlir::Value dstSlot = emitCoercionToMemory(builder, loc, dstTy, src,
621 slotBlock, dl, createdOps, offset);
622 auto load = cir::LoadOp::create(builder, loc, dstSlot);
623 createdOps.insert(load);
624 return load;
625}
626
627/// Convenience overload for callers that don't need the createdOps set
628/// (e.g. call-site coercion where we don't replaceAllUsesExcept).
629mlir::Value emitCoercion(mlir::OpBuilder &builder, mlir::Location loc,
630 mlir::Type dstTy, mlir::Value src,
631 mlir::Block *slotBlock, const mlir::DataLayout &dl,
632 unsigned offset) {
633 SmallPtrSet<mlir::Operation *, 4> ignored;
634 return emitCoercion(builder, loc, dstTy, src, slotBlock, dl, ignored, offset);
635}
636
637/// The block a coercion slot's alloca belongs at the start of.
638///
639/// Normally the enclosing function's entry block, where HoistAllocas expects
640/// allocas to be. A body carrying a call is not always inside a function
641/// when this pass runs, though, because LoweringPrepare runs after it: a
642/// namespace-scope `T g = makeT();` is still in its cir.global ctor region,
643/// and an OpenACC recipe's init and destroy bodies are in regions the module
644/// owns. Those take the outermost region below the module, which dominates
645/// the whole body and travels with it when the body is outlined.
646mlir::Block *coercionSlotBlock(mlir::Operation *op) {
647 if (auto funcOp = op->getParentOfType<mlir::FunctionOpInterface>())
648 return &funcOp->getRegion(0).front();
649 mlir::Region *region = op->getParentRegion();
650 while (mlir::Region *outer = region->getParentRegion()) {
651 if (mlir::isa<mlir::ModuleOp>(outer->getParentOp()))
652 break;
653 region = outer;
654 }
655 assert(!region->empty() && "coercion slot needs a block to hold the alloca");
656 return &region->front();
657}
658
659/// \p val's defining load, if it is simple, meaning neither volatile nor
660/// atomic. Null otherwise: a non-simple load's access has to survive as
661/// written, and a call result or any other first-class value has no defining
662/// load at all.
663static cir::LoadOp maybeGetSimpleLoad(mlir::Value val) {
664 cir::LoadOp load = val.getDefiningOp<cir::LoadOp>();
665 if (!load || load.isVolatileOrAtomic())
666 return {};
667 return load;
668}
669
670/// \p val's defining load, if it loads a record and is not atomic. Null
671/// otherwise. The load may be volatile, and then its bytes may only be read
672/// through a volatile copy, never in place.
673static cir::LoadOp maybeGetCopyableRecordLoad(mlir::Value val) {
674 cir::LoadOp load = val.getDefiningOp<cir::LoadOp>();
675 if (!load || load.getMemOrder() ||
676 !mlir::isa<cir::RecordType>(load.getType()))
677 return {};
678 return load;
679}
680
681/// Emits an error and returns failure if \p val, an operand of \p user, is an
682/// atomic load of a record. The record's bytes are read through a copy or in
683/// place, neither of which keeps the load atomic.
684static mlir::LogicalResult rejectAtomicRecordLoad(mlir::Operation *user,
685 mlir::Value val) {
686 auto load = val.getDefiningOp<cir::LoadOp>();
687 if (!load || !load.getMemOrder() ||
688 !mlir::isa<cir::RecordType>(load.getType()))
689 return mlir::success();
690 return user->emitOpError()
691 << "atomic load of a record operand not yet implemented in "
692 "CallConvLowering";
693}
694
695/// Whether the storage the record load \p load reads is an alloca that holds
696/// \p coercedTy at \p offset. With no offset, the coerced type's alloc size
697/// has to fit in the record's. At an offset, the coerced value has to end
698/// within the record's alloc size.
699static bool canReadInPlace(cir::LoadOp load, mlir::Type coercedTy,
700 const cir::CIRDataLayout &dl, unsigned offset) {
701 if (!cir::getUnderlyingAlloca(load.getAddr()))
702 return false;
703 uint64_t readEnd =
704 offset == 0 ? dl.getTypeAllocSize(coercedTy).getFixedValue()
705 : offset + dl.getTypeStoreSize(coercedTy).getFixedValue();
706 return readEnd <= dl.getTypeAllocSize(load.getType()).getFixedValue();
707}
708
709/// Read \p coercedTy at \p offset straight out of the storage the record load
710/// \p load reads, which must be an alloca. The read goes just before \p load,
711/// so it reads the bytes \p load reads, and takes the alloca's alignment at
712/// \p offset.
713static mlir::Value emitInPlaceCoercedLoad(mlir::OpBuilder &builder,
714 mlir::Location loc, cir::LoadOp load,
715 mlir::Type coercedTy,
716 unsigned offset) {
717 cir::AllocaOp src = cir::getUnderlyingAlloca(load.getAddr());
718 assert(src && "the record load must read an alloca");
719 mlir::OpBuilder::InsertionGuard guard(builder);
720 builder.setInsertionPoint(load);
721 SmallPtrSet<mlir::Operation *, 4> ignored;
722 mlir::Value view = emitViewAtOffset(builder, loc, coercedTy, load.getAddr(),
723 ignored, offset);
724 auto coerced = cir::LoadOp::create(builder, loc, view);
725 coerced.setAlignment(llvm::MinAlign(src.getAlignment(), offset));
726 return coerced;
727}
728
729/// Copy the bytes of the record \p load reads into a new coercion slot for
730/// \p coercedTy at \p offset, placed at the start of \p slotBlock, and return
731/// the slot. The slot is at least as aligned as the storage copied from. The
732/// copy goes just before \p load, so it reads the bytes \p load reads, and is
733/// volatile if \p load is.
734static cir::AllocaOp
735emitCopiedCoercionSlot(mlir::OpBuilder &builder, mlir::Location loc,
736 cir::LoadOp load, mlir::Type coercedTy,
737 mlir::Block *slotBlock, const mlir::DataLayout &dl,
738 unsigned offset) {
739 auto recTy = cast<cir::RecordType>(load.getType());
740 uint64_t srcAlign;
741 if (cir::AllocaOp src = cir::getUnderlyingAlloca(load.getAddr()))
742 srcAlign = src.getAlignment();
743 else
744 srcAlign = load.getAlignment().value_or(
745 cir::CIRDataLayout(load->getParentOfType<mlir::ModuleOp>())
747 SmallPtrSet<mlir::Operation *, 4> ignored;
748 cir::AllocaOp slot = createCoercionSlot(builder, loc, recTy, coercedTy,
749 slotBlock, dl, ignored, offset);
750 slot.setAlignment(std::max(slot.getAlignment(), srcAlign));
751 assert((offset == 0 || slot.getAllocaType() == recTy) &&
752 "a direct offset must leave the record as the slot's type");
753 mlir::OpBuilder::InsertionGuard guard(builder);
754 builder.setInsertionPoint(load);
755 mlir::Value recView =
756 emitViewAtOffset(builder, loc, recTy, slot, ignored, /*offset=*/0);
757 auto copy =
758 cir::CopyOp::create(builder, loc, recView, load.getAddr(),
759 builder.getI64IntegerAttr(slot.getAlignment()),
760 builder.getI64IntegerAttr(srcAlign));
761 copy.setIsVolatile(load.getIsVolatile());
762 return slot;
763}
764
765/// Copy the bytes of the record \p load reads into a coercion slot, as
766/// emitCopiedCoercionSlot does, then read \p coercedTy out of the slot at
767/// \p offset. The read takes the slot's alignment at \p offset.
768static mlir::Value emitCopiedCoercedLoad(mlir::OpBuilder &builder,
769 mlir::Location loc, cir::LoadOp load,
770 mlir::Type coercedTy,
771 mlir::Block *slotBlock,
772 const mlir::DataLayout &dl,
773 unsigned offset) {
774 cir::AllocaOp slot = emitCopiedCoercionSlot(builder, loc, load, coercedTy,
775 slotBlock, dl, offset);
776 mlir::OpBuilder::InsertionGuard guard(builder);
777 builder.setInsertionPoint(load);
778 SmallPtrSet<mlir::Operation *, 4> ignored;
779 mlir::Value coercedView =
780 emitViewAtOffset(builder, loc, coercedTy, slot, ignored, offset);
781 auto coerced = cir::LoadOp::create(builder, loc, coercedView);
782 coerced.setAlignment(llvm::MinAlign(slot.getAlignment(), offset));
783 return coerced;
784}
785
786/// Read \p coercedTy at \p offset out of the bytes the record load \p load
787/// reads: straight out of its storage if \p load is not volatile and
788/// canReadInPlace accepts it, and otherwise out of a coercion slot at the start
789/// of \p slotBlock that those bytes are copied into. emitInPlaceCoercedLoad
790/// does not mark its read volatile, so a volatile load is read through the
791/// volatile copy instead. Either way no new load of the record type is
792/// emitted.
793static mlir::Value emitCoercedRecordLoad(
794 mlir::OpBuilder &builder, mlir::Location loc, cir::LoadOp load,
795 mlir::Type coercedTy, mlir::Block *slotBlock, const mlir::DataLayout &dl,
796 const cir::CIRDataLayout &cirDataLayout, unsigned offset) {
797 if (!load.getIsVolatile() &&
798 canReadInPlace(load, coercedTy, cirDataLayout, offset))
799 return emitInPlaceCoercedLoad(builder, loc, load, coercedTy, offset);
800 return emitCopiedCoercedLoad(builder, loc, load, coercedTy, slotBlock, dl,
801 offset);
802}
803
804/// Whether a cir.copy of \p ty into \p dst that stands in for a store of it
805/// skips tail padding. Unless \p dst is an alloca, which holds a complete
806/// object, it can be a potentially-overlapping subobject, such as a
807/// [[no_unique_address]] member or a base, whose tail padding holds another
808/// object. Classic CodeGen writes only the data size into a destination it is
809/// handed (EmitCall) and into one that may overlap (EmitAggregateCopy).
810/// Copying the whole object into an alloca is equivalent, since nothing else
811/// lives in its tail padding. A struct has tail padding when its last members
812/// are pad members, which CIRGen emits for padding another object may reuse and
813/// for some other structs, such as an over-aligned one.
814static bool shouldSkipTailPadding(mlir::Value dst, mlir::Type ty) {
815 auto structTy = mlir::dyn_cast<cir::StructType>(ty);
816 if (!structTy || cir::getUnderlyingAlloca(dst))
817 return false;
818 llvm::ArrayRef<mlir::Type> members = structTy.getMembers();
819 llvm::ArrayRef<cir::RecordMemberKind> kinds = structTy.getMemberKinds();
820 for (auto [member, kind] : llvm::reverse(llvm::zip_equal(members, kinds)))
821 if (cir::memberOwnsBytes(member))
822 return kind == cir::RecordMemberKind::Pad;
823 return false;
824}
825
826/// Rewire the uses of the record value \p val, whose bytes sit at \p addr,
827/// which is aligned to \p addrAlign, so that each one finds the record in
828/// memory. \p val may already have been retyped to the type it is passed as, a
829/// coerced type or a pointer, but its uses still expect the record.
830///
831/// A store of \p val becomes a cir.copy from \p addr at the store, volatile if
832/// the store is and skipping tail padding as shouldSkipTailPadding says. A
833/// store of the record value writes only what its lowered type stores, so
834/// another union member's data past those bytes would be lost. A consumer may
835/// be rewritten before \p val's defining op, and has then already stored \p val
836/// into a slot of its own. That store becomes a copy here too.
837///
838/// Every other use is pointed at one cir.load of \p addr created at the
839/// builder's insertion point. Only a call argument, a return and a read of a
840/// member that is not itself a record may use it, since those either read
841/// \p addr when they are rewritten or read a field. Uses by an operation in
842/// \p exceptions are left alone. Fails, after reporting it, on an atomic store
843/// of \p val or a use by anything else, before anything is rewired.
844static mlir::LogicalResult
845rewireRecordUses(mlir::OpBuilder &builder, mlir::Location loc, mlir::Value val,
846 mlir::Value addr, uint64_t addrAlign,
847 const mlir::DataLayout &dl,
848 const SmallPtrSetImpl<mlir::Operation *> &exceptions) {
849 mlir::Type recTy = mlir::cast<cir::PointerType>(addr.getType()).getPointee();
850 assert(mlir::isa<cir::RecordType>(recTy) && "only a record is rewired");
853 for (mlir::OpOperand &use : val.getUses()) {
854 mlir::Operation *user = use.getOwner();
855 if (exceptions.contains(user))
856 continue;
857 if (auto store = mlir::dyn_cast<cir::StoreOp>(user)) {
858 if (store.getMemOrder())
859 return store.emitOpError()
860 << "atomic store of a record argument or result not yet "
861 "implemented in CallConvLowering";
862 stores.push_back(store);
863 continue;
864 }
865 auto member = mlir::dyn_cast<cir::ExtractMemberOp>(user);
866 bool isFieldRead = member && !mlir::isa<cir::RecordType>(member.getType());
867 if (!isFieldRead &&
868 !mlir::isa<cir::CIRCallOpInterface, cir::ReturnOp>(user))
869 return user->emitOpError()
870 << "use of a record argument or result other than by a store, "
871 "call, return or member read not yet implemented in "
872 "CallConvLowering";
873 otherUses.push_back(&use);
874 }
875
876 mlir::IntegerAttr srcAlign = builder.getI64IntegerAttr(addrAlign);
877 cir::CIRDataLayout cirDataLayout(
878 val.getParentRegion()->getParentOfType<mlir::ModuleOp>());
879 for (cir::StoreOp store : stores) {
880 mlir::OpBuilder::InsertionGuard guard(builder);
881 builder.setInsertionPoint(store);
882 uint64_t dstAlign = store.getAlignment().value_or(
883 cirDataLayout.getTypeLanguageAlignment(recTy));
884 auto copy =
885 cir::CopyOp::create(builder, store.getLoc(), store.getAddr(), addr,
886 builder.getI64IntegerAttr(dstAlign), srcAlign);
887 copy.setIsVolatile(store.getIsVolatile());
888 copy.setSkipTailPadding(shouldSkipTailPadding(store.getAddr(), recTy));
889 store->erase();
890 }
891
892 if (otherUses.empty())
893 return mlir::success();
894 auto load = cir::LoadOp::create(builder, loc, addr);
895 load.setAlignment(addrAlign);
896 for (mlir::OpOperand *use : otherUses)
897 use->set(load);
898 return mlir::success();
899}
900
901/// Point the uses of \p val outside \p exceptions at the value of \p val's
902/// original type that \p view, a view of the start of a coercion slot, holds.
903/// For a record, rewireRecordUses points the uses at the slot. Any other type
904/// is loaded out of it at the builder's insertion point.
905static mlir::LogicalResult
906replaceUsesFromSlot(mlir::OpBuilder &builder, mlir::Location loc,
907 mlir::Value val, mlir::Value view,
908 const mlir::DataLayout &dl,
909 const SmallPtrSetImpl<mlir::Operation *> &exceptions) {
910 if (!mlir::isa<cir::RecordType>(
911 mlir::cast<cir::PointerType>(view.getType()).getPointee())) {
912 auto load = cir::LoadOp::create(builder, loc, view);
913 val.replaceAllUsesExcept(load, exceptions);
914 return mlir::success();
915 }
916 cir::AllocaOp slot = cir::getUnderlyingAlloca(view);
917 assert(slot && "the view must start at the coercion slot");
918 return rewireRecordUses(builder, loc, val, view, slot.getAlignment(), dl,
919 exceptions);
920}
921
922/// Coerce \p src, which is \p val retyped or the value replacing it, back to
923/// \p origTy through a coercion slot at the start of \p slotBlock, and point
924/// the uses of \p val outside \p createdOps at the result with
925/// replaceUsesFromSlot. A direct \p offset lands on the coerced side, so the
926/// view of \p origTy starts at the slot. A pointer that only changes address
927/// space is cast instead. The coercion's operations are added to
928/// \p createdOps.
929static mlir::LogicalResult
930emitCoercionAndReplaceUses(mlir::OpBuilder &builder, mlir::Location loc,
931 mlir::Type origTy, mlir::Value src, mlir::Value val,
932 mlir::Block *slotBlock, const mlir::DataLayout &dl,
933 SmallPtrSetImpl<mlir::Operation *> &createdOps,
934 unsigned offset) {
935 if (mlir::Value cast = emitAddrSpaceCoercion(builder, loc, origTy, src,
936 createdOps, offset)) {
937 val.replaceAllUsesExcept(cast, createdOps);
938 return mlir::success();
939 }
940 mlir::Value view = emitCoercionToMemory(builder, loc, origTy, src, slotBlock,
941 dl, createdOps, offset);
942 return replaceUsesFromSlot(builder, loc, val, view, dl, createdOps);
943}
944
945/// Coerce the value each cir.return returns to the new (coerced) return type.
946///
947/// When the returned value is a non-atomic load of a record, the coerced value
948/// is read by emitCoercedRecordLoad, and the record load is erased once nothing
949/// else uses it. Any other value is stored into a coercion slot and read back.
950/// A record with no storage behind it, such as a constant, defines no bytes
951/// beyond its fields, so the store writes every byte it defines. A call
952/// result's store is turned into a copy when its call is rewritten later.
953/// Fails, after reporting it, on an atomic load of a record.
954mlir::LogicalResult
955insertReturnCoercion(mlir::FunctionOpInterface funcOp, mlir::Type origRetTy,
956 mlir::Type coercedRetTy, mlir::OpBuilder &builder,
957 const mlir::DataLayout &dl,
958 const cir::CIRDataLayout &cirDataLayout, unsigned offset) {
960 funcOp.walk([&](cir::ReturnOp r) { returns.push_back(r); });
961 for (cir::ReturnOp r : returns) {
962 if (r.getInput().empty())
963 continue;
964 mlir::Value origVal = r.getInput()[0];
965 if (origVal.getType() == coercedRetTy)
966 continue;
967
968 if (failed(rejectAtomicRecordLoad(r, origVal)))
969 return mlir::failure();
970 if (cir::LoadOp recLoad = maybeGetCopyableRecordLoad(origVal)) {
971 mlir::Value coerced = emitCoercedRecordLoad(
972 builder, r.getLoc(), recLoad, coercedRetTy,
973 &funcOp->getRegion(0).front(), dl, cirDataLayout, offset);
974 r->setOperand(0, coerced);
975 if (recLoad->use_empty())
976 recLoad->erase();
977 continue;
978 }
979
980 builder.setInsertionPoint(r);
981 mlir::Value coerced =
982 emitCoercion(builder, r.getLoc(), coercedRetTy, origVal,
983 &funcOp->getRegion(0).front(), dl, offset);
984 r->setOperand(0, coerced);
985 }
986 return mlir::success();
987}
988
989/// \p recordVal's defining load, if it is simple and its address resolves to
990/// an alloca. Null otherwise.
991static cir::LoadOp getWholeRecordLoad(mlir::Value recordVal) {
992 cir::LoadOp load = maybeGetSimpleLoad(recordVal);
993 if (!load || !cir::getUnderlyingAlloca(load.getAddr()))
994 return {};
995 return load;
996}
997
998/// Returns the address \p load read from, as a pointer of type \p paramTy, if
999/// it can be passed in place of the loaded value for an indirect argument that
1000/// needs \p minAlign alignment, and null otherwise, including when \p load is
1001/// null. A byval or byref argument also needs storageUnwrittenBetween. On
1002/// null the caller reports a non-byval argument or fills a slot of its own.
1003///
1004/// The address has to have \p paramTy, the rewritten parameter's type, since a
1005/// cir.load pins the pointee type without pinning the address space. An
1006/// address_space cast of a \p paramTy pointer qualifies through its source.
1007/// The storage it names has to be a slot allocated here, reached through
1008/// storage-preserving casts, already stating at least \p minAlign. The
1009/// enclosing function's own non-byval parameter qualifies as well, since its
1010/// slot stands until finalizeParameterSlots and prepareNonByvalParameters has
1011/// restated it with the alignment that parameter promises rather than the one
1012/// CIRGen chose for a local copy. A byval or byref parameter's slot keeps
1013/// CIRGen's alignment, so it qualifies only where that already covers
1014/// \p minAlign.
1015///
1016/// Raising a slot's alignment here would not hold for one that stands in
1017/// for a parameter, since finalizeParameterSlots replaces it with the
1018/// incoming pointer, which promises only what the caller gave it.
1019static mlir::Value forwardableIndirectAddr(cir::LoadOp load,
1020 cir::PointerType paramTy,
1021 uint64_t minAlign) {
1022 if (!load)
1023 return {};
1024 mlir::Value addr = load.getAddr();
1025 // CIRGen reads an alloca outside the default address space through a cast.
1026 if (auto view = addr.getDefiningOp<cir::CastOp>();
1027 view && view.getKind() == cir::CastKind::address_space &&
1028 view.getSrc().getType() == paramTy)
1029 addr = view.getSrc();
1030 if (addr.getType() != paramTy)
1031 return {};
1032 cir::AllocaOp slot = cir::getUnderlyingAlloca(addr);
1033 return slot && slot.getAlignment() >= minAlign ? addr : mlir::Value();
1034}
1035
1036/// Whether a non-byval indirect argument of type \p ty is passed from the
1037/// caller's storage rather than from a copy of it. CIRGen gives each call its
1038/// own temporary for a record that cannot be passed in registers, built by
1039/// the record's copy or move constructor, so the call passes that temporary.
1040/// Every other type is copied to a temporary at the call, since the callee
1041/// may write the memory it is passed. A record with no layout entry can be
1042/// passed in registers.
1043static bool passesCallerStorage(mlir::ModuleOp module, mlir::Type ty) {
1044 auto recTy = mlir::dyn_cast<cir::RecordType>(ty);
1045 if (!recTy)
1046 return false;
1047 cir::RecordLayoutAttr layout =
1048 cir::tryGetRecordLayout(module, recTy.getName());
1049 return layout &&
1050 layout.getArgPassingKind() != cir::ArgPassingKind::CanPassInRegs;
1051}
1052
1053/// True when \p aliasAnalysis shows that nothing between \p load and \p call
1054/// can write the storage \p load read, so a byval argument may name that
1055/// storage rather than a copy of it. byval takes the callee's copy at the
1056/// call, while the operand carries the value as of the load, so a write in
1057/// between would reach the callee that the operand does not hold.
1058/// prepareNonByvalParameters reads a parameter at its spill, which leaves the
1059/// body's own stores in between.
1060///
1061/// A load in another block is not forwardable here, since the paths from it
1062/// to the call are not walked.
1063static bool storageUnwrittenBetween(cir::LoadOp load, mlir::Operation *call,
1064 mlir::AliasAnalysis &aliasAnalysis) {
1065 if (load->getBlock() != call->getBlock())
1066 return false;
1067 for (mlir::Operation *op = load->getNextNode(); op != call;
1068 op = op->getNextNode()) {
1069 assert(op && "the load must precede the call in the block they share");
1070 if (op->getNumRegions() != 0 ||
1071 aliasAnalysis.getModRef(op, load.getAddr()).isMod())
1072 return false;
1073 }
1074 return true;
1075}
1076
1077/// The alignment a copy may claim for the storage \p load read, which is the
1078/// one \p load states, or the underlying slot's when it states none. A load
1079/// with neither names storage this pass cannot reason about, so the copy is
1080/// left to assume nothing.
1081static mlir::IntegerAttr loadSourceAlignment(cir::LoadOp load,
1082 mlir::OpBuilder &builder) {
1083 if (mlir::IntegerAttr stated = load.getAlignmentAttr())
1084 return stated;
1085 if (cir::AllocaOp slot = cir::getUnderlyingAlloca(load.getAddr()))
1086 return builder.getI64IntegerAttr(slot.getAlignment());
1087 return builder.getI64IntegerAttr(1);
1088}
1089
1090/// Decompose a struct value into one scalar call argument per field of \p
1091/// recTy, appending the field values to \p newArgs. When \p structVal is a
1092/// simple load from an alloca, read each field with cir.get_member +
1093/// cir.load from the address the load used, emitted at the original load's
1094/// position so they observe the same memory state, and record the now-dead
1095/// whole-struct load in \p deadRecordLoads for later erasure. Otherwise (a
1096/// call result, compound literal, or a volatile or atomic load) extract each
1097/// field from the value with cir.extract_member. Loading the members from
1098/// memory rather than extracting from a whole-struct value keeps the result in
1099/// a form SROA can promote (it does not reason about extractvalue). Shared by
1100/// the Expand and Direct+canFlatten argument paths.
1101static void emitStructFieldArgs(mlir::OpBuilder &builder, mlir::Location loc,
1102 mlir::Value structVal, cir::RecordType recTy,
1103 SmallVectorImpl<mlir::Value> &newArgs,
1104 SmallVectorImpl<cir::LoadOp> &deadRecordLoads) {
1105 cir::LoadOp srcLoad = getWholeRecordLoad(structVal);
1106
1107 if (srcLoad) {
1108 mlir::OpBuilder::InsertionGuard guard(builder);
1109 builder.setInsertionPoint(srcLoad);
1110 cir::PointerType baseTy = srcLoad.getAddr().getType();
1111 for (auto [f, fieldTy] : llvm::enumerate(recTy.getMembers())) {
1112 mlir::Type fieldPtrTy =
1113 cir::PointerType::get(fieldTy, baseTy.getAddrSpace());
1114 mlir::Value fieldPtr = cir::GetMemberOp::create(
1115 builder, loc, fieldPtrTy, srcLoad.getAddr(), /*name=*/"",
1116 /*index=*/f);
1117 newArgs.push_back(cir::LoadOp::create(builder, loc, fieldPtr));
1118 }
1119 deadRecordLoads.push_back(srcLoad);
1120 } else {
1121 for (unsigned f = 0; f < recTy.getNumElements(); ++f)
1122 newArgs.push_back(
1123 cir::ExtractMemberOp::create(builder, loc, structVal, f));
1124 }
1125}
1126
1127/// Erase the loads that a rewritten call left unused. The old call must
1128/// already be erased, since until then it still counts as a user. One load can
1129/// feed two operands of the same call, as in f(s, s), so \p loads can hold the
1130/// same load twice. A load that another op still reads is left alone.
1131static void eraseDeadRecordLoads(ArrayRef<cir::LoadOp> loads) {
1132 llvm::SmallSetVector<mlir::Operation *, 4> uniqueLoads(llvm::from_range,
1133 loads);
1134 for (mlir::Operation *load : uniqueLoads)
1135 if (load->use_empty())
1136 load->erase();
1137}
1138
1139/// The old call, their only user, must already be erased.
1140static void eraseDeadFreezes(ArrayRef<cir::FreezeOp> freezes) {
1141 for (cir::FreezeOp freeze : freezes)
1142 freeze->erase();
1143}
1144
1145/// The store that spills indirect parameter \p blockArg, if the parameter's
1146/// only use is that store. Null otherwise.
1147static cir::StoreOp maybeFindParamSpill(mlir::BlockArgument blockArg) {
1148 if (!blockArg.hasOneUse())
1149 return {};
1150 auto store = dyn_cast<cir::StoreOp>(*blockArg.user_begin());
1151 if (!store || store.getValue() != blockArg)
1152 return {};
1153 return store;
1154}
1155
1156/// The alloca a parameter spill writes to through \p addr, either directly or
1157/// through an address_space cast of it. Null otherwise.
1158static cir::AllocaOp getSpillSlot(mlir::Value addr) {
1159 if (auto view = addr.getDefiningOp<cir::CastOp>();
1160 view && view.getKind() == cir::CastKind::address_space)
1161 addr = view.getSrc();
1162 return addr.getDefiningOp<cir::AllocaOp>();
1163}
1164
1165/// The store that spills non-byval indirect parameter \p blockArg, and the
1166/// slot it spills into. prepareNonByvalParameters has already established
1167/// that the spill is the block argument's only use and that it stores into
1168/// an alloca, which is what the assertions below rest on. Both results are
1169/// null when the parameter has no spill, which is so only when nothing uses
1170/// it at all.
1171static std::pair<cir::StoreOp, cir::AllocaOp>
1172findParamSpill(mlir::BlockArgument blockArg) {
1173 if (blockArg.use_empty())
1174 return {};
1175 cir::StoreOp store = maybeFindParamSpill(blockArg);
1176 assert(store && "non-byval arg's only use must be its CIRGen param spill");
1177 cir::AllocaOp slot = getSpillSlot(store.getAddr());
1178 assert(slot && "non-byval arg's spill must store to an alloca");
1179 return {store, slot};
1180}
1181
1182/// For each Direct arg with a coerced type, change the block argument's type to
1183/// the coerced type and insert a coercion at function entry that maps it back
1184/// to the original type for body uses, which find a record in the coercion slot
1185/// through rewireRecordUses. For each Indirect byval arg and each
1186/// IndirectAliased arg, change the block argument's type to a pointer, then
1187/// replace a record's single param spill with a copy from that pointer.
1188/// Without such a spill, a record's uses find it at the pointer through
1189/// rewireRecordUses, and a value of any other type is loaded from the pointer
1190/// at entry. For each Indirect non-byval arg, change the block argument to a
1191/// pointer and queue the param-slot alloca to be replaced by it (no entry load
1192/// or byte-copy) so the body operates on the caller's storage in place. For
1193/// each Expand arg, replace the single struct block argument with N scalar
1194/// block arguments (one per field) and store each field directly into the
1195/// parameter's own alloca (the CIRGen spill slot), erasing the original
1196/// whole-struct store.
1197///
1198/// \p hasSRetArg is true when the function has an sret return (a hidden return
1199/// pointer is prepended as block argument 0). Expand arguments expand the
1200/// block argument count, so a running index tracks the current block argument
1201/// position rather than computing the classification index + \p hasSRetArg
1202/// directly. Fails, after reporting it, when rewireRecordUses does.
1203mlir::LogicalResult
1204insertArgCoercion(mlir::FunctionOpInterface funcOp,
1205 const FunctionClassification &fc, mlir::OpBuilder &builder,
1206 const mlir::DataLayout &dl, bool hasSRetArg,
1207 SmallVectorImpl<std::pair<cir::AllocaOp, mlir::BlockArgument>>
1208 &pendingParamSlots) {
1209 mlir::Region &body = funcOp->getRegion(0);
1210 if (body.empty())
1211 return mlir::success();
1212 mlir::Block &entry = body.front();
1213
1214 // Running block argument index. Each non-Expand classification occupies
1215 // one block argument slot; each Expand classification occupies N slots
1216 // (one per struct field), so the running index must be incremented by N
1217 // rather than 1 after processing an Expand arg.
1218 unsigned blockArgIdx = hasSRetArg ? 1 : 0;
1219
1220 for (const ArgClassification &ac : fc.argInfos) {
1221 assert(blockArgIdx < entry.getNumArguments() &&
1222 "classification count must not exceed entry block arguments");
1223
1224 if (ac.kind == ArgKind::Expand) {
1225 // The block arg at blockArgIdx currently has the original struct type.
1226 // Replace it with N scalar args (one per field) and store each field
1227 // directly into the parameter's own alloca.
1228 mlir::BlockArgument origArg = entry.getArgument(blockArgIdx);
1229 auto recTy = cast<cir::RecordType>(origArg.getType());
1230 assert(recTy.isStruct() &&
1231 "Expand classification requires a struct type, not a union");
1232 unsigned numFields = recTy.getNumElements();
1233 assert(numFields > 0 &&
1234 "Expand classification requires at least one struct field");
1235 mlir::Location loc = funcOp.getLoc();
1236
1237 // CIRGen spills every by-value struct parameter into its local alloca
1238 // with a single store before any other use, so the struct block arg's
1239 // only use is that spill. Capture it and the destination alloca so the
1240 // expanded fields can be stored straight into that alloca, preserving
1241 // the alloca's variable name and `init` flag and avoiding a
1242 // reassemble-then-reload roundtrip. DCE may have run earlier and
1243 // removed the spill (leaving the block arg unused); tolerate that by
1244 // only flattening the signature and emitting no field stores.
1245 cir::StoreOp paramStore;
1246 cir::AllocaOp destAlloca;
1247 if (!origArg.use_empty()) {
1248 assert(origArg.hasOneUse() &&
1249 "Expand arg must have exactly one use (the CIRGen param spill)");
1250 paramStore = cast<cir::StoreOp>(*origArg.user_begin());
1251 assert(paramStore.getValue() == origArg &&
1252 "Expand arg's use must be the value operand of its store");
1253 destAlloca = cast<cir::AllocaOp>(paramStore.getAddr().getDefiningOp());
1254 }
1255
1256 // Erase the original whole-struct spill before retyping the block
1257 // argument, so the store is never left feeding a type-mismatched value.
1258 // The field stores take its place, just before the following operation
1259 // (the spill always precedes the entry block's terminator).
1260 mlir::Operation *fieldStoreInsertPt = nullptr;
1261 if (paramStore) {
1262 fieldStoreInsertPt = paramStore->getNextNode();
1263 assert(fieldStoreInsertPt &&
1264 "param spill must be followed by a block terminator");
1265 paramStore->erase();
1266 }
1267
1268 // Split the single struct block arg into N scalar field block args (slot
1269 // 0 reuses the original; slots 1..N-1 are inserted after it). The
1270 // reshape needs no insertion point. The field stores are gated on the
1271 // same destAlloca condition: when the spill survived we set the insert
1272 // point to its old slot (which sits after the CIRGen allocas) and store
1273 // each field there; when DCE removed the spill the parameter is dead, so
1274 // we only reshape the signature and emit no stores.
1275 if (destAlloca)
1276 builder.setInsertionPoint(fieldStoreInsertPt);
1277 for (auto [f, fieldTy] : llvm::enumerate(recTy.getMembers())) {
1278 if (f == 0)
1279 origArg.setType(fieldTy);
1280 else
1281 entry.insertArgument(blockArgIdx + f, fieldTy, loc);
1282 if (!destAlloca)
1283 continue;
1284 mlir::Type fieldPtrTy = cir::PointerType::get(
1285 fieldTy,
1286 mlir::cast<cir::PointerType>(destAlloca.getType()).getAddrSpace());
1287 auto fieldPtr = cir::GetMemberOp::create(builder, loc, fieldPtrTy,
1288 destAlloca, /*name=*/"",
1289 /*index=*/f);
1290 cir::StoreOp::create(builder, loc, entry.getArgument(blockArgIdx + f),
1291 fieldPtr);
1292 }
1293
1294 blockArgIdx += numFields;
1295 continue;
1296 }
1297
1298 mlir::BlockArgument blockArg = entry.getArgument(blockArgIdx);
1299
1300 if (cir::RecordType flatTy = getFlattenedCoercedType(ac, dl)) {
1301 // Direct + canFlatten: the coerced type is a struct whose fields are
1302 // passed as separate arguments. As in the Expand path, the single block
1303 // arg becomes N scalar block args, and each is stored straight into a
1304 // slot sized and aligned for both the coerced struct and the original
1305 // argument type, which the body then reads.
1306 unsigned numFields = flatTy.getNumElements();
1307 Type origTy = blockArg.getType();
1308 Location loc = funcOp.getLoc();
1309
1310 // Change slot 0 to field 0's type; insert slots 1..N-1 after it.
1311 blockArg.setType(flatTy.getElementType(0));
1312 for (unsigned f = 1; f < numFields; ++f)
1313 entry.insertArgument(blockArgIdx + f, flatTy.getElementType(f), loc);
1314
1315 // setInsertionPointToStart: see comment in the Expand arm above.
1316 builder.setInsertionPointToStart(&entry);
1317 assert(!ac.directOffset &&
1318 "the coerced struct starts at slot offset 0 here, so a flattened "
1319 "coercion cannot honor a direct offset");
1320 SmallPtrSet<Operation *, 8> flattenOps;
1321 cir::AllocaOp slot;
1322 if (origTy == flatTy) {
1323 slot = cir::AllocaOp::create(
1324 builder, loc, getAllocaPtrTy(flatTy, dl),
1325 builder.getStringAttr("coerce"),
1326 builder.getI64IntegerAttr(
1327 cir::CIRDataLayout(funcOp->getParentOfType<mlir::ModuleOp>())
1328 .getTypeLanguageAlignment(flatTy)));
1329 flattenOps.insert(slot);
1330 } else {
1331 slot = createCoercionSlot(builder, loc, flatTy, origTy, &entry, dl,
1332 flattenOps, /*offset=*/0);
1333 }
1334 Value flatView = emitViewAtOffset(builder, loc, flatTy, slot, flattenOps,
1335 /*offset=*/0);
1336 auto flatPtrTy = cast<cir::PointerType>(flatView.getType());
1337 for (auto [f, fieldTy] : llvm::enumerate(flatTy.getMembers())) {
1338 Type fieldPtrTy =
1339 cir::PointerType::get(fieldTy, flatPtrTy.getAddrSpace());
1340 auto fieldPtr = cir::GetMemberOp::create(builder, loc, fieldPtrTy,
1341 flatView, /*name=*/"",
1342 /*index=*/f);
1343 flattenOps.insert(fieldPtr);
1344 auto storeOp = cir::StoreOp::create(
1345 builder, loc, entry.getArgument(blockArgIdx + f), fieldPtr);
1346 // A packed slot can be less aligned than the field's own type.
1347 uint64_t fieldAlign =
1348 llvm::MinAlign(slot.getAlignment(), flatTy.getElementOffset(dl, f));
1349 if (fieldAlign < dl.getTypeABIAlignment(fieldTy))
1350 storeOp.setAlignment(fieldAlign);
1351 flattenOps.insert(storeOp);
1352 }
1353
1354 // Point the original body uses of the struct block arg, now field 0, at
1355 // the original-type view of the slot.
1356 Value origView = emitViewAtOffset(builder, loc, origTy, slot, flattenOps,
1357 /*offset=*/0);
1358 if (failed(replaceUsesFromSlot(builder, loc, blockArg, origView, dl,
1359 flattenOps)))
1360 return mlir::failure();
1361
1362 blockArgIdx += numFields;
1363 continue;
1364 }
1365
1366 if ((ac.kind == ArgKind::Direct && ac.coercedType) ||
1367 isRecordExtend(ac, blockArg.getType())) {
1368 mlir::Type oldArgTy = blockArg.getType();
1369 mlir::Type newArgTy = ac.coercedType;
1370 if (oldArgTy == newArgTy) {
1371 ++blockArgIdx;
1372 continue;
1373 }
1374 blockArg.setType(newArgTy);
1375
1376 // The coercion's own operations are left out of the rewiring, since they
1377 // read blockArg as the coerced type.
1378 builder.setInsertionPointToStart(&entry);
1379 SmallPtrSet<mlir::Operation *, 4> coercionOps;
1380 if (failed(emitCoercionAndReplaceUses(builder, funcOp.getLoc(), oldArgTy,
1381 blockArg, blockArg, &entry, dl,
1382 coercionOps, ac.directOffset)))
1383 return mlir::failure();
1384 } else if (ac.kind == ArgKind::Indirect ||
1385 ac.kind == ArgKind::IndirectAliased) {
1386 // byval and non-byval both lower to a pointer to T in the classified
1387 // address space, and which it is shows up only in the attrs
1388 // updateArgAttrs applies. Body lowering differs: the body addresses a
1389 // byval parameter through the CIRGen slot it was spilled into, so that
1390 // slot has to be filled from the incoming pointer, while a non-byval
1391 // parameter's slot is replaced by the pointer so the body works on the
1392 // caller's storage in place. A byref parameter takes the byval path.
1393 bool byRef = ac.kind == ArgKind::IndirectAliased;
1394 cir::PointerType ptrTy = getIndirectPtrTy(blockArg.getType(), ac);
1395
1396 if (!byRef && !ac.byVal) {
1397 // Without byval, drop the spill store and let the slot's uses read the
1398 // incoming pointer, so the body operates on the caller's storage in
1399 // place. A byte-copy would be wrong for non-trivially-copyable
1400 // aggregates (e.g. libstdc++ SSO std::string, where it would leave
1401 // `_M_p` aliasing the source's `_M_local_buf`).
1402 auto [paramStore, destAlloca] = findParamSpill(blockArg);
1403
1404 if (paramStore)
1405 paramStore->erase();
1406
1407 // Update the block argument to point to its original type.
1408 blockArg.setType(ptrTy);
1409
1410 // Pointing the slot's uses at the incoming pointer waits until every
1411 // call site has been rewritten. A call that hands this parameter
1412 // straight on recognizes it by the slot its operand was loaded from,
1413 // and collapsing the slot here would leave that call reading a block
1414 // argument with no defining operation to inspect. A dead spill DCE
1415 // already removed leaves nothing to collapse.
1416 if (destAlloca)
1417 pendingParamSlots.emplace_back(destAlloca, blockArg);
1418 } else {
1419 // A record's spill slot is filled by a byte copy of the incoming
1420 // object rather than by a store of the loaded value: its padding
1421 // bytes can hold another union member's live data, which a value
1422 // store would leave unwritten. A _BitInt keeps its load and spill
1423 // store, which are its conversion between value and in-memory form.
1424 cir::StoreOp paramStore;
1425 if (mlir::isa<cir::RecordType>(blockArg.getType()))
1426 paramStore = maybeFindParamSpill(blockArg);
1427
1428 // Erasing the spill before the block argument is retyped keeps the
1429 // store from being left with a value operand of the wrong type.
1430 mlir::Value destAddr;
1431 mlir::IntegerAttr destAlign;
1432 mlir::Operation *spillPos = nullptr;
1433 bool spillIsVolatile = false;
1434 if (paramStore) {
1435 if (paramStore.getMemOrder())
1436 return paramStore.emitOpError()
1437 << "atomic store of a record argument or result not yet "
1438 "implemented in CallConvLowering";
1439 spillIsVolatile = paramStore.getIsVolatile();
1440 destAddr = paramStore.getAddr();
1441 cir::AllocaOp destAlloca = cir::getUnderlyingAlloca(destAddr);
1442 destAlign = paramStore.getAlignmentAttr();
1443 if (!destAlign && destAlloca)
1444 destAlign = destAlloca.getAlignmentAttr();
1445 spillPos = paramStore->getNextNode();
1446 assert(spillPos && "param spill must be followed by a block "
1447 "terminator");
1448 paramStore->erase();
1449 }
1450
1451 blockArg.setType(ptrTy);
1452
1453 if (destAddr) {
1454 mlir::OpBuilder::InsertionGuard guard(builder);
1455 builder.setInsertionPoint(spillPos);
1456 auto copy = cir::CopyOp::create(
1457 builder, funcOp.getLoc(), destAddr, blockArg, destAlign,
1458 builder.getI64IntegerAttr(ac.indirectAlign.value()));
1459 copy.setIsVolatile(spillIsVolatile);
1460 copy.setSkipTailPadding(
1461 shouldSkipTailPadding(destAddr, ptrTy.getPointee()));
1462 } else if (!blockArg.use_empty()) {
1463 builder.setInsertionPointToStart(&entry);
1464 if (mlir::isa<cir::RecordType>(ptrTy.getPointee())) {
1465 SmallPtrSet<mlir::Operation *, 1> noExceptions;
1466 if (failed(rewireRecordUses(builder, funcOp.getLoc(), blockArg,
1467 blockArg, ac.indirectAlign.value(), dl,
1468 noExceptions)))
1469 return mlir::failure();
1470 } else {
1471 auto loadOp =
1472 cir::LoadOp::create(builder, funcOp.getLoc(), blockArg);
1473 SmallPtrSet<mlir::Operation *, 1> loadOps = {loadOp};
1474 blockArg.replaceAllUsesExcept(loadOp.getResult(), loadOps);
1475 }
1476 }
1477 }
1478 }
1479 // Ignore, Extend, and Direct-without-coerce need no block-level changes.
1480
1481 ++blockArgIdx;
1482 }
1483 return mlir::success();
1484}
1485
1486/// Replace each address_space cast of \p slot to the type of \p ptr with
1487/// \p ptr.
1488void replaceAddrSpaceViews(cir::AllocaOp slot, mlir::Value ptr) {
1489 for (mlir::Operation *user : llvm::make_early_inc_range(slot->getUsers())) {
1490 auto view = mlir::dyn_cast<cir::CastOp>(user);
1491 if (view && view.getKind() == cir::CastKind::address_space &&
1492 view.getType() == ptr.getType()) {
1493 view.getResult().replaceAllUsesWith(ptr);
1494 view->erase();
1495 }
1496 }
1497}
1498
1499/// Rewrite each cir.return so the return value flows through the sret
1500/// pointer (the prepended first block argument) and the function returns
1501/// void.
1502///
1503/// CIRGen emits a local return slot alloca and emits `cir.return %loaded`
1504/// where `%loaded = cir.load <slot>`. The naive lowering, storing the
1505/// loaded SSA value through the sret pointer, byte-copies the record,
1506/// which is wrong for non-trivially-copyable types: e.g. libstdc++'s SSO
1507/// `std::string` has a `_M_p` pointer that aliases the source's internal
1508/// `_M_local_buf`, so a byte-copy leaves the destination pointing at the
1509/// source's (now-dying) stack storage and the destination's destructor
1510/// later `free()`s a stack pointer.
1511///
1512/// Instead, route construction directly into the sret slot: find the
1513/// return slot alloca, replace its uses with the sret pointer, and drop the
1514/// trailing `cir.load <slot>` so the rewritten return has no operand.
1515/// The CIRGen-emitted constructor / store-into-slot then targets the
1516/// sret slot uniformly, matching classic CodeGen's "construct directly into
1517/// `%agg.result`" pattern.
1518///
1519/// CIRGen emits one `%v = cir.load %slot` / `cir.return %v` pair per
1520/// return statement, and every such load reads the single return slot
1521/// alloca (CIR does not merge returns into a shared epilogue block). The
1522/// alloca is therefore rewired to the sret pointer once; each cir.return is
1523/// then collapsed to a bare return and its now-dead load erased. This
1524/// `cir.return (cir.load <alloca>)` shape is an invariant guaranteed by
1525/// CIRGen, so it is asserted via `cast<>` rather than guarded with a
1526/// fallback.
1527///
1528/// A return slot outside the sret pointer's address space is not replaced
1529/// itself. Its address_space casts to the sret pointer's type are.
1530void insertSRetStores(mlir::FunctionOpInterface funcOp, mlir::Type origRetTy,
1531 mlir::OpBuilder &builder) {
1532 mlir::Value sretPtr = funcOp.getArguments()[0];
1533
1535 funcOp->walk([&](cir::ReturnOp retOp) { returnOps.push_back(retOp); });
1536
1537 cir::AllocaOp retAlloca = nullptr;
1538 for (cir::ReturnOp retOp : returnOps) {
1539 // Every cir.return in an sret function must carry the loaded return
1540 // value -- a bare return would mean the sret slot was never written.
1541 assert(!retOp.getInput().empty() &&
1542 "cir.return in sret function must have an operand");
1543
1544 cir::LoadOp retLoad =
1545 mlir::cast<cir::LoadOp>(retOp.getInput()[0].getDefiningOp());
1546
1547 // Rewire the shared return slot alloca to the sret pointer once.
1548 // replaceAllUsesWith updates every load of the alloca (including those
1549 // feeding the other cir.return ops) to read from sretPtr instead, so
1550 // all returns are covered by this single rewiring.
1551 if (!retAlloca) {
1552 retAlloca = mlir::cast<cir::AllocaOp>(retLoad.getAddr().getDefiningOp());
1553 if (retAlloca.getType() == sretPtr.getType())
1554 retAlloca.getResult().replaceAllUsesWith(sretPtr);
1555 else
1556 replaceAddrSpaceViews(retAlloca, sretPtr);
1557 }
1558
1559 // The sret slot now holds the return value directly; replace the
1560 // value-carrying return with a void return (no operand).
1561 builder.setInsertionPoint(retOp);
1562 cir::ReturnOp::create(builder, retOp.getLoc());
1563 retOp->erase();
1564 if (retLoad.use_empty())
1565 retLoad->erase();
1566 }
1567
1568 if (retAlloca) {
1569 assert(retAlloca->use_empty() &&
1570 "return slot used other than by its returns and address_space "
1571 "views");
1572 retAlloca->erase();
1573 }
1574}
1575
1576/// Build the attribute dictionary for the sret slot (slot 0 of an
1577/// sret-returning function or call). Matches classic CodeGen's
1578/// `sret(T) align A [noalias] writable dead_on_unwind`. noalias is only
1579/// valid on the callee's parameter, not at the call site, so it is gated by
1580/// \p withNoalias. Key order is irrelevant: DictionaryAttr sorts by name.
1581SmallVector<mlir::NamedAttribute> buildSretSlotAttrs(mlir::OpBuilder &builder,
1582 mlir::Type retTy,
1583 uint64_t align,
1584 bool withNoalias) {
1586 // The sret type must be carried explicitly: LLVM's sret attribute requires
1587 // it, and once the CIR `!cir.ptr<retTy>` lowers to an opaque LLVM `ptr` the
1588 // pointee type can no longer be recovered from the pointer.
1589 attrs.push_back(
1590 builder.getNamedAttr("llvm.sret", mlir::TypeAttr::get(retTy)));
1591 attrs.push_back(
1592 builder.getNamedAttr("llvm.align", builder.getI64IntegerAttr(align)));
1593 if (withNoalias)
1594 attrs.push_back(
1595 builder.getNamedAttr("llvm.noalias", builder.getUnitAttr()));
1596 attrs.push_back(builder.getNamedAttr("llvm.writable", builder.getUnitAttr()));
1597 attrs.push_back(
1598 builder.getNamedAttr("llvm.dead_on_unwind", builder.getUnitAttr()));
1599 return attrs;
1600}
1601
1602/// Prepend the sret slot's attrs at position 0 of newCall's arg_attrs.
1603/// Called after the call has been rewritten with the sret pointer at
1604/// operand 0, so the operand count now includes the sret slot. \p argAttrs
1605/// must already be shaped for the rewritten argument list (Extend slots
1606/// carry signext/zeroext, Ignore slots dropped); it is shifted to slots
1607/// 1..N behind the sret slot.
1608void applySretSlotAttrs(cir::CallOp newCall, mlir::ArrayAttr argAttrs,
1609 mlir::Type retTy, uint64_t align,
1610 mlir::OpBuilder &builder) {
1611 mlir::MLIRContext *ctx = newCall->getContext();
1613 buildSretSlotAttrs(builder, retTy, align, /*withNoalias=*/false);
1614
1615 SmallVector<mlir::Attribute> newArgAttrs;
1616 newArgAttrs.reserve(newCall.getArgOperands().size());
1617 newArgAttrs.push_back(mlir::DictionaryAttr::get(ctx, sretAttrs));
1618 if (argAttrs)
1619 llvm::append_range(newArgAttrs, argAttrs);
1620 assert(newArgAttrs.size() <= newCall.getArgOperands().size() &&
1621 "arg_attrs wider than the rewritten call's operand list");
1622 newArgAttrs.resize(newCall.getArgOperands().size(),
1623 mlir::DictionaryAttr::get(ctx));
1624 newCall->setAttr("arg_attrs", mlir::ArrayAttr::get(ctx, newArgAttrs));
1625}
1626
1627/// Copy the call attributes from \p source to the rebuilt \p target. The
1628/// callee is already established by CallOp::create and may have been rewritten,
1629/// so it is not copied. Existing discardable attributes on \p target take
1630/// precedence over attributes from \p source.
1631static void copyCallAttributes(cir::CallOp source, cir::CallOp target) {
1632 source->getName().walkInherentAttrs(source, [&](llvm::StringRef name,
1633 mlir::Attribute &attr) {
1634 if (name != cir::CIRDialect::getCalleeAttrName())
1635 target->setInherentAttr(mlir::StringAttr::get(source->getContext(), name),
1636 attr);
1637 });
1638 for (mlir::NamedAttribute attr : source->getDiscardableAttrs())
1639 if (!target->hasDiscardableAttr(attr.getName()))
1640 target->setDiscardableAttr(attr.getName(), attr.getValue());
1641}
1642
1643/// For an indirect call, prepend the callee function pointer as operand 0 so
1644/// CallOp::create rebuilds it as an indirect call, bitcasting it to a function
1645/// pointer that takes \p args, less the last \p numEllipsisArgs, and returns
1646/// \p retTy. Those last arguments were passed through the callee's ellipsis
1647/// and stay out of the function type, as in classic CodeGen's
1648/// GetFunctionType: LLVM treats operands past a call's function type as
1649/// variadic, and some backends pass variadic arguments differently. No-op
1650/// for direct calls.
1651static void prependIndirectCallee(cir::CallOp call,
1652 SmallVectorImpl<mlir::Value> &args,
1653 mlir::Type retTy, unsigned numEllipsisArgs,
1654 mlir::OpBuilder &builder) {
1655 if (!call.isIndirect())
1656 return;
1657 assert(numEllipsisArgs <= args.size() &&
1658 "more ellipsis arguments than arguments");
1659 mlir::Value calleePtr = call.getIndirectCall();
1660 SmallVector<mlir::Type> paramTypes;
1661 paramTypes.reserve(args.size() - numEllipsisArgs);
1662 llvm::transform(ArrayRef(args).drop_back(numEllipsisArgs),
1663 std::back_inserter(paramTypes),
1664 [](mlir::Value v) { return v.getType(); });
1665 // Lowering builds an indirect call's LLVM function type from the callee
1666 // pointer's pointee and takes the call's result from that type, so the
1667 // pointee's return type has to track the rewrite: an sret return would
1668 // leave a result the call no longer produces, and a coerced return one of
1669 // the wrong type. The ellipsis has to survive for the same reason: the
1670 // rebuilt pointee is what makes the lowered call variadic, and only a
1671 // variadic call gets the vector-register count that the x86_64 SysV ABI
1672 // passes in AL and that the callee's va_arg reads back.
1673 cir::FuncType calleeFnTy = getIndirectCalleeType(call);
1674 assert((calleeFnTy.isVarArg() || numEllipsisArgs == 0) &&
1675 "only a variadic callee takes arguments through an ellipsis");
1676 auto newPtrTy = cir::PointerType::get(
1677 cir::FuncType::get(paramTypes, retTy, calleeFnTy.isVarArg()));
1678 if (calleePtr.getType() != newPtrTy)
1679 calleePtr = cir::CastOp::create(builder, call.getLoc(), newPtrTy,
1680 cir::CastKind::bitcast, calleePtr);
1681 args.insert(args.begin(), calleePtr);
1682}
1683
1684/// Rewrite an indirect-return (sret) call site: prepend a return-slot pointer
1685/// as operand 0, make the call return void, and either reuse a dominating
1686/// single-use store destination as the slot (so construction flows directly
1687/// into it) or allocate a fresh slot and point the result's uses at it, a
1688/// record's through rewireRecordUses and any other type's through a load of the
1689/// slot after the call. \p newArgs is the already-shaped (Ignore-dropped,
1690/// coercion-applied) non-sret argument list, the last \p numEllipsisArgs of
1691/// which were passed through the callee's ellipsis. The caller guarantees the
1692/// call has a result and an indirect-return classification. Fails, after
1693/// reporting it, when rewireRecordUses does.
1694mlir::LogicalResult
1695rewriteIndirectReturnCall(cir::CallOp call, const FunctionClassification &fc,
1696 ArrayRef<mlir::Value> newArgs,
1697 unsigned numEllipsisArgs, mlir::Type origRetTy,
1698 ArrayRef<mlir::Type> origCallArgTypes,
1699 mlir::OpBuilder &builder, const mlir::DataLayout &dl,
1700 bool enableNoundefAttrs) {
1701 mlir::MLIRContext *ctx = call->getContext();
1702 cir::PointerType ptrTy = getIndirectPtrTy(origRetTy, fc.returnInfo);
1703 builder.setInsertionPoint(call);
1704 uint64_t sretAlign = fc.returnInfo.indirectAlign.value();
1705
1706 // CIRGen emits `cir.store %callResult, %dest` when the call's result is
1707 // bound to a local (e.g. `T s = make();`). Allocating a fresh sret slot
1708 // and copying into %dest would byte-copy the record, which is wrong for
1709 // non-trivially-copyable types (the libstdc++ SSO `_M_p` pointer
1710 // survives a byte-copy but ends up pointing at the dying temp's local
1711 // buffer, so the destination's destructor later `free()`s a stack
1712 // pointer). When the result has a single store-into-%dest use, use
1713 // %dest as the sret slot directly so construction flows into it,
1714 // matching classic CodeGen's "pass %s as sret" pattern. %dest must
1715 // dominate the call so the rewritten call (which takes it as operand 0)
1716 // does not use a value before its definition. An address_space cast of a
1717 // slot that already has the sret pointer's type stands for that slot.
1718 mlir::Value sretSlot = nullptr;
1719 cir::StoreOp reuseStore = nullptr;
1720 if (call.getResult().hasOneUse()) {
1721 mlir::Operation *user = *call.getResult().getUsers().begin();
1722 auto store = mlir::dyn_cast<cir::StoreOp>(user);
1723 if (store && store.getValue() == call.getResult()) {
1724 mlir::Value dest = store.getAddr();
1725 if (auto view = dest.getDefiningOp<cir::CastOp>();
1726 view && view.getKind() == cir::CastKind::address_space &&
1727 view.getSrc().getType() == ptrTy)
1728 dest = view.getSrc();
1729 if (dest.getType() == ptrTy &&
1730 mlir::DominanceInfo().properlyDominates(dest, call)) {
1731 sretSlot = dest;
1732 reuseStore = store;
1733 }
1734 }
1735 }
1736 if (!sretSlot) {
1737 cir::PointerType allocaPtrTy = getAllocaPtrTy(origRetTy, dl);
1738 auto slot = cir::AllocaOp::create(
1739 builder, call.getLoc(), allocaPtrTy,
1740 /*name=*/builder.getStringAttr(""),
1741 /*alignment=*/builder.getI64IntegerAttr(sretAlign));
1742 slot.setReturnSlot(true);
1743 sretSlot = slot;
1744 // The sret pointer can be outside the alloca address space.
1745 if (allocaPtrTy != ptrTy)
1746 sretSlot = cir::CastOp::create(builder, call.getLoc(), ptrTy,
1747 cir::CastKind::address_space, sretSlot);
1748 }
1749
1750 SmallVector<mlir::Value> sretArgs;
1751 sretArgs.push_back(sretSlot);
1752 sretArgs.append(newArgs.begin(), newArgs.end());
1753
1754 // numEllipsisArgs counts from the end, so the sret slot prepended here stays
1755 // in the retyped signature, as it does in classic CodeGen.
1756 mlir::Type sretVoidTy = cir::VoidType::get(ctx);
1757 prependIndirectCallee(call, sretArgs, sretVoidTy, numEllipsisArgs, builder);
1758 auto newCall = cir::CallOp::create(
1759 builder, call.getLoc(), call.getCalleeAttr(), sretVoidTy, sretArgs);
1760 copyCallAttributes(call, newCall);
1761 newCall->removeAttr("res_attrs");
1762
1763 // Shape the per-argument attrs exactly as the non-sret path does, through
1764 // updateArgAttrs, before prepending the sret slot, so sret composes with
1765 // every argument classification.
1766 mlir::ArrayAttr argAttrs = call->getAttrOfType<mlir::ArrayAttr>("arg_attrs");
1767 if (needsArgAttrUpdate(fc))
1768 argAttrs =
1769 updateArgAttrs(ctx, call->getParentOfType<mlir::ModuleOp>(),
1770 origCallArgTypes, argAttrs, fc, dl, enableNoundefAttrs,
1771 /*isCallSite=*/true);
1772 applySretSlotAttrs(newCall, argAttrs, origRetTy, sretAlign, builder);
1773
1774 if (reuseStore) {
1775 // The callee now constructs directly into the destination slot, so the
1776 // original store-from-result is redundant; dropping it avoids a
1777 // byte-copy of the record.
1778 reuseStore->erase();
1779 } else if (mlir::isa<cir::RecordType>(origRetTy)) {
1780 builder.setInsertionPointAfter(newCall);
1781 SmallPtrSet<mlir::Operation *, 1> noExceptions;
1782 if (failed(rewireRecordUses(builder, call.getLoc(), call.getResult(),
1783 sretSlot, sretAlign, dl, noExceptions)))
1784 return mlir::failure();
1785 } else {
1786 builder.setInsertionPointAfter(newCall);
1787 auto load = cir::LoadOp::create(builder, call.getLoc(), origRetTy, sretSlot,
1788 /*isDeref=*/mlir::UnitAttr(),
1789 /*isVolatile=*/mlir::UnitAttr(),
1790 /*is_nontemporal=*/mlir::UnitAttr(),
1791 /*alignment=*/mlir::IntegerAttr(),
1792 /*sync_scope=*/cir::SyncScopeKindAttr(),
1793 /*mem_order=*/cir::MemOrderAttr(),
1794 /*invariant=*/mlir::UnitAttr());
1795 call.getResult().replaceAllUsesWith(load);
1796 }
1797 call->erase();
1798 return mlir::success();
1799}
1800
1801/// Whether \p ty, a type the classifier named for one register of a
1802/// coercion, is carried in a vector register.
1803bool isSSERegisterClass(mlir::Type ty) {
1804 return mlir::isa<cir::VectorType, cir::FPTypeInterface>(ty);
1805}
1806
1807} // namespace
1808
1809cir::FuncType cir::getIndirectCalleeType(cir::CIRCallOpInterface call) {
1810 assert(call.isIndirect() && "expected an indirect call");
1811 return cast<cir::FuncType>(
1812 cast<cir::PointerType>(call.getIndirectCall().getType()).getPointee());
1813}
1814
1815/// Bring \p funcOp's non-byval indirect parameter \p argNo into the shape the
1816/// rest of the rewrite assumes. \p claimedSlots carries the slots \p funcOp's
1817/// earlier non-byval indirect parameters took. The shape itself, and the
1818/// cases reported rather than repaired, are documented on
1819/// CIRABIRewriteContext::prepareNonByvalParameters in the header.
1820static mlir::LogicalResult prepareOneNonByvalParameter(
1821 cir::FuncOp funcOp, unsigned argNo, const ArgClassification &ac,
1822 mlir::BlockArgument blockArg, mlir::DominanceInfo &dom,
1823 SmallPtrSetImpl<mlir::Operation *> &claimedSlots) {
1824 cir::PointerType paramPtrTy = getIndirectPtrTy(blockArg.getType(), ac);
1825
1826 // The spill is the store that writes the parameter itself. Any other use
1827 // consumes the record value. At -O1 and above such a use comes from
1828 // cir-simplify: CIRGen marks a const-qualified parameter's slot const, so
1829 // the load of it folds to the stored parameter.
1830 cir::StoreOp spill;
1831 cir::StoreOp extraSpill;
1832 mlir::Operation *otherUse = nullptr;
1834 for (mlir::OpOperand &use : blockArg.getUses()) {
1835 auto store = dyn_cast<cir::StoreOp>(use.getOwner());
1836 if (store && store.getValue() == blockArg) {
1837 // Which of two stores is the spill decides which slot stands in for the
1838 // parameter, and the use list is in no particular order, so there is
1839 // nothing to prefer between them.
1840 if (spill)
1841 extraSpill = store;
1842 else
1843 spill = store;
1844 continue;
1845 }
1846 // Only an argument is served by a load of the slot. Any other consumer
1847 // belongs to a rewrite that reads the parameter its own way: a returned
1848 // record, for one, is rewritten through the sret slot, which assumes the
1849 // returned load names the return slot and not this one.
1850 auto call = dyn_cast<cir::CIRCallOpInterface>(use.getOwner());
1851 if (call && llvm::is_contained(call.getArgOperands(), blockArg))
1852 callArgs.push_back(&use);
1853 else if (!otherUse)
1854 otherUse = use.getOwner();
1855 }
1856
1857 if (extraSpill)
1858 return extraSpill->emitOpError()
1859 << "non-byval parameter " << argNo
1860 << " spilled more than once is not yet implemented in "
1861 "CallConvLowering";
1862
1863 if (otherUse)
1864 return otherUse->emitOpError()
1865 << "non-byval parameter " << argNo
1866 << " consumed other than as a call argument is not yet implemented "
1867 "in CallConvLowering";
1868
1869 if (!spill) {
1870 // Every other kind of use was reported above, so the parameter has no
1871 // uses at all and needs neither a slot nor a read.
1872 if (callArgs.empty())
1873 return mlir::success();
1874
1875 // Without a spill the parameter becomes the incoming pointer directly,
1876 // which is the storage an argument taken from it has to name. Giving it
1877 // the spill it lacks lets the checks and the read below apply unchanged,
1878 // and neither survives the pass: insertArgCoercion erases the store and
1879 // finalizeParameterSlots replaces the slot.
1880 mlir::OpBuilder builder(funcOp.getContext());
1881 builder.setInsertionPointToStart(blockArg.getOwner());
1882 auto synthesized = cir::AllocaOp::create(
1883 builder, funcOp.getLoc(), paramPtrTy,
1884 builder.getStringAttr("nonbyval.param"),
1885 builder.getI64IntegerAttr(ac.indirectAlign.value()));
1886 spill =
1887 cir::StoreOp::create(builder, funcOp.getLoc(), blockArg, synthesized);
1888 }
1889
1890 // The incoming pointer replaces the slot itself, which also covers a spill
1891 // through an address_space cast of it. Retargeting only the cast would
1892 // leave the allocation's other views reading storage nothing writes.
1893 // Storage in another address space than the incoming pointer, or storage
1894 // that is not a local alloca at all, is not something the incoming pointer
1895 // can be substituted for.
1896 cir::AllocaOp slot = getSpillSlot(spill.getAddr());
1897 if (!slot || slot.getType() != paramPtrTy)
1898 return spill->emitOpError()
1899 << "non-byval parameter " << argNo
1900 << " spilled to storage that cannot take the incoming pointer is "
1901 "not yet implemented in CallConvLowering";
1902
1903 // One slot stands in for one non-byval parameter, since the incoming
1904 // pointer replaces it. Two of them spilled to the same slot are each
1905 // spilled once, so the check above cannot see the collision and only
1906 // comparing the slots can.
1907 if (!claimedSlots.insert(slot).second)
1908 return spill->emitOpError()
1909 << "non-byval parameter " << argNo
1910 << " sharing its spill slot with another parameter is not yet "
1911 "implemented in CallConvLowering";
1912
1913 // CIRGen picked the slot's alignment for a local copy of the record, but the
1914 // slot is about to stand in for the parameter, and a call forwarding it may
1915 // only promise what the incoming pointer does.
1916 slot.setAlignment(ac.indirectAlign.value());
1917
1918 if (callArgs.empty())
1919 return mlir::success();
1920
1921 // A reader the spill does not dominate could read the slot before anything
1922 // wrote it, and a load placed at the spill would not dominate it either.
1923 for (mlir::OpOperand *callArg : callArgs)
1924 if (!dom.properlyDominates(spill, callArg->getOwner()))
1925 return callArg->getOwner()->emitOpError()
1926 << "non-byval parameter " << argNo
1927 << " read before its spill is not yet implemented in "
1928 "CallConvLowering";
1929
1930 // Read the record back out of the slot instead, so every reader sees the
1931 // shape CIRGen emits without cir-simplify: a load naming the storage the
1932 // argument would have to name anyway. Reading at the spill, not at the
1933 // reader, keeps the value the parameter's own whatever the body later
1934 // stores into the slot, and the load promises only the alignment the
1935 // classification gives the incoming pointer.
1936 //
1937 // A call that forwards the argument consumes the load once it recognizes
1938 // the slot. One that wants a copy keeps it, reading the incoming pointer
1939 // once finalizeParameterSlots replaces the slot.
1940 mlir::OpBuilder builder(spill);
1941 builder.setInsertionPointAfter(spill);
1942 auto reload = cir::LoadOp::create(builder, spill.getLoc(), slot);
1943 reload.setAlignment(ac.indirectAlign.value());
1944 for (mlir::OpOperand *callArg : callArgs)
1945 callArg->set(reload.getResult());
1946 return mlir::success();
1947}
1948
1950 cir::FuncOp funcOp, const FunctionClassification &fc) {
1951 if (!funcOp.isDefinition())
1952 return mlir::success();
1953 mlir::Region &body = funcOp->getRegion(0);
1954 if (body.empty())
1955 return mlir::success();
1956 mlir::Block &entry = body.front();
1957 mlir::DominanceInfo dom;
1958 SmallPtrSet<mlir::Operation *, 4> claimedSlots;
1959
1960 // No signature has been rewritten yet, so no sret pointer has been prepended
1961 // and no Expand argument has been split into its fields. Every
1962 // classification therefore still maps to the entry block argument at its own
1963 // index.
1964 for (auto [idx, ac] : llvm::enumerate(fc.argInfos)) {
1965 if (ac.kind != ArgKind::Indirect || ac.byVal)
1966 continue;
1967 assert(idx < entry.getNumArguments() &&
1968 "classification count must not exceed entry block arguments");
1969 if (failed(prepareOneNonByvalParameter(
1970 funcOp, idx, ac, entry.getArgument(idx), dom, claimedSlots)))
1971 return mlir::failure();
1972 }
1973 return mlir::success();
1974}
1975
1977 for (auto [slot, incoming] : pendingParamSlots) {
1978 slot.getResult().replaceAllUsesWith(incoming);
1979 slot->erase();
1980 }
1981 pendingParamSlots.clear();
1982}
1983
1985 mlir::FunctionOpInterface funcOpInterface, const FunctionClassification &fc,
1986 mlir::OpBuilder &builder) {
1987 // The pass driver (CallConvLoweringPass) only ever hands us cir.func ops.
1988 // Cast once at the top so the rest of the function reads in CIR's own
1989 // vocabulary, and so we can dispatch to the CIRGlobalValueInterface for
1990 // isDefinition() (FunctionOpInterface alone does not inherit from
1991 // CIRGlobalValueInterface).
1992 cir::FuncOp funcOp = mlir::cast<cir::FuncOp>(funcOpInterface);
1993
1994 if (!fc.needsRewrite())
1995 return mlir::success();
1996
1997 ArrayRef<mlir::Type> oldArgTypes = funcOp.getArgumentTypes();
1998 ArrayRef<mlir::Type> oldResultTypes = funcOp.getResultTypes();
1999 mlir::MLIRContext *ctx = funcOp->getContext();
2000
2001 // CIR follows LLVM IR's single-result rule: a function returns either
2002 // zero or one value. Document the invariant so a future multi-result
2003 // change forces us to revisit the return-handling below.
2004 assert(oldResultTypes.size() <= 1 &&
2005 "CIR functions return zero or one value");
2006
2007 SmallVector<mlir::Type> newArgTypes;
2008 if (mlir::failed(buildNewArgTypes(oldArgTypes, fc, newArgTypes, dl,
2009 [&]() { return funcOp.emitOpError(); })))
2010 return mlir::failure();
2011
2012 mlir::Type voidTy = cir::VoidType::get(ctx);
2013 mlir::Type origRetTy = oldResultTypes.empty() ? voidTy : oldResultTypes[0];
2014 mlir::Type newRetTy = computeNewReturnType(
2015 origRetTy, fc.returnInfo, ctx, [&]() { return funcOp.emitOpError(); });
2016 if (!newRetTy)
2017 return mlir::failure();
2018 SmallVector<mlir::Type> newResultTypes = {newRetTy};
2019
2020 // sret return: the value is returned through a pointer the ABI inserts as
2021 // argument 0. This pointer is not part of the function's source-level
2022 // signature -- it is synthesized here -- and the wire return type was
2023 // already set to void by computeNewReturnType. Every classification index
2024 // therefore maps to a block argument shifted by one in the body handling
2025 // below.
2026 bool hasSRet =
2027 fc.returnInfo.kind == ArgKind::Indirect && !oldResultTypes.empty();
2028 cir::PointerType sretPtrTy;
2029 if (hasSRet) {
2030 sretPtrTy = getIndirectPtrTy(origRetTy, fc.returnInfo);
2031 newArgTypes.insert(newArgTypes.begin(), sretPtrTy);
2032 }
2033
2034 if (funcOp.isDefinition()) {
2035 mlir::Region &body = funcOp->getRegion(0);
2036 if (!body.empty()) {
2037 // Prepend the sret pointer block argument and route every cir.return
2038 // through it before any index-based argument handling below (which
2039 // then accounts for the +1 offset).
2040 if (hasSRet) {
2041 body.front().insertArgument(0u, sretPtrTy, funcOp.getLoc());
2042 insertSRetStores(funcOp, origRetTy, builder);
2043 }
2044
2045 // Reshape the entry block for the classifications that change what a
2046 // parameter looks like to the body: a Direct arg with a coerced type
2047 // gets a memory roundtrip back to its original type, an Indirect arg
2048 // becomes a pointer, and an Expand arg becomes one block argument per
2049 // field. Done before the Ignore-drop below so the entry block
2050 // argument indices used here still refer to the original positions.
2051 if (failed(insertArgCoercion(funcOp, fc, builder, dl, hasSRet,
2052 pendingParamSlots)))
2053 return mlir::failure();
2054
2055 // Direct return with coerced type: insert a coercion at every
2056 // cir.return so the returned value matches the (coerced) return
2057 // type in the new function signature set below.
2058 if (fc.returnInfo.kind == ArgKind::Direct && fc.returnInfo.coercedType &&
2059 !oldResultTypes.empty() && fc.returnInfo.coercedType != origRetTy &&
2060 failed(insertReturnCoercion(
2061 funcOp, origRetTy, fc.returnInfo.coercedType, builder, dl,
2062 cirDataLayout, fc.returnInfo.directOffset)))
2063 return mlir::failure();
2064
2065 mlir::Block &entry = body.front();
2066
2067 // Drop each Ignored argument's block argument, replacing any remaining
2068 // body uses with a poison constant (an Ignore arg is not passed at the
2069 // ABI level, so any use is vacuous; poison says exactly that). Walk
2070 // forward with a running block-argument index that mirrors
2071 // insertArgCoercion: an Expand arg or a Direct+canFlatten arg occupies N
2072 // slots, every other kept kind one. On erase, do not advance the index
2073 // -- the next block argument shifts into the vacated slot.
2074 unsigned blockArgIdx = hasSRet ? 1 : 0;
2075 for (auto [i, ac] : llvm::enumerate(fc.argInfos)) {
2076 if (blockArgIdx >= entry.getNumArguments())
2077 break;
2078 if (ac.kind == ArgKind::Ignore) {
2079 mlir::BlockArgument arg = entry.getArgument(blockArgIdx);
2080 if (!arg.use_empty()) {
2081 builder.setInsertionPointToStart(&entry);
2082 mlir::Value poison =
2083 createIgnoredValue(builder, funcOp.getLoc(), arg.getType());
2084 arg.replaceAllUsesWith(poison);
2085 }
2086 entry.eraseArgument(blockArgIdx);
2087 continue;
2088 }
2089 if (cir::RecordType flatTy = getFlattenedCoercedType(ac, dl))
2090 blockArgIdx += flatTy.getNumElements();
2091 else if (ac.kind == ArgKind::Expand)
2092 blockArgIdx += cast<cir::RecordType>(oldArgTypes[i]).getNumElements();
2093 else
2094 ++blockArgIdx;
2095 }
2096 }
2097
2098 // When the return is classified Ignore but the original function had
2099 // a non-void return type, every cir.return becomes a naked return.
2100 // This relies on the invariant that computeNewReturnType has set
2101 // newRetTy = void for Ignore above, and that the function type is
2102 // updated below to match. Asserting this keeps the dependency
2103 // explicit.
2104 if (fc.returnInfo.kind == ArgKind::Ignore && !oldResultTypes.empty()) {
2105 assert(mlir::isa<cir::VoidType>(newRetTy) &&
2106 "Ignore-return path requires the new return type to be void");
2108 funcOp.walk([&](cir::ReturnOp r) { returns.push_back(r); });
2109 for (cir::ReturnOp r : returns) {
2110 if (r.getNumOperands() == 0)
2111 continue;
2112 builder.setInsertionPoint(r);
2113 cir::ReturnOp::create(builder, r.getLoc());
2114 r.erase();
2115 }
2116 }
2117 }
2118
2119 mlir::Type newFnTy = funcOp.cloneTypeWith(newArgTypes, newResultTypes);
2120 funcOp.setFunctionTypeAttr(mlir::TypeAttr::get(newFnTy));
2121
2122 // Rebuild arg_attrs when the function has an sret slot (slot 0 needs the
2123 // sret attribute set) or any arg needs updateArgAttrs.
2124 if (hasSRet || needsArgAttrUpdate(fc)) {
2125 auto existing = funcOp->getAttrOfType<mlir::ArrayAttr>("arg_attrs");
2126 mlir::ArrayAttr updated = updateArgAttrs(ctx, module, oldArgTypes, existing,
2127 fc, dl, enableNoundefAttrs,
2128 /*isCallSite=*/false);
2129 if (hasSRet) {
2130 // Prepend the sret slot's attribute dict (slot 0); the per-argument
2131 // dicts shift to slots 1..N. noalias is valid only on the callee's
2132 // parameter, so it is added only for definitions.
2133 SmallVector<mlir::NamedAttribute> sretAttrs = buildSretSlotAttrs(
2134 builder, origRetTy, fc.returnInfo.indirectAlign.value(),
2135 /*withNoalias=*/funcOp.isDefinition());
2137 withSret.push_back(mlir::DictionaryAttr::get(ctx, sretAttrs));
2138 llvm::append_range(withSret, updated);
2139 funcOp->setAttr("arg_attrs", mlir::ArrayAttr::get(ctx, withSret));
2140 } else {
2141 funcOp->setAttr("arg_attrs", updated);
2142 }
2143 }
2144
2145 if (mlir::isa<cir::VoidType>(newRetTy)) {
2146 funcOp->removeAttr("res_attrs");
2147 } else if (fc.returnInfo.kind == ArgKind::Extend ||
2148 fc.returnInfo.kind == ArgKind::Direct) {
2149 auto existing = funcOp->getAttrOfType<mlir::ArrayAttr>("res_attrs");
2150 if (mlir::ArrayAttr updated =
2151 updateResAttrs(ctx, existing, fc.returnInfo, origRetTy, dl))
2152 funcOp->setAttr("res_attrs", updated);
2153 }
2154
2155 return mlir::success();
2156}
2157
2158mlir::LogicalResult
2160 const FunctionClassification &fc,
2161 mlir::OpBuilder &builder) {
2162 // The rewrite below pairs the classification with the call's operands one
2163 // for one, so a call passing arguments through an ellipsis needs a
2164 // classification built from its own operands rather than from the callee's
2165 // declared parameters. Both directions of a mismatch have to be reported
2166 // before the pass-through early return, or a call whose declared parameters
2167 // happen to be pass-through is left as written with its surplus operands
2168 // never classified.
2169 //
2170 // A surplus operand means fc was built from the callee's declared
2171 // parameters alone. A shortfall means the callee was declared no_proto,
2172 // which turns off the verifier's argument-count check altogether.
2173 unsigned numOperands =
2174 mlir::cast<cir::CIRCallOpInterface>(callOp).getNumArgOperands();
2175 if (numOperands > fc.argInfos.size())
2176 return callOp->emitOpError()
2177 << "variadic arguments not yet implemented in CallConvLowering";
2178 if (numOperands < fc.argInfos.size())
2179 return callOp->emitOpError()
2180 << "call passes fewer arguments than the callee declares, which is "
2181 "not yet implemented in CallConvLowering";
2182
2183 if (!fc.needsRewrite())
2184 return mlir::success();
2185
2186 if (mlir::isa<cir::TryCallOp>(callOp))
2187 return callOp->emitOpError()
2188 << "TryCallOp not yet implemented in CallConvLowering";
2189
2190 auto call = mlir::cast<cir::CallOp>(callOp);
2191 mlir::MLIRContext *ctx = callOp->getContext();
2192 mlir::Block *slotBlock = coercionSlotBlock(call);
2193
2194 builder.setInsertionPoint(call);
2195
2197 mlir::ValueRange argOperands = call.getArgOperands();
2198 newArgs.reserve(argOperands.size());
2199
2200 // Loads that the new call leaves unused: a Direct (coerced or flattened) or
2201 // Expand record is read out of its load's storage or a copy of it, and an
2202 // Indirect argument passes or copies from the address the load read from.
2203 // The old call still uses them, so erase them only after it is gone.
2204 SmallVector<cir::LoadOp> deadRecordLoads;
2205 // Erased before deadRecordLoads, since a freeze keeps its load alive.
2206 SmallVector<cir::FreezeOp> deadFreezes;
2207
2208 // Capture original arg types before building newArgs (an Indirect argument
2209 // changes the wire argument from T to !cir.ptr<T>, so we save the
2210 // pre-rewrite types here for use in updateArgAttrs).
2211 SmallVector<mlir::Type> origCallArgTypes;
2212 llvm::append_range(origCallArgTypes, argOperands.getTypes());
2213
2214 // Operands past an indirect callee's declared parameters were passed
2215 // through its ellipsis. Note where they begin in newArgs, so
2216 // prependIndirectCallee can leave them out of the retyped callee type. A
2217 // direct call has no callee pointer to retype, so it records no boundary.
2218 unsigned numDeclared = fc.argInfos.size();
2219 if (call.isIndirect()) {
2220 numDeclared = getIndirectCalleeType(call).getNumInputs();
2221 assert(numDeclared <= fc.argInfos.size() &&
2222 "the classification covers at least the declared parameters");
2223 }
2224 // Recorded before the Ignore skip below, so an ignored first ellipsis
2225 // argument still marks where the ellipsis arguments begin in newArgs.
2226 std::optional<unsigned> ellipsisStart;
2227 // Where each argument starts in newArgs, and the freezes to reapply there
2228 // once every argument is rewritten.
2229 SmallVector<unsigned> argBegin;
2231 for (auto [idx, ac] : llvm::enumerate(fc.argInfos)) {
2232 if (idx == numDeclared)
2233 ellipsisStart = newArgs.size();
2234 argBegin.push_back(newArgs.size());
2235 mlir::Value arg = argOperands[idx];
2236 auto freeze = arg.getDefiningOp<cir::FreezeOp>();
2237 if (freeze && !freeze->hasOneUse())
2238 freeze = {};
2239 if (ac.kind == ArgKind::Ignore) {
2240 if (freeze)
2241 deadFreezes.push_back(freeze);
2242 continue;
2243 }
2244
2245 // Refreeze after the ABI rewrite, as classic CodeGen does, so padding is
2246 // frozen too. Indirect freezes only the pointer, so keep non-load freezes.
2247 if (freeze && ((ac.kind != ArgKind::Indirect &&
2248 ac.kind != ArgKind::IndirectAliased) ||
2249 freeze.getInput().getDefiningOp<cir::LoadOp>())) {
2250 arg = freeze.getInput();
2251 deadFreezes.push_back(freeze);
2252 refreezes.push_back({idx, freeze});
2253 }
2254 if (cir::RecordType flatTy = getFlattenedCoercedType(ac, dl)) {
2255 // Direct + canFlatten: pass one scalar call argument per field of the
2256 // ABI-coerced struct. A non-atomic record load is read in place or
2257 // through a copy of its storage, as emitCoercedRecordLoad decides, and
2258 // any other operand is stored into a coercion slot first. When the types
2259 // already match, the fields come from the struct value directly (reading
2260 // from its source alloca when possible).
2261 if (arg.getType() != flatTy) {
2262 SmallPtrSet<mlir::Operation *, 4> coercionOps;
2263 assert(!ac.directOffset &&
2264 "the coerced struct starts at slot offset 0 here, so a "
2265 "flattened coercion cannot honor a direct offset");
2266 if (failed(rejectAtomicRecordLoad(call, arg)))
2267 return mlir::failure();
2268 mlir::OpBuilder::InsertionGuard guard(builder);
2269 mlir::Value coercedPtr;
2270 uint64_t baseAlign = 0;
2271 if (cir::LoadOp recLoad = maybeGetCopyableRecordLoad(arg)) {
2272 mlir::Value base = recLoad.getAddr();
2273 if (!recLoad.getIsVolatile() &&
2274 canReadInPlace(recLoad, flatTy, cirDataLayout, /*offset=*/0)) {
2275 cir::AllocaOp baseAlloca = cir::getUnderlyingAlloca(base);
2276 assert(baseAlloca && "canReadInPlace requires an alloca");
2277 baseAlign = baseAlloca.getAlignment();
2278 } else {
2279 base = emitCopiedCoercionSlot(builder, call.getLoc(), recLoad,
2280 flatTy, slotBlock, dl, /*offset=*/0);
2281 }
2282 builder.setInsertionPoint(recLoad);
2283 coercedPtr = emitViewAtOffset(builder, call.getLoc(), flatTy, base,
2284 coercionOps, /*offset=*/0);
2285 deadRecordLoads.push_back(recLoad);
2286 } else {
2287 coercedPtr =
2288 emitCoercionToMemory(builder, call.getLoc(), flatTy, arg,
2289 slotBlock, dl, coercionOps, /*offset=*/0);
2290 }
2291 auto coercedPtrTy = mlir::cast<cir::PointerType>(coercedPtr.getType());
2292 for (auto [f, fieldTy] : llvm::enumerate(flatTy.getMembers())) {
2293 mlir::Type fieldPtrTy =
2294 cir::PointerType::get(fieldTy, coercedPtrTy.getAddrSpace());
2295 auto fieldPtr =
2296 cir::GetMemberOp::create(builder, call.getLoc(), fieldPtrTy,
2297 coercedPtr, /*name=*/"", /*index=*/f);
2298 auto field = cir::LoadOp::create(builder, call.getLoc(), fieldTy,
2299 fieldPtr.getResult());
2300 // Storage read in place may be less aligned than the coerced struct,
2301 // so each field claims only what its offset in it allows.
2302 if (baseAlign)
2303 field.setAlignment(
2304 llvm::MinAlign(baseAlign, flatTy.getElementOffset(dl, f)));
2305 newArgs.push_back(field);
2306 }
2307 } else {
2308 emitStructFieldArgs(builder, call.getLoc(), arg, flatTy, newArgs,
2309 deadRecordLoads);
2310 }
2311 } else if (ac.kind == ArgKind::Expand) {
2312 // Decompose the struct value into its constituent scalar fields and
2313 // pass each as a separate argument.
2314 auto recTy = cast<cir::RecordType>(arg.getType());
2315 assert(recTy.isStruct() &&
2316 "Expand classification requires a struct type, not a union");
2317 emitStructFieldArgs(builder, call.getLoc(), arg, recTy, newArgs,
2318 deadRecordLoads);
2319 } else if ((ac.kind == ArgKind::Direct && ac.coercedType &&
2320 arg.getType() != ac.coercedType) ||
2321 isRecordExtend(ac, arg.getType())) {
2322 if (failed(rejectAtomicRecordLoad(call, arg)))
2323 return mlir::failure();
2324 if (cir::LoadOp recLoad = maybeGetCopyableRecordLoad(arg)) {
2325 newArgs.push_back(emitCoercedRecordLoad(
2326 builder, call.getLoc(), recLoad, ac.coercedType, slotBlock, dl,
2327 cirDataLayout, ac.directOffset));
2328 deadRecordLoads.push_back(recLoad);
2329 } else {
2330 newArgs.push_back(emitCoercion(builder, call.getLoc(), ac.coercedType,
2331 arg, slotBlock, dl, ac.directOffset));
2332 }
2333 } else if (ac.kind == ArgKind::Indirect ||
2334 ac.kind == ArgKind::IndirectAliased) {
2335 uint64_t minAlign = ac.indirectAlign.value();
2336 // The callee copies a byref object at entry, so the caller treats it
2337 // like byval.
2338 bool byRef = ac.kind == ArgKind::IndirectAliased;
2339 bool byCopy = byRef || ac.byVal;
2340 bool fromCallerStorage =
2341 !byCopy && passesCallerStorage(module, arg.getType());
2342 cir::PointerType ptrTy = getIndirectPtrTy(arg.getType(), ac);
2343
2344 // A record operand that names storage is passed from that storage
2345 // rather than from the loaded value: a record value carries only the
2346 // fields of its type, so a store leaves the type's padding bytes
2347 // unwritten, and for a union those can be another member's live data.
2348 // A _BitInt is passed from its value, since the load and the store
2349 // below are its conversion between value and in-memory form.
2350 cir::LoadOp srcLoad;
2351 if (mlir::isa<cir::RecordType>(arg.getType()))
2352 srcLoad = maybeGetSimpleLoad(arg);
2353
2354 // A record passed from the caller's storage must name that storage, so
2355 // that the object the callee operates on is the one the caller
2356 // destroys. That means passing the address the operand was loaded from
2357 // rather than the loaded value, so a store to that storage after the
2358 // load is visible to the callee.
2359 if (fromCallerStorage) {
2360 mlir::Value fwdAddr = forwardableIndirectAddr(srcLoad, ptrTy, minAlign);
2361 if (!fwdAddr)
2362 return call->emitOpError()
2363 << "non-byval indirect argument that does not name the "
2364 "caller's storage is not yet implemented in "
2365 "CallConvLowering";
2366 newArgs.push_back(fwdAddr);
2367 deadRecordLoads.push_back(srcLoad);
2368 continue;
2369 }
2370
2371 // byval hands the callee a copy taken at the call, so naming the object's
2372 // own storage leaves it with the same copy and saves this one. That
2373 // holds only while nothing writes that storage between the load and the
2374 // call, since the operand carries the value as of the load. A volatile
2375 // load is not forwarded, since the copy byval takes at the call is not
2376 // volatile. Any other non-byval argument is copied to a temporary,
2377 // since the callee may write the memory it is passed.
2378 if (mlir::Value fwdAddr =
2379 byCopy ? forwardableIndirectAddr(srcLoad, ptrTy, minAlign)
2380 : mlir::Value();
2381 fwdAddr && storageUnwrittenBetween(srcLoad, call.getOperation(),
2382 aliasAnalysis)) {
2383 newArgs.push_back(fwdAddr);
2384 deadRecordLoads.push_back(srcLoad);
2385 continue;
2386 }
2387
2388 // A byref slot has to be an alloca of the parameter's own type, which
2389 // only the alloca address space can hold.
2390 if (byRef && ptrTy != getAllocaPtrTy(arg.getType(), dl))
2391 return call->emitOpError()
2392 << "byref argument outside the alloca address space that does "
2393 "not name forwardable storage is not yet implemented in "
2394 "CallConvLowering";
2395
2396 // Otherwise fill a slot, at the load's position when there is one so
2397 // the copy reads the memory state the load read.
2398 if (failed(rejectAtomicRecordLoad(call, arg)))
2399 return mlir::failure();
2400 if (!srcLoad)
2401 srcLoad = maybeGetCopyableRecordLoad(arg);
2402 mlir::IntegerAttr slotAlign = builder.getI64IntegerAttr(minAlign);
2403 mlir::OpBuilder::InsertionGuard guard(builder);
2404 if (srcLoad)
2405 builder.setInsertionPoint(srcLoad);
2406
2407 llvm::StringRef slotName =
2408 byRef ? "byref" : (ac.byVal ? "byval" : "indirect.tmp");
2409 auto slot =
2410 cir::AllocaOp::create(builder, call.getLoc(), ptrTy,
2411 builder.getStringAttr(slotName), slotAlign);
2412 if (srcLoad) {
2413 auto copy = cir::CopyOp::create(builder, call.getLoc(), slot,
2414 srcLoad.getAddr(), slotAlign,
2415 loadSourceAlignment(srcLoad, builder));
2416 copy.setIsVolatile(srcLoad.getIsVolatile());
2417 deadRecordLoads.push_back(srcLoad);
2418 } else {
2419 // A record with no storage behind it, such as a constant, defines no
2420 // bytes beyond its fields. A producer rewritten later turns this store
2421 // into a copy through rewireRecordUses.
2422 cir::StoreOp::create(builder, call.getLoc(), arg, slot);
2423 }
2424 newArgs.push_back(slot);
2425 } else {
2426 newArgs.push_back(arg);
2427 }
2428 }
2429 argBegin.push_back(newArgs.size());
2430 builder.setInsertionPoint(call);
2431 for (auto [idx, freeze] : refreezes)
2432 for (unsigned i = argBegin[idx]; i != argBegin[idx + 1]; ++i)
2433 newArgs[i] = cir::FreezeOp::create(builder, freeze.getLoc(), newArgs[i]);
2434 unsigned numEllipsisArgs =
2435 ellipsisStart ? newArgs.size() - *ellipsisStart : 0;
2436
2437 bool hasResult = call.getNumResults() > 0;
2438 mlir::Type origRetTy =
2439 hasResult ? call.getResult().getType() : cir::VoidType::get(ctx);
2440
2441 // An indirect (sret) return has a different call shape than the coerce /
2442 // extend / ignore return handling further down (the value is returned
2443 // through a prepended pointer slot, not as a result), so dispatch to a
2444 // dedicated helper for it; everything below handles the by-value returns.
2445 if (fc.returnInfo.kind == ArgKind::Indirect && hasResult) {
2446 if (failed(rewriteIndirectReturnCall(call, fc, newArgs, numEllipsisArgs,
2447 origRetTy, origCallArgTypes, builder,
2448 dl, enableNoundefAttrs)))
2449 return mlir::failure();
2450 eraseDeadFreezes(deadFreezes);
2451 eraseDeadRecordLoads(deadRecordLoads);
2452 return mlir::success();
2453 }
2454
2455 mlir::Type callRetTy = origRetTy;
2456 if (fc.returnInfo.kind == ArgKind::Ignore && hasResult)
2457 callRetTy = cir::VoidType::get(ctx);
2458 bool returnNeedsCoercion =
2459 hasResult && fc.returnInfo.kind == ArgKind::Direct &&
2460 fc.returnInfo.coercedType && fc.returnInfo.coercedType != origRetTy;
2461 if (returnNeedsCoercion)
2462 callRetTy = fc.returnInfo.coercedType;
2463
2464 builder.setInsertionPoint(call);
2465 prependIndirectCallee(call, newArgs, callRetTy, numEllipsisArgs, builder);
2466 auto newCall = cir::CallOp::create(builder, call.getLoc(),
2467 call.getCalleeAttr(), callRetTy, newArgs);
2468 copyCallAttributes(call, newCall);
2469
2470 // Direct return with coercion: the new call returns the coerced type, which
2471 // is stored into a coercion slot where the old call's uses find the original
2472 // type.
2473 if (returnNeedsCoercion) {
2474 builder.setInsertionPointAfter(newCall);
2475 SmallPtrSet<mlir::Operation *, 4> coercionOps;
2476 if (failed(emitCoercionAndReplaceUses(builder, call.getLoc(), origRetTy,
2477 newCall.getResult(), call.getResult(),
2478 slotBlock, dl, coercionOps,
2479 fc.returnInfo.directOffset)))
2480 return mlir::failure();
2481 }
2482
2483 if (needsArgAttrUpdate(fc)) {
2484 auto existing = call->getAttrOfType<mlir::ArrayAttr>("arg_attrs");
2485 newCall->setAttr("arg_attrs",
2486 updateArgAttrs(ctx, module, origCallArgTypes, existing, fc,
2487 dl, enableNoundefAttrs,
2488 /*isCallSite=*/true));
2489 }
2490 // Add llvm.signext / llvm.zeroext to an Extend return, and drop llvm.noundef
2491 // from a coerced Direct return that passes undefined bits.
2492 if (fc.returnInfo.kind == ArgKind::Extend ||
2493 (hasResult && fc.returnInfo.kind == ArgKind::Direct)) {
2494 auto existing = call->getAttrOfType<mlir::ArrayAttr>("res_attrs");
2495 if (mlir::ArrayAttr updated =
2496 updateResAttrs(ctx, existing, fc.returnInfo, origRetTy, dl))
2497 newCall->setAttr("res_attrs", updated);
2498 } else if (hasResult && mlir::isa<cir::VoidType>(callRetTy)) {
2499 newCall->removeAttr("res_attrs");
2500 }
2501
2502 if (hasResult && fc.returnInfo.kind == ArgKind::Ignore) {
2503 // The new call returns void, but the original call's result may still
2504 // have uses. Substitute a poison constant of the original type so
2505 // those uses remain well-formed without pretending we have a real
2506 // value at the ABI boundary.
2507 if (!call.getResult().use_empty()) {
2508 builder.setInsertionPointAfter(newCall);
2509 mlir::Value poison =
2510 createIgnoredValue(builder, call.getLoc(), origRetTy);
2511 call.getResult().replaceAllUsesWith(poison);
2512 }
2513 } else if (hasResult && !returnNeedsCoercion) {
2514 // returnNeedsCoercion already wired up the coerced result above.
2515 call.getResult().replaceAllUsesWith(newCall.getResult());
2516 }
2517
2518 call->erase();
2519 eraseDeadFreezes(deadFreezes);
2520 eraseDeadRecordLoads(deadRecordLoads);
2521
2522 return mlir::success();
2523}
2524
2526 cir::FuncOp funcOp,
2527 mlir::OpBuilder &builder) {
2528 auto oldPtrTy = mlir::cast<cir::PointerType>(addrOp.getAddr().getType());
2529 cir::FuncType newFuncTy = funcOp.getFunctionType();
2530 // An extension rides on an argument attribute and leaves the signature
2531 // alone, so such a callee still matches the written type.
2532 if (newFuncTy == oldPtrTy.getPointee())
2533 return;
2534
2535 // The verifier requires the retype even when nothing reads the address.
2536 addrOp.getAddr().setType(cir::PointerType::get(newFuncTy));
2537 if (addrOp.getAddr().use_empty())
2538 return;
2539
2540 // A later indirect call through the written type is classified and coerced
2541 // on its own, so casting back leaves it to that rewrite.
2542 mlir::OpBuilder::InsertionGuard guard(builder);
2543 builder.setInsertionPointAfter(addrOp);
2544 auto bitcast = cir::CastOp::create(builder, addrOp.getLoc(), oldPtrTy,
2545 cir::CastKind::bitcast, addrOp.getAddr());
2546 addrOp.getAddr().replaceAllUsesExcept(bitcast.getResult(), bitcast);
2547}
2548
2549namespace {
2550
2551/// What one `va_arg` expansion needs from the op it rewrites. The x86-64
2552/// cursor fields are reached through `vaFields` by index: 0 gp_offset,
2553/// 1 fp_offset, 2 overflow_arg_area, 3 reg_save_area.
2554struct VAArgFetch {
2555 VAArgFetch(mlir::Location loc, mlir::Value valist,
2556 llvm::ArrayRef<mlir::Type> vaFields, mlir::Type resultTy,
2557 const ArgClassification &ac, const mlir::DataLayout &dl,
2558 mlir::ModuleOp module)
2559 : loc(loc), valist(valist), vaFields(vaFields), resultTy(resultTy),
2560 ac(ac), dl(dl), module(module) {
2561 assert(vaFields.size() == 4 &&
2562 "the x86-64 va_list is a four-field cursor, checked by the caller");
2563 }
2564
2565 mlir::Location loc;
2566 mlir::Value valist;
2568 mlir::Type resultTy;
2569 const ArgClassification &ac;
2570 const mlir::DataLayout &dl;
2571 mlir::ModuleOp module;
2572};
2573
2574/// The cursor fields a register fetch reads, and the predicate saying every
2575/// class it needs still has room. An offset is null when the fetch needs no
2576/// register of that class.
2577struct RegisterCursor {
2578 mlir::Value gpOffsetP;
2579 mlir::Value fpOffsetP;
2580 mlir::Value gpOffset;
2581 mlir::Value fpOffset;
2582 mlir::Value inRegs;
2583};
2584
2585mlir::LogicalResult reportVAArgNYI(cir::VAArgOp op, llvm::StringRef what) {
2586 op->emitOpError() << "va_arg of " << what
2587 << " not yet implemented in CallConvLowering";
2588 return mlir::failure();
2589}
2590
2591/// Sets \p isRegPair when a two-register argument is a coerced pair, one
2592/// register per member, rather than a single wide scalar, and records in
2593/// \p pairIsSse which element is SSE class. Fails on a coercion that is not
2594/// two eightbytes.
2595mlir::LogicalResult classifyRegisterPair(cir::VAArgOp op,
2596 const ArgClassification &ac,
2597 std::array<bool, 2> &pairIsSse,
2598 bool &isRegPair) {
2599 auto pairTy = mlir::dyn_cast<cir::RecordType>(ac.coercedType);
2600 if (!pairTy)
2601 return mlir::success();
2602
2603 if (pairTy.getNumElements() != 2)
2604 return reportVAArgNYI(op, "a register coercion that is not two eightbytes");
2605
2606 assert(!ac.directOffset &&
2607 "a pair already spans both eightbytes, so it cannot also start "
2608 "partway into the value");
2609 for (auto [i, memberTy] : llvm::enumerate(pairTy.getMembers()))
2610 pairIsSse[i] = isSSERegisterClass(memberTy);
2611 isRegPair = true;
2612 return mlir::success();
2613}
2614
2615/// The alignment an argument is placed at, which is the language alignment of
2616/// its type.
2617uint64_t argumentAreaAlign(mlir::Type ty, mlir::ModuleOp modOp) {
2618 return cir::CIRDataLayout(modOp).getTypeLanguageAlignment(ty);
2619}
2620
2621mlir::Value roundPointerUpToAlignment(CIRBaseBuilderTy &b, mlir::Location loc,
2622 mlir::Value bytePtr, uint64_t align,
2623 const mlir::DataLayout &dl) {
2624 assert(mlir::cast<cir::PointerType>(bytePtr.getType()).getPointee() ==
2625 b.getUIntNTy(8) &&
2626 "the bump strides in bytes, so the pointee must be u8");
2627 assert(llvm::isPowerOf2_64(align) &&
2628 "mask rounding needs a power-of-two alignment");
2629 mlir::Value bumped =
2630 b.createPtrStride(loc, bytePtr, b.getSignedInt(loc, align - 1, 32));
2631 std::optional<uint64_t> indexWidth =
2632 dl.getTypeIndexBitwidth(bytePtr.getType());
2633 assert(indexWidth && "a pointer in the argument area has an index width");
2634 mlir::Value mask = b.getSignedInt(loc, -static_cast<int64_t>(align),
2635 static_cast<unsigned>(*indexWidth));
2636 return cir::PtrMaskOp::create(b, loc, bytePtr.getType(), bumped, mask);
2637}
2638
2639/// Reads the argument's address out of the overflow area, which also advances
2640/// the cursor past the argument.
2641mlir::Value buildOverflowAddrAndAdvance(CIRBaseBuilderTy &b,
2642 const VAArgFetch &f) {
2643 cir::IntType byteTy = b.getUIntNTy(8);
2644 mlir::Value overflowP = b.createGetMember(
2645 f.loc, b.getPointerTo(f.vaFields[2]), f.valist, "overflow_arg_area", 2);
2646 mlir::Value overflow = b.createLoad(f.loc, overflowP);
2647 mlir::Value bytePtr = b.createPtrBitcast(overflow, byteTy);
2648
2649 uint64_t tyAlign = argumentAreaAlign(f.resultTy, f.module);
2650 if (tyAlign > 8)
2651 bytePtr = roundPointerUpToAlignment(b, f.loc, bytePtr, tyAlign, f.dl);
2652
2653 uint64_t stride =
2654 llvm::alignTo(f.dl.getTypeAllocSize(f.resultTy).getFixedValue(), 8);
2655 mlir::Value strideVal = b.getSignedInt(f.loc, stride, 32);
2656 mlir::Value next = b.createPtrStride(f.loc, bytePtr, strideVal);
2657 b.createStore(f.loc, next, overflowP);
2658 return bytePtr;
2659}
2660
2661/// Loads the cursor offsets and builds the predicate that sends the fetch to
2662/// the register-save area. Both offsets count from the start of that area, so
2663/// the integer limit is the six GP registers at 48 and the vector limit is
2664/// those plus the eight SSE registers at 176.
2665RegisterCursor buildRegisterGate(CIRBaseBuilderTy &b, const VAArgFetch &f,
2666 unsigned neededInt, unsigned neededSse) {
2667 RegisterCursor cursor;
2668 if (neededInt) {
2669 cursor.gpOffsetP = b.createGetMember(f.loc, b.getPointerTo(f.vaFields[0]),
2670 f.valist, "gp_offset", 0);
2671 cursor.gpOffset = b.createLoad(f.loc, cursor.gpOffsetP);
2672 mlir::Value limit =
2673 b.getConstantInt(f.loc, cursor.gpOffset.getType(), 48 - neededInt * 8);
2674 cursor.inRegs =
2675 b.createCompare(f.loc, cir::CmpOpKind::le, cursor.gpOffset, limit);
2676 }
2677 if (neededSse) {
2678 cursor.fpOffsetP = b.createGetMember(f.loc, b.getPointerTo(f.vaFields[1]),
2679 f.valist, "fp_offset", 1);
2680 cursor.fpOffset = b.createLoad(f.loc, cursor.fpOffsetP);
2681 mlir::Value limit = b.getConstantInt(f.loc, cursor.fpOffset.getType(),
2682 176 - neededSse * 16);
2683 mlir::Value fitsInFp =
2684 b.createCompare(f.loc, cir::CmpOpKind::le, cursor.fpOffset, limit);
2685 cursor.inRegs = cursor.inRegs
2686 ? b.createLogicalAnd(f.loc, cursor.inRegs, fitsInFp)
2687 : fitsInFp;
2688 }
2689 return cursor;
2690}
2691
2692/// Copies each half of a non-contiguous pair out of the register-save area
2693/// into \p regPairTemp, laid out as the coerced pair.
2694void reassembleRegisterPair(CIRBaseBuilderTy &b, mlir::Location loc,
2695 const ArgClassification &ac,
2696 const RegisterCursor &cursor,
2697 const std::array<bool, 2> &pairIsSse,
2698 mlir::Value regSaveArea, mlir::Value regPairTemp) {
2699 auto pairTy = mlir::cast<cir::RecordType>(ac.coercedType);
2700 // Both halves of an all-SSE pair sit in 16-byte slots, which classic
2701 // CodeGen tells the load about. It leaves a mixed pair to the element's
2702 // own alignment, so match that rather than claiming the slot there.
2703 bool bothSse = pairIsSse[0] && pairIsSse[1];
2704 // Track how many of each class came before, since a slot is reached from
2705 // its class's own cursor.
2706 unsigned seenOfClass[2] = {0, 0};
2707 for (unsigned i = 0; i < 2; ++i) {
2708 bool isSse = pairIsSse[i];
2709 mlir::Value base = isSse ? cursor.fpOffset : cursor.gpOffset;
2710 unsigned regSize = isSse ? 16 : 8;
2711 unsigned prior = seenOfClass[isSse];
2712 ++seenOfClass[isSse];
2713 mlir::Value off = base;
2714 if (prior) {
2715 off = b.createAdd(loc, base,
2716 b.getConstantInt(loc, base.getType(), prior * regSize));
2717 }
2718 mlir::Value src = b.createPtrStride(loc, regSaveArea, off);
2719 mlir::Type elemTy = pairTy.getElementType(i);
2720 mlir::Value elemPtr = b.createPtrBitcast(src, elemTy);
2721 mlir::Value val = bothSse ? b.createAlignedLoad(loc, elemPtr, 16)
2722 : b.createLoad(loc, elemPtr);
2723 b.createStore(
2724 loc, val,
2725 b.createGetMember(loc, b.getPointerTo(elemTy), regPairTemp, "", i));
2726 }
2727}
2728
2729/// The bytes carried by the registers of this fetch's one class.
2730uint64_t registerSlotSize(unsigned neededInt, unsigned neededSse) {
2731 assert(!(neededInt && neededSse) &&
2732 "a fetch needing both classes is a pair, reassembled elsewhere");
2733 return neededSse ? neededSse * 16 : neededInt * 8;
2734}
2735
2736/// Whether the register cannot be read in place, either because it carries
2737/// less than the whole result or because its slot is under-aligned for it.
2738bool needsTempCopy(const VAArgFetch &f, unsigned neededInt,
2739 unsigned neededSse) {
2740 uint64_t tySize = f.dl.getTypeSize(f.resultTy).getFixedValue();
2741 if (f.ac.coercedType &&
2742 (f.ac.directOffset || registerSlotSize(neededInt, neededSse) < tySize))
2743 return true;
2744 // A slot is only as aligned as its class, 8 for a GP register and 16 for an
2745 // SSE one, so a fetch the ABI places more strictly is copied through a temp.
2746 uint64_t slotAlign = neededSse ? 16 : 8;
2747 return argumentAreaAlign(f.resultTy, f.module) > slotAlign;
2748}
2749
2750/// Copies what the registers carry into \p temp, which is the size of the
2751/// whole result, and returns the address to read the result from.
2752mlir::Value copyRegisterToTemp(CIRBaseBuilderTy &b, mlir::Location loc,
2753 const VAArgFetch &f, mlir::Value regAddr,
2754 mlir::Value temp, unsigned neededInt,
2755 unsigned neededSse) {
2756 cir::IntType byteTy = b.getUIntNTy(8);
2757 uint64_t tySize = f.dl.getTypeSize(f.resultTy).getFixedValue();
2758
2759 if (f.ac.coercedType &&
2760 (f.ac.directOffset || registerSlotSize(neededInt, neededSse) < tySize)) {
2761 // The registers carry less than the whole result, either because the
2762 // eightbytes below directOffset hold no field or because the result is
2763 // wider than the registers carrying it. Copy only what they carry, so
2764 // that reading the temp cannot run on into the neighboring slot.
2765 mlir::Value val = b.createAlignedLoad(
2766 loc, b.createPtrBitcast(regAddr, f.ac.coercedType), 8);
2767 mlir::Value dst = temp;
2768 if (f.ac.directOffset) {
2769 mlir::Value tempByte = b.createPtrBitcast(temp, byteTy);
2770 mlir::Value offset = b.getSignedInt(loc, f.ac.directOffset, 32);
2771 dst = b.createPtrStride(loc, tempByte, offset);
2772 }
2773 b.createStore(loc, val, b.createPtrBitcast(dst, f.ac.coercedType));
2774 return b.createPtrBitcast(temp, byteTy);
2775 }
2776
2777 mlir::Value regView = b.createPtrBitcast(regAddr, f.resultTy);
2778 if (mlir::isa<cir::RecordType>(f.resultTy))
2779 cir::CopyOp::create(
2780 b, loc, temp, regView,
2781 b.getI64IntegerAttr(argumentAreaAlign(f.resultTy, f.module)),
2782 b.getI64IntegerAttr(8));
2783 else
2784 b.createStore(loc, b.createAlignedLoad(loc, regView, 8), temp);
2785 return b.createPtrBitcast(temp, byteTy);
2786}
2787
2788void advanceRegisterCursors(CIRBaseBuilderTy &b, mlir::Location loc,
2789 const RegisterCursor &cursor, unsigned neededInt,
2790 unsigned neededSse) {
2791 if (neededInt) {
2792 b.createStore(loc,
2793 b.createAdd(loc, cursor.gpOffset,
2794 b.getConstantInt(loc, cursor.gpOffset.getType(),
2795 neededInt * 8)),
2796 cursor.gpOffsetP);
2797 }
2798 if (neededSse) {
2799 b.createStore(loc,
2800 b.createAdd(loc, cursor.fpOffset,
2801 b.getConstantInt(loc, cursor.fpOffset.getType(),
2802 neededSse * 16)),
2803 cursor.fpOffsetP);
2804 }
2805}
2806
2807/// Advances the pointer cursor at \p valist past the argument's slots and
2808/// returns the argument's address, which is the old cursor.
2809mlir::Value buildSlotAddrAndAdvance(CIRBaseBuilderTy &b, mlir::Location loc,
2810 mlir::Value valist, mlir::Type resultTy,
2811 uint64_t slotSize,
2812 const mlir::DataLayout &dl) {
2813 mlir::Value cur = b.createLoad(loc, valist);
2814 mlir::Value bytePtr = b.createPtrBitcast(cur, b.getUIntNTy(8));
2815 uint64_t stride =
2816 llvm::alignTo(dl.getTypeAllocSize(resultTy).getFixedValue(), slotSize);
2817 mlir::Value next =
2818 b.createPtrStride(loc, bytePtr, b.getSignedInt(loc, stride, 32));
2819 b.createStore(loc, b.createBitcast(next, cur.getType()), valist);
2820 return bytePtr;
2821}
2822
2823/// Replaces \p op's result with the value at \p addr, which is \p align
2824/// aligned, and erases \p op.
2825mlir::LogicalResult replaceVAArgResult(CIRBaseBuilderTy &b, cir::VAArgOp op,
2826 mlir::Value addr, uint64_t align,
2827 const mlir::DataLayout &dl) {
2828 mlir::Location loc = op.getLoc();
2829 mlir::Type resultTy = op.getType();
2830 mlir::Value resultAddr = b.createPtrBitcast(addr, resultTy);
2831 if (mlir::isa<cir::RecordType>(resultTy)) {
2832 SmallPtrSet<mlir::Operation *, 1> noExceptions;
2833 if (failed(rewireRecordUses(b, loc, op.getResult(), resultAddr, align, dl,
2834 noExceptions)))
2835 return mlir::failure();
2836 } else {
2837 op.getResult().replaceAllUsesWith(
2838 b.createAlignedLoad(loc, resultAddr, align));
2839 }
2840 op->erase();
2841 return mlir::success();
2842}
2843
2844} // namespace
2845
2846mlir::LogicalResult
2847CIRABIRewriteContext::rewriteVAArg(mlir::Operation *vaArgOp,
2848 const ArgClassification &ac,
2849 mlir::OpBuilder &opBuilder) {
2850 auto op = mlir::cast<cir::VAArgOp>(vaArgOp);
2851 CIRBaseBuilderTy builder(opBuilder);
2852
2853 // An ignored type travels in no register and no stack slot, so the fetch
2854 // reads nothing and must leave the cursor unchanged. The value holds no
2855 // bytes, so poison stands in for it.
2856 if (ac.kind == ArgKind::Ignore) {
2857 builder.setInsertionPoint(op);
2858 op.getResult().replaceAllUsesWith(
2859 createIgnoredValue(builder, op.getLoc(), op.getType()));
2860 op->erase();
2861 return mlir::success();
2862 }
2863
2864 switch (target) {
2866 return rewriteVAArgX86_64(op, ac, builder);
2868 return rewriteVAArgAMDGPU(op, ac, builder);
2873 break;
2874 }
2875 return reportVAArgNYI(op, "a type on this target");
2876}
2877
2878mlir::LogicalResult CIRABIRewriteContext::rewriteVAArgAMDGPU(
2879 cir::VAArgOp op, const ArgClassification &ac, CIRBaseBuilderTy &builder) {
2880 assert(ac.kind == ArgKind::Direct && !ac.coercedType && ac.directAlign &&
2881 "AMDGPU reads every variadic argument in place from its slots");
2882 builder.setInsertionPoint(op);
2883 uint64_t slotSize = ac.directAlign->value();
2884 mlir::Value addr = buildSlotAddrAndAdvance(
2885 builder, op.getLoc(), op.getArgList(), op.getType(), slotSize, dl);
2886 return replaceVAArgResult(builder, op, addr, slotSize, dl);
2887}
2888
2889mlir::LogicalResult CIRABIRewriteContext::rewriteVAArgX86_64(
2890 cir::VAArgOp op, const ArgClassification &ac, CIRBaseBuilderTy &builder) {
2891 mlir::Location loc = op.getLoc();
2892 mlir::Type resultTy = op.getType();
2893 mlir::Value valist = op.getArgList();
2894
2895 if (ac.kind == ArgKind::Indirect && !ac.byVal)
2896 return reportVAArgNYI(op, "a non-trivially-copyable type");
2897 if (ac.kind == ArgKind::IndirectAliased)
2898 return reportVAArgNYI(op, "a type passed byref");
2899
2900 // neededInt counts 8-byte integer slots and neededSse counts 16-byte vector
2901 // slots. Zero of both means the type travels in memory and is read
2902 // straight from the overflow area.
2903 unsigned neededInt = ac.neededIntRegs;
2904 unsigned neededSse = ac.neededSseRegs;
2905
2906 // Which coerced-pair element (0 = low eightbyte, 1 = high) is SSE rather
2907 // than INTEGER class. Only meaningful when isRegPair is set.
2908 std::array<bool, 2> pairIsSse = {false, false};
2909 bool isRegPair = false;
2910 if (ac.kind == ArgKind::Direct && neededInt + neededSse == 2 &&
2911 ac.coercedType) {
2912 if (classifyRegisterPair(op, ac, pairIsSse, isRegPair).failed())
2913 return mlir::failure();
2914 }
2915
2916 auto vaListRecTy = mlir::dyn_cast<cir::RecordType>(
2917 mlir::cast<cir::PointerType>(valist.getType()).getPointee());
2918 if (!vaListRecTy || vaListRecTy.getNumElements() != 4) {
2919 return reportVAArgNYI(op,
2920 "a va_list that is not the four-field gp_offset / "
2921 "fp_offset / overflow_arg_area / reg_save_area "
2922 "cursor");
2923 }
2924
2925 const VAArgFetch fetch{loc, valist, vaListRecTy.getMembers(), resultTy, ac,
2926 dl, module};
2927 cir::IntType byteTy = builder.getUIntNTy(8);
2928
2929 builder.setInsertionPoint(op);
2930
2931 mlir::Value addr;
2932 if (neededInt == 0 && neededSse == 0) {
2933 addr = buildOverflowAddrAndAdvance(builder, fetch);
2934 } else {
2935 RegisterCursor cursor =
2936 buildRegisterGate(builder, fetch, neededInt, neededSse);
2937
2938 // A two-eightbyte pair that is purely INTEGER class is contiguous in the
2939 // register-save area, since GP slots are 8-byte packed, so the address of
2940 // its low eightbyte is already the address of the whole value. A pure
2941 // SSE pair or a mixed pair is not contiguous, since SSE slots are 16-byte
2942 // spaced and a mixed pair's halves live in disjoint areas, so each half is
2943 // copied into a temp laid out as the coerced pair.
2944 bool pairNeedsReassembly = isRegPair && neededSse != 0;
2945
2946 // Both temps are allocated here, since a ternary arm yields their address.
2947 mlir::Value regPairTemp;
2948 if (pairNeedsReassembly) {
2949 // The temp is written one member at a time through the coerced pair, so
2950 // it has to meet that type's alignment, and read back as the result, so
2951 // it has to meet the result's alignment too.
2952 regPairTemp = builder.createAlloca(
2953 loc, builder.getPointerTo(ac.coercedType), "vaarg.reg",
2955 std::max(cirDataLayout.getTypeLanguageAlignment(ac.coercedType),
2956 argumentAreaAlign(resultTy, module))));
2957 }
2958
2959 mlir::Value regTemp;
2960 bool copyThroughTemp =
2961 !pairNeedsReassembly && needsTempCopy(fetch, neededInt, neededSse);
2962 if (copyThroughTemp) {
2963 regTemp = builder.createAlloca(
2964 loc, builder.getPointerTo(resultTy), "vaarg.reg",
2965 clang::CharUnits::fromQuantity(argumentAreaAlign(resultTy, module)));
2966 }
2967
2968 addr = cir::TernaryOp::create(
2969 builder, loc, cursor.inRegs,
2970 /*trueBuilder=*/
2971 [&](mlir::OpBuilder &ob, mlir::Location l) {
2972 CIRBaseBuilderTy b(ob);
2973 mlir::Value regSaveArea = b.createLoad(
2974 l, b.createGetMember(l, b.getPointerTo(fetch.vaFields[3]),
2975 valist, "reg_save_area", 3));
2976 regSaveArea = b.createPtrBitcast(regSaveArea, byteTy);
2977
2978 mlir::Value regAddr;
2979 if (pairNeedsReassembly) {
2980 reassembleRegisterPair(b, l, ac, cursor, pairIsSse,
2981 regSaveArea, regPairTemp);
2982 regAddr = b.createPtrBitcast(regPairTemp, byteTy);
2983 } else {
2984 mlir::Value off =
2985 neededSse ? cursor.fpOffset : cursor.gpOffset;
2986 regAddr = b.createPtrStride(l, regSaveArea, off);
2987 if (copyThroughTemp) {
2988 regAddr = copyRegisterToTemp(b, l, fetch, regAddr, regTemp,
2989 neededInt, neededSse);
2990 }
2991 }
2992
2993 advanceRegisterCursors(b, l, cursor, neededInt, neededSse);
2994 cir::YieldOp::create(b, l, regAddr);
2995 },
2996 /*falseBuilder=*/
2997 [&](mlir::OpBuilder &ob, mlir::Location l) {
2998 CIRBaseBuilderTy b(ob);
2999 mlir::Value memAddr = buildOverflowAddrAndAdvance(b, fetch);
3000 cir::YieldOp::create(b, l, memAddr);
3001 })
3002 .getResult();
3003 }
3004
3005 // Every path above places the result at least this well aligned.
3006 return replaceVAArgResult(builder, op, addr,
3007 argumentAreaAlign(resultTy, module), dl);
3008}
static mlir::LogicalResult prepareOneNonByvalParameter(cir::FuncOp funcOp, unsigned argNo, const ArgClassification &ac, mlir::BlockArgument blockArg, mlir::DominanceInfo &dom, SmallPtrSetImpl< mlir::Operation * > &claimedSlots)
Bring funcOp's non-byval indirect parameter argNo into the shape the rest of the rewrite assumes.
*collection of selector each with an associated kind and an ordered *collection of selectors A selector has a kind
void rewriteFunctionAddress(cir::GetGlobalOp addrOp, cir::FuncOp funcOp, mlir::OpBuilder &builder)
Retype addrOp, which holds the address of funcOp, to the signature funcOp was rewritten to,...
mlir::LogicalResult rewriteFunctionDefinition(mlir::FunctionOpInterface funcOp, const mlir::abi::FunctionClassification &fc, mlir::OpBuilder &builder) override
void finalizeParameterSlots()
Replace each non-byval indirect parameter's spill slot with the incoming pointer, so the body operate...
mlir::LogicalResult prepareNonByvalParameters(cir::FuncOp funcOp, const mlir::abi::FunctionClassification &fc)
Bring each non-byval indirect parameter of funcOp into the shape the rest of the rewrite assumes: the...
mlir::LogicalResult rewriteVAArg(mlir::Operation *vaArgOp, const mlir::abi::ArgClassification &ac, mlir::OpBuilder &builder) override
Expand a cir.va_arg with the va_arg rules of the target this context lowers for.
mlir::LogicalResult rewriteCallSite(mlir::Operation *callOp, const mlir::abi::FunctionClassification &fc, mlir::OpBuilder &builder) override
mlir::Value createAdd(mlir::Location loc, mlir::Value lhs, mlir::Value rhs, OverflowFlags flags=OverflowFlags::None)
cir::PtrStrideOp createPtrStride(mlir::Location loc, mlir::Value base, mlir::Value stride)
cir::GetMemberOp createGetMember(mlir::Location loc, mlir::Type resultTy, mlir::Value base, llvm::StringRef name, unsigned index)
cir::PointerType getPointerTo(mlir::Type ty)
cir::IntType getUIntNTy(int n)
mlir::Value createPtrBitcast(mlir::Value src, mlir::Type newPointeeTy)
mlir::Value createAlloca(mlir::Location loc, cir::PointerType addrType, llvm::StringRef name, mlir::IntegerAttr alignment, mlir::Value dynAllocSize)
cir::LoadOp createLoad(mlir::Location loc, mlir::Value ptr, bool isVolatile=false, uint64_t alignment=0, bool isNontemporal=false)
mlir::Value getSignedInt(mlir::Location loc, int64_t val, unsigned numBits)
mlir::Value createBitcast(mlir::Value src, mlir::Type newTy)
cir::CmpOp createCompare(mlir::Location loc, cir::CmpOpKind kind, mlir::Value lhs, mlir::Value rhs)
cir::ConstantOp getConstantInt(mlir::Location loc, mlir::Type ty, int64_t value)
mlir::Value createAlignedLoad(mlir::Location loc, mlir::Value ptr, uint64_t alignment)
mlir::Value createLogicalAnd(mlir::Location loc, mlir::Value lhs, mlir::Value rhs)
cir::StoreOp createStore(mlir::Location loc, mlir::Value val, mlir::Value dst, bool isVolatile=false, bool isNontemporal=false, mlir::IntegerAttr align={}, cir::SyncScopeKindAttr scope={}, cir::MemOrderAttr order={})
uint64_t getTypeLanguageAlignment(mlir::Type ty) const
Returns the alignment, in bytes, that the source language requires for an object of type ty.
llvm::TypeSize getTypeAllocSize(mlir::Type ty) const
Returns the offset in bytes between successive objects of the specified type, including alignment pad...
llvm::TypeSize getTypeStoreSize(mlir::Type ty) const
Returns the maximum number of bytes that may be overwritten by storing the specified type.
C++ view class that accepts both !cir.struct and !cir.union types.
Definition CIRTypes.h:150
llvm::ArrayRef< mlir::Type > getMembers() const
Definition CIRTypes.cpp:648
static llvm::SmallVector< RecordMemberKind > getAllDataKinds(llvm::ArrayRef< mlir::Type > members)
One Data kind per member.
Definition CIRTypes.cpp:151
bool isStruct() const
Definition CIRTypes.cpp:683
size_t getNumElements() const
Definition CIRTypes.h:188
static CharUnits fromQuantity(QuantityType Quantity)
Construct a CharUnits quantity from a raw integer type.
Definition CharUnits.h:58
RecordLayoutAttr tryGetRecordLayout(mlir::ModuleOp mod, mlir::StringAttr name)
Same lookup as getRecordLayout, but returns a null attribute instead of asserting when the record has...
bool memberOwnsBytes(mlir::Type memberTy)
Whether a record member occupies bytes of its record.
Definition CIRTypes.h:126
cir::FuncType getIndirectCalleeType(cir::CIRCallOpInterface call)
The signature the indirect call call reaches its callee through.
AllocaOp getUnderlyingAlloca(mlir::Value addr)
The alloca that defines addr, looking through casts that preserve the underlying storage.
const internal::VariadicAllOfMatcher< Attr > attr
RangeSelector member(std::string ID)
Given a MemberExpr, selects the member token. ID is the node's binding in the match result.
U cast(CodeGen::Address addr)
Definition Address.h:327
__builtin_elementwise_add_sat __builtin_elementwise_sub_sat uint32_t int64_t
__builtin_elementwise_add_sat __builtin_elementwise_sub_sat uint32_t uint64_t __builtin_riscv_ssha_i32 __builtin_riscv_sshl_u32 uint64_t
static bool noaliasOnByvalAttr()