]> git.lizzy.rs Git - rust.git/blob - src/librustc_codegen_llvm/abi.rs
Various minor/cosmetic improvements to code
[rust.git] / src / librustc_codegen_llvm / abi.rs
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.
4 //
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.
10
11 use llvm::{self, AttributePlace};
12 use rustc_codegen_ssa::MemFlags;
13 use builder::Builder;
14 use context::CodegenCx;
15 use rustc_codegen_ssa::mir::place::PlaceRef;
16 use rustc_codegen_ssa::mir::operand::OperandValue;
17 use type_::Type;
18 use type_of::{LayoutLlvmExt, PointerKind};
19 use value::Value;
20 use rustc_target::abi::call::ArgType;
21
22 use rustc_codegen_ssa::traits::*;
23
24 use rustc_target::abi::{HasDataLayout, LayoutOf, Size, TyLayout, Abi as LayoutAbi};
25 use rustc::ty::{self, Ty, Instance};
26 use rustc::ty::layout;
27
28 use libc::c_uint;
29
30 pub use rustc_target::spec::abi::Abi;
31 pub use rustc::ty::layout::{FAT_PTR_ADDR, FAT_PTR_EXTRA};
32 pub use rustc_target::abi::call::*;
33
34 macro_rules! for_each_kind {
35     ($flags: ident, $f: ident, $($kind: ident),+) => ({
36         $(if $flags.contains(ArgAttribute::$kind) { $f(llvm::Attribute::$kind) })+
37     })
38 }
39
40 trait ArgAttributeExt {
41     fn for_each_kind<F>(&self, f: F) where F: FnMut(llvm::Attribute);
42 }
43
44 impl ArgAttributeExt for ArgAttribute {
45     fn for_each_kind<F>(&self, mut f: F) where F: FnMut(llvm::Attribute) {
46         for_each_kind!(self, f,
47                        ByVal, NoAlias, NoCapture, NonNull, ReadOnly, SExt, StructRet, ZExt, InReg)
48     }
49 }
50
51 pub trait ArgAttributesExt {
52     fn apply_llfn(&self, idx: AttributePlace, llfn: &Value);
53     fn apply_callsite(&self, idx: AttributePlace, callsite: &Value);
54 }
55
56 impl ArgAttributesExt for ArgAttributes {
57     fn apply_llfn(&self, idx: AttributePlace, llfn: &Value) {
58         let mut regular = self.regular;
59         unsafe {
60             let deref = self.pointee_size.bytes();
61             if deref != 0 {
62                 if regular.contains(ArgAttribute::NonNull) {
63                     llvm::LLVMRustAddDereferenceableAttr(llfn,
64                                                          idx.as_uint(),
65                                                          deref);
66                 } else {
67                     llvm::LLVMRustAddDereferenceableOrNullAttr(llfn,
68                                                                idx.as_uint(),
69                                                                deref);
70                 }
71                 regular -= ArgAttribute::NonNull;
72             }
73             if let Some(align) = self.pointee_align {
74                 llvm::LLVMRustAddAlignmentAttr(llfn,
75                                                idx.as_uint(),
76                                                align.bytes() as u32);
77             }
78             regular.for_each_kind(|attr| attr.apply_llfn(idx, llfn));
79         }
80     }
81
82     fn apply_callsite(&self, idx: AttributePlace, callsite: &Value) {
83         let mut regular = self.regular;
84         unsafe {
85             let deref = self.pointee_size.bytes();
86             if deref != 0 {
87                 if regular.contains(ArgAttribute::NonNull) {
88                     llvm::LLVMRustAddDereferenceableCallSiteAttr(callsite,
89                                                                  idx.as_uint(),
90                                                                  deref);
91                 } else {
92                     llvm::LLVMRustAddDereferenceableOrNullCallSiteAttr(callsite,
93                                                                        idx.as_uint(),
94                                                                        deref);
95                 }
96                 regular -= ArgAttribute::NonNull;
97             }
98             if let Some(align) = self.pointee_align {
99                 llvm::LLVMRustAddAlignmentCallSiteAttr(callsite,
100                                                        idx.as_uint(),
101                                                        align.bytes() as u32);
102             }
103             regular.for_each_kind(|attr| attr.apply_callsite(idx, callsite));
104         }
105     }
106 }
107
108 pub trait LlvmType {
109     fn llvm_type(&self, cx: &CodegenCx<'ll, '_>) -> &'ll Type;
110 }
111
112 impl LlvmType for Reg {
113     fn llvm_type(&self, cx: &CodegenCx<'ll, '_>) -> &'ll Type {
114         match self.kind {
115             RegKind::Integer => cx.type_ix(self.size.bits()),
116             RegKind::Float => {
117                 match self.size.bits() {
118                     32 => cx.type_f32(),
119                     64 => cx.type_f64(),
120                     _ => bug!("unsupported float: {:?}", self)
121                 }
122             }
123             RegKind::Vector => {
124                 cx.type_vector(cx.type_i8(), self.size.bytes())
125             }
126         }
127     }
128 }
129
130 impl LlvmType for CastTarget {
131     fn llvm_type(&self, cx: &CodegenCx<'ll, '_>) -> &'ll Type {
132         let rest_ll_unit = self.rest.unit.llvm_type(cx);
133         let (rest_count, rem_bytes) = if self.rest.unit.size.bytes() == 0 {
134             (0, 0)
135         } else {
136             (self.rest.total.bytes() / self.rest.unit.size.bytes(),
137             self.rest.total.bytes() % self.rest.unit.size.bytes())
138         };
139
140         if self.prefix.iter().all(|x| x.is_none()) {
141             // Simplify to a single unit when there is no prefix and size <= unit size
142             if self.rest.total <= self.rest.unit.size {
143                 return rest_ll_unit;
144             }
145
146             // Simplify to array when all chunks are the same size and type
147             if rem_bytes == 0 {
148                 return cx.type_array(rest_ll_unit, rest_count);
149             }
150         }
151
152         // Create list of fields in the main structure
153         let mut args: Vec<_> =
154             self.prefix.iter().flat_map(|option_kind| option_kind.map(
155                 |kind| Reg { kind: kind, size: self.prefix_chunk }.llvm_type(cx)))
156             .chain((0..rest_count).map(|_| rest_ll_unit))
157             .collect();
158
159         // Append final integer
160         if rem_bytes != 0 {
161             // Only integers can be really split further.
162             assert_eq!(self.rest.unit.kind, RegKind::Integer);
163             args.push(cx.type_ix(rem_bytes * 8));
164         }
165
166         cx.type_struct(&args, false)
167     }
168 }
169
170 pub trait ArgTypeExt<'ll, 'tcx> {
171     fn memory_ty(&self, cx: &CodegenCx<'ll, 'tcx>) -> &'ll Type;
172     fn store(
173         &self,
174         bx: &mut Builder<'_, 'll, 'tcx>,
175         val: &'ll Value,
176         dst: PlaceRef<'tcx, &'ll Value>,
177     );
178     fn store_fn_arg(
179         &self,
180         bx: &mut Builder<'_, 'll, 'tcx>,
181         idx: &mut usize,
182         dst: PlaceRef<'tcx, &'ll Value>,
183     );
184 }
185
186 impl ArgTypeExt<'ll, 'tcx> for ArgType<'tcx, Ty<'tcx>> {
187     /// Get the LLVM type for a place of the original Rust type of
188     /// this argument/return, i.e., the result of `type_of::type_of`.
189     fn memory_ty(&self, cx: &CodegenCx<'ll, 'tcx>) -> &'ll Type {
190         self.layout.llvm_type(cx)
191     }
192
193     /// Store a direct/indirect value described by this ArgType into a
194     /// place for the original Rust type of this argument/return.
195     /// Can be used for both storing formal arguments into Rust variables
196     /// or results of call/invoke instructions into their destinations.
197     fn store(
198         &self,
199         bx: &mut Builder<'_, 'll, 'tcx>,
200         val: &'ll Value,
201         dst: PlaceRef<'tcx, &'ll Value>,
202     ) {
203         if self.is_ignore() {
204             return;
205         }
206         if self.is_sized_indirect() {
207             OperandValue::Ref(val, None, self.layout.align.abi).store(bx, dst)
208         } else if self.is_unsized_indirect() {
209             bug!("unsized ArgType must be handled through store_fn_arg");
210         } else if let PassMode::Cast(cast) = self.mode {
211             // FIXME(eddyb): Figure out when the simpler Store is safe, clang
212             // uses it for i16 -> {i8, i8}, but not for i24 -> {i8, i8, i8}.
213             let can_store_through_cast_ptr = false;
214             if can_store_through_cast_ptr {
215                 let cast_ptr_llty = bx.type_ptr_to(cast.llvm_type(bx));
216                 let cast_dst = bx.pointercast(dst.llval, cast_ptr_llty);
217                 bx.store(val, cast_dst, self.layout.align.abi);
218             } else {
219                 // The actual return type is a struct, but the ABI
220                 // adaptation code has cast it into some scalar type.  The
221                 // code that follows is the only reliable way I have
222                 // found to do a transform like i64 -> {i32,i32}.
223                 // Basically we dump the data onto the stack then memcpy it.
224                 //
225                 // Other approaches I tried:
226                 // - Casting rust ret pointer to the foreign type and using Store
227                 //   is (a) unsafe if size of foreign type > size of rust type and
228                 //   (b) runs afoul of strict aliasing rules, yielding invalid
229                 //   assembly under -O (specifically, the store gets removed).
230                 // - Truncating foreign type to correct integral type and then
231                 //   bitcasting to the struct type yields invalid cast errors.
232
233                 // We instead thus allocate some scratch space...
234                 let scratch_size = cast.size(bx);
235                 let scratch_align = cast.align(bx);
236                 let llscratch = bx.alloca(cast.llvm_type(bx), "abi_cast", scratch_align);
237                 bx.lifetime_start(llscratch, scratch_size);
238
239                 // ...where we first store the value...
240                 bx.store(val, llscratch, scratch_align);
241
242                 // ...and then memcpy it to the intended destination.
243                 bx.memcpy(
244                     dst.llval,
245                     self.layout.align.abi,
246                     llscratch,
247                     scratch_align,
248                     bx.const_usize(self.layout.size.bytes()),
249                     MemFlags::empty()
250                 );
251
252                 bx.lifetime_end(llscratch, scratch_size);
253             }
254         } else {
255             OperandValue::Immediate(val).store(bx, dst);
256         }
257     }
258
259     fn store_fn_arg(
260         &self,
261         bx: &mut Builder<'a, 'll, 'tcx>,
262         idx: &mut usize,
263         dst: PlaceRef<'tcx, &'ll Value>,
264     ) {
265         let mut next = || {
266             let val = llvm::get_param(bx.llfn(), *idx as c_uint);
267             *idx += 1;
268             val
269         };
270         match self.mode {
271             PassMode::Ignore => {},
272             PassMode::Pair(..) => {
273                 OperandValue::Pair(next(), next()).store(bx, dst);
274             }
275             PassMode::Indirect(_, Some(_)) => {
276                 OperandValue::Ref(next(), Some(next()), self.layout.align.abi).store(bx, dst);
277             }
278             PassMode::Direct(_) | PassMode::Indirect(_, None) | PassMode::Cast(_) => {
279                 self.store(bx, next(), dst);
280             }
281         }
282     }
283 }
284
285 impl ArgTypeMethods<'tcx> for Builder<'a, 'll, 'tcx> {
286     fn store_fn_arg(
287         &mut self,
288         ty: &ArgType<'tcx, Ty<'tcx>>,
289         idx: &mut usize, dst: PlaceRef<'tcx, Self::Value>
290     ) {
291         ty.store_fn_arg(self, idx, dst)
292     }
293     fn store_arg_ty(
294         &mut self,
295         ty: &ArgType<'tcx, Ty<'tcx>>,
296         val: &'ll Value,
297         dst: PlaceRef<'tcx, &'ll Value>
298     ) {
299         ty.store(self, val, dst)
300     }
301     fn memory_ty(&self, ty: &ArgType<'tcx, Ty<'tcx>>) -> &'ll Type {
302         ty.memory_ty(self)
303     }
304 }
305
306 pub trait FnTypeExt<'tcx> {
307     fn of_instance(cx: &CodegenCx<'ll, 'tcx>, instance: &ty::Instance<'tcx>) -> Self;
308     fn new(cx: &CodegenCx<'ll, 'tcx>,
309            sig: ty::FnSig<'tcx>,
310            extra_args: &[Ty<'tcx>]) -> Self;
311     fn new_vtable(cx: &CodegenCx<'ll, 'tcx>,
312                   sig: ty::FnSig<'tcx>,
313                   extra_args: &[Ty<'tcx>]) -> Self;
314     fn new_internal(
315         cx: &CodegenCx<'ll, 'tcx>,
316         sig: ty::FnSig<'tcx>,
317         extra_args: &[Ty<'tcx>],
318         mk_arg_type: impl Fn(Ty<'tcx>, Option<usize>) -> ArgType<'tcx, Ty<'tcx>>,
319     ) -> Self;
320     fn adjust_for_abi(&mut self,
321                       cx: &CodegenCx<'ll, 'tcx>,
322                       abi: Abi);
323     fn llvm_type(&self, cx: &CodegenCx<'ll, 'tcx>) -> &'ll Type;
324     fn ptr_to_llvm_type(&self, cx: &CodegenCx<'ll, 'tcx>) -> &'ll Type;
325     fn llvm_cconv(&self) -> llvm::CallConv;
326     fn apply_attrs_llfn(&self, llfn: &'ll Value);
327     fn apply_attrs_callsite(&self, bx: &mut Builder<'a, 'll, 'tcx>, callsite: &'ll Value);
328 }
329
330 impl<'tcx> FnTypeExt<'tcx> for FnType<'tcx, Ty<'tcx>> {
331     fn of_instance(cx: &CodegenCx<'ll, 'tcx>, instance: &ty::Instance<'tcx>) -> Self {
332         let sig = instance.fn_sig(cx.tcx);
333         let sig = cx.tcx.normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), &sig);
334         FnType::new(cx, sig, &[])
335     }
336
337     fn new(cx: &CodegenCx<'ll, 'tcx>,
338            sig: ty::FnSig<'tcx>,
339            extra_args: &[Ty<'tcx>]) -> Self {
340         FnType::new_internal(cx, sig, extra_args, |ty, _| {
341             ArgType::new(cx.layout_of(ty))
342         })
343     }
344
345     fn new_vtable(cx: &CodegenCx<'ll, 'tcx>,
346                   sig: ty::FnSig<'tcx>,
347                   extra_args: &[Ty<'tcx>]) -> Self {
348         FnType::new_internal(cx, sig, extra_args, |ty, arg_idx| {
349             let mut layout = cx.layout_of(ty);
350             // Don't pass the vtable, it's not an argument of the virtual fn.
351             // Instead, pass just the data pointer, but give it the type `*const/mut dyn Trait`
352             // or `&/&mut dyn Trait` because this is special-cased elsewhere in codegen
353             if arg_idx == Some(0) {
354                 let fat_pointer_ty = if layout.is_unsized() {
355                     // unsized `self` is passed as a pointer to `self`
356                     // FIXME (mikeyhew) change this to use &own if it is ever added to the language
357                     cx.tcx.mk_mut_ptr(layout.ty)
358                 } else {
359                     match layout.abi {
360                         LayoutAbi::ScalarPair(..) => (),
361                         _ => bug!("receiver type has unsupported layout: {:?}", layout)
362                     }
363
364                     // In the case of Rc<Self>, we need to explicitly pass a *mut RcBox<Self>
365                     // with a Scalar (not ScalarPair) ABI. This is a hack that is understood
366                     // elsewhere in the compiler as a method on a `dyn Trait`.
367                     // To get the type `*mut RcBox<Self>`, we just keep unwrapping newtypes until we
368                     // get a built-in pointer type
369                     let mut fat_pointer_layout = layout;
370                     'descend_newtypes: while !fat_pointer_layout.ty.is_unsafe_ptr()
371                         && !fat_pointer_layout.ty.is_region_ptr()
372                     {
373                         'iter_fields: for i in 0..fat_pointer_layout.fields.count() {
374                             let field_layout = fat_pointer_layout.field(cx, i);
375
376                             if !field_layout.is_zst() {
377                                 fat_pointer_layout = field_layout;
378                                 continue 'descend_newtypes
379                             }
380                         }
381
382                         bug!("receiver has no non-zero-sized fields {:?}", fat_pointer_layout);
383                     }
384
385                     fat_pointer_layout.ty
386                 };
387
388                 // we now have a type like `*mut RcBox<dyn Trait>`
389                 // change its layout to that of `*mut ()`, a thin pointer, but keep the same type
390                 // this is understood as a special case elsewhere in the compiler
391                 let unit_pointer_ty = cx.tcx.mk_mut_ptr(cx.tcx.mk_unit());
392                 layout = cx.layout_of(unit_pointer_ty);
393                 layout.ty = fat_pointer_ty;
394             }
395             ArgType::new(layout)
396         })
397     }
398
399     fn new_internal(
400         cx: &CodegenCx<'ll, 'tcx>,
401         sig: ty::FnSig<'tcx>,
402         extra_args: &[Ty<'tcx>],
403         mk_arg_type: impl Fn(Ty<'tcx>, Option<usize>) -> ArgType<'tcx, Ty<'tcx>>,
404     ) -> Self {
405         debug!("FnType::new_internal({:?}, {:?})", sig, extra_args);
406
407         use self::Abi::*;
408         let conv = match cx.sess().target.target.adjust_abi(sig.abi) {
409             RustIntrinsic | PlatformIntrinsic |
410             Rust | RustCall => Conv::C,
411
412             // It's the ABI's job to select this, not ours.
413             System => bug!("system abi should be selected elsewhere"),
414
415             Stdcall => Conv::X86Stdcall,
416             Fastcall => Conv::X86Fastcall,
417             Vectorcall => Conv::X86VectorCall,
418             Thiscall => Conv::X86ThisCall,
419             C => Conv::C,
420             Unadjusted => Conv::C,
421             Win64 => Conv::X86_64Win64,
422             SysV64 => Conv::X86_64SysV,
423             Aapcs => Conv::ArmAapcs,
424             PtxKernel => Conv::PtxKernel,
425             Msp430Interrupt => Conv::Msp430Intr,
426             X86Interrupt => Conv::X86Intr,
427             AmdGpuKernel => Conv::AmdGpuKernel,
428
429             // These API constants ought to be more specific...
430             Cdecl => Conv::C,
431         };
432
433         let mut inputs = sig.inputs();
434         let extra_args = if sig.abi == RustCall {
435             assert!(!sig.variadic && extra_args.is_empty());
436
437             match sig.inputs().last().unwrap().sty {
438                 ty::Tuple(ref tupled_arguments) => {
439                     inputs = &sig.inputs()[0..sig.inputs().len() - 1];
440                     tupled_arguments
441                 }
442                 _ => {
443                     bug!("argument to function with \"rust-call\" ABI \
444                           is not a tuple");
445                 }
446             }
447         } else {
448             assert!(sig.variadic || extra_args.is_empty());
449             extra_args
450         };
451
452         let target = &cx.sess().target.target;
453         let win_x64_gnu = target.target_os == "windows"
454                        && target.arch == "x86_64"
455                        && target.target_env == "gnu";
456         let linux_s390x = target.target_os == "linux"
457                        && target.arch == "s390x"
458                        && target.target_env == "gnu";
459         let rust_abi = match sig.abi {
460             RustIntrinsic | PlatformIntrinsic | Rust | RustCall => true,
461             _ => false
462         };
463
464         // Handle safe Rust thin and fat pointers.
465         let adjust_for_rust_scalar = |attrs: &mut ArgAttributes,
466                                       scalar: &layout::Scalar,
467                                       layout: TyLayout<'tcx, Ty<'tcx>>,
468                                       offset: Size,
469                                       is_return: bool| {
470             // Booleans are always an i1 that needs to be zero-extended.
471             if scalar.is_bool() {
472                 attrs.set(ArgAttribute::ZExt);
473                 return;
474             }
475
476             // Only pointer types handled below.
477             if scalar.value != layout::Pointer {
478                 return;
479             }
480
481             if scalar.valid_range.start() < scalar.valid_range.end() {
482                 if *scalar.valid_range.start() > 0 {
483                     attrs.set(ArgAttribute::NonNull);
484                 }
485             }
486
487             if let Some(pointee) = layout.pointee_info_at(cx, offset) {
488                 if let Some(kind) = pointee.safe {
489                     attrs.pointee_size = pointee.size;
490                     attrs.pointee_align = Some(pointee.align);
491
492                     // HACK(eddyb) LLVM inserts `llvm.assume` calls when inlining functions
493                     // with align attributes, and those calls later block optimizations.
494                     if !is_return && !cx.tcx.sess.opts.debugging_opts.arg_align_attributes {
495                         attrs.pointee_align = None;
496                     }
497
498                     // `Box` pointer parameters never alias because ownership is transferred
499                     // `&mut` pointer parameters never alias other parameters,
500                     // or mutable global data
501                     //
502                     // `&T` where `T` contains no `UnsafeCell<U>` is immutable,
503                     // and can be marked as both `readonly` and `noalias`, as
504                     // LLVM's definition of `noalias` is based solely on memory
505                     // dependencies rather than pointer equality
506                     let no_alias = match kind {
507                         PointerKind::Shared => false,
508                         PointerKind::UniqueOwned => true,
509                         PointerKind::Frozen |
510                         PointerKind::UniqueBorrowed => !is_return
511                     };
512                     if no_alias {
513                         attrs.set(ArgAttribute::NoAlias);
514                     }
515
516                     if kind == PointerKind::Frozen && !is_return {
517                         attrs.set(ArgAttribute::ReadOnly);
518                     }
519                 }
520             }
521         };
522
523         let arg_of = |ty: Ty<'tcx>, arg_idx: Option<usize>| {
524             let is_return = arg_idx.is_none();
525             let mut arg = mk_arg_type(ty, arg_idx);
526             if arg.layout.is_zst() {
527                 // For some forsaken reason, x86_64-pc-windows-gnu
528                 // doesn't ignore zero-sized struct arguments.
529                 // The same is true for s390x-unknown-linux-gnu.
530                 if is_return || rust_abi || (!win_x64_gnu && !linux_s390x) {
531                     arg.mode = PassMode::Ignore;
532                 }
533             }
534
535             // FIXME(eddyb) other ABIs don't have logic for scalar pairs.
536             if !is_return && rust_abi {
537                 if let layout::Abi::ScalarPair(ref a, ref b) = arg.layout.abi {
538                     let mut a_attrs = ArgAttributes::new();
539                     let mut b_attrs = ArgAttributes::new();
540                     adjust_for_rust_scalar(&mut a_attrs,
541                                            a,
542                                            arg.layout,
543                                            Size::ZERO,
544                                            false);
545                     adjust_for_rust_scalar(&mut b_attrs,
546                                            b,
547                                            arg.layout,
548                                            a.value.size(cx).align_to(b.value.align(cx).abi),
549                                            false);
550                     arg.mode = PassMode::Pair(a_attrs, b_attrs);
551                     return arg;
552                 }
553             }
554
555             if let layout::Abi::Scalar(ref scalar) = arg.layout.abi {
556                 if let PassMode::Direct(ref mut attrs) = arg.mode {
557                     adjust_for_rust_scalar(attrs,
558                                            scalar,
559                                            arg.layout,
560                                            Size::ZERO,
561                                            is_return);
562                 }
563             }
564
565             arg
566         };
567
568         let mut fn_ty = FnType {
569             ret: arg_of(sig.output(), None),
570             args: inputs.iter().chain(extra_args).enumerate().map(|(i, ty)| {
571                 arg_of(ty, Some(i))
572             }).collect(),
573             variadic: sig.variadic,
574             conv,
575         };
576         fn_ty.adjust_for_abi(cx, sig.abi);
577         fn_ty
578     }
579
580     fn adjust_for_abi(&mut self,
581                       cx: &CodegenCx<'ll, 'tcx>,
582                       abi: Abi) {
583         if abi == Abi::Unadjusted { return }
584
585         if abi == Abi::Rust || abi == Abi::RustCall ||
586            abi == Abi::RustIntrinsic || abi == Abi::PlatformIntrinsic {
587             let fixup = |arg: &mut ArgType<'tcx, Ty<'tcx>>| {
588                 if arg.is_ignore() { return; }
589
590                 match arg.layout.abi {
591                     layout::Abi::Aggregate { .. } => {}
592
593                     // This is a fun case! The gist of what this is doing is
594                     // that we want callers and callees to always agree on the
595                     // ABI of how they pass SIMD arguments. If we were to *not*
596                     // make these arguments indirect then they'd be immediates
597                     // in LLVM, which means that they'd used whatever the
598                     // appropriate ABI is for the callee and the caller. That
599                     // means, for example, if the caller doesn't have AVX
600                     // enabled but the callee does, then passing an AVX argument
601                     // across this boundary would cause corrupt data to show up.
602                     //
603                     // This problem is fixed by unconditionally passing SIMD
604                     // arguments through memory between callers and callees
605                     // which should get them all to agree on ABI regardless of
606                     // target feature sets. Some more information about this
607                     // issue can be found in #44367.
608                     //
609                     // Note that the platform intrinsic ABI is exempt here as
610                     // that's how we connect up to LLVM and it's unstable
611                     // anyway, we control all calls to it in libstd.
612                     layout::Abi::Vector { .. }
613                         if abi != Abi::PlatformIntrinsic &&
614                             cx.sess().target.target.options.simd_types_indirect =>
615                     {
616                         arg.make_indirect();
617                         return
618                     }
619
620                     _ => return
621                 }
622
623                 let size = arg.layout.size;
624                 if arg.layout.is_unsized() || size > layout::Pointer.size(cx) {
625                     arg.make_indirect();
626                 } else {
627                     // We want to pass small aggregates as immediates, but using
628                     // a LLVM aggregate type for this leads to bad optimizations,
629                     // so we pick an appropriately sized integer type instead.
630                     arg.cast_to(Reg {
631                         kind: RegKind::Integer,
632                         size
633                     });
634                 }
635             };
636             fixup(&mut self.ret);
637             for arg in &mut self.args {
638                 fixup(arg);
639             }
640             if let PassMode::Indirect(ref mut attrs, _) = self.ret.mode {
641                 attrs.set(ArgAttribute::StructRet);
642             }
643             return;
644         }
645
646         if let Err(msg) = self.adjust_for_cabi(cx, abi) {
647             cx.sess().fatal(&msg);
648         }
649     }
650
651     fn llvm_type(&self, cx: &CodegenCx<'ll, 'tcx>) -> &'ll Type {
652         let args_capacity: usize = self.args.iter().map(|arg|
653             if arg.pad.is_some() { 1 } else { 0 } +
654             if let PassMode::Pair(_, _) = arg.mode { 2 } else { 1 }
655         ).sum();
656         let mut llargument_tys = Vec::with_capacity(
657             if let PassMode::Indirect(..) = self.ret.mode { 1 } else { 0 } + args_capacity
658         );
659
660         let llreturn_ty = match self.ret.mode {
661             PassMode::Ignore => cx.type_void(),
662             PassMode::Direct(_) | PassMode::Pair(..) => {
663                 self.ret.layout.immediate_llvm_type(cx)
664             }
665             PassMode::Cast(cast) => cast.llvm_type(cx),
666             PassMode::Indirect(..) => {
667                 llargument_tys.push(cx.type_ptr_to(self.ret.memory_ty(cx)));
668                 cx.type_void()
669             }
670         };
671
672         for arg in &self.args {
673             // add padding
674             if let Some(ty) = arg.pad {
675                 llargument_tys.push(ty.llvm_type(cx));
676             }
677
678             let llarg_ty = match arg.mode {
679                 PassMode::Ignore => continue,
680                 PassMode::Direct(_) => arg.layout.immediate_llvm_type(cx),
681                 PassMode::Pair(..) => {
682                     llargument_tys.push(arg.layout.scalar_pair_element_llvm_type(cx, 0, true));
683                     llargument_tys.push(arg.layout.scalar_pair_element_llvm_type(cx, 1, true));
684                     continue;
685                 }
686                 PassMode::Indirect(_, Some(_)) => {
687                     let ptr_ty = cx.tcx.mk_mut_ptr(arg.layout.ty);
688                     let ptr_layout = cx.layout_of(ptr_ty);
689                     llargument_tys.push(ptr_layout.scalar_pair_element_llvm_type(cx, 0, true));
690                     llargument_tys.push(ptr_layout.scalar_pair_element_llvm_type(cx, 1, true));
691                     continue;
692                 }
693                 PassMode::Cast(cast) => cast.llvm_type(cx),
694                 PassMode::Indirect(_, None) => cx.type_ptr_to(arg.memory_ty(cx)),
695             };
696             llargument_tys.push(llarg_ty);
697         }
698
699         if self.variadic {
700             cx.type_variadic_func(&llargument_tys, llreturn_ty)
701         } else {
702             cx.type_func(&llargument_tys, llreturn_ty)
703         }
704     }
705
706     fn ptr_to_llvm_type(&self, cx: &CodegenCx<'ll, 'tcx>) -> &'ll Type {
707         unsafe {
708             llvm::LLVMPointerType(self.llvm_type(cx),
709                                   cx.data_layout().instruction_address_space as c_uint)
710         }
711     }
712
713     fn llvm_cconv(&self) -> llvm::CallConv {
714         match self.conv {
715             Conv::C => llvm::CCallConv,
716             Conv::AmdGpuKernel => llvm::AmdGpuKernel,
717             Conv::ArmAapcs => llvm::ArmAapcsCallConv,
718             Conv::Msp430Intr => llvm::Msp430Intr,
719             Conv::PtxKernel => llvm::PtxKernel,
720             Conv::X86Fastcall => llvm::X86FastcallCallConv,
721             Conv::X86Intr => llvm::X86_Intr,
722             Conv::X86Stdcall => llvm::X86StdcallCallConv,
723             Conv::X86ThisCall => llvm::X86_ThisCall,
724             Conv::X86VectorCall => llvm::X86_VectorCall,
725             Conv::X86_64SysV => llvm::X86_64_SysV,
726             Conv::X86_64Win64 => llvm::X86_64_Win64,
727         }
728     }
729
730     fn apply_attrs_llfn(&self, llfn: &'ll Value) {
731         let mut i = 0;
732         let mut apply = |attrs: &ArgAttributes| {
733             attrs.apply_llfn(llvm::AttributePlace::Argument(i), llfn);
734             i += 1;
735         };
736         match self.ret.mode {
737             PassMode::Direct(ref attrs) => {
738                 attrs.apply_llfn(llvm::AttributePlace::ReturnValue, llfn);
739             }
740             PassMode::Indirect(ref attrs, _) => apply(attrs),
741             _ => {}
742         }
743         for arg in &self.args {
744             if arg.pad.is_some() {
745                 apply(&ArgAttributes::new());
746             }
747             match arg.mode {
748                 PassMode::Ignore => {}
749                 PassMode::Direct(ref attrs) |
750                 PassMode::Indirect(ref attrs, None) => apply(attrs),
751                 PassMode::Indirect(ref attrs, Some(ref extra_attrs)) => {
752                     apply(attrs);
753                     apply(extra_attrs);
754                 }
755                 PassMode::Pair(ref a, ref b) => {
756                     apply(a);
757                     apply(b);
758                 }
759                 PassMode::Cast(_) => apply(&ArgAttributes::new()),
760             }
761         }
762     }
763
764     fn apply_attrs_callsite(&self, bx: &mut Builder<'a, 'll, 'tcx>, callsite: &'ll Value) {
765         let mut i = 0;
766         let mut apply = |attrs: &ArgAttributes| {
767             attrs.apply_callsite(llvm::AttributePlace::Argument(i), callsite);
768             i += 1;
769         };
770         match self.ret.mode {
771             PassMode::Direct(ref attrs) => {
772                 attrs.apply_callsite(llvm::AttributePlace::ReturnValue, callsite);
773             }
774             PassMode::Indirect(ref attrs, _) => apply(attrs),
775             _ => {}
776         }
777         if let layout::Abi::Scalar(ref scalar) = self.ret.layout.abi {
778             // If the value is a boolean, the range is 0..2 and that ultimately
779             // become 0..0 when the type becomes i1, which would be rejected
780             // by the LLVM verifier.
781             if let layout::Int(..) = scalar.value {
782                 if !scalar.is_bool() {
783                     let range = scalar.valid_range_exclusive(bx);
784                     if range.start != range.end {
785                         bx.range_metadata(callsite, range);
786                     }
787                 }
788             }
789         }
790         for arg in &self.args {
791             if arg.pad.is_some() {
792                 apply(&ArgAttributes::new());
793             }
794             match arg.mode {
795                 PassMode::Ignore => {}
796                 PassMode::Direct(ref attrs) |
797                 PassMode::Indirect(ref attrs, None) => apply(attrs),
798                 PassMode::Indirect(ref attrs, Some(ref extra_attrs)) => {
799                     apply(attrs);
800                     apply(extra_attrs);
801                 }
802                 PassMode::Pair(ref a, ref b) => {
803                     apply(a);
804                     apply(b);
805                 }
806                 PassMode::Cast(_) => apply(&ArgAttributes::new()),
807             }
808         }
809
810         let cconv = self.llvm_cconv();
811         if cconv != llvm::CCallConv {
812             llvm::SetInstructionCallConv(callsite, cconv);
813         }
814     }
815 }
816
817 impl AbiMethods<'tcx> for CodegenCx<'ll, 'tcx> {
818     fn new_fn_type(&self, sig: ty::FnSig<'tcx>, extra_args: &[Ty<'tcx>]) -> FnType<'tcx, Ty<'tcx>> {
819         FnType::new(&self, sig, extra_args)
820     }
821     fn new_vtable(
822         &self,
823         sig: ty::FnSig<'tcx>,
824         extra_args: &[Ty<'tcx>]
825     ) -> FnType<'tcx, Ty<'tcx>> {
826         FnType::new_vtable(&self, sig, extra_args)
827     }
828     fn fn_type_of_instance(&self, instance: &Instance<'tcx>) -> FnType<'tcx, Ty<'tcx>> {
829         FnType::of_instance(&self, instance)
830     }
831 }
832
833 impl AbiBuilderMethods<'tcx> for Builder<'a, 'll, 'tcx> {
834     fn apply_attrs_callsite(
835         &mut self,
836         ty: &FnType<'tcx, Ty<'tcx>>,
837         callsite: Self::Value
838     ) {
839         ty.apply_attrs_callsite(self, callsite)
840     }
841 }