diff --git a/clang/lib/CIR/Dialect/Transforms/CallConvLoweringPass.cpp b/clang/lib/CIR/Dialect/Transforms/CallConvLoweringPass.cpp index c429aded2ec47..d0d8479ae89ab 100644 --- a/clang/lib/CIR/Dialect/Transforms/CallConvLoweringPass.cpp +++ b/clang/lib/CIR/Dialect/Transforms/CallConvLoweringPass.cpp @@ -484,14 +484,16 @@ static const llvm::abi::Type *mapCIRType(mlir::Type type, /// CIRABIRewriteContext. /// /// Direct: the value passes in register(s). A coercion is forwarded in the -/// three cases where the value has to be rebuilt on the wire: an aggregate +/// four cases where the value has to be rebuilt on the wire: an aggregate /// unpacked into the register(s) holding it, a scalar too wide for one register -/// split into a tuple of them, and a scalar the classifier widens to fill its -/// eightbyte. getDirect keeps canFlatten set so the rewriter can split a -/// multi-field coerced struct into individual wire arguments. Any other scalar -/// passes in its natural CIR type, which a null coercion denotes. A coercion -/// this bridge cannot represent yields std::nullopt so the caller reports NYI -/// rather than silently passing the value unchanged. +/// split into a tuple of them, a scalar the classifier widens to fill its +/// eightbyte, and a value whose live bytes start partway into its storage +/// because a leading eightbyte holds no field (getDirectOffset). getDirect +/// keeps canFlatten set so the rewriter can split a multi-field coerced +/// struct into individual wire arguments. Any other scalar passes in its +/// natural CIR type, which a null coercion denotes. A coercion this bridge +/// cannot represent yields std::nullopt so the caller reports NYI rather than +/// silently passing the value unchanged. /// /// Extend: bool or a sub-register integer needs a signext/zeroext attribute. /// The x86_64 classifier (llvm/lib/ABI/Targets/X86.cpp) only returns Extend @@ -506,11 +508,7 @@ static std::optional convertABIArgInfo(const llvm::abi::ArgInfo &info, MLIRContext *ctx, mlir::Type origTy) { if (info.isDirect()) { - // The rewriter reads a coercion from the start of the value's storage, so a - // classification naming an offset into it has no representation here. The - // classifier names one when the low eightbyte holds no field. - if (info.getDirectOffset()) - return std::nullopt; + unsigned offset = info.getDirectOffset(); // The classifier names a coerce type even where it matches the natural // type, so a non-null coerce does not by itself mean a rewrite is needed. const llvm::abi::Type *coerceAbi = info.getCoerceToType(); @@ -521,6 +519,10 @@ convertABIArgInfo(const llvm::abi::ArgInfo &info, MLIRContext *ctx, coerceAbi && isa_and_present(origTy); bool coerceIsRegisterTuple = isa_and_present(coerceAbi); + // A tuple coercion cannot be read at an offset, so refuse the pair rather + // than emit a read of the wrong bytes. + if (offset && coerceIsRegisterTuple) + return std::nullopt; // Compare widths rather than identity: a coerce no wider than the natural // type carries the same value and needs no rewrite. auto origInt = dyn_cast_if_present(origTy); @@ -531,19 +533,27 @@ convertABIArgInfo(const llvm::abi::ArgInfo &info, MLIRContext *ctx, coerceInt->getSizeInBits().getFixedValue() > origInt.getWidth(); // Leaving the rest alone also avoids a lossy round trip: abiTypeToCIR // drops the LongDoubleType wrapper and a pointer's pointee, so comparing a - // scalar against its own coerce would report a difference that is not one. - if (!isAggregate && !comparesAgainstCoerce && !coerceIsRegisterTuple && - !coerceWidensScalar) - return ArgClassification::getDirect(nullptr); + // scalar against its own coerce would report a difference that is not + // one. Passing a value through reads it from byte 0, so one living at + // an offset cannot take this path. + if (!offset && !isAggregate && !comparesAgainstCoerce && + !coerceIsRegisterTuple && !coerceWidensScalar) + return ArgClassification::getDirect(); mlir::Type coerced = abiTypeToCIR(coerceAbi, ctx); if (!coerced) return std::nullopt; + // An offset would be lost here, since a coercion to the value's own type + // is indistinguishable from no coercion at all. + if (offset && coerced == origTy) + return std::nullopt; // Coercing a value to the type it already has would add a memory round // trip for nothing. if (comparesAgainstCoerce && coerced == origTy) - return ArgClassification::getDirect(nullptr); - return ArgClassification::getDirect(coerced); + return ArgClassification::getDirect(); + return ArgClassification::getDirect(offset, coerced); } + // An extended value is always read from byte 0 of its own storage, so + // there is no offset to honor here. if (info.isExtend()) { if (isa_and_present(origTy)) return ArgClassification::getExtend(nullptr, info.isSignExt()); diff --git a/clang/lib/CIR/Dialect/Transforms/TargetLowering/CIRABIRewriteContext.cpp b/clang/lib/CIR/Dialect/Transforms/TargetLowering/CIRABIRewriteContext.cpp index 918f3f17b9933..d67ffe3122900 100644 --- a/clang/lib/CIR/Dialect/Transforms/TargetLowering/CIRABIRewriteContext.cpp +++ b/clang/lib/CIR/Dialect/Transforms/TargetLowering/CIRABIRewriteContext.cpp @@ -302,14 +302,21 @@ static uint64_t coercionByteSize(mlir::Type ty, const mlir::DataLayout &dl) { /// dominate every use of the coerced value and must be a block that ends up /// inside the enclosing function's entry block after any later outlining. /// +/// \p offset is where the coerced value sits within the larger of the two +/// types, non-zero when the ABI passes a value in a register read from +/// partway into its storage. The coerced type must be the smaller of the +/// two, so one that can exceed the value it coerces, such as a multi-field +/// register tuple, must not be given an offset. +/// /// Any operations the helper creates are appended to \p createdOps so the /// caller can pass them to replaceAllUsesExcept and avoid clobbering the /// store's value operand when later rewiring the source value. -mlir::Value -emitCoercionToMemory(mlir::OpBuilder &builder, mlir::Location loc, - mlir::Type dstTy, mlir::Value src, mlir::Block *slotBlock, - const mlir::DataLayout &dl, - SmallPtrSetImpl &createdOps) { +mlir::Value emitCoercionToMemory(mlir::OpBuilder &builder, mlir::Location loc, + mlir::Type dstTy, mlir::Value src, + mlir::Block *slotBlock, + const mlir::DataLayout &dl, + SmallPtrSetImpl &createdOps, + unsigned offset) { mlir::Type srcTy = src.getType(); assert(srcTy != dstTy && "emitCoercion callers must pre-check that the types differ"); @@ -321,6 +328,19 @@ emitCoercionToMemory(mlir::OpBuilder &builder, mlir::Location loc, ? srcTy : dstTy; + // Sizes are compared two ways on purpose: relative size in + // coercionByteSize terms, which is how slotTy was picked, and capacity in + // getTypeSize terms, which is what the alloca is given. + [[maybe_unused]] mlir::Type coercedTy = ((slotTy == srcTy) ? dstTy : srcTy); + assert((offset == 0 || + coercionByteSize(coercedTy, dl) < coercionByteSize(slotTy, dl)) && + "a direct offset must land on the coerced side, the smaller one"); + assert((offset == 0 || + offset + dl.getTypeSize(coercedTy) <= dl.getTypeSize(slotTy)) && + "coerce slot too small for offset access"); + assert((offset == 0 || offset % dl.getTypeABIAlignment(coercedTy) == 0) && + "a direct offset must be aligned for the coerced access"); + auto slotPtrTy = cir::PointerType::get(slotTy); auto srcPtrTy = cir::PointerType::get(srcTy); auto dstPtrTy = cir::PointerType::get(dstTy); @@ -335,25 +355,42 @@ emitCoercionToMemory(mlir::OpBuilder &builder, mlir::Location loc, } createdOps.insert(alloca); + // The alloca already has slotTy, so asking for that type returns it + // unchanged. Any other type is reached by a bitcast, preceded by a byte + // stride when the coerced value lives at an offset. + auto slotView = [&](mlir::Type wantTy, + cir::PointerType wantPtrTy) -> mlir::Value { + if (wantTy == slotTy) + return alloca; + mlir::Value base = alloca; + if (offset != 0) { + auto u8Ty = + cir::IntType::get(builder.getContext(), 8, /*isSigned=*/false); + auto u8PtrTy = cir::PointerType::get(u8Ty); + auto u8Base = cir::CastOp::create(builder, loc, u8PtrTy, + cir::CastKind::bitcast, alloca); + createdOps.insert(u8Base); + auto strideTy = + cir::IntType::get(builder.getContext(), 64, /*isSigned=*/true); + auto strideVal = cir::ConstantOp::create( + builder, loc, cir::IntAttr::get(strideTy, offset)); + createdOps.insert(strideVal); + base = cir::PtrStrideOp::create(builder, loc, u8PtrTy, u8Base, strideVal); + createdOps.insert(base.getDefiningOp()); + } + auto cast = cir::CastOp::create(builder, loc, wantPtrTy, + cir::CastKind::bitcast, base); + createdOps.insert(cast); + return cast; + }; + // Store through a source-typed view of the slot. - mlir::Value srcSlot = alloca; - if (slotTy != srcTy) { - auto srcCast = cir::CastOp::create(builder, loc, srcPtrTy, - cir::CastKind::bitcast, alloca); - createdOps.insert(srcCast); - srcSlot = srcCast; - } + mlir::Value srcSlot = slotView(srcTy, srcPtrTy); auto store = cir::StoreOp::create(builder, loc, src, srcSlot); createdOps.insert(store); // Return a destination-typed view of the slot. - if (slotTy != dstTy) { - auto dstCast = cir::CastOp::create(builder, loc, dstPtrTy, - cir::CastKind::bitcast, alloca); - createdOps.insert(dstCast); - return dstCast; - } - return alloca; + return slotView(dstTy, dstPtrTy); } /// Coerce \p src to type \p dstTy by going through memory and load the whole @@ -362,9 +399,10 @@ emitCoercionToMemory(mlir::OpBuilder &builder, mlir::Location loc, mlir::Value emitCoercion(mlir::OpBuilder &builder, mlir::Location loc, mlir::Type dstTy, mlir::Value src, mlir::Block *slotBlock, const mlir::DataLayout &dl, - SmallPtrSetImpl &createdOps) { - mlir::Value dstSlot = - emitCoercionToMemory(builder, loc, dstTy, src, slotBlock, dl, createdOps); + SmallPtrSetImpl &createdOps, + unsigned offset) { + mlir::Value dstSlot = emitCoercionToMemory(builder, loc, dstTy, src, + slotBlock, dl, createdOps, offset); auto load = cir::LoadOp::create(builder, loc, dstSlot); createdOps.insert(load); return load; @@ -374,9 +412,10 @@ mlir::Value emitCoercion(mlir::OpBuilder &builder, mlir::Location loc, /// (e.g. call-site coercion where we don't replaceAllUsesExcept). mlir::Value emitCoercion(mlir::OpBuilder &builder, mlir::Location loc, mlir::Type dstTy, mlir::Value src, - mlir::Block *slotBlock, const mlir::DataLayout &dl) { + mlir::Block *slotBlock, const mlir::DataLayout &dl, + unsigned offset) { SmallPtrSet ignored; - return emitCoercion(builder, loc, dstTy, src, slotBlock, dl, ignored); + return emitCoercion(builder, loc, dstTy, src, slotBlock, dl, ignored, offset); } /// The block a coercion slot's alloca belongs at the start of. @@ -405,8 +444,8 @@ mlir::Block *coercionSlotBlock(mlir::Operation *op) { /// new (coerced) return type. void insertReturnCoercion(mlir::FunctionOpInterface funcOp, mlir::Type origRetTy, mlir::Type coercedRetTy, - mlir::OpBuilder &builder, - const mlir::DataLayout &dl) { + mlir::OpBuilder &builder, const mlir::DataLayout &dl, + unsigned offset) { SmallVector returns; funcOp.walk([&](cir::ReturnOp r) { returns.push_back(r); }); for (cir::ReturnOp r : returns) { @@ -418,7 +457,7 @@ void insertReturnCoercion(mlir::FunctionOpInterface funcOp, builder.setInsertionPoint(r); mlir::Value coerced = emitCoercion(builder, r.getLoc(), coercedRetTy, origVal, - &funcOp->getRegion(0).front(), dl); + &funcOp->getRegion(0).front(), dl, offset); r->setOperand(0, coerced); } } @@ -641,8 +680,11 @@ void insertArgCoercion(mlir::FunctionOpInterface funcOp, Value finalVal = flatLoaded; if (origTy != flatTy) { SmallPtrSet coercionOps; + assert(!ac.directOffset && + "each field is read from slot offset 0 here, so a flattened " + "coercion cannot honor a direct offset"); finalVal = emitCoercion(builder, loc, origTy, flatLoaded, &entry, dl, - coercionOps); + coercionOps, /*offset=*/0); flattenOps.insert(coercionOps.begin(), coercionOps.end()); } @@ -665,8 +707,9 @@ void insertArgCoercion(mlir::FunctionOpInterface funcOp, builder.setInsertionPointToStart(&entry); SmallPtrSet coercionOps; - mlir::Value adapted = emitCoercion(builder, funcOp.getLoc(), oldArgTy, - blockArg, &entry, dl, coercionOps); + mlir::Value adapted = + emitCoercion(builder, funcOp.getLoc(), oldArgTy, blockArg, &entry, dl, + coercionOps, ac.directOffset); // Replace blockArg uses with the adapted value, except inside the // helper ops we just created. This is critical: the StoreOp's value @@ -1053,7 +1096,7 @@ mlir::LogicalResult CIRABIRewriteContext::rewriteFunctionDefinition( if (fc.returnInfo.kind == ArgKind::Direct && fc.returnInfo.coercedType && !oldResultTypes.empty() && fc.returnInfo.coercedType != origRetTy) insertReturnCoercion(funcOp, origRetTy, fc.returnInfo.coercedType, - builder, dl); + builder, dl, fc.returnInfo.directOffset); mlir::Block &entry = body.front(); @@ -1215,8 +1258,12 @@ CIRABIRewriteContext::rewriteCallSite(mlir::Operation *callOp, // alloca when possible). if (arg.getType() != flatTy) { SmallPtrSet coercionOps; - mlir::Value coercedPtr = emitCoercionToMemory( - builder, call.getLoc(), flatTy, arg, slotBlock, dl, coercionOps); + assert(!ac.directOffset && + "each field is read from slot offset 0 here, so a flattened " + "coercion cannot honor a direct offset"); + mlir::Value coercedPtr = + emitCoercionToMemory(builder, call.getLoc(), flatTy, arg, slotBlock, + dl, coercionOps, /*offset=*/0); for (auto [f, fieldTy] : llvm::enumerate(flatTy.getMembers())) { mlir::Type fieldPtrTy = cir::PointerType::get(fieldTy); auto fieldPtr = @@ -1240,7 +1287,7 @@ CIRABIRewriteContext::rewriteCallSite(mlir::Operation *callOp, } else if (ac.kind == ArgKind::Direct && ac.coercedType && arg.getType() != ac.coercedType) { arg = emitCoercion(builder, call.getLoc(), ac.coercedType, arg, slotBlock, - dl); + dl, ac.directOffset); newArgs.push_back(arg); } else if (ac.kind == ArgKind::Indirect) { // byval hands the callee its own copy. byref must name the caller's @@ -1308,8 +1355,9 @@ CIRABIRewriteContext::rewriteCallSite(mlir::Operation *callOp, // emit a coercion back to the original type for the call's existing uses. if (returnNeedsCoercion) { builder.setInsertionPointAfter(newCall); - mlir::Value coercedBack = emitCoercion(builder, call.getLoc(), origRetTy, - newCall.getResult(), slotBlock, dl); + mlir::Value coercedBack = + emitCoercion(builder, call.getLoc(), origRetTy, newCall.getResult(), + slotBlock, dl, fc.returnInfo.directOffset); call.getResult().replaceAllUsesWith(coercedBack); } diff --git a/clang/test/CIR/CodeGen/call-conv-lowering-x86_64-empty.cpp b/clang/test/CIR/CodeGen/call-conv-lowering-x86_64-empty.cpp index 91414084e0845..ceafb23baf14c 100644 --- a/clang/test/CIR/CodeGen/call-conv-lowering-x86_64-empty.cpp +++ b/clang/test/CIR/CodeGen/call-conv-lowering-x86_64-empty.cpp @@ -24,6 +24,7 @@ struct EmptySecond { long a; Empty e; }; struct EmptySSE { double a; Empty e; }; struct FloatEmpty { float a; Empty e; }; struct FloatEmptyFirst { Empty e; float a; }; +struct HiWord { Empty e; long hi; }; struct alignas(32) Big32 {}; union UBits { unsigned : 3; }; union UNone {}; @@ -147,6 +148,36 @@ float takeFloatEmptyFirst(FloatEmptyFirst v) { return v.a; } // CIR: cir.func {{.*}}@_Z19takeFloatEmptyFirst15FloatEmptyFirst(%arg0: !cir.double {{.*}}) -> (!cir.float // LLVM: define dso_local noundef float @_Z19takeFloatEmptyFirst15FloatEmptyFirst(double %{{[^,]+}}) +// Here the empty member owns eightbyte 0 rather than eightbyte 1, so NoClass +// cannot just be dropped: the coercion has to start at byte 8. +long takeHiWord(HiWord v) { return v.hi; } + +// CIR: cir.func {{.*}}@_Z10takeHiWord6HiWord(%arg0: !s64i {{.*}}) -> (!s64i +// LLVM: define dso_local noundef i64 @_Z10takeHiWord6HiWord(i64 %{{[^,]+}}) +// LLVM: %{{.+}} = getelementptr{{( inbounds)?}} i8, ptr %{{.+}}, i64 8 +// LLVM: store i64 %{{.+}}, ptr %{{.+}}, align 8 + +// The same offset on the return side. +HiWord giveHiWord(long hi) { + HiWord w; + w.hi = hi; + return w; +} + +// CIR: cir.func {{.*}}@_Z10giveHiWordl(%arg0: !s64i {llvm.noundef} {{.*}}) -> !s64i +// LLVM: define dso_local i64 @_Z10giveHiWordl(i64 noundef %{{[^,]+}}) +// LLVM: %[[RGEP:.+]] = getelementptr{{( inbounds)?}} i8, ptr %{{.+}}, i64 8 +// LLVM: %[[RVAL:.+]] = load i64, ptr %[[RGEP]], align 8 +// LLVM: ret i64 %[[RVAL]] + +// The caller's own signature is unaffected by the callee's coercion. +long callerHiWord(long hi) { + return takeHiWord(giveHiWord(hi)); +} + +// CIR: cir.func {{.*}}@_Z12callerHiWordl(%arg0: !s64i {{.*}}) -> (!s64i +// LLVM: define dso_local noundef i64 @_Z12callerHiWordl(i64 noundef %{{[^,]+}}) + // Past two eightbytes SysV says memory whatever the content, so an empty class // this size is passed indirectly at its declared alignment. int takeBig32(Big32 v, int k) { return k; } diff --git a/clang/test/CIR/CodeGenCXX/x86_64-arguments.cpp b/clang/test/CIR/CodeGenCXX/x86_64-arguments.cpp index 7270c36df7df6..acd6eb6a5264c 100644 --- a/clang/test/CIR/CodeGenCXX/x86_64-arguments.cpp +++ b/clang/test/CIR/CodeGenCXX/x86_64-arguments.cpp @@ -1,9 +1,6 @@ -// TODO(cir): drop -fno-clangir-call-conv-lowering once CallConvLowering -// supports parameters of an empty or tag class and padded, packed, and -// over-aligned record shapes. -// RUN: %clang_cc1 -no-enable-noundef-analysis -triple x86_64-unknown-unknown -fclangir -fno-clangir-call-conv-lowering -emit-cir %s -o %t.cir +// RUN: %clang_cc1 -no-enable-noundef-analysis -triple x86_64-unknown-unknown -fclangir -emit-cir %s -o %t.cir // RUN: FileCheck --check-prefix=CIR --input-file=%t.cir %s -// RUN: %clang_cc1 -no-enable-noundef-analysis -triple x86_64-unknown-unknown -fclangir -fno-clangir-call-conv-lowering -emit-llvm %s -o %t-cir.ll +// RUN: %clang_cc1 -no-enable-noundef-analysis -triple x86_64-unknown-unknown -fclangir -emit-llvm %s -o %t-cir.ll // RUN: FileCheck --check-prefix=LLVM --input-file=%t-cir.ll %s // RUN: %clang_cc1 -no-enable-noundef-analysis -triple x86_64-unknown-unknown -emit-llvm %s -o %t.ll // RUN: FileCheck --check-prefix=OGCG --input-file=%t.ll %s @@ -44,9 +41,17 @@ struct s3_0 {}; struct s3_1 { struct s3_0 a; long b; }; void f3(struct s3_1 x) {} +// The empty member owns eightbyte 0, so the live long is the second eightbyte +// and the coercion starts at byte 8. // CIR-LABEL: cir.func {{.*}} @_Z2f34s3_1 -// LLVM-LABEL: define {{.*}} void @_Z2f34s3_1( +// LLVM-LABEL: define {{.*}} void @_Z2f34s3_1(i64 %{{[^,)]+}}) +// LLVM: %[[SLOT:.+]] = alloca %struct.s3_1, align 8 +// LLVM: %[[HI:.+]] = getelementptr{{( inbounds)?}} i8, ptr %[[SLOT]], i64 8 +// LLVM: store i64 %{{.+}}, ptr %[[HI]], align 8 // OGCG-LABEL: define {{.*}} void @_Z2f34s3_1(i64 %x.coerce) +// OGCG: %[[SLOT:.+]] = alloca %struct.s3_1, align 8 +// OGCG: %[[HI:.+]] = getelementptr{{( inbounds)?}} i8, ptr %[[SLOT]], i64 8 +// OGCG: store i64 %x.coerce, ptr %[[HI]], align 8 // Member data pointer and member function pointer. struct s4 {}; @@ -121,9 +126,16 @@ namespace PR5179 { const void *bar(B2 b2) { return b2.b1.pa; } } +// The empty base owns eightbyte 0, so the pointer is read from byte 8. // CIR-LABEL: cir.func {{.*}} @_ZN6PR51793barENS_2B2E -// LLVM-LABEL: define {{.*}} @_ZN6PR51793barENS_2B2E( +// LLVM-LABEL: define {{.*}} ptr @_ZN6PR51793barENS_2B2E(ptr %{{[^,)]+}}) +// LLVM: %[[SLOT:.+]] = alloca %"struct.PR5179::B2", align 8 +// LLVM: %[[PA:.+]] = getelementptr{{( inbounds)?}} i8, ptr %[[SLOT]], i64 8 +// LLVM: store ptr %{{.+}}, ptr %[[PA]], align 8 // OGCG-LABEL: define {{.*}} ptr @_ZN6PR51793barENS_2B2E(ptr %b2.coerce) +// OGCG: %[[SLOT:.+]] = alloca %"struct.PR5179::B2", align 8 +// OGCG: %[[PA:.+]] = getelementptr{{( inbounds)?}} i8, ptr %[[SLOT]], i64 8 +// OGCG: store ptr %b2.coerce, ptr %[[PA]], align 8 namespace test5 { struct Xbase { }; diff --git a/clang/test/CIR/Transforms/abi-lowering/x86_64-aggregate-nyi.cir b/clang/test/CIR/Transforms/abi-lowering/x86_64-aggregate-nyi.cir index 7da3a76abc494..b9e2d795e70b4 100644 --- a/clang/test/CIR/Transforms/abi-lowering/x86_64-aggregate-nyi.cir +++ b/clang/test/CIR/Transforms/abi-lowering/x86_64-aggregate-nyi.cir @@ -33,7 +33,6 @@ !rec_HoldsAllPad = !cir.struct<"HoldsAllPad" {data !s32i, empty !rec_E}> !rec_EBits = !cir.struct<"EBits" {empty !u32i}> !rec_HoldsEmptyBits = !cir.struct<"HoldsEmptyBits" {empty !rec_EBits, data !s32i}> -!rec_LeadPad = !cir.struct<"LeadPad" {pad !cir.array, data !s32i}> !rec_Incomplete = !cir.struct<"Incomplete" incomplete> module attributes { @@ -196,15 +195,6 @@ module attributes { // CHECK: not yet implemented for type '!cir.struct<"HoldsEmptyBits" {empty - // With no field in the low eightbyte the classifier coerces the high one and - // names an offset of 8 into the record, which the rewriter cannot express: it - // reads a coercion from offset 0, so the argument would land in the padding. - cir.func @take_lead_pad(%arg0: !rec_LeadPad) { - cir.return - } - - // CHECK: not yet implemented for the ABI coercion of type '!cir.struct<"LeadPad" - // A scalable vector has no size the eightbyte rules can read. cir.func @take_scalable(%arg0: !cir.vector<[4] x !cir.float>) { cir.return diff --git a/clang/test/CIR/Transforms/abi-lowering/x86_64-struct-direct-offset.cir b/clang/test/CIR/Transforms/abi-lowering/x86_64-struct-direct-offset.cir new file mode 100644 index 0000000000000..585087886a09a --- /dev/null +++ b/clang/test/CIR/Transforms/abi-lowering/x86_64-struct-direct-offset.cir @@ -0,0 +1,123 @@ +// RUN: cir-opt %s -cir-call-conv-lowering=target=x86_64 | FileCheck %s --check-prefix=CIR +// RUN: cir-opt %s -cir-call-conv-lowering=target=x86_64 -cir-to-llvm -o - 2>/dev/null \ +// RUN: | mlir-translate -mlir-to-llvmir --allow-unregistered-dialect \ +// RUN: | FileCheck %s --check-prefix=LLVM + +!u8i = !cir.int +!s32i = !cir.int +!s64i = !cir.int +!rec_Empty = !cir.struct<"Empty" {pad !u8i}> +!rec_HiWord = !cir.struct<"HiWord" {data !rec_Empty, data !s64i}> +!rec_LeadPad = !cir.struct<"LeadPad" {pad !cir.array, data !s32i}> + +module attributes { + cir.triple = "x86_64-unknown-linux-gnu", + dlti.dl_spec = #dlti.dl_spec< + #dlti.dl_entry: vector<2xi64>>, + #dlti.dl_entry: vector<2xi64>>, + #dlti.dl_entry: vector<2xi64>>> +} { + + // HiWord is 16 bytes: a leading ABI-empty byte, then an i64 at offset 8. + // The low eightbyte carries no field (NO_CLASS), so the classifier passes + // the value in one register taken from byte 8. + cir.func @take_hiword(%arg0: !rec_HiWord) -> !s64i { + %0 = cir.alloca "h" align(8) : !cir.ptr + cir.store %arg0, %0 : !rec_HiWord, !cir.ptr + %1 = cir.get_member %0[1] {name = "hi"} : !cir.ptr -> !cir.ptr + %2 = cir.load %1 : !cir.ptr, !s64i + cir.return %2 : !s64i + } + + // CIR-LABEL: cir.func{{.*}} @take_hiword(%arg0: !s64i) -> !s64i + // CIR: %[[SLOT:.*]] = cir.alloca "coerce" {{.*}} : !cir.ptr + // CIR: %[[U8:.*]] = cir.cast bitcast %[[SLOT]] : !cir.ptr -> !cir.ptr + // CIR: %[[OFF:.*]] = cir.const #cir.int<8> : !s64i + // CIR: %[[GEP:.*]] = cir.ptr_stride %[[U8]], %[[OFF]] : (!cir.ptr, !s64i) -> !cir.ptr + // CIR: %[[CAST:.*]] = cir.cast bitcast %[[GEP]] : !cir.ptr -> !cir.ptr + // CIR: cir.store %arg0, %[[CAST]] : !s64i, !cir.ptr + // CIR: %{{.*}} = cir.load %[[SLOT]] : !cir.ptr, !rec_HiWord + + // The return value is likewise coerced from byte 8 of the local aggregate. + cir.func @give_hiword() -> !rec_HiWord { + %0 = cir.alloca "h" align(8) : !cir.ptr + %1 = cir.load %0 : !cir.ptr, !rec_HiWord + cir.return %1 : !rec_HiWord + } + + // CIR-LABEL: cir.func{{.*}} @give_hiword() -> !s64i + // CIR: %[[RSLOT:.*]] = cir.alloca "coerce" {{.*}} : !cir.ptr + // CIR: cir.store %{{.*}}, %[[RSLOT]] : !rec_HiWord, !cir.ptr + // CIR: %[[RU8:.*]] = cir.cast bitcast %[[RSLOT]] : !cir.ptr -> !cir.ptr + // CIR: %[[ROFF:.*]] = cir.const #cir.int<8> : !s64i + // CIR: %[[RGEP:.*]] = cir.ptr_stride %[[RU8]], %[[ROFF]] : (!cir.ptr, !s64i) -> !cir.ptr + // CIR: %[[RCAST:.*]] = cir.cast bitcast %[[RGEP]] : !cir.ptr -> !cir.ptr + // CIR: %[[RVAL:.*]] = cir.load %[[RCAST]] : !cir.ptr, !s64i + // CIR: cir.return %[[RVAL]] : !s64i + + // The caller reconstructs the aggregate from the callee's i64 result, so + // the received register is written back to byte 8 of a slot. + cir.func @call_hiword() -> !s64i { + %0 = cir.call @give_hiword() : () -> !rec_HiWord + %1 = cir.alloca "r" align(8) : !cir.ptr + cir.store %0, %1 : !rec_HiWord, !cir.ptr + %2 = cir.get_member %1[1] {name = "hi"} : !cir.ptr -> !cir.ptr + %3 = cir.load %2 : !cir.ptr, !s64i + cir.return %3 : !s64i + } + + // CIR-LABEL: cir.func{{.*}} @call_hiword() -> !s64i + // CIR: %[[CSLOT:.*]] = cir.alloca "coerce" {{.*}} : !cir.ptr + // CIR: %[[CRET:.*]] = cir.call @give_hiword() : () -> !s64i + // CIR: %[[CU8:.*]] = cir.cast bitcast %[[CSLOT]] : !cir.ptr -> !cir.ptr + // CIR: %[[COFF:.*]] = cir.const #cir.int<8> : !s64i + // CIR: %[[CGEP:.*]] = cir.ptr_stride %[[CU8]], %[[COFF]] : (!cir.ptr, !s64i) -> !cir.ptr + // CIR: %[[CCAST:.*]] = cir.cast bitcast %[[CGEP]] : !cir.ptr -> !cir.ptr + // CIR: cir.store %[[CRET]], %[[CCAST]] : !s64i, !cir.ptr + // CIR: %{{.*}} = cir.load %[[CSLOT]] : !cir.ptr, !rec_HiWord + + // Passing an aggregate argument runs the extraction direction at the call + // site: the operand's byte 8 is read out to form the register. + cir.func @pass_hiword(%arg0: !rec_HiWord) { + %0 = cir.call @take_hiword(%arg0) : (!rec_HiWord) -> !s64i + cir.return + } + + // CIR-LABEL: cir.func{{.*}} @pass_hiword(%arg0: !s64i) + // CIR: %[[PREC:.*]] = cir.load %{{.*}} : !cir.ptr, !rec_HiWord + // CIR: %[[PSLOT:.*]] = cir.alloca "coerce" {{.*}} : !cir.ptr + // CIR: cir.store %[[PREC]], %[[PSLOT]] : !rec_HiWord, !cir.ptr + // CIR: %[[PU8:.*]] = cir.cast bitcast %[[PSLOT]] : !cir.ptr -> !cir.ptr + // CIR: %[[POFF:.*]] = cir.const #cir.int<8> : !s64i + // CIR: %[[PGEP:.*]] = cir.ptr_stride %[[PU8]], %[[POFF]] : (!cir.ptr, !s64i) -> !cir.ptr + // CIR: %[[PCAST:.*]] = cir.cast bitcast %[[PGEP]] : !cir.ptr -> !cir.ptr + // CIR: %[[PVAL:.*]] = cir.load %[[PCAST]] : !cir.ptr, !s64i + // CIR: %{{.*}} = cir.call @take_hiword(%[[PVAL]]) : (!s64i) -> !s64i + + // The same offset-8 coercion from a leading pad field rather than a nested + // empty record. Only 4 live bytes in the high eightbyte, so i32 not i64. + cir.func @take_lead_pad(%arg0: !rec_LeadPad) -> !s32i { + %0 = cir.alloca "l" align(4) : !cir.ptr + cir.store %arg0, %0 : !rec_LeadPad, !cir.ptr + %1 = cir.get_member %0[1] {name = "data"} : !cir.ptr -> !cir.ptr + %2 = cir.load %1 : !cir.ptr, !s32i + cir.return %2 : !s32i + } + + // CIR-LABEL: cir.func{{.*}} @take_lead_pad(%arg0: !s32i) -> !s32i + // CIR: %[[LSLOT:.*]] = cir.alloca "coerce" {{.*}} : !cir.ptr + // CIR: %[[LU8:.*]] = cir.cast bitcast %[[LSLOT]] : !cir.ptr -> !cir.ptr + // CIR: %[[LOFF:.*]] = cir.const #cir.int<8> : !s64i + // CIR: %[[LGEP:.*]] = cir.ptr_stride %[[LU8]], %[[LOFF]] : (!cir.ptr, !s64i) -> !cir.ptr + // CIR: %[[LCAST:.*]] = cir.cast bitcast %[[LGEP]] : !cir.ptr -> !cir.ptr + // CIR: cir.store %arg0, %[[LCAST]] : !s32i, !cir.ptr + // CIR: %{{.*}} = cir.load %[[LSLOT]] : !cir.ptr, !rec_LeadPad +} + +// LLVM: define i64 @take_hiword(i64 %{{.+}}) +// LLVM: define i64 @give_hiword() +// LLVM: define i64 @call_hiword() +// LLVM: %{{.+}} = call i64 @give_hiword() +// LLVM: define void @pass_hiword(i64 %{{.+}}) +// LLVM: %{{.+}} = call i64 @take_hiword(i64 %{{.+}}) +// LLVM: define i32 @take_lead_pad(i32 %{{.+}}) diff --git a/mlir/include/mlir/ABI/ABIRewriteContext.h b/mlir/include/mlir/ABI/ABIRewriteContext.h index 8394aeccc75ce..430ebe94bc5b6 100644 --- a/mlir/include/mlir/ABI/ABIRewriteContext.h +++ b/mlir/include/mlir/ABI/ABIRewriteContext.h @@ -27,6 +27,8 @@ #include "llvm/ADT/STLExtras.h" #include "llvm/Support/Alignment.h" +#include + namespace mlir { namespace abi { @@ -75,6 +77,11 @@ struct ArgClassification { /// For Indirect: whether the callee gets ownership (byval). bool byVal = false; + /// For Direct with coercion: the byte offset within the original aggregate + /// at which the coerced value lives. Non-zero when the low eightbyte is + /// NO_CLASS and the value is carried in a later eightbyte (x86-64 SysV). + unsigned directOffset = 0; + /// Whether the value is passed as-is, so a rewriter can leave it alone. /// Only an uncoerced Direct qualifies. Extend counts as needing a rewrite /// even though it only adds an attribute, because the attribute changes @@ -87,13 +94,22 @@ struct ArgClassification { return kind == other.kind && coercedType == other.coercedType && indirectAlign == other.indirectAlign && signExtend == other.signExtend && canFlatten == other.canFlatten && - byVal == other.byVal; + byVal == other.byVal && directOffset == other.directOffset; + } + + static ArgClassification getDirect() { + return getDirect(/*offset=*/0, /*coerced=*/nullptr); } - static ArgClassification getDirect(Type coerced = nullptr) { + static ArgClassification getDirect(unsigned offset, Type coerced) { + // isPassThrough reads only coercedType, so an offset with no coerced + // type to read at it would be silently ignored. + assert((!offset || coerced) && + "a direct offset needs a coerced type to read at it"); ArgClassification c; c.kind = ArgKind::Direct; c.coercedType = coerced; + c.directOffset = offset; return c; } diff --git a/mlir/lib/ABI/Targets/Test/TestTarget.cpp b/mlir/lib/ABI/Targets/Test/TestTarget.cpp index 0cfdb2eb3fdb0..f36595ae52bb4 100644 --- a/mlir/lib/ABI/Targets/Test/TestTarget.cpp +++ b/mlir/lib/ABI/Targets/Test/TestTarget.cpp @@ -161,7 +161,7 @@ parseOne(DictionaryAttr argDict, function_ref emitError) { Type coerced; if (auto t = argDict.getAs("coerced_type")) coerced = t.getValue(); - auto c = ArgClassification::getDirect(coerced); + auto c = ArgClassification::getDirect(/*offset=*/0, coerced); if (auto cf = argDict.getAs("can_flatten")) c.canFlatten = cf.getValue(); return c; diff --git a/mlir/unittests/ABI/ABIRewriteContextTest.cpp b/mlir/unittests/ABI/ABIRewriteContextTest.cpp index 59a5307225e0d..79c9124206562 100644 --- a/mlir/unittests/ABI/ABIRewriteContextTest.cpp +++ b/mlir/unittests/ABI/ABIRewriteContextTest.cpp @@ -45,7 +45,7 @@ TEST(ABIRewriteContextTest, ArgClassificationDirect) { TEST(ABIRewriteContextTest, ArgClassificationDirectWithType) { MLIRContext mlirCtx; auto i32 = IntegerType::get(&mlirCtx, 32); - auto c = ArgClassification::getDirect(i32); + auto c = ArgClassification::getDirect(/*offset=*/0, i32); EXPECT_EQ(c.kind, ArgKind::Direct); EXPECT_EQ(c.coercedType, i32); }