2 use crate::builder::Builder;
3 use crate::context::CodegenCx;
4 use crate::llvm::{self, Attribute, 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_session::config;
18 use rustc_target::abi::call::ArgAbi;
19 pub use rustc_target::abi::call::*;
20 use rustc_target::abi::{self, HasDataLayout, Int};
21 pub use rustc_target::spec::abi::Abi;
22 use rustc_target::spec::SanitizerSet;
25 use smallvec::SmallVec;
27 pub trait ArgAttributesExt {
28 fn apply_attrs_to_llfn(&self, idx: AttributePlace, cx: &CodegenCx<'_, '_>, llfn: &Value);
29 fn apply_attrs_to_callsite(
32 cx: &CodegenCx<'_, '_>,
37 const ABI_AFFECTING_ATTRIBUTES: [(ArgAttribute, llvm::AttributeKind); 1] =
38 [(ArgAttribute::InReg, llvm::AttributeKind::InReg)];
40 const OPTIMIZATION_ATTRIBUTES: [(ArgAttribute, llvm::AttributeKind); 5] = [
41 (ArgAttribute::NoAlias, llvm::AttributeKind::NoAlias),
42 (ArgAttribute::NoCapture, llvm::AttributeKind::NoCapture),
43 (ArgAttribute::NonNull, llvm::AttributeKind::NonNull),
44 (ArgAttribute::ReadOnly, llvm::AttributeKind::ReadOnly),
45 (ArgAttribute::NoUndef, llvm::AttributeKind::NoUndef),
48 fn get_attrs<'ll>(this: &ArgAttributes, cx: &CodegenCx<'ll, '_>) -> SmallVec<[&'ll Attribute; 8]> {
49 let mut regular = this.regular;
51 let mut attrs = SmallVec::new();
53 // ABI-affecting attributes must always be applied
54 for (attr, llattr) in ABI_AFFECTING_ATTRIBUTES {
55 if regular.contains(attr) {
56 attrs.push(llattr.create_attr(cx.llcx));
59 if let Some(align) = this.pointee_align {
60 attrs.push(llvm::CreateAlignmentAttr(cx.llcx, align.bytes()));
63 ArgExtension::None => {}
64 ArgExtension::Zext => attrs.push(llvm::AttributeKind::ZExt.create_attr(cx.llcx)),
65 ArgExtension::Sext => attrs.push(llvm::AttributeKind::SExt.create_attr(cx.llcx)),
68 // Only apply remaining attributes when optimizing
69 if cx.sess().opts.optimize != config::OptLevel::No {
70 let deref = this.pointee_size.bytes();
72 if regular.contains(ArgAttribute::NonNull) {
73 attrs.push(llvm::CreateDereferenceableAttr(cx.llcx, deref));
75 attrs.push(llvm::CreateDereferenceableOrNullAttr(cx.llcx, deref));
77 regular -= ArgAttribute::NonNull;
79 for (attr, llattr) in OPTIMIZATION_ATTRIBUTES {
80 if regular.contains(attr) {
81 attrs.push(llattr.create_attr(cx.llcx));
84 } else if cx.tcx.sess.opts.unstable_opts.sanitizer.contains(SanitizerSet::MEMORY) {
85 // If we're not optimising, *but* memory sanitizer is on, emit noundef, since it affects
86 // memory sanitizer's behavior.
88 if regular.contains(ArgAttribute::NoUndef) {
89 attrs.push(llvm::AttributeKind::NoUndef.create_attr(cx.llcx));
96 impl ArgAttributesExt for ArgAttributes {
97 fn apply_attrs_to_llfn(&self, idx: AttributePlace, cx: &CodegenCx<'_, '_>, llfn: &Value) {
98 let attrs = get_attrs(self, cx);
99 attributes::apply_to_llfn(llfn, idx, &attrs);
102 fn apply_attrs_to_callsite(
105 cx: &CodegenCx<'_, '_>,
108 let attrs = get_attrs(self, cx);
109 attributes::apply_to_callsite(callsite, idx, &attrs);
114 fn llvm_type<'ll>(&self, cx: &CodegenCx<'ll, '_>) -> &'ll Type;
117 impl LlvmType for Reg {
118 fn llvm_type<'ll>(&self, cx: &CodegenCx<'ll, '_>) -> &'ll Type {
120 RegKind::Integer => cx.type_ix(self.size.bits()),
121 RegKind::Float => match self.size.bits() {
124 _ => bug!("unsupported float: {:?}", self),
126 RegKind::Vector => cx.type_vector(cx.type_i8(), self.size.bytes()),
131 impl LlvmType for CastTarget {
132 fn llvm_type<'ll>(&self, cx: &CodegenCx<'ll, '_>) -> &'ll Type {
133 let rest_ll_unit = self.rest.unit.llvm_type(cx);
134 let (rest_count, rem_bytes) = if self.rest.unit.size.bytes() == 0 {
138 self.rest.total.bytes() / self.rest.unit.size.bytes(),
139 self.rest.total.bytes() % self.rest.unit.size.bytes(),
143 if self.prefix.iter().all(|x| x.is_none()) {
144 // Simplify to a single unit when there is no prefix and size <= unit size
145 if self.rest.total <= self.rest.unit.size {
149 // Simplify to array when all chunks are the same size and type
151 return cx.type_array(rest_ll_unit, rest_count);
155 // Create list of fields in the main structure
156 let mut args: Vec<_> = self
159 .flat_map(|option_reg| option_reg.map(|reg| reg.llvm_type(cx)))
160 .chain((0..rest_count).map(|_| rest_ll_unit))
163 // Append final integer
165 // Only integers can be really split further.
166 assert_eq!(self.rest.unit.kind, RegKind::Integer);
167 args.push(cx.type_ix(rem_bytes * 8));
170 cx.type_struct(&args, false)
174 pub trait ArgAbiExt<'ll, 'tcx> {
175 fn memory_ty(&self, cx: &CodegenCx<'ll, 'tcx>) -> &'ll Type;
178 bx: &mut Builder<'_, 'll, 'tcx>,
180 dst: PlaceRef<'tcx, &'ll Value>,
184 bx: &mut Builder<'_, 'll, 'tcx>,
186 dst: PlaceRef<'tcx, &'ll Value>,
190 impl<'ll, 'tcx> ArgAbiExt<'ll, 'tcx> for ArgAbi<'tcx, Ty<'tcx>> {
191 /// Gets the LLVM type for a place of the original Rust type of
192 /// this argument/return, i.e., the result of `type_of::type_of`.
193 fn memory_ty(&self, cx: &CodegenCx<'ll, 'tcx>) -> &'ll Type {
194 self.layout.llvm_type(cx)
197 /// Stores a direct/indirect value described by this ArgAbi into a
198 /// place for the original Rust type of this argument/return.
199 /// Can be used for both storing formal arguments into Rust variables
200 /// or results of call/invoke instructions into their destinations.
203 bx: &mut Builder<'_, 'll, 'tcx>,
205 dst: PlaceRef<'tcx, &'ll Value>,
207 if self.is_ignore() {
210 if self.is_sized_indirect() {
211 OperandValue::Ref(val, None, self.layout.align.abi).store(bx, dst)
212 } else if self.is_unsized_indirect() {
213 bug!("unsized `ArgAbi` must be handled through `store_fn_arg`");
214 } else if let PassMode::Cast(cast, _) = &self.mode {
215 // FIXME(eddyb): Figure out when the simpler Store is safe, clang
216 // uses it for i16 -> {i8, i8}, but not for i24 -> {i8, i8, i8}.
217 let can_store_through_cast_ptr = false;
218 if can_store_through_cast_ptr {
219 let cast_ptr_llty = bx.type_ptr_to(cast.llvm_type(bx));
220 let cast_dst = bx.pointercast(dst.llval, cast_ptr_llty);
221 bx.store(val, cast_dst, self.layout.align.abi);
223 // The actual return type is a struct, but the ABI
224 // adaptation code has cast it into some scalar type. The
225 // code that follows is the only reliable way I have
226 // found to do a transform like i64 -> {i32,i32}.
227 // Basically we dump the data onto the stack then memcpy it.
229 // Other approaches I tried:
230 // - Casting rust ret pointer to the foreign type and using Store
231 // is (a) unsafe if size of foreign type > size of rust type and
232 // (b) runs afoul of strict aliasing rules, yielding invalid
233 // assembly under -O (specifically, the store gets removed).
234 // - Truncating foreign type to correct integral type and then
235 // bitcasting to the struct type yields invalid cast errors.
237 // We instead thus allocate some scratch space...
238 let scratch_size = cast.size(bx);
239 let scratch_align = cast.align(bx);
240 let llscratch = bx.alloca(cast.llvm_type(bx), scratch_align);
241 bx.lifetime_start(llscratch, scratch_size);
243 // ... where we first store the value...
244 bx.store(val, llscratch, scratch_align);
246 // ... and then memcpy it to the intended destination.
249 self.layout.align.abi,
252 bx.const_usize(self.layout.size.bytes()),
256 bx.lifetime_end(llscratch, scratch_size);
259 OperandValue::Immediate(val).store(bx, dst);
265 bx: &mut Builder<'_, 'll, 'tcx>,
267 dst: PlaceRef<'tcx, &'ll Value>,
270 let val = llvm::get_param(bx.llfn(), *idx as c_uint);
275 PassMode::Ignore => {}
276 PassMode::Pair(..) => {
277 OperandValue::Pair(next(), next()).store(bx, dst);
279 PassMode::Indirect { attrs: _, extra_attrs: Some(_), on_stack: _ } => {
280 OperandValue::Ref(next(), Some(next()), self.layout.align.abi).store(bx, dst);
283 | PassMode::Indirect { attrs: _, extra_attrs: None, on_stack: _ }
284 | PassMode::Cast(..) => {
285 let next_arg = next();
286 self.store(bx, next_arg, dst);
292 impl<'ll, 'tcx> ArgAbiMethods<'tcx> for Builder<'_, 'll, 'tcx> {
295 arg_abi: &ArgAbi<'tcx, Ty<'tcx>>,
297 dst: PlaceRef<'tcx, Self::Value>,
299 arg_abi.store_fn_arg(self, idx, dst)
303 arg_abi: &ArgAbi<'tcx, Ty<'tcx>>,
305 dst: PlaceRef<'tcx, &'ll Value>,
307 arg_abi.store(self, val, dst)
309 fn arg_memory_ty(&self, arg_abi: &ArgAbi<'tcx, Ty<'tcx>>) -> &'ll Type {
310 arg_abi.memory_ty(self)
314 pub trait FnAbiLlvmExt<'ll, 'tcx> {
315 fn llvm_type(&self, cx: &CodegenCx<'ll, 'tcx>) -> &'ll Type;
316 fn ptr_to_llvm_type(&self, cx: &CodegenCx<'ll, 'tcx>) -> &'ll Type;
317 fn llvm_cconv(&self) -> llvm::CallConv;
318 fn apply_attrs_llfn(&self, cx: &CodegenCx<'ll, 'tcx>, llfn: &'ll Value);
319 fn apply_attrs_callsite(&self, bx: &mut Builder<'_, 'll, 'tcx>, callsite: &'ll Value);
322 impl<'ll, 'tcx> FnAbiLlvmExt<'ll, 'tcx> for FnAbi<'tcx, Ty<'tcx>> {
323 fn llvm_type(&self, cx: &CodegenCx<'ll, 'tcx>) -> &'ll Type {
324 // Ignore "extra" args from the call site for C variadic functions.
325 // Only the "fixed" args are part of the LLVM function signature.
327 if self.c_variadic { &self.args[..self.fixed_count as usize] } else { &self.args };
329 // This capacity calculation is approximate.
330 let mut llargument_tys = Vec::with_capacity(
331 self.args.len() + if let PassMode::Indirect { .. } = self.ret.mode { 1 } else { 0 },
334 let llreturn_ty = match &self.ret.mode {
335 PassMode::Ignore => cx.type_void(),
336 PassMode::Direct(_) | PassMode::Pair(..) => self.ret.layout.immediate_llvm_type(cx),
337 PassMode::Cast(cast, _) => cast.llvm_type(cx),
338 PassMode::Indirect { .. } => {
339 llargument_tys.push(cx.type_ptr_to(self.ret.memory_ty(cx)));
345 let llarg_ty = match &arg.mode {
346 PassMode::Ignore => continue,
347 PassMode::Direct(_) => arg.layout.immediate_llvm_type(cx),
348 PassMode::Pair(..) => {
349 llargument_tys.push(arg.layout.scalar_pair_element_llvm_type(cx, 0, true));
350 llargument_tys.push(arg.layout.scalar_pair_element_llvm_type(cx, 1, true));
353 PassMode::Indirect { attrs: _, extra_attrs: Some(_), on_stack: _ } => {
354 let ptr_ty = cx.tcx.mk_mut_ptr(arg.layout.ty);
355 let ptr_layout = cx.layout_of(ptr_ty);
356 llargument_tys.push(ptr_layout.scalar_pair_element_llvm_type(cx, 0, true));
357 llargument_tys.push(ptr_layout.scalar_pair_element_llvm_type(cx, 1, true));
360 PassMode::Cast(cast, pad_i32) => {
363 llargument_tys.push(Reg::i32().llvm_type(cx));
367 PassMode::Indirect { attrs: _, extra_attrs: None, on_stack: _ } => {
368 cx.type_ptr_to(arg.memory_ty(cx))
371 llargument_tys.push(llarg_ty);
375 cx.type_variadic_func(&llargument_tys, llreturn_ty)
377 cx.type_func(&llargument_tys, llreturn_ty)
381 fn ptr_to_llvm_type(&self, cx: &CodegenCx<'ll, 'tcx>) -> &'ll Type {
383 llvm::LLVMPointerType(
385 cx.data_layout().instruction_address_space.0 as c_uint,
390 fn llvm_cconv(&self) -> llvm::CallConv {
394 fn apply_attrs_llfn(&self, cx: &CodegenCx<'ll, 'tcx>, llfn: &'ll Value) {
395 let mut func_attrs = SmallVec::<[_; 2]>::new();
396 if self.ret.layout.abi.is_uninhabited() {
397 func_attrs.push(llvm::AttributeKind::NoReturn.create_attr(cx.llcx));
399 if !self.can_unwind {
400 func_attrs.push(llvm::AttributeKind::NoUnwind.create_attr(cx.llcx));
402 attributes::apply_to_llfn(llfn, llvm::AttributePlace::Function, &{ func_attrs });
405 let mut apply = |attrs: &ArgAttributes| {
406 attrs.apply_attrs_to_llfn(llvm::AttributePlace::Argument(i), cx, llfn);
410 match &self.ret.mode {
411 PassMode::Direct(attrs) => {
412 attrs.apply_attrs_to_llfn(llvm::AttributePlace::ReturnValue, cx, llfn);
414 PassMode::Indirect { attrs, extra_attrs: _, on_stack } => {
416 let i = apply(attrs);
417 let sret = llvm::CreateStructRetAttr(cx.llcx, self.ret.layout.llvm_type(cx));
418 attributes::apply_to_llfn(llfn, llvm::AttributePlace::Argument(i), &[sret]);
420 PassMode::Cast(cast, _) => {
421 cast.attrs.apply_attrs_to_llfn(llvm::AttributePlace::ReturnValue, cx, llfn);
425 for arg in self.args.iter() {
427 PassMode::Ignore => {}
428 PassMode::Indirect { attrs, extra_attrs: None, on_stack: true } => {
429 let i = apply(attrs);
430 let byval = llvm::CreateByValAttr(cx.llcx, arg.layout.llvm_type(cx));
431 attributes::apply_to_llfn(llfn, llvm::AttributePlace::Argument(i), &[byval]);
433 PassMode::Direct(attrs)
434 | PassMode::Indirect { attrs, extra_attrs: None, on_stack: false } => {
437 PassMode::Indirect { attrs, extra_attrs: Some(extra_attrs), on_stack } => {
442 PassMode::Pair(a, b) => {
446 PassMode::Cast(cast, pad_i32) => {
448 apply(&ArgAttributes::new());
456 fn apply_attrs_callsite(&self, bx: &mut Builder<'_, 'll, 'tcx>, callsite: &'ll Value) {
457 let mut func_attrs = SmallVec::<[_; 2]>::new();
458 if self.ret.layout.abi.is_uninhabited() {
459 func_attrs.push(llvm::AttributeKind::NoReturn.create_attr(bx.cx.llcx));
461 if !self.can_unwind {
462 func_attrs.push(llvm::AttributeKind::NoUnwind.create_attr(bx.cx.llcx));
464 attributes::apply_to_callsite(callsite, llvm::AttributePlace::Function, &{ func_attrs });
467 let mut apply = |cx: &CodegenCx<'_, '_>, attrs: &ArgAttributes| {
468 attrs.apply_attrs_to_callsite(llvm::AttributePlace::Argument(i), cx, callsite);
472 match &self.ret.mode {
473 PassMode::Direct(attrs) => {
474 attrs.apply_attrs_to_callsite(llvm::AttributePlace::ReturnValue, bx.cx, callsite);
476 PassMode::Indirect { attrs, extra_attrs: _, on_stack } => {
478 let i = apply(bx.cx, attrs);
479 let sret = llvm::CreateStructRetAttr(bx.cx.llcx, self.ret.layout.llvm_type(bx));
480 attributes::apply_to_callsite(callsite, llvm::AttributePlace::Argument(i), &[sret]);
482 PassMode::Cast(cast, _) => {
483 cast.attrs.apply_attrs_to_callsite(
484 llvm::AttributePlace::ReturnValue,
491 if let abi::Abi::Scalar(scalar) = self.ret.layout.abi {
492 // If the value is a boolean, the range is 0..2 and that ultimately
493 // become 0..0 when the type becomes i1, which would be rejected
494 // by the LLVM verifier.
495 if let Int(..) = scalar.primitive() {
496 if !scalar.is_bool() && !scalar.is_always_valid(bx) {
497 bx.range_metadata(callsite, scalar.valid_range(bx));
501 for arg in self.args.iter() {
503 PassMode::Ignore => {}
504 PassMode::Indirect { attrs, extra_attrs: None, on_stack: true } => {
505 let i = apply(bx.cx, attrs);
506 let byval = llvm::CreateByValAttr(bx.cx.llcx, arg.layout.llvm_type(bx));
507 attributes::apply_to_callsite(
509 llvm::AttributePlace::Argument(i),
513 PassMode::Direct(attrs)
514 | PassMode::Indirect { attrs, extra_attrs: None, on_stack: false } => {
517 PassMode::Indirect { attrs, extra_attrs: Some(extra_attrs), on_stack: _ } => {
519 apply(bx.cx, extra_attrs);
521 PassMode::Pair(a, b) => {
525 PassMode::Cast(cast, pad_i32) => {
527 apply(bx.cx, &ArgAttributes::new());
529 apply(bx.cx, &cast.attrs);
534 let cconv = self.llvm_cconv();
535 if cconv != llvm::CCallConv {
536 llvm::SetInstructionCallConv(callsite, cconv);
539 if self.conv == Conv::CCmseNonSecureCall {
540 // This will probably get ignored on all targets but those supporting the TrustZone-M
541 // extension (thumbv8m targets).
542 let cmse_nonsecure_call = llvm::CreateAttrString(bx.cx.llcx, "cmse_nonsecure_call");
543 attributes::apply_to_callsite(
545 llvm::AttributePlace::Function,
546 &[cmse_nonsecure_call],
550 // Some intrinsics require that an elementtype attribute (with the pointee type of a
551 // pointer argument) is added to the callsite.
552 let element_type_index = unsafe { llvm::LLVMRustGetElementTypeArgIndex(callsite) };
553 if element_type_index >= 0 {
554 let arg_ty = self.args[element_type_index as usize].layout.ty;
555 let pointee_ty = arg_ty.builtin_deref(true).expect("Must be pointer argument").ty;
556 let element_type_attr = unsafe {
557 llvm::LLVMRustCreateElementTypeAttr(bx.llcx, bx.layout_of(pointee_ty).llvm_type(bx))
559 attributes::apply_to_callsite(
561 llvm::AttributePlace::Argument(element_type_index as u32),
562 &[element_type_attr],
568 impl<'tcx> AbiBuilderMethods<'tcx> for Builder<'_, '_, 'tcx> {
569 fn get_param(&mut self, index: usize) -> Self::Value {
570 llvm::get_param(self.llfn(), index as c_uint)
574 impl From<Conv> for llvm::CallConv {
575 fn from(conv: Conv) -> Self {
577 Conv::C | Conv::Rust | Conv::CCmseNonSecureCall => llvm::CCallConv,
578 Conv::RustCold => llvm::ColdCallConv,
579 Conv::AmdGpuKernel => llvm::AmdGpuKernel,
580 Conv::AvrInterrupt => llvm::AvrInterrupt,
581 Conv::AvrNonBlockingInterrupt => llvm::AvrNonBlockingInterrupt,
582 Conv::ArmAapcs => llvm::ArmAapcsCallConv,
583 Conv::Msp430Intr => llvm::Msp430Intr,
584 Conv::PtxKernel => llvm::PtxKernel,
585 Conv::X86Fastcall => llvm::X86FastcallCallConv,
586 Conv::X86Intr => llvm::X86_Intr,
587 Conv::X86Stdcall => llvm::X86StdcallCallConv,
588 Conv::X86ThisCall => llvm::X86_ThisCall,
589 Conv::X86VectorCall => llvm::X86_VectorCall,
590 Conv::X86_64SysV => llvm::X86_64_SysV,
591 Conv::X86_64Win64 => llvm::X86_64_Win64,