Skip to content

Commit c9fdc0b

Browse files
committed
Codegen **non-overloaded** LLVM intrinsics using their name
1 parent 033c0a4 commit c9fdc0b

File tree

13 files changed

+215
-46
lines changed

13 files changed

+215
-46
lines changed

compiler/rustc_codegen_gcc/src/type_of.rs

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
use std::fmt::Write;
22

3-
use gccjit::{Struct, Type};
3+
use gccjit::{RValue, Struct, Type};
44
use rustc_abi as abi;
55
use rustc_abi::Primitive::*;
66
use rustc_abi::{
@@ -373,7 +373,11 @@ impl<'gcc, 'tcx> LayoutTypeCodegenMethods<'tcx> for CodegenCx<'gcc, 'tcx> {
373373
unimplemented!();
374374
}
375375

376-
fn fn_decl_backend_type(&self, fn_abi: &FnAbi<'tcx, Ty<'tcx>>) -> Type<'gcc> {
376+
fn fn_decl_backend_type(
377+
&self,
378+
fn_abi: &FnAbi<'tcx, Ty<'tcx>>,
379+
_fn_ptr: RValue<'gcc>,
380+
) -> Type<'gcc> {
377381
// FIXME(antoyo): Should we do something with `FnAbiGcc::fn_attributes`?
378382
let FnAbiGcc { return_type, arguments_type, is_c_variadic, .. } = fn_abi.gcc_type(self);
379383
self.context.new_function_pointer_type(None, return_type, &arguments_type, is_c_variadic)

compiler/rustc_codegen_llvm/src/abi.rs

Lines changed: 136 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
use std::borrow::Borrow;
2-
use std::cmp;
2+
use std::{cmp, iter};
33

44
use libc::c_uint;
55
use rustc_abi::{
@@ -308,8 +308,37 @@ impl<'ll, 'tcx> ArgAbiBuilderMethods<'tcx> for Builder<'_, 'll, 'tcx> {
308308
}
309309
}
310310

311+
pub(crate) enum FunctionSignature<'ll> {
312+
/// The signature is obtained directly from LLVM, and **may not match the Rust signature**
313+
Intrinsic(&'ll Type),
314+
/// The name starts with `llvm.`, but can't obtain the intrinsic ID. May be invalid or upgradable
315+
MaybeInvalidIntrinsic(&'ll Type),
316+
/// Just the Rust signature
317+
Rust(&'ll Type),
318+
}
319+
320+
impl<'ll> FunctionSignature<'ll> {
321+
pub(crate) fn fn_ty(&self) -> &'ll Type {
322+
match self {
323+
FunctionSignature::Intrinsic(fn_ty)
324+
| FunctionSignature::MaybeInvalidIntrinsic(fn_ty)
325+
| FunctionSignature::Rust(fn_ty) => fn_ty,
326+
}
327+
}
328+
}
329+
311330
pub(crate) trait FnAbiLlvmExt<'ll, 'tcx> {
312-
fn llvm_type(&self, cx: &CodegenCx<'ll, 'tcx>) -> &'ll Type;
331+
fn llvm_return_type(&self, cx: &CodegenCx<'ll, 'tcx>) -> &'ll Type;
332+
fn llvm_argument_types(&self, cx: &CodegenCx<'ll, 'tcx>) -> Vec<&'ll Type>;
333+
fn llvm_type(
334+
&self,
335+
cx: &CodegenCx<'ll, 'tcx>,
336+
name: &[u8],
337+
do_verify: bool,
338+
) -> FunctionSignature<'ll>;
339+
/// **If this function is an LLVM intrinsic** checks if the LLVM signature provided matches with this
340+
fn verify_intrinsic_signature(&self, cx: &CodegenCx<'ll, 'tcx>, llvm_ty: &'ll Type) -> bool;
341+
313342
fn ptr_to_llvm_type(&self, cx: &CodegenCx<'ll, 'tcx>) -> &'ll Type;
314343
fn llvm_cconv(&self, cx: &CodegenCx<'ll, 'tcx>) -> llvm::CallConv;
315344

@@ -322,30 +351,39 @@ pub(crate) trait FnAbiLlvmExt<'ll, 'tcx> {
322351
);
323352

324353
/// Apply attributes to a function call.
325-
fn apply_attrs_callsite(&self, bx: &mut Builder<'_, 'll, 'tcx>, callsite: &'ll Value);
354+
fn apply_attrs_callsite(
355+
&self,
356+
bx: &mut Builder<'_, 'll, 'tcx>,
357+
callsite: &'ll Value,
358+
llfn: &'ll Value,
359+
);
326360
}
327361

328362
impl<'ll, 'tcx> FnAbiLlvmExt<'ll, 'tcx> for FnAbi<'tcx, Ty<'tcx>> {
329-
fn llvm_type(&self, cx: &CodegenCx<'ll, 'tcx>) -> &'ll Type {
363+
fn llvm_return_type(&self, cx: &CodegenCx<'ll, 'tcx>) -> &'ll Type {
364+
match &self.ret.mode {
365+
PassMode::Ignore => cx.type_void(),
366+
PassMode::Direct(_) | PassMode::Pair(..) => self.ret.layout.immediate_llvm_type(cx),
367+
PassMode::Cast { cast, pad_i32: _ } => cast.llvm_type(cx),
368+
PassMode::Indirect { .. } => cx.type_void(),
369+
}
370+
}
371+
372+
fn llvm_argument_types(&self, cx: &CodegenCx<'ll, 'tcx>) -> Vec<&'ll Type> {
373+
let indirect_return = matches!(self.ret.mode, PassMode::Indirect { .. });
374+
330375
// Ignore "extra" args from the call site for C variadic functions.
331376
// Only the "fixed" args are part of the LLVM function signature.
332377
let args =
333378
if self.c_variadic { &self.args[..self.fixed_count as usize] } else { &self.args };
334379

335380
// This capacity calculation is approximate.
336-
let mut llargument_tys = Vec::with_capacity(
337-
self.args.len() + if let PassMode::Indirect { .. } = self.ret.mode { 1 } else { 0 },
338-
);
381+
let mut llargument_tys =
382+
Vec::with_capacity(args.len() + if indirect_return { 1 } else { 0 });
339383

340-
let llreturn_ty = match &self.ret.mode {
341-
PassMode::Ignore => cx.type_void(),
342-
PassMode::Direct(_) | PassMode::Pair(..) => self.ret.layout.immediate_llvm_type(cx),
343-
PassMode::Cast { cast, pad_i32: _ } => cast.llvm_type(cx),
344-
PassMode::Indirect { .. } => {
345-
llargument_tys.push(cx.type_ptr());
346-
cx.type_void()
347-
}
348-
};
384+
if indirect_return {
385+
llargument_tys.push(cx.type_ptr());
386+
}
349387

350388
for arg in args {
351389
// Note that the exact number of arguments pushed here is carefully synchronized with
@@ -392,10 +430,72 @@ impl<'ll, 'tcx> FnAbiLlvmExt<'ll, 'tcx> for FnAbi<'tcx, Ty<'tcx>> {
392430
llargument_tys.push(llarg_ty);
393431
}
394432

395-
if self.c_variadic {
396-
cx.type_variadic_func(&llargument_tys, llreturn_ty)
433+
llargument_tys
434+
}
435+
436+
fn verify_intrinsic_signature(&self, cx: &CodegenCx<'ll, 'tcx>, llvm_fn_ty: &'ll Type) -> bool {
437+
let rust_return_ty = self.llvm_return_type(cx);
438+
let rust_argument_tys = self.llvm_argument_types(cx);
439+
440+
let llvm_return_ty = cx.get_return_type(llvm_fn_ty);
441+
let llvm_argument_tys = cx.func_params_types(llvm_fn_ty);
442+
let llvm_is_variadic = cx.func_is_variadic(llvm_fn_ty);
443+
444+
if self.c_variadic != llvm_is_variadic || rust_argument_tys.len() != llvm_argument_tys.len()
445+
{
446+
return false;
447+
}
448+
449+
iter::once((rust_return_ty, llvm_return_ty))
450+
.chain(iter::zip(rust_argument_tys, llvm_argument_tys))
451+
.all(|(rust_ty, llvm_ty)| rust_ty == llvm_ty)
452+
}
453+
454+
fn llvm_type(
455+
&self,
456+
cx: &CodegenCx<'ll, 'tcx>,
457+
name: &[u8],
458+
do_verify: bool,
459+
) -> FunctionSignature<'ll> {
460+
let mut maybe_invalid = false;
461+
462+
if name.starts_with(b"llvm.") {
463+
if let Some(intrinsic) = llvm::Intrinsic::lookup(name) {
464+
if !intrinsic.is_overloaded() {
465+
// FIXME: also do this for overloaded intrinsics
466+
let llvm_fn_ty = intrinsic.get_type(cx.llcx, &[]);
467+
if do_verify {
468+
if !self.verify_intrinsic_signature(cx, llvm_fn_ty) {
469+
cx.tcx.dcx().fatal(format!(
470+
"Intrinsic signature mismatch for `{}`: expected signature `{llvm_fn_ty:?}`",
471+
str::from_utf8(name).unwrap()
472+
));
473+
}
474+
}
475+
return FunctionSignature::Intrinsic(llvm_fn_ty);
476+
}
477+
} else {
478+
// it's one of 2 cases,
479+
// - either the base name is invalid
480+
// - it has been superseded by something else, so the intrinsic was removed entirely
481+
// to check for upgrades, we need the `llfn`, so we defer it for now
482+
maybe_invalid = true;
483+
}
484+
}
485+
486+
let return_ty = self.llvm_return_type(cx);
487+
let argument_tys = self.llvm_argument_types(cx);
488+
489+
let fn_ty = if self.c_variadic {
490+
cx.type_variadic_func(&argument_tys, return_ty)
397491
} else {
398-
cx.type_func(&llargument_tys, llreturn_ty)
492+
cx.type_func(&argument_tys, return_ty)
493+
};
494+
495+
if maybe_invalid {
496+
FunctionSignature::MaybeInvalidIntrinsic(fn_ty)
497+
} else {
498+
FunctionSignature::Rust(fn_ty)
399499
}
400500
}
401501

@@ -547,7 +647,23 @@ impl<'ll, 'tcx> FnAbiLlvmExt<'ll, 'tcx> for FnAbi<'tcx, Ty<'tcx>> {
547647
}
548648
}
549649

550-
fn apply_attrs_callsite(&self, bx: &mut Builder<'_, 'll, 'tcx>, callsite: &'ll Value) {
650+
fn apply_attrs_callsite(
651+
&self,
652+
bx: &mut Builder<'_, 'll, 'tcx>,
653+
callsite: &'ll Value,
654+
llfn: &'ll Value,
655+
) {
656+
// if we are using the LLVM signature, use the LLVM attributes otherwise it might be problematic
657+
let name = llvm::get_value_name(llfn);
658+
if name.starts_with(b"llvm.")
659+
&& let Some(intrinsic) = llvm::Intrinsic::lookup(&name)
660+
{
661+
// FIXME: also do this for overloaded intrinsics
662+
if !intrinsic.is_overloaded() {
663+
return;
664+
}
665+
}
666+
551667
let mut func_attrs = SmallVec::<[_; 2]>::new();
552668
if self.ret.layout.is_uninhabited() {
553669
func_attrs.push(llvm::AttributeKind::NoReturn.create_attr(bx.cx.llcx));

compiler/rustc_codegen_llvm/src/builder.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -446,7 +446,7 @@ impl<'a, 'll, 'tcx> BuilderMethods<'a, 'tcx> for Builder<'a, 'll, 'tcx> {
446446
)
447447
};
448448
if let Some(fn_abi) = fn_abi {
449-
fn_abi.apply_attrs_callsite(self, invoke);
449+
fn_abi.apply_attrs_callsite(self, invoke, llfn);
450450
}
451451
invoke
452452
}
@@ -1453,7 +1453,7 @@ impl<'a, 'll, 'tcx> BuilderMethods<'a, 'tcx> for Builder<'a, 'll, 'tcx> {
14531453
}
14541454

14551455
if let Some(fn_abi) = fn_abi {
1456-
fn_abi.apply_attrs_callsite(self, call);
1456+
fn_abi.apply_attrs_callsite(self, call, llfn);
14571457
}
14581458
call
14591459
}
@@ -1802,7 +1802,7 @@ impl<'a, 'll, 'tcx> Builder<'a, 'll, 'tcx> {
18021802
)
18031803
};
18041804
if let Some(fn_abi) = fn_abi {
1805-
fn_abi.apply_attrs_callsite(self, callbr);
1805+
fn_abi.apply_attrs_callsite(self, callbr, llfn);
18061806
}
18071807
callbr
18081808
}

compiler/rustc_codegen_llvm/src/declare.rs

Lines changed: 29 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ use rustc_target::callconv::FnAbi;
2222
use smallvec::SmallVec;
2323
use tracing::debug;
2424

25-
use crate::abi::FnAbiLlvmExt;
25+
use crate::abi::{FnAbiLlvmExt, FunctionSignature};
2626
use crate::common::AsCCharPtr;
2727
use crate::context::{CodegenCx, GenericCx, SCx, SimpleCx};
2828
use crate::llvm::AttributePlace::Function;
@@ -150,17 +150,34 @@ impl<'ll, 'tcx> CodegenCx<'ll, 'tcx> {
150150
) -> &'ll Value {
151151
debug!("declare_rust_fn(name={:?}, fn_abi={:?})", name, fn_abi);
152152

153-
// Function addresses in Rust are never significant, allowing functions to
154-
// be merged.
155-
let llfn = declare_raw_fn(
156-
self,
157-
name,
158-
fn_abi.llvm_cconv(self),
159-
llvm::UnnamedAddr::Global,
160-
llvm::Visibility::Default,
161-
fn_abi.llvm_type(self),
162-
);
163-
fn_abi.apply_attrs_llfn(self, llfn, instance);
153+
let signature = fn_abi.llvm_type(self, name.as_bytes(), true);
154+
let llfn;
155+
156+
if let FunctionSignature::Intrinsic(fn_ty) = signature {
157+
// intrinsics have a specified set of attributes, so we don't use the `FnAbi` set for them
158+
llfn = declare_simple_fn(
159+
self,
160+
name,
161+
fn_abi.llvm_cconv(self),
162+
llvm::UnnamedAddr::Global,
163+
llvm::Visibility::Default,
164+
fn_ty,
165+
);
166+
} else {
167+
// Function addresses in Rust are never significant, allowing functions to
168+
// be merged.
169+
llfn = declare_raw_fn(
170+
self,
171+
name,
172+
fn_abi.llvm_cconv(self),
173+
llvm::UnnamedAddr::Global,
174+
llvm::Visibility::Default,
175+
signature.fn_ty(),
176+
);
177+
fn_abi.apply_attrs_llfn(self, llfn, instance);
178+
}
179+
180+
// todo: check for upgrades, and emit error if not upgradable
164181

165182
if self.tcx.sess.is_sanitizer_cfi_enabled() {
166183
if let Some(instance) = instance {

compiler/rustc_codegen_llvm/src/intrinsic.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1066,7 +1066,7 @@ fn gen_fn<'a, 'll, 'tcx>(
10661066
codegen: &mut dyn FnMut(Builder<'a, 'll, 'tcx>),
10671067
) -> (&'ll Type, &'ll Value) {
10681068
let fn_abi = cx.fn_abi_of_fn_ptr(rust_fn_sig, ty::List::empty());
1069-
let llty = fn_abi.llvm_type(cx);
1069+
let llty = fn_abi.llvm_type(cx, name.as_bytes(), true).fn_ty();
10701070
let llfn = cx.declare_fn(name, fn_abi, None);
10711071
cx.set_frame_pointer_type(llfn);
10721072
cx.apply_target_cpu_attr(llfn);

compiler/rustc_codegen_llvm/src/llvm/enzyme_ffi.rs

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,6 @@ unsafe extern "C" {
4646
pub(crate) fn LLVMDumpModule(M: &Module);
4747
pub(crate) fn LLVMDumpValue(V: &Value);
4848
pub(crate) fn LLVMGetFunctionCallConv(F: &Value) -> c_uint;
49-
pub(crate) fn LLVMGetReturnType(T: &Type) -> &Type;
5049
pub(crate) fn LLVMGetParams(Fnc: &Value, params: *mut &Value);
5150
pub(crate) fn LLVMGetNamedFunction(M: &Module, Name: *const c_char) -> Option<&Value>;
5251
}

compiler/rustc_codegen_llvm/src/llvm/ffi.rs

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1110,6 +1110,8 @@ unsafe extern "C" {
11101110
) -> &'a Type;
11111111
pub(crate) fn LLVMCountParamTypes(FunctionTy: &Type) -> c_uint;
11121112
pub(crate) fn LLVMGetParamTypes<'a>(FunctionTy: &'a Type, Dest: *mut &'a Type);
1113+
pub(crate) fn LLVMGetReturnType(FunctionTy: &Type) -> &Type;
1114+
pub(crate) fn LLVMIsFunctionVarArg(FunctionTy: &Type) -> Bool;
11131115

11141116
// Operations on struct types
11151117
pub(crate) fn LLVMStructTypeInContext<'a>(
@@ -1252,6 +1254,13 @@ unsafe extern "C" {
12521254

12531255
// Operations about llvm intrinsics
12541256
pub(crate) fn LLVMLookupIntrinsicID(Name: *const c_char, NameLen: size_t) -> c_uint;
1257+
pub(crate) fn LLVMIntrinsicIsOverloaded(ID: NonZero<c_uint>) -> Bool;
1258+
pub(crate) fn LLVMIntrinsicGetType<'a>(
1259+
C: &'a Context,
1260+
ID: NonZero<c_uint>,
1261+
ParamTypes: *const &'a Type,
1262+
ParamCount: size_t,
1263+
) -> &'a Type;
12551264
pub(crate) fn LLVMGetIntrinsicDeclaration<'a>(
12561265
Mod: &'a Module,
12571266
ID: NonZero<c_uint>,

compiler/rustc_codegen_llvm/src/llvm/mod.rs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -304,6 +304,14 @@ impl Intrinsic {
304304
NonZero::new(id).map(|id| Self { id })
305305
}
306306

307+
pub(crate) fn is_overloaded(self) -> bool {
308+
unsafe { LLVMIntrinsicIsOverloaded(self.id).is_true() }
309+
}
310+
311+
pub(crate) fn get_type<'ll>(self, llcx: &'ll Context, type_params: &[&'ll Type]) -> &'ll Type {
312+
unsafe { LLVMIntrinsicGetType(llcx, self.id, type_params.as_ptr(), type_params.len()) }
313+
}
314+
307315
pub(crate) fn get_declaration<'ll>(
308316
self,
309317
llmod: &'ll Module,

compiler/rustc_codegen_llvm/src/type_.rs

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,10 @@ impl<'ll, CX: Borrow<SCx<'ll>>> GenericCx<'ll, CX> {
7070
unsafe { llvm::LLVMVectorType(ty, len as c_uint) }
7171
}
7272

73+
pub(crate) fn get_return_type(&self, ty: &'ll Type) -> &'ll Type {
74+
unsafe { llvm::LLVMGetReturnType(ty) }
75+
}
76+
7377
pub(crate) fn func_params_types(&self, ty: &'ll Type) -> Vec<&'ll Type> {
7478
unsafe {
7579
let n_args = llvm::LLVMCountParamTypes(ty) as usize;
@@ -79,6 +83,10 @@ impl<'ll, CX: Borrow<SCx<'ll>>> GenericCx<'ll, CX> {
7983
args
8084
}
8185
}
86+
87+
pub(crate) fn func_is_variadic(&self, ty: &'ll Type) -> bool {
88+
unsafe { llvm::LLVMIsFunctionVarArg(ty).is_true() }
89+
}
8290
}
8391
impl<'ll, 'tcx> CodegenCx<'ll, 'tcx> {
8492
pub(crate) fn type_bool(&self) -> &'ll Type {
@@ -288,8 +296,12 @@ impl<'ll, 'tcx> LayoutTypeCodegenMethods<'tcx> for CodegenCx<'ll, 'tcx> {
288296
fn cast_backend_type(&self, ty: &CastTarget) -> &'ll Type {
289297
ty.llvm_type(self)
290298
}
291-
fn fn_decl_backend_type(&self, fn_abi: &FnAbi<'tcx, Ty<'tcx>>) -> &'ll Type {
292-
fn_abi.llvm_type(self)
299+
fn fn_decl_backend_type(
300+
&self,
301+
fn_abi: &FnAbi<'tcx, Ty<'tcx>>,
302+
fn_ptr: &'ll Value,
303+
) -> &'ll Type {
304+
fn_abi.llvm_type(self, &llvm::get_value_name(fn_ptr), false).fn_ty()
293305
}
294306
fn fn_ptr_backend_type(&self, fn_abi: &FnAbi<'tcx, Ty<'tcx>>) -> &'ll Type {
295307
fn_abi.ptr_to_llvm_type(self)

0 commit comments

Comments
 (0)