1 // Copyright 2012-2016 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 use llvm::{self, ValueRef, AttributePlace};
13 use builder::{Builder, MemFlags};
14 use common::{ty_fn_sig, C_usize};
15 use context::CodegenCx;
16 use mir::place::PlaceRef;
17 use mir::operand::OperandValue;
19 use type_of::{LayoutLlvmExt, PointerKind};
21 use rustc_target::abi::{LayoutOf, Size, TyLayout};
22 use rustc::ty::{self, Ty};
23 use rustc::ty::layout;
27 pub use rustc_target::spec::abi::Abi;
28 pub use rustc::ty::layout::{FAT_PTR_ADDR, FAT_PTR_EXTRA};
29 pub use rustc_target::abi::call::*;
31 macro_rules! for_each_kind {
32 ($flags: ident, $f: ident, $($kind: ident),+) => ({
33 $(if $flags.contains(ArgAttribute::$kind) { $f(llvm::Attribute::$kind) })+
37 trait ArgAttributeExt {
38 fn for_each_kind<F>(&self, f: F) where F: FnMut(llvm::Attribute);
41 impl ArgAttributeExt for ArgAttribute {
42 fn for_each_kind<F>(&self, mut f: F) where F: FnMut(llvm::Attribute) {
43 for_each_kind!(self, f,
44 ByVal, NoAlias, NoCapture, NonNull, ReadOnly, SExt, StructRet, ZExt, InReg)
48 pub trait ArgAttributesExt {
49 fn apply_llfn(&self, idx: AttributePlace, llfn: ValueRef);
50 fn apply_callsite(&self, idx: AttributePlace, callsite: ValueRef);
53 impl ArgAttributesExt for ArgAttributes {
54 fn apply_llfn(&self, idx: AttributePlace, llfn: ValueRef) {
55 let mut regular = self.regular;
57 let deref = self.pointee_size.bytes();
59 if regular.contains(ArgAttribute::NonNull) {
60 llvm::LLVMRustAddDereferenceableAttr(llfn,
64 llvm::LLVMRustAddDereferenceableOrNullAttr(llfn,
68 regular -= ArgAttribute::NonNull;
70 if let Some(align) = self.pointee_align {
71 llvm::LLVMRustAddAlignmentAttr(llfn,
75 regular.for_each_kind(|attr| attr.apply_llfn(idx, llfn));
79 fn apply_callsite(&self, idx: AttributePlace, callsite: ValueRef) {
80 let mut regular = self.regular;
82 let deref = self.pointee_size.bytes();
84 if regular.contains(ArgAttribute::NonNull) {
85 llvm::LLVMRustAddDereferenceableCallSiteAttr(callsite,
89 llvm::LLVMRustAddDereferenceableOrNullCallSiteAttr(callsite,
93 regular -= ArgAttribute::NonNull;
95 if let Some(align) = self.pointee_align {
96 llvm::LLVMRustAddAlignmentCallSiteAttr(callsite,
100 regular.for_each_kind(|attr| attr.apply_callsite(idx, callsite));
106 fn llvm_type(&self, cx: &CodegenCx) -> Type;
109 impl LlvmType for Reg {
110 fn llvm_type(&self, cx: &CodegenCx) -> Type {
112 RegKind::Integer => Type::ix(cx, self.size.bits()),
114 match self.size.bits() {
117 _ => bug!("unsupported float: {:?}", self)
121 Type::vector(&Type::i8(cx), self.size.bytes())
127 impl LlvmType for CastTarget {
128 fn llvm_type(&self, cx: &CodegenCx) -> Type {
129 let rest_ll_unit = self.rest.unit.llvm_type(cx);
130 let rest_count = self.rest.total.bytes() / self.rest.unit.size.bytes();
131 let rem_bytes = self.rest.total.bytes() % self.rest.unit.size.bytes();
133 if self.prefix.iter().all(|x| x.is_none()) {
134 // Simplify to a single unit when there is no prefix and size <= unit size
135 if self.rest.total <= self.rest.unit.size {
139 // Simplify to array when all chunks are the same size and type
141 return Type::array(&rest_ll_unit, rest_count);
145 // Create list of fields in the main structure
146 let mut args: Vec<_> =
147 self.prefix.iter().flat_map(|option_kind| option_kind.map(
148 |kind| Reg { kind: kind, size: self.prefix_chunk }.llvm_type(cx)))
149 .chain((0..rest_count).map(|_| rest_ll_unit))
152 // Append final integer
154 // Only integers can be really split further.
155 assert_eq!(self.rest.unit.kind, RegKind::Integer);
156 args.push(Type::ix(cx, rem_bytes * 8));
159 Type::struct_(cx, &args, false)
163 pub trait ArgTypeExt<'a, 'tcx> {
164 fn memory_ty(&self, cx: &CodegenCx<'a, 'tcx>) -> Type;
165 fn store(&self, bx: &Builder<'a, 'tcx>, val: ValueRef, dst: PlaceRef<'tcx>);
166 fn store_fn_arg(&self, bx: &Builder<'a, 'tcx>, idx: &mut usize, dst: PlaceRef<'tcx>);
169 impl<'a, 'tcx> ArgTypeExt<'a, 'tcx> for ArgType<'tcx, Ty<'tcx>> {
170 /// Get the LLVM type for a place of the original Rust type of
171 /// this argument/return, i.e. the result of `type_of::type_of`.
172 fn memory_ty(&self, cx: &CodegenCx<'a, 'tcx>) -> Type {
173 self.layout.llvm_type(cx)
176 /// Store a direct/indirect value described by this ArgType into a
177 /// place for the original Rust type of this argument/return.
178 /// Can be used for both storing formal arguments into Rust variables
179 /// or results of call/invoke instructions into their destinations.
180 fn store(&self, bx: &Builder<'a, 'tcx>, val: ValueRef, dst: PlaceRef<'tcx>) {
181 if self.is_ignore() {
185 if self.is_indirect() {
186 OperandValue::Ref(val, self.layout.align).store(bx, dst)
187 } else if let PassMode::Cast(cast) = self.mode {
188 // FIXME(eddyb): Figure out when the simpler Store is safe, clang
189 // uses it for i16 -> {i8, i8}, but not for i24 -> {i8, i8, i8}.
190 let can_store_through_cast_ptr = false;
191 if can_store_through_cast_ptr {
192 let cast_dst = bx.pointercast(dst.llval, cast.llvm_type(cx).ptr_to());
193 bx.store(val, cast_dst, self.layout.align);
195 // The actual return type is a struct, but the ABI
196 // adaptation code has cast it into some scalar type. The
197 // code that follows is the only reliable way I have
198 // found to do a transform like i64 -> {i32,i32}.
199 // Basically we dump the data onto the stack then memcpy it.
201 // Other approaches I tried:
202 // - Casting rust ret pointer to the foreign type and using Store
203 // is (a) unsafe if size of foreign type > size of rust type and
204 // (b) runs afoul of strict aliasing rules, yielding invalid
205 // assembly under -O (specifically, the store gets removed).
206 // - Truncating foreign type to correct integral type and then
207 // bitcasting to the struct type yields invalid cast errors.
209 // We instead thus allocate some scratch space...
210 let scratch_size = cast.size(cx);
211 let scratch_align = cast.align(cx);
212 let llscratch = bx.alloca(cast.llvm_type(cx), "abi_cast", scratch_align);
213 bx.lifetime_start(llscratch, scratch_size);
215 // ...where we first store the value...
216 bx.store(val, llscratch, scratch_align);
218 // ...and then memcpy it to the intended destination.
219 base::call_memcpy(bx,
220 bx.pointercast(dst.llval, Type::i8p(cx)),
221 bx.pointercast(llscratch, Type::i8p(cx)),
222 C_usize(cx, self.layout.size.bytes()),
223 self.layout.align.min(scratch_align),
226 bx.lifetime_end(llscratch, scratch_size);
229 OperandValue::Immediate(val).store(bx, dst);
233 fn store_fn_arg(&self, bx: &Builder<'a, 'tcx>, idx: &mut usize, dst: PlaceRef<'tcx>) {
235 let val = llvm::get_param(bx.llfn(), *idx as c_uint);
240 PassMode::Ignore => {},
241 PassMode::Pair(..) => {
242 OperandValue::Pair(next(), next()).store(bx, dst);
244 PassMode::Direct(_) | PassMode::Indirect(_) | PassMode::Cast(_) => {
245 self.store(bx, next(), dst);
251 pub trait FnTypeExt<'a, 'tcx> {
252 fn of_instance(cx: &CodegenCx<'a, 'tcx>, instance: &ty::Instance<'tcx>)
254 fn new(cx: &CodegenCx<'a, 'tcx>,
255 sig: ty::FnSig<'tcx>,
256 extra_args: &[Ty<'tcx>]) -> Self;
257 fn new_vtable(cx: &CodegenCx<'a, 'tcx>,
258 sig: ty::FnSig<'tcx>,
259 extra_args: &[Ty<'tcx>]) -> Self;
260 fn unadjusted(cx: &CodegenCx<'a, 'tcx>,
261 sig: ty::FnSig<'tcx>,
262 extra_args: &[Ty<'tcx>]) -> Self;
263 fn adjust_for_abi(&mut self,
264 cx: &CodegenCx<'a, 'tcx>,
266 fn llvm_type(&self, cx: &CodegenCx<'a, 'tcx>) -> Type;
267 fn llvm_cconv(&self) -> llvm::CallConv;
268 fn apply_attrs_llfn(&self, llfn: ValueRef);
269 fn apply_attrs_callsite(&self, bx: &Builder<'a, 'tcx>, callsite: ValueRef);
272 impl<'a, 'tcx> FnTypeExt<'a, 'tcx> for FnType<'tcx, Ty<'tcx>> {
273 fn of_instance(cx: &CodegenCx<'a, 'tcx>, instance: &ty::Instance<'tcx>)
275 let fn_ty = instance.ty(cx.tcx);
276 let sig = ty_fn_sig(cx, fn_ty);
277 let sig = cx.tcx.normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), &sig);
278 FnType::new(cx, sig, &[])
281 fn new(cx: &CodegenCx<'a, 'tcx>,
282 sig: ty::FnSig<'tcx>,
283 extra_args: &[Ty<'tcx>]) -> Self {
284 let mut fn_ty = FnType::unadjusted(cx, sig, extra_args);
285 fn_ty.adjust_for_abi(cx, sig.abi);
289 fn new_vtable(cx: &CodegenCx<'a, 'tcx>,
290 sig: ty::FnSig<'tcx>,
291 extra_args: &[Ty<'tcx>]) -> Self {
292 let mut fn_ty = FnType::unadjusted(cx, sig, extra_args);
293 // Don't pass the vtable, it's not an argument of the virtual fn.
295 let self_arg = &mut fn_ty.args[0];
296 match self_arg.mode {
297 PassMode::Pair(data_ptr, _) => {
298 self_arg.mode = PassMode::Direct(data_ptr);
300 _ => bug!("FnType::new_vtable: non-pair self {:?}", self_arg)
303 let pointee = self_arg.layout.ty.builtin_deref(true)
305 bug!("FnType::new_vtable: non-pointer self {:?}", self_arg)
307 let fat_ptr_ty = cx.tcx.mk_mut_ptr(pointee);
308 self_arg.layout = cx.layout_of(fat_ptr_ty).field(cx, 0);
310 fn_ty.adjust_for_abi(cx, sig.abi);
314 fn unadjusted(cx: &CodegenCx<'a, 'tcx>,
315 sig: ty::FnSig<'tcx>,
316 extra_args: &[Ty<'tcx>]) -> Self {
317 debug!("FnType::unadjusted({:?}, {:?})", sig, extra_args);
320 let conv = match cx.sess().target.target.adjust_abi(sig.abi) {
321 RustIntrinsic | PlatformIntrinsic |
322 Rust | RustCall => Conv::C,
324 // It's the ABI's job to select this, not us.
325 System => bug!("system abi should be selected elsewhere"),
327 Stdcall => Conv::X86Stdcall,
328 Fastcall => Conv::X86Fastcall,
329 Vectorcall => Conv::X86VectorCall,
330 Thiscall => Conv::X86ThisCall,
332 Unadjusted => Conv::C,
333 Win64 => Conv::X86_64Win64,
334 SysV64 => Conv::X86_64SysV,
335 Aapcs => Conv::ArmAapcs,
336 PtxKernel => Conv::PtxKernel,
337 Msp430Interrupt => Conv::Msp430Intr,
338 X86Interrupt => Conv::X86Intr,
340 // These API constants ought to be more specific...
344 let mut inputs = sig.inputs();
345 let extra_args = if sig.abi == RustCall {
346 assert!(!sig.variadic && extra_args.is_empty());
348 match sig.inputs().last().unwrap().sty {
349 ty::TyTuple(ref tupled_arguments) => {
350 inputs = &sig.inputs()[0..sig.inputs().len() - 1];
354 bug!("argument to function with \"rust-call\" ABI \
359 assert!(sig.variadic || extra_args.is_empty());
363 let target = &cx.sess().target.target;
364 let win_x64_gnu = target.target_os == "windows"
365 && target.arch == "x86_64"
366 && target.target_env == "gnu";
367 let linux_s390x = target.target_os == "linux"
368 && target.arch == "s390x"
369 && target.target_env == "gnu";
370 let rust_abi = match sig.abi {
371 RustIntrinsic | PlatformIntrinsic | Rust | RustCall => true,
375 // Handle safe Rust thin and fat pointers.
376 let adjust_for_rust_scalar = |attrs: &mut ArgAttributes,
377 scalar: &layout::Scalar,
378 layout: TyLayout<'tcx, Ty<'tcx>>,
381 // Booleans are always an i1 that needs to be zero-extended.
382 if scalar.is_bool() {
383 attrs.set(ArgAttribute::ZExt);
387 // Only pointer types handled below.
388 if scalar.value != layout::Pointer {
392 if scalar.valid_range.start() < scalar.valid_range.end() {
393 if *scalar.valid_range.start() > 0 {
394 attrs.set(ArgAttribute::NonNull);
398 if let Some(pointee) = layout.pointee_info_at(cx, offset) {
399 if let Some(kind) = pointee.safe {
400 attrs.pointee_size = pointee.size;
401 attrs.pointee_align = Some(pointee.align);
403 // HACK(eddyb) LLVM inserts `llvm.assume` calls when inlining functions
404 // with align attributes, and those calls later block optimizations.
405 if !is_return && !cx.tcx.sess.opts.debugging_opts.arg_align_attributes {
406 attrs.pointee_align = None;
409 // `Box` pointer parameters never alias because ownership is transferred
410 // `&mut` pointer parameters never alias other parameters,
411 // or mutable global data
413 // `&T` where `T` contains no `UnsafeCell<U>` is immutable,
414 // and can be marked as both `readonly` and `noalias`, as
415 // LLVM's definition of `noalias` is based solely on memory
416 // dependencies rather than pointer equality
417 let no_alias = match kind {
418 PointerKind::Shared => false,
419 PointerKind::UniqueOwned => true,
420 PointerKind::Frozen |
421 PointerKind::UniqueBorrowed => !is_return
424 attrs.set(ArgAttribute::NoAlias);
427 if kind == PointerKind::Frozen && !is_return {
428 attrs.set(ArgAttribute::ReadOnly);
434 let arg_of = |ty: Ty<'tcx>, is_return: bool| {
435 let mut arg = ArgType::new(cx.layout_of(ty));
436 if arg.layout.is_zst() {
437 // For some forsaken reason, x86_64-pc-windows-gnu
438 // doesn't ignore zero-sized struct arguments.
439 // The same is true for s390x-unknown-linux-gnu.
440 if is_return || rust_abi || (!win_x64_gnu && !linux_s390x) {
441 arg.mode = PassMode::Ignore;
445 // FIXME(eddyb) other ABIs don't have logic for scalar pairs.
446 if !is_return && rust_abi {
447 if let layout::Abi::ScalarPair(ref a, ref b) = arg.layout.abi {
448 let mut a_attrs = ArgAttributes::new();
449 let mut b_attrs = ArgAttributes::new();
450 adjust_for_rust_scalar(&mut a_attrs,
455 adjust_for_rust_scalar(&mut b_attrs,
458 a.value.size(cx).abi_align(b.value.align(cx)),
460 arg.mode = PassMode::Pair(a_attrs, b_attrs);
465 if let layout::Abi::Scalar(ref scalar) = arg.layout.abi {
466 if let PassMode::Direct(ref mut attrs) = arg.mode {
467 adjust_for_rust_scalar(attrs,
479 ret: arg_of(sig.output(), true),
480 args: inputs.iter().chain(extra_args.iter()).map(|ty| {
483 variadic: sig.variadic,
488 fn adjust_for_abi(&mut self,
489 cx: &CodegenCx<'a, 'tcx>,
491 if abi == Abi::Unadjusted { return }
493 if abi == Abi::Rust || abi == Abi::RustCall ||
494 abi == Abi::RustIntrinsic || abi == Abi::PlatformIntrinsic {
495 let fixup = |arg: &mut ArgType<'tcx, Ty<'tcx>>| {
496 if arg.is_ignore() { return; }
498 match arg.layout.abi {
499 layout::Abi::Aggregate { .. } => {}
501 // This is a fun case! The gist of what this is doing is
502 // that we want callers and callees to always agree on the
503 // ABI of how they pass SIMD arguments. If we were to *not*
504 // make these arguments indirect then they'd be immediates
505 // in LLVM, which means that they'd used whatever the
506 // appropriate ABI is for the callee and the caller. That
507 // means, for example, if the caller doesn't have AVX
508 // enabled but the callee does, then passing an AVX argument
509 // across this boundary would cause corrupt data to show up.
511 // This problem is fixed by unconditionally passing SIMD
512 // arguments through memory between callers and callees
513 // which should get them all to agree on ABI regardless of
514 // target feature sets. Some more information about this
515 // issue can be found in #44367.
517 // Note that the platform intrinsic ABI is exempt here as
518 // that's how we connect up to LLVM and it's unstable
519 // anyway, we control all calls to it in libstd.
520 layout::Abi::Vector { .. } if abi != Abi::PlatformIntrinsic => {
528 let size = arg.layout.size;
529 if size > layout::Pointer.size(cx) {
532 // We want to pass small aggregates as immediates, but using
533 // a LLVM aggregate type for this leads to bad optimizations,
534 // so we pick an appropriately sized integer type instead.
536 kind: RegKind::Integer,
541 fixup(&mut self.ret);
542 for arg in &mut self.args {
545 if let PassMode::Indirect(ref mut attrs) = self.ret.mode {
546 attrs.set(ArgAttribute::StructRet);
551 if let Err(msg) = self.adjust_for_cabi(cx, abi) {
552 cx.sess().fatal(&msg);
556 fn llvm_type(&self, cx: &CodegenCx<'a, 'tcx>) -> Type {
557 let mut llargument_tys = Vec::new();
559 let llreturn_ty = match self.ret.mode {
560 PassMode::Ignore => Type::void(cx),
561 PassMode::Direct(_) | PassMode::Pair(..) => {
562 self.ret.layout.immediate_llvm_type(cx)
564 PassMode::Cast(cast) => cast.llvm_type(cx),
565 PassMode::Indirect(_) => {
566 llargument_tys.push(self.ret.memory_ty(cx).ptr_to());
571 for arg in &self.args {
573 if let Some(ty) = arg.pad {
574 llargument_tys.push(ty.llvm_type(cx));
577 let llarg_ty = match arg.mode {
578 PassMode::Ignore => continue,
579 PassMode::Direct(_) => arg.layout.immediate_llvm_type(cx),
580 PassMode::Pair(..) => {
581 llargument_tys.push(arg.layout.scalar_pair_element_llvm_type(cx, 0));
582 llargument_tys.push(arg.layout.scalar_pair_element_llvm_type(cx, 1));
585 PassMode::Cast(cast) => cast.llvm_type(cx),
586 PassMode::Indirect(_) => arg.memory_ty(cx).ptr_to(),
588 llargument_tys.push(llarg_ty);
592 Type::variadic_func(&llargument_tys, &llreturn_ty)
594 Type::func(&llargument_tys, &llreturn_ty)
598 fn llvm_cconv(&self) -> llvm::CallConv {
600 Conv::C => llvm::CCallConv,
601 Conv::ArmAapcs => llvm::ArmAapcsCallConv,
602 Conv::Msp430Intr => llvm::Msp430Intr,
603 Conv::PtxKernel => llvm::PtxKernel,
604 Conv::X86Fastcall => llvm::X86FastcallCallConv,
605 Conv::X86Intr => llvm::X86_Intr,
606 Conv::X86Stdcall => llvm::X86StdcallCallConv,
607 Conv::X86ThisCall => llvm::X86_ThisCall,
608 Conv::X86VectorCall => llvm::X86_VectorCall,
609 Conv::X86_64SysV => llvm::X86_64_SysV,
610 Conv::X86_64Win64 => llvm::X86_64_Win64,
614 fn apply_attrs_llfn(&self, llfn: ValueRef) {
616 let mut apply = |attrs: &ArgAttributes| {
617 attrs.apply_llfn(llvm::AttributePlace::Argument(i), llfn);
620 match self.ret.mode {
621 PassMode::Direct(ref attrs) => {
622 attrs.apply_llfn(llvm::AttributePlace::ReturnValue, llfn);
624 PassMode::Indirect(ref attrs) => apply(attrs),
627 for arg in &self.args {
628 if arg.pad.is_some() {
629 apply(&ArgAttributes::new());
632 PassMode::Ignore => {}
633 PassMode::Direct(ref attrs) |
634 PassMode::Indirect(ref attrs) => apply(attrs),
635 PassMode::Pair(ref a, ref b) => {
639 PassMode::Cast(_) => apply(&ArgAttributes::new()),
644 fn apply_attrs_callsite(&self, bx: &Builder<'a, 'tcx>, callsite: ValueRef) {
646 let mut apply = |attrs: &ArgAttributes| {
647 attrs.apply_callsite(llvm::AttributePlace::Argument(i), callsite);
650 match self.ret.mode {
651 PassMode::Direct(ref attrs) => {
652 attrs.apply_callsite(llvm::AttributePlace::ReturnValue, callsite);
654 PassMode::Indirect(ref attrs) => apply(attrs),
657 if let layout::Abi::Scalar(ref scalar) = self.ret.layout.abi {
658 // If the value is a boolean, the range is 0..2 and that ultimately
659 // become 0..0 when the type becomes i1, which would be rejected
660 // by the LLVM verifier.
662 layout::Int(..) if !scalar.is_bool() => {
663 let range = scalar.valid_range_exclusive(bx.cx);
664 if range.start != range.end {
665 // FIXME(nox): This causes very weird type errors about
666 // SHL operators in constants in stage 2 with LLVM 3.9.
667 if unsafe { llvm::LLVMRustVersionMajor() >= 4 } {
668 bx.range_metadata(callsite, range);
675 for arg in &self.args {
676 if arg.pad.is_some() {
677 apply(&ArgAttributes::new());
680 PassMode::Ignore => {}
681 PassMode::Direct(ref attrs) |
682 PassMode::Indirect(ref attrs) => apply(attrs),
683 PassMode::Pair(ref a, ref b) => {
687 PassMode::Cast(_) => apply(&ArgAttributes::new()),
691 let cconv = self.llvm_cconv();
692 if cconv != llvm::CCallConv {
693 llvm::SetInstructionCallConv(callsite, cconv);