1 use crate::builder::Builder;
2 use crate::context::CodegenCx;
3 use crate::llvm::{self, AttributePlace};
5 use crate::type_::Type;
6 use crate::type_of::LayoutLlvmExt;
7 use crate::value::Value;
9 use rustc_codegen_ssa::mir::operand::OperandValue;
10 use rustc_codegen_ssa::mir::place::PlaceRef;
11 use rustc_codegen_ssa::traits::*;
12 use rustc_codegen_ssa::MemFlags;
13 use rustc_middle::bug;
14 use rustc_middle::ty::layout::LayoutOf;
15 pub use rustc_middle::ty::layout::{FAT_PTR_ADDR, FAT_PTR_EXTRA};
16 use rustc_middle::ty::Ty;
17 use rustc_target::abi::call::ArgAbi;
18 pub use rustc_target::abi::call::*;
19 use rustc_target::abi::{self, HasDataLayout, Int};
20 pub use rustc_target::spec::abi::Abi;
24 macro_rules! for_each_kind {
25 ($flags: ident, $f: ident, $($kind: ident),+) => ({
26 $(if $flags.contains(ArgAttribute::$kind) { $f(llvm::Attribute::$kind) })+
30 trait ArgAttributeExt {
31 fn for_each_kind<F>(&self, f: F)
33 F: FnMut(llvm::Attribute);
36 impl ArgAttributeExt for ArgAttribute {
37 fn for_each_kind<F>(&self, mut f: F)
39 F: FnMut(llvm::Attribute),
41 for_each_kind!(self, f, NoAlias, NoCapture, NonNull, ReadOnly, InReg)
45 pub trait ArgAttributesExt {
46 fn apply_attrs_to_llfn(&self, idx: AttributePlace, cx: &CodegenCx<'_, '_>, llfn: &Value);
47 fn apply_attrs_to_callsite(
50 cx: &CodegenCx<'_, '_>,
55 fn should_use_mutable_noalias(cx: &CodegenCx<'_, '_>) -> bool {
56 // LLVM prior to version 12 has known miscompiles in the presence of
57 // noalias attributes (see #54878). Only enable mutable noalias by
58 // default for versions we believe to be safe.
64 .unwrap_or_else(|| llvm_util::get_version() >= (12, 0, 0))
67 impl ArgAttributesExt for ArgAttributes {
68 fn apply_attrs_to_llfn(&self, idx: AttributePlace, cx: &CodegenCx<'_, '_>, llfn: &Value) {
69 let mut regular = self.regular;
71 let deref = self.pointee_size.bytes();
73 if regular.contains(ArgAttribute::NonNull) {
74 llvm::LLVMRustAddDereferenceableAttr(llfn, idx.as_uint(), deref);
76 llvm::LLVMRustAddDereferenceableOrNullAttr(llfn, idx.as_uint(), deref);
78 regular -= ArgAttribute::NonNull;
80 if let Some(align) = self.pointee_align {
81 llvm::LLVMRustAddAlignmentAttr(llfn, idx.as_uint(), align.bytes() as u32);
83 regular.for_each_kind(|attr| attr.apply_llfn(idx, llfn));
84 if regular.contains(ArgAttribute::NoAliasMutRef) && should_use_mutable_noalias(cx) {
85 llvm::Attribute::NoAlias.apply_llfn(idx, llfn);
88 ArgExtension::None => {}
89 ArgExtension::Zext => {
90 llvm::Attribute::ZExt.apply_llfn(idx, llfn);
92 ArgExtension::Sext => {
93 llvm::Attribute::SExt.apply_llfn(idx, llfn);
99 fn apply_attrs_to_callsite(
102 cx: &CodegenCx<'_, '_>,
105 let mut regular = self.regular;
107 let deref = self.pointee_size.bytes();
109 if regular.contains(ArgAttribute::NonNull) {
110 llvm::LLVMRustAddDereferenceableCallSiteAttr(callsite, idx.as_uint(), deref);
112 llvm::LLVMRustAddDereferenceableOrNullCallSiteAttr(
118 regular -= ArgAttribute::NonNull;
120 if let Some(align) = self.pointee_align {
121 llvm::LLVMRustAddAlignmentCallSiteAttr(
124 align.bytes() as u32,
127 regular.for_each_kind(|attr| attr.apply_callsite(idx, callsite));
128 if regular.contains(ArgAttribute::NoAliasMutRef) && should_use_mutable_noalias(cx) {
129 llvm::Attribute::NoAlias.apply_callsite(idx, callsite);
132 ArgExtension::None => {}
133 ArgExtension::Zext => {
134 llvm::Attribute::ZExt.apply_callsite(idx, callsite);
136 ArgExtension::Sext => {
137 llvm::Attribute::SExt.apply_callsite(idx, callsite);
145 fn llvm_type(&self, cx: &CodegenCx<'ll, '_>) -> &'ll Type;
148 impl LlvmType for Reg {
149 fn llvm_type(&self, cx: &CodegenCx<'ll, '_>) -> &'ll Type {
151 RegKind::Integer => cx.type_ix(self.size.bits()),
152 RegKind::Float => match self.size.bits() {
155 _ => bug!("unsupported float: {:?}", self),
157 RegKind::Vector => cx.type_vector(cx.type_i8(), self.size.bytes()),
162 impl LlvmType for CastTarget {
163 fn llvm_type(&self, cx: &CodegenCx<'ll, '_>) -> &'ll Type {
164 let rest_ll_unit = self.rest.unit.llvm_type(cx);
165 let (rest_count, rem_bytes) = if self.rest.unit.size.bytes() == 0 {
169 self.rest.total.bytes() / self.rest.unit.size.bytes(),
170 self.rest.total.bytes() % self.rest.unit.size.bytes(),
174 if self.prefix.iter().all(|x| x.is_none()) {
175 // Simplify to a single unit when there is no prefix and size <= unit size
176 if self.rest.total <= self.rest.unit.size {
180 // Simplify to array when all chunks are the same size and type
182 return cx.type_array(rest_ll_unit, rest_count);
186 // Create list of fields in the main structure
187 let mut args: Vec<_> = self
190 .flat_map(|option_kind| {
191 option_kind.map(|kind| Reg { kind, size: self.prefix_chunk_size }.llvm_type(cx))
193 .chain((0..rest_count).map(|_| rest_ll_unit))
196 // Append final integer
198 // Only integers can be really split further.
199 assert_eq!(self.rest.unit.kind, RegKind::Integer);
200 args.push(cx.type_ix(rem_bytes * 8));
203 cx.type_struct(&args, false)
207 pub trait ArgAbiExt<'ll, 'tcx> {
208 fn memory_ty(&self, cx: &CodegenCx<'ll, 'tcx>) -> &'ll Type;
211 bx: &mut Builder<'_, 'll, 'tcx>,
213 dst: PlaceRef<'tcx, &'ll Value>,
217 bx: &mut Builder<'_, 'll, 'tcx>,
219 dst: PlaceRef<'tcx, &'ll Value>,
223 impl ArgAbiExt<'ll, 'tcx> for ArgAbi<'tcx, Ty<'tcx>> {
224 /// Gets the LLVM type for a place of the original Rust type of
225 /// this argument/return, i.e., the result of `type_of::type_of`.
226 fn memory_ty(&self, cx: &CodegenCx<'ll, 'tcx>) -> &'ll Type {
227 self.layout.llvm_type(cx)
230 /// Stores a direct/indirect value described by this ArgAbi into a
231 /// place for the original Rust type of this argument/return.
232 /// Can be used for both storing formal arguments into Rust variables
233 /// or results of call/invoke instructions into their destinations.
236 bx: &mut Builder<'_, 'll, 'tcx>,
238 dst: PlaceRef<'tcx, &'ll Value>,
240 if self.is_ignore() {
243 if self.is_sized_indirect() {
244 OperandValue::Ref(val, None, self.layout.align.abi).store(bx, dst)
245 } else if self.is_unsized_indirect() {
246 bug!("unsized `ArgAbi` must be handled through `store_fn_arg`");
247 } else if let PassMode::Cast(cast) = self.mode {
248 // FIXME(eddyb): Figure out when the simpler Store is safe, clang
249 // uses it for i16 -> {i8, i8}, but not for i24 -> {i8, i8, i8}.
250 let can_store_through_cast_ptr = false;
251 if can_store_through_cast_ptr {
252 let cast_ptr_llty = bx.type_ptr_to(cast.llvm_type(bx));
253 let cast_dst = bx.pointercast(dst.llval, cast_ptr_llty);
254 bx.store(val, cast_dst, self.layout.align.abi);
256 // The actual return type is a struct, but the ABI
257 // adaptation code has cast it into some scalar type. The
258 // code that follows is the only reliable way I have
259 // found to do a transform like i64 -> {i32,i32}.
260 // Basically we dump the data onto the stack then memcpy it.
262 // Other approaches I tried:
263 // - Casting rust ret pointer to the foreign type and using Store
264 // is (a) unsafe if size of foreign type > size of rust type and
265 // (b) runs afoul of strict aliasing rules, yielding invalid
266 // assembly under -O (specifically, the store gets removed).
267 // - Truncating foreign type to correct integral type and then
268 // bitcasting to the struct type yields invalid cast errors.
270 // We instead thus allocate some scratch space...
271 let scratch_size = cast.size(bx);
272 let scratch_align = cast.align(bx);
273 let llscratch = bx.alloca(cast.llvm_type(bx), scratch_align);
274 bx.lifetime_start(llscratch, scratch_size);
276 // ... where we first store the value...
277 bx.store(val, llscratch, scratch_align);
279 // ... and then memcpy it to the intended destination.
282 self.layout.align.abi,
285 bx.const_usize(self.layout.size.bytes()),
289 bx.lifetime_end(llscratch, scratch_size);
292 OperandValue::Immediate(val).store(bx, dst);
298 bx: &mut Builder<'a, 'll, 'tcx>,
300 dst: PlaceRef<'tcx, &'ll Value>,
303 let val = llvm::get_param(bx.llfn(), *idx as c_uint);
308 PassMode::Ignore => {}
309 PassMode::Pair(..) => {
310 OperandValue::Pair(next(), next()).store(bx, dst);
312 PassMode::Indirect { attrs: _, extra_attrs: Some(_), on_stack: _ } => {
313 OperandValue::Ref(next(), Some(next()), self.layout.align.abi).store(bx, dst);
316 | PassMode::Indirect { attrs: _, extra_attrs: None, on_stack: _ }
317 | PassMode::Cast(_) => {
318 let next_arg = next();
319 self.store(bx, next_arg, dst);
325 impl ArgAbiMethods<'tcx> for Builder<'a, 'll, 'tcx> {
328 arg_abi: &ArgAbi<'tcx, Ty<'tcx>>,
330 dst: PlaceRef<'tcx, Self::Value>,
332 arg_abi.store_fn_arg(self, idx, dst)
336 arg_abi: &ArgAbi<'tcx, Ty<'tcx>>,
338 dst: PlaceRef<'tcx, &'ll Value>,
340 arg_abi.store(self, val, dst)
342 fn arg_memory_ty(&self, arg_abi: &ArgAbi<'tcx, Ty<'tcx>>) -> &'ll Type {
343 arg_abi.memory_ty(self)
347 pub trait FnAbiLlvmExt<'tcx> {
348 fn llvm_type(&self, cx: &CodegenCx<'ll, 'tcx>) -> &'ll Type;
349 fn ptr_to_llvm_type(&self, cx: &CodegenCx<'ll, 'tcx>) -> &'ll Type;
350 fn llvm_cconv(&self) -> llvm::CallConv;
351 fn apply_attrs_llfn(&self, cx: &CodegenCx<'ll, 'tcx>, llfn: &'ll Value);
352 fn apply_attrs_callsite(&self, bx: &mut Builder<'a, 'll, 'tcx>, callsite: &'ll Value);
355 impl<'tcx> FnAbiLlvmExt<'tcx> for FnAbi<'tcx, Ty<'tcx>> {
356 fn llvm_type(&self, cx: &CodegenCx<'ll, 'tcx>) -> &'ll Type {
357 // Ignore "extra" args from the call site for C variadic functions.
358 // Only the "fixed" args are part of the LLVM function signature.
359 let args = if self.c_variadic { &self.args[..self.fixed_count] } else { &self.args };
361 let args_capacity: usize = args.iter().map(|arg|
362 if arg.pad.is_some() { 1 } else { 0 } +
363 if let PassMode::Pair(_, _) = arg.mode { 2 } else { 1 }
365 let mut llargument_tys = Vec::with_capacity(
366 if let PassMode::Indirect { .. } = self.ret.mode { 1 } else { 0 } + args_capacity,
369 let llreturn_ty = match self.ret.mode {
370 PassMode::Ignore => cx.type_void(),
371 PassMode::Direct(_) | PassMode::Pair(..) => self.ret.layout.immediate_llvm_type(cx),
372 PassMode::Cast(cast) => cast.llvm_type(cx),
373 PassMode::Indirect { .. } => {
374 llargument_tys.push(cx.type_ptr_to(self.ret.memory_ty(cx)));
381 if let Some(ty) = arg.pad {
382 llargument_tys.push(ty.llvm_type(cx));
385 let llarg_ty = match arg.mode {
386 PassMode::Ignore => continue,
387 PassMode::Direct(_) => arg.layout.immediate_llvm_type(cx),
388 PassMode::Pair(..) => {
389 llargument_tys.push(arg.layout.scalar_pair_element_llvm_type(cx, 0, true));
390 llargument_tys.push(arg.layout.scalar_pair_element_llvm_type(cx, 1, true));
393 PassMode::Indirect { attrs: _, extra_attrs: Some(_), on_stack: _ } => {
394 let ptr_ty = cx.tcx.mk_mut_ptr(arg.layout.ty);
395 let ptr_layout = cx.layout_of(ptr_ty);
396 llargument_tys.push(ptr_layout.scalar_pair_element_llvm_type(cx, 0, true));
397 llargument_tys.push(ptr_layout.scalar_pair_element_llvm_type(cx, 1, true));
400 PassMode::Cast(cast) => cast.llvm_type(cx),
401 PassMode::Indirect { attrs: _, extra_attrs: None, on_stack: _ } => {
402 cx.type_ptr_to(arg.memory_ty(cx))
405 llargument_tys.push(llarg_ty);
409 cx.type_variadic_func(&llargument_tys, llreturn_ty)
411 cx.type_func(&llargument_tys, llreturn_ty)
415 fn ptr_to_llvm_type(&self, cx: &CodegenCx<'ll, 'tcx>) -> &'ll Type {
417 llvm::LLVMPointerType(
419 cx.data_layout().instruction_address_space.0 as c_uint,
424 fn llvm_cconv(&self) -> llvm::CallConv {
426 Conv::C | Conv::Rust | Conv::CCmseNonSecureCall => llvm::CCallConv,
427 Conv::AmdGpuKernel => llvm::AmdGpuKernel,
428 Conv::AvrInterrupt => llvm::AvrInterrupt,
429 Conv::AvrNonBlockingInterrupt => llvm::AvrNonBlockingInterrupt,
430 Conv::ArmAapcs => llvm::ArmAapcsCallConv,
431 Conv::Msp430Intr => llvm::Msp430Intr,
432 Conv::PtxKernel => llvm::PtxKernel,
433 Conv::X86Fastcall => llvm::X86FastcallCallConv,
434 Conv::X86Intr => llvm::X86_Intr,
435 Conv::X86Stdcall => llvm::X86StdcallCallConv,
436 Conv::X86ThisCall => llvm::X86_ThisCall,
437 Conv::X86VectorCall => llvm::X86_VectorCall,
438 Conv::X86_64SysV => llvm::X86_64_SysV,
439 Conv::X86_64Win64 => llvm::X86_64_Win64,
443 fn apply_attrs_llfn(&self, cx: &CodegenCx<'ll, 'tcx>, llfn: &'ll Value) {
444 // FIXME(eddyb) can this also be applied to callsites?
445 if self.ret.layout.abi.is_uninhabited() {
446 llvm::Attribute::NoReturn.apply_llfn(llvm::AttributePlace::Function, llfn);
449 // FIXME(eddyb, wesleywiser): apply this to callsites as well?
450 if !self.can_unwind {
451 llvm::Attribute::NoUnwind.apply_llfn(llvm::AttributePlace::Function, llfn);
455 let mut apply = |attrs: &ArgAttributes| {
456 attrs.apply_attrs_to_llfn(llvm::AttributePlace::Argument(i), cx, llfn);
460 match self.ret.mode {
461 PassMode::Direct(ref attrs) => {
462 attrs.apply_attrs_to_llfn(llvm::AttributePlace::ReturnValue, cx, llfn);
464 PassMode::Indirect { ref attrs, extra_attrs: _, on_stack } => {
466 let i = apply(attrs);
468 llvm::LLVMRustAddStructRetAttr(
470 llvm::AttributePlace::Argument(i).as_uint(),
471 self.ret.layout.llvm_type(cx),
477 for arg in &self.args {
478 if arg.pad.is_some() {
479 apply(&ArgAttributes::new());
482 PassMode::Ignore => {}
483 PassMode::Indirect { ref attrs, extra_attrs: None, on_stack: true } => {
484 let i = apply(attrs);
486 llvm::LLVMRustAddByValAttr(
488 llvm::AttributePlace::Argument(i).as_uint(),
489 arg.layout.llvm_type(cx),
493 PassMode::Direct(ref attrs)
494 | PassMode::Indirect { ref attrs, extra_attrs: None, on_stack: false } => {
497 PassMode::Indirect { ref attrs, extra_attrs: Some(ref extra_attrs), on_stack } => {
502 PassMode::Pair(ref a, ref b) => {
506 PassMode::Cast(_) => {
507 apply(&ArgAttributes::new());
513 fn apply_attrs_callsite(&self, bx: &mut Builder<'a, 'll, 'tcx>, callsite: &'ll Value) {
514 if self.ret.layout.abi.is_uninhabited() {
515 llvm::Attribute::NoReturn.apply_callsite(llvm::AttributePlace::Function, callsite);
517 if !self.can_unwind {
518 llvm::Attribute::NoUnwind.apply_callsite(llvm::AttributePlace::Function, callsite);
522 let mut apply = |cx: &CodegenCx<'_, '_>, attrs: &ArgAttributes| {
523 attrs.apply_attrs_to_callsite(llvm::AttributePlace::Argument(i), cx, callsite);
527 match self.ret.mode {
528 PassMode::Direct(ref attrs) => {
529 attrs.apply_attrs_to_callsite(llvm::AttributePlace::ReturnValue, bx.cx, callsite);
531 PassMode::Indirect { ref attrs, extra_attrs: _, on_stack } => {
533 let i = apply(bx.cx, attrs);
535 llvm::LLVMRustAddStructRetCallSiteAttr(
537 llvm::AttributePlace::Argument(i).as_uint(),
538 self.ret.layout.llvm_type(bx),
544 if let abi::Abi::Scalar(scalar) = self.ret.layout.abi {
545 // If the value is a boolean, the range is 0..2 and that ultimately
546 // become 0..0 when the type becomes i1, which would be rejected
547 // by the LLVM verifier.
548 if let Int(..) = scalar.value {
549 if !scalar.is_bool() && !scalar.is_always_valid(bx) {
550 bx.range_metadata(callsite, scalar.valid_range);
554 for arg in &self.args {
555 if arg.pad.is_some() {
556 apply(bx.cx, &ArgAttributes::new());
559 PassMode::Ignore => {}
560 PassMode::Indirect { ref attrs, extra_attrs: None, on_stack: true } => {
561 let i = apply(bx.cx, attrs);
563 llvm::LLVMRustAddByValCallSiteAttr(
565 llvm::AttributePlace::Argument(i).as_uint(),
566 arg.layout.llvm_type(bx),
570 PassMode::Direct(ref attrs)
571 | PassMode::Indirect { ref attrs, extra_attrs: None, on_stack: false } => {
576 extra_attrs: Some(ref extra_attrs),
580 apply(bx.cx, extra_attrs);
582 PassMode::Pair(ref a, ref b) => {
586 PassMode::Cast(_) => {
587 apply(bx.cx, &ArgAttributes::new());
592 let cconv = self.llvm_cconv();
593 if cconv != llvm::CCallConv {
594 llvm::SetInstructionCallConv(callsite, cconv);
597 if self.conv == Conv::CCmseNonSecureCall {
598 // This will probably get ignored on all targets but those supporting the TrustZone-M
599 // extension (thumbv8m targets).
601 llvm::AddCallSiteAttrString(
603 llvm::AttributePlace::Function,
604 cstr::cstr!("cmse_nonsecure_call"),
611 impl AbiBuilderMethods<'tcx> for Builder<'a, 'll, 'tcx> {
612 fn apply_attrs_callsite(&mut self, fn_abi: &FnAbi<'tcx, Ty<'tcx>>, callsite: Self::Value) {
613 fn_abi.apply_attrs_callsite(self, callsite)
616 fn get_param(&self, index: usize) -> Self::Value {
617 llvm::get_param(self.llfn(), index as c_uint)