]> git.lizzy.rs Git - rust.git/blob - src/librustc_codegen_llvm/abi.rs
Auto merge of #50603 - eddyb:issue-49955, r=nikomatsakis
[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, ValueRef, AttributePlace};
12 use base;
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;
18 use type_::Type;
19 use type_of::{LayoutLlvmExt, PointerKind};
20
21 use rustc_target::abi::{LayoutOf, Size, TyLayout};
22 use rustc::ty::{self, Ty};
23 use rustc::ty::layout;
24
25 use libc::c_uint;
26
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::*;
30
31 macro_rules! for_each_kind {
32     ($flags: ident, $f: ident, $($kind: ident),+) => ({
33         $(if $flags.contains(ArgAttribute::$kind) { $f(llvm::Attribute::$kind) })+
34     })
35 }
36
37 trait ArgAttributeExt {
38     fn for_each_kind<F>(&self, f: F) where F: FnMut(llvm::Attribute);
39 }
40
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)
45     }
46 }
47
48 pub trait ArgAttributesExt {
49     fn apply_llfn(&self, idx: AttributePlace, llfn: ValueRef);
50     fn apply_callsite(&self, idx: AttributePlace, callsite: ValueRef);
51 }
52
53 impl ArgAttributesExt for ArgAttributes {
54     fn apply_llfn(&self, idx: AttributePlace, llfn: ValueRef) {
55         let mut regular = self.regular;
56         unsafe {
57             let deref = self.pointee_size.bytes();
58             if deref != 0 {
59                 if regular.contains(ArgAttribute::NonNull) {
60                     llvm::LLVMRustAddDereferenceableAttr(llfn,
61                                                          idx.as_uint(),
62                                                          deref);
63                 } else {
64                     llvm::LLVMRustAddDereferenceableOrNullAttr(llfn,
65                                                                idx.as_uint(),
66                                                                deref);
67                 }
68                 regular -= ArgAttribute::NonNull;
69             }
70             if let Some(align) = self.pointee_align {
71                 llvm::LLVMRustAddAlignmentAttr(llfn,
72                                                idx.as_uint(),
73                                                align.abi() as u32);
74             }
75             regular.for_each_kind(|attr| attr.apply_llfn(idx, llfn));
76         }
77     }
78
79     fn apply_callsite(&self, idx: AttributePlace, callsite: ValueRef) {
80         let mut regular = self.regular;
81         unsafe {
82             let deref = self.pointee_size.bytes();
83             if deref != 0 {
84                 if regular.contains(ArgAttribute::NonNull) {
85                     llvm::LLVMRustAddDereferenceableCallSiteAttr(callsite,
86                                                                  idx.as_uint(),
87                                                                  deref);
88                 } else {
89                     llvm::LLVMRustAddDereferenceableOrNullCallSiteAttr(callsite,
90                                                                        idx.as_uint(),
91                                                                        deref);
92                 }
93                 regular -= ArgAttribute::NonNull;
94             }
95             if let Some(align) = self.pointee_align {
96                 llvm::LLVMRustAddAlignmentCallSiteAttr(callsite,
97                                                        idx.as_uint(),
98                                                        align.abi() as u32);
99             }
100             regular.for_each_kind(|attr| attr.apply_callsite(idx, callsite));
101         }
102     }
103 }
104
105 pub trait LlvmType {
106     fn llvm_type(&self, cx: &CodegenCx) -> Type;
107 }
108
109 impl LlvmType for Reg {
110     fn llvm_type(&self, cx: &CodegenCx) -> Type {
111         match self.kind {
112             RegKind::Integer => Type::ix(cx, self.size.bits()),
113             RegKind::Float => {
114                 match self.size.bits() {
115                     32 => Type::f32(cx),
116                     64 => Type::f64(cx),
117                     _ => bug!("unsupported float: {:?}", self)
118                 }
119             }
120             RegKind::Vector => {
121                 Type::vector(&Type::i8(cx), self.size.bytes())
122             }
123         }
124     }
125 }
126
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();
132
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 {
136                 return rest_ll_unit;
137             }
138
139             // Simplify to array when all chunks are the same size and type
140             if rem_bytes == 0 {
141                 return Type::array(&rest_ll_unit, rest_count);
142             }
143         }
144
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))
150             .collect();
151
152         // Append final integer
153         if rem_bytes != 0 {
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));
157         }
158
159         Type::struct_(cx, &args, false)
160     }
161 }
162
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>);
167 }
168
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)
174     }
175
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() {
182             return;
183         }
184         let cx = bx.cx;
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);
194             } else {
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.
200                 //
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.
208
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);
214
215                 // ...where we first store the value...
216                 bx.store(val, llscratch, scratch_align);
217
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),
224                                   MemFlags::empty());
225
226                 bx.lifetime_end(llscratch, scratch_size);
227             }
228         } else {
229             OperandValue::Immediate(val).store(bx, dst);
230         }
231     }
232
233     fn store_fn_arg(&self, bx: &Builder<'a, 'tcx>, idx: &mut usize, dst: PlaceRef<'tcx>) {
234         let mut next = || {
235             let val = llvm::get_param(bx.llfn(), *idx as c_uint);
236             *idx += 1;
237             val
238         };
239         match self.mode {
240             PassMode::Ignore => {},
241             PassMode::Pair(..) => {
242                 OperandValue::Pair(next(), next()).store(bx, dst);
243             }
244             PassMode::Direct(_) | PassMode::Indirect(_) | PassMode::Cast(_) => {
245                 self.store(bx, next(), dst);
246             }
247         }
248     }
249 }
250
251 pub trait FnTypeExt<'a, 'tcx> {
252     fn of_instance(cx: &CodegenCx<'a, 'tcx>, instance: &ty::Instance<'tcx>)
253                    -> Self;
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>,
265                       abi: Abi);
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);
270 }
271
272 impl<'a, 'tcx> FnTypeExt<'a, 'tcx> for FnType<'tcx, Ty<'tcx>> {
273     fn of_instance(cx: &CodegenCx<'a, 'tcx>, instance: &ty::Instance<'tcx>)
274                        -> Self {
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, &[])
279     }
280
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);
286         fn_ty
287     }
288
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.
294         {
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);
299                 }
300                 _ => bug!("FnType::new_vtable: non-pair self {:?}", self_arg)
301             }
302
303             let pointee = self_arg.layout.ty.builtin_deref(true)
304                 .unwrap_or_else(|| {
305                     bug!("FnType::new_vtable: non-pointer self {:?}", self_arg)
306                 }).ty;
307             let fat_ptr_ty = cx.tcx.mk_mut_ptr(pointee);
308             self_arg.layout = cx.layout_of(fat_ptr_ty).field(cx, 0);
309         }
310         fn_ty.adjust_for_abi(cx, sig.abi);
311         fn_ty
312     }
313
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);
318
319         use self::Abi::*;
320         let conv = match cx.sess().target.target.adjust_abi(sig.abi) {
321             RustIntrinsic | PlatformIntrinsic |
322             Rust | RustCall => Conv::C,
323
324             // It's the ABI's job to select this, not us.
325             System => bug!("system abi should be selected elsewhere"),
326
327             Stdcall => Conv::X86Stdcall,
328             Fastcall => Conv::X86Fastcall,
329             Vectorcall => Conv::X86VectorCall,
330             Thiscall => Conv::X86ThisCall,
331             C => Conv::C,
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,
339
340             // These API constants ought to be more specific...
341             Cdecl => Conv::C,
342         };
343
344         let mut inputs = sig.inputs();
345         let extra_args = if sig.abi == RustCall {
346             assert!(!sig.variadic && extra_args.is_empty());
347
348             match sig.inputs().last().unwrap().sty {
349                 ty::TyTuple(ref tupled_arguments) => {
350                     inputs = &sig.inputs()[0..sig.inputs().len() - 1];
351                     tupled_arguments
352                 }
353                 _ => {
354                     bug!("argument to function with \"rust-call\" ABI \
355                           is not a tuple");
356                 }
357             }
358         } else {
359             assert!(sig.variadic || extra_args.is_empty());
360             extra_args
361         };
362
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,
372             _ => false
373         };
374
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>>,
379                                       offset: Size,
380                                       is_return: bool| {
381             // Booleans are always an i1 that needs to be zero-extended.
382             if scalar.is_bool() {
383                 attrs.set(ArgAttribute::ZExt);
384                 return;
385             }
386
387             // Only pointer types handled below.
388             if scalar.value != layout::Pointer {
389                 return;
390             }
391
392             if scalar.valid_range.start() < scalar.valid_range.end() {
393                 if *scalar.valid_range.start() > 0 {
394                     attrs.set(ArgAttribute::NonNull);
395                 }
396             }
397
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);
402
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;
407                     }
408
409                     // `Box` pointer parameters never alias because ownership is transferred
410                     // `&mut` pointer parameters never alias other parameters,
411                     // or mutable global data
412                     //
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
422                     };
423                     if no_alias {
424                         attrs.set(ArgAttribute::NoAlias);
425                     }
426
427                     if kind == PointerKind::Frozen && !is_return {
428                         attrs.set(ArgAttribute::ReadOnly);
429                     }
430                 }
431             }
432         };
433
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;
442                 }
443             }
444
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,
451                                            a,
452                                            arg.layout,
453                                            Size::from_bytes(0),
454                                            false);
455                     adjust_for_rust_scalar(&mut b_attrs,
456                                            b,
457                                            arg.layout,
458                                            a.value.size(cx).abi_align(b.value.align(cx)),
459                                            false);
460                     arg.mode = PassMode::Pair(a_attrs, b_attrs);
461                     return arg;
462                 }
463             }
464
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,
468                                            scalar,
469                                            arg.layout,
470                                            Size::from_bytes(0),
471                                            is_return);
472                 }
473             }
474
475             arg
476         };
477
478         FnType {
479             ret: arg_of(sig.output(), true),
480             args: inputs.iter().chain(extra_args.iter()).map(|ty| {
481                 arg_of(ty, false)
482             }).collect(),
483             variadic: sig.variadic,
484             conv,
485         }
486     }
487
488     fn adjust_for_abi(&mut self,
489                       cx: &CodegenCx<'a, 'tcx>,
490                       abi: Abi) {
491         if abi == Abi::Unadjusted { return }
492
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; }
497
498                 match arg.layout.abi {
499                     layout::Abi::Aggregate { .. } => {}
500
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.
510                     //
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.
516                     //
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 => {
521                         arg.make_indirect();
522                         return
523                     }
524
525                     _ => return
526                 }
527
528                 let size = arg.layout.size;
529                 if size > layout::Pointer.size(cx) {
530                     arg.make_indirect();
531                 } else {
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.
535                     arg.cast_to(Reg {
536                         kind: RegKind::Integer,
537                         size
538                     });
539                 }
540             };
541             fixup(&mut self.ret);
542             for arg in &mut self.args {
543                 fixup(arg);
544             }
545             if let PassMode::Indirect(ref mut attrs) = self.ret.mode {
546                 attrs.set(ArgAttribute::StructRet);
547             }
548             return;
549         }
550
551         if let Err(msg) = self.adjust_for_cabi(cx, abi) {
552             cx.sess().fatal(&msg);
553         }
554     }
555
556     fn llvm_type(&self, cx: &CodegenCx<'a, 'tcx>) -> Type {
557         let mut llargument_tys = Vec::new();
558
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)
563             }
564             PassMode::Cast(cast) => cast.llvm_type(cx),
565             PassMode::Indirect(_) => {
566                 llargument_tys.push(self.ret.memory_ty(cx).ptr_to());
567                 Type::void(cx)
568             }
569         };
570
571         for arg in &self.args {
572             // add padding
573             if let Some(ty) = arg.pad {
574                 llargument_tys.push(ty.llvm_type(cx));
575             }
576
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));
583                     continue;
584                 }
585                 PassMode::Cast(cast) => cast.llvm_type(cx),
586                 PassMode::Indirect(_) => arg.memory_ty(cx).ptr_to(),
587             };
588             llargument_tys.push(llarg_ty);
589         }
590
591         if self.variadic {
592             Type::variadic_func(&llargument_tys, &llreturn_ty)
593         } else {
594             Type::func(&llargument_tys, &llreturn_ty)
595         }
596     }
597
598     fn llvm_cconv(&self) -> llvm::CallConv {
599         match self.conv {
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,
611         }
612     }
613
614     fn apply_attrs_llfn(&self, llfn: ValueRef) {
615         let mut i = 0;
616         let mut apply = |attrs: &ArgAttributes| {
617             attrs.apply_llfn(llvm::AttributePlace::Argument(i), llfn);
618             i += 1;
619         };
620         match self.ret.mode {
621             PassMode::Direct(ref attrs) => {
622                 attrs.apply_llfn(llvm::AttributePlace::ReturnValue, llfn);
623             }
624             PassMode::Indirect(ref attrs) => apply(attrs),
625             _ => {}
626         }
627         for arg in &self.args {
628             if arg.pad.is_some() {
629                 apply(&ArgAttributes::new());
630             }
631             match arg.mode {
632                 PassMode::Ignore => {}
633                 PassMode::Direct(ref attrs) |
634                 PassMode::Indirect(ref attrs) => apply(attrs),
635                 PassMode::Pair(ref a, ref b) => {
636                     apply(a);
637                     apply(b);
638                 }
639                 PassMode::Cast(_) => apply(&ArgAttributes::new()),
640             }
641         }
642     }
643
644     fn apply_attrs_callsite(&self, bx: &Builder<'a, 'tcx>, callsite: ValueRef) {
645         let mut i = 0;
646         let mut apply = |attrs: &ArgAttributes| {
647             attrs.apply_callsite(llvm::AttributePlace::Argument(i), callsite);
648             i += 1;
649         };
650         match self.ret.mode {
651             PassMode::Direct(ref attrs) => {
652                 attrs.apply_callsite(llvm::AttributePlace::ReturnValue, callsite);
653             }
654             PassMode::Indirect(ref attrs) => apply(attrs),
655             _ => {}
656         }
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.
661             match scalar.value {
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);
669                         }
670                     }
671                 }
672                 _ => {}
673             }
674         }
675         for arg in &self.args {
676             if arg.pad.is_some() {
677                 apply(&ArgAttributes::new());
678             }
679             match arg.mode {
680                 PassMode::Ignore => {}
681                 PassMode::Direct(ref attrs) |
682                 PassMode::Indirect(ref attrs) => apply(attrs),
683                 PassMode::Pair(ref a, ref b) => {
684                     apply(a);
685                     apply(b);
686                 }
687                 PassMode::Cast(_) => apply(&ArgAttributes::new()),
688             }
689         }
690
691         let cconv = self.llvm_cconv();
692         if cconv != llvm::CCallConv {
693             llvm::SetInstructionCallConv(callsite, cconv);
694         }
695     }
696 }