]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/abi.rs
run EndRegion when unwinding otherwise-empty scopes
[rust.git] / src / librustc_trans / 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;
14 use common::{instance_ty, ty_fn_sig, type_is_fat_ptr, C_usize};
15 use context::CrateContext;
16 use cabi_x86;
17 use cabi_x86_64;
18 use cabi_x86_win64;
19 use cabi_arm;
20 use cabi_aarch64;
21 use cabi_powerpc;
22 use cabi_powerpc64;
23 use cabi_s390x;
24 use cabi_mips;
25 use cabi_mips64;
26 use cabi_asmjs;
27 use cabi_msp430;
28 use cabi_sparc;
29 use cabi_sparc64;
30 use cabi_nvptx;
31 use cabi_nvptx64;
32 use cabi_hexagon;
33 use machine::llalign_of_min;
34 use type_::Type;
35 use type_of;
36
37 use rustc::hir;
38 use rustc::ty::{self, Ty};
39 use rustc::ty::layout::{self, Layout, LayoutTyper, TyLayout, Size};
40 use rustc_back::PanicStrategy;
41
42 use libc::c_uint;
43 use std::cmp;
44 use std::iter;
45
46 pub use syntax::abi::Abi;
47 pub use rustc::ty::layout::{FAT_PTR_ADDR, FAT_PTR_EXTRA};
48
49 #[derive(Clone, Copy, PartialEq, Debug)]
50 enum ArgKind {
51     /// Pass the argument directly using the normal converted
52     /// LLVM type or by coercing to another specified type
53     Direct,
54     /// Pass the argument indirectly via a hidden pointer
55     Indirect,
56     /// Ignore the argument (useful for empty struct)
57     Ignore,
58 }
59
60 // Hack to disable non_upper_case_globals only for the bitflags! and not for the rest
61 // of this module
62 pub use self::attr_impl::ArgAttribute;
63
64 #[allow(non_upper_case_globals)]
65 #[allow(unused)]
66 mod attr_impl {
67     // The subset of llvm::Attribute needed for arguments, packed into a bitfield.
68     bitflags! {
69         #[derive(Default)]
70         pub struct ArgAttribute: u16 {
71             const ByVal     = 1 << 0;
72             const NoAlias   = 1 << 1;
73             const NoCapture = 1 << 2;
74             const NonNull   = 1 << 3;
75             const ReadOnly  = 1 << 4;
76             const SExt      = 1 << 5;
77             const StructRet = 1 << 6;
78             const ZExt      = 1 << 7;
79             const InReg     = 1 << 8;
80         }
81     }
82 }
83
84 macro_rules! for_each_kind {
85     ($flags: ident, $f: ident, $($kind: ident),+) => ({
86         $(if $flags.contains(ArgAttribute::$kind) { $f(llvm::Attribute::$kind) })+
87     })
88 }
89
90 impl ArgAttribute {
91     fn for_each_kind<F>(&self, mut f: F) where F: FnMut(llvm::Attribute) {
92         for_each_kind!(self, f,
93                        ByVal, NoAlias, NoCapture, NonNull, ReadOnly, SExt, StructRet, ZExt, InReg)
94     }
95 }
96
97 /// A compact representation of LLVM attributes (at least those relevant for this module)
98 /// that can be manipulated without interacting with LLVM's Attribute machinery.
99 #[derive(Copy, Clone, Debug, Default)]
100 pub struct ArgAttributes {
101     regular: ArgAttribute,
102     dereferenceable_bytes: u64,
103 }
104
105 impl ArgAttributes {
106     pub fn set(&mut self, attr: ArgAttribute) -> &mut Self {
107         self.regular = self.regular | attr;
108         self
109     }
110
111     pub fn set_dereferenceable(&mut self, bytes: u64) -> &mut Self {
112         self.dereferenceable_bytes = bytes;
113         self
114     }
115
116     pub fn apply_llfn(&self, idx: AttributePlace, llfn: ValueRef) {
117         unsafe {
118             self.regular.for_each_kind(|attr| attr.apply_llfn(idx, llfn));
119             if self.dereferenceable_bytes != 0 {
120                 llvm::LLVMRustAddDereferenceableAttr(llfn,
121                                                      idx.as_uint(),
122                                                      self.dereferenceable_bytes);
123             }
124         }
125     }
126
127     pub fn apply_callsite(&self, idx: AttributePlace, callsite: ValueRef) {
128         unsafe {
129             self.regular.for_each_kind(|attr| attr.apply_callsite(idx, callsite));
130             if self.dereferenceable_bytes != 0 {
131                 llvm::LLVMRustAddDereferenceableCallSiteAttr(callsite,
132                                                              idx.as_uint(),
133                                                              self.dereferenceable_bytes);
134             }
135         }
136     }
137 }
138 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
139 pub enum RegKind {
140     Integer,
141     Float,
142     Vector
143 }
144
145 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
146 pub struct Reg {
147     pub kind: RegKind,
148     pub size: Size,
149 }
150
151 macro_rules! reg_ctor {
152     ($name:ident, $kind:ident, $bits:expr) => {
153         pub fn $name() -> Reg {
154             Reg {
155                 kind: RegKind::$kind,
156                 size: Size::from_bits($bits)
157             }
158         }
159     }
160 }
161
162 impl Reg {
163     reg_ctor!(i8, Integer, 8);
164     reg_ctor!(i16, Integer, 16);
165     reg_ctor!(i32, Integer, 32);
166     reg_ctor!(i64, Integer, 64);
167
168     reg_ctor!(f32, Float, 32);
169     reg_ctor!(f64, Float, 64);
170 }
171
172 impl Reg {
173     fn llvm_type(&self, ccx: &CrateContext) -> Type {
174         match self.kind {
175             RegKind::Integer => Type::ix(ccx, self.size.bits()),
176             RegKind::Float => {
177                 match self.size.bits() {
178                     32 => Type::f32(ccx),
179                     64 => Type::f64(ccx),
180                     _ => bug!("unsupported float: {:?}", self)
181                 }
182             }
183             RegKind::Vector => {
184                 Type::vector(&Type::i8(ccx), self.size.bytes())
185             }
186         }
187     }
188 }
189
190 /// An argument passed entirely registers with the
191 /// same kind (e.g. HFA / HVA on PPC64 and AArch64).
192 #[derive(Copy, Clone)]
193 pub struct Uniform {
194     pub unit: Reg,
195
196     /// The total size of the argument, which can be:
197     /// * equal to `unit.size` (one scalar/vector)
198     /// * a multiple of `unit.size` (an array of scalar/vectors)
199     /// * if `unit.kind` is `Integer`, the last element
200     ///   can be shorter, i.e. `{ i64, i64, i32 }` for
201     ///   64-bit integers with a total size of 20 bytes
202     pub total: Size,
203 }
204
205 impl From<Reg> for Uniform {
206     fn from(unit: Reg) -> Uniform {
207         Uniform {
208             unit,
209             total: unit.size
210         }
211     }
212 }
213
214 impl Uniform {
215     fn llvm_type(&self, ccx: &CrateContext) -> Type {
216         let llunit = self.unit.llvm_type(ccx);
217
218         if self.total <= self.unit.size {
219             return llunit;
220         }
221
222         let count = self.total.bytes() / self.unit.size.bytes();
223         let rem_bytes = self.total.bytes() % self.unit.size.bytes();
224
225         if rem_bytes == 0 {
226             return Type::array(&llunit, count);
227         }
228
229         // Only integers can be really split further.
230         assert_eq!(self.unit.kind, RegKind::Integer);
231
232         let args: Vec<_> = (0..count).map(|_| llunit)
233             .chain(iter::once(Type::ix(ccx, rem_bytes * 8)))
234             .collect();
235
236         Type::struct_(ccx, &args, false)
237     }
238 }
239
240 pub trait LayoutExt<'tcx> {
241     fn is_aggregate(&self) -> bool;
242     fn homogeneous_aggregate<'a>(&self, ccx: &CrateContext<'a, 'tcx>) -> Option<Reg>;
243 }
244
245 impl<'tcx> LayoutExt<'tcx> for TyLayout<'tcx> {
246     fn is_aggregate(&self) -> bool {
247         match *self.layout {
248             Layout::Scalar { .. } |
249             Layout::RawNullablePointer { .. } |
250             Layout::CEnum { .. } |
251             Layout::Vector { .. } => false,
252
253             Layout::Array { .. } |
254             Layout::FatPointer { .. } |
255             Layout::Univariant { .. } |
256             Layout::UntaggedUnion { .. } |
257             Layout::General { .. } |
258             Layout::StructWrappedNullablePointer { .. } => true
259         }
260     }
261
262     fn homogeneous_aggregate<'a>(&self, ccx: &CrateContext<'a, 'tcx>) -> Option<Reg> {
263         match *self.layout {
264             // The primitives for this algorithm.
265             Layout::Scalar { value, .. } |
266             Layout::RawNullablePointer { value, .. } => {
267                 let kind = match value {
268                     layout::Int(_) |
269                     layout::Pointer => RegKind::Integer,
270                     layout::F32 |
271                     layout::F64 => RegKind::Float
272                 };
273                 Some(Reg {
274                     kind,
275                     size: self.size(ccx)
276                 })
277             }
278
279             Layout::CEnum { .. } => {
280                 Some(Reg {
281                     kind: RegKind::Integer,
282                     size: self.size(ccx)
283                 })
284             }
285
286             Layout::Vector { .. } => {
287                 Some(Reg {
288                     kind: RegKind::Vector,
289                     size: self.size(ccx)
290                 })
291             }
292
293             Layout::Array { count, .. } => {
294                 if count > 0 {
295                     self.field(ccx, 0).homogeneous_aggregate(ccx)
296                 } else {
297                     None
298                 }
299             }
300
301             Layout::Univariant { ref variant, .. } => {
302                 let mut unaligned_offset = Size::from_bytes(0);
303                 let mut result = None;
304
305                 for i in 0..self.field_count() {
306                     if unaligned_offset != variant.offsets[i] {
307                         return None;
308                     }
309
310                     let field = self.field(ccx, i);
311                     match (result, field.homogeneous_aggregate(ccx)) {
312                         // The field itself must be a homogeneous aggregate.
313                         (_, None) => return None,
314                         // If this is the first field, record the unit.
315                         (None, Some(unit)) => {
316                             result = Some(unit);
317                         }
318                         // For all following fields, the unit must be the same.
319                         (Some(prev_unit), Some(unit)) => {
320                             if prev_unit != unit {
321                                 return None;
322                             }
323                         }
324                     }
325
326                     // Keep track of the offset (without padding).
327                     let size = field.size(ccx);
328                     match unaligned_offset.checked_add(size, ccx) {
329                         Some(offset) => unaligned_offset = offset,
330                         None => return None
331                     }
332                 }
333
334                 // There needs to be no padding.
335                 if unaligned_offset != self.size(ccx) {
336                     None
337                 } else {
338                     result
339                 }
340             }
341
342             Layout::UntaggedUnion { .. } => {
343                 let mut max = Size::from_bytes(0);
344                 let mut result = None;
345
346                 for i in 0..self.field_count() {
347                     let field = self.field(ccx, i);
348                     match (result, field.homogeneous_aggregate(ccx)) {
349                         // The field itself must be a homogeneous aggregate.
350                         (_, None) => return None,
351                         // If this is the first field, record the unit.
352                         (None, Some(unit)) => {
353                             result = Some(unit);
354                         }
355                         // For all following fields, the unit must be the same.
356                         (Some(prev_unit), Some(unit)) => {
357                             if prev_unit != unit {
358                                 return None;
359                             }
360                         }
361                     }
362
363                     // Keep track of the offset (without padding).
364                     let size = field.size(ccx);
365                     if size > max {
366                         max = size;
367                     }
368                 }
369
370                 // There needs to be no padding.
371                 if max != self.size(ccx) {
372                     None
373                 } else {
374                     result
375                 }
376             }
377
378             // Rust-specific types, which we can ignore for C ABIs.
379             Layout::FatPointer { .. } |
380             Layout::General { .. } |
381             Layout::StructWrappedNullablePointer { .. } => None
382         }
383     }
384 }
385
386 pub enum CastTarget {
387     Uniform(Uniform),
388     Pair(Reg, Reg)
389 }
390
391 impl From<Reg> for CastTarget {
392     fn from(unit: Reg) -> CastTarget {
393         CastTarget::Uniform(Uniform::from(unit))
394     }
395 }
396
397 impl From<Uniform> for CastTarget {
398     fn from(uniform: Uniform) -> CastTarget {
399         CastTarget::Uniform(uniform)
400     }
401 }
402
403 impl CastTarget {
404     fn llvm_type(&self, ccx: &CrateContext) -> Type {
405         match *self {
406             CastTarget::Uniform(u) => u.llvm_type(ccx),
407             CastTarget::Pair(a, b) => {
408                 Type::struct_(ccx, &[
409                     a.llvm_type(ccx),
410                     b.llvm_type(ccx)
411                 ], false)
412             }
413         }
414     }
415 }
416
417 /// Information about how a specific C type
418 /// should be passed to or returned from a function
419 ///
420 /// This is borrowed from clang's ABIInfo.h
421 #[derive(Clone, Copy, Debug)]
422 pub struct ArgType<'tcx> {
423     kind: ArgKind,
424     pub layout: TyLayout<'tcx>,
425     /// Coerced LLVM Type
426     pub cast: Option<Type>,
427     /// Dummy argument, which is emitted before the real argument
428     pub pad: Option<Type>,
429     /// LLVM attributes of argument
430     pub attrs: ArgAttributes
431 }
432
433 impl<'a, 'tcx> ArgType<'tcx> {
434     fn new(layout: TyLayout<'tcx>) -> ArgType<'tcx> {
435         ArgType {
436             kind: ArgKind::Direct,
437             layout,
438             cast: None,
439             pad: None,
440             attrs: ArgAttributes::default()
441         }
442     }
443
444     pub fn make_indirect(&mut self, ccx: &CrateContext<'a, 'tcx>) {
445         assert_eq!(self.kind, ArgKind::Direct);
446
447         // Wipe old attributes, likely not valid through indirection.
448         self.attrs = ArgAttributes::default();
449
450         let llarg_sz = self.layout.size(ccx).bytes();
451
452         // For non-immediate arguments the callee gets its own copy of
453         // the value on the stack, so there are no aliases. It's also
454         // program-invisible so can't possibly capture
455         self.attrs.set(ArgAttribute::NoAlias)
456                   .set(ArgAttribute::NoCapture)
457                   .set_dereferenceable(llarg_sz);
458
459         self.kind = ArgKind::Indirect;
460     }
461
462     pub fn ignore(&mut self) {
463         assert_eq!(self.kind, ArgKind::Direct);
464         self.kind = ArgKind::Ignore;
465     }
466
467     pub fn extend_integer_width_to(&mut self, bits: u64) {
468         // Only integers have signedness
469         let (i, signed) = match *self.layout {
470             Layout::Scalar { value, .. } => {
471                 match value {
472                     layout::Int(i) => {
473                         if self.layout.ty.is_integral() {
474                             (i, self.layout.ty.is_signed())
475                         } else {
476                             return;
477                         }
478                     }
479                     _ => return
480                 }
481             }
482
483             // Rust enum types that map onto C enums also need to follow
484             // the target ABI zero-/sign-extension rules.
485             Layout::CEnum { discr, signed, .. } => (discr, signed),
486
487             _ => return
488         };
489
490         if i.size().bits() < bits {
491             self.attrs.set(if signed {
492                 ArgAttribute::SExt
493             } else {
494                 ArgAttribute::ZExt
495             });
496         }
497     }
498
499     pub fn cast_to<T: Into<CastTarget>>(&mut self, ccx: &CrateContext, target: T) {
500         self.cast = Some(target.into().llvm_type(ccx));
501     }
502
503     pub fn pad_with(&mut self, ccx: &CrateContext, reg: Reg) {
504         self.pad = Some(reg.llvm_type(ccx));
505     }
506
507     pub fn is_indirect(&self) -> bool {
508         self.kind == ArgKind::Indirect
509     }
510
511     pub fn is_ignore(&self) -> bool {
512         self.kind == ArgKind::Ignore
513     }
514
515     /// Get the LLVM type for an lvalue of the original Rust type of
516     /// this argument/return, i.e. the result of `type_of::type_of`.
517     pub fn memory_ty(&self, ccx: &CrateContext<'a, 'tcx>) -> Type {
518         type_of::type_of(ccx, self.layout.ty)
519     }
520
521     /// Store a direct/indirect value described by this ArgType into a
522     /// lvalue for the original Rust type of this argument/return.
523     /// Can be used for both storing formal arguments into Rust variables
524     /// or results of call/invoke instructions into their destinations.
525     pub fn store(&self, bcx: &Builder<'a, 'tcx>, mut val: ValueRef, dst: ValueRef) {
526         if self.is_ignore() {
527             return;
528         }
529         let ccx = bcx.ccx;
530         if self.is_indirect() {
531             let llsz = C_usize(ccx, self.layout.size(ccx).bytes());
532             let llalign = self.layout.align(ccx).abi();
533             base::call_memcpy(bcx, dst, val, llsz, llalign as u32);
534         } else if let Some(ty) = self.cast {
535             // FIXME(eddyb): Figure out when the simpler Store is safe, clang
536             // uses it for i16 -> {i8, i8}, but not for i24 -> {i8, i8, i8}.
537             let can_store_through_cast_ptr = false;
538             if can_store_through_cast_ptr {
539                 let cast_dst = bcx.pointercast(dst, ty.ptr_to());
540                 let llalign = self.layout.align(ccx).abi();
541                 bcx.store(val, cast_dst, Some(llalign as u32));
542             } else {
543                 // The actual return type is a struct, but the ABI
544                 // adaptation code has cast it into some scalar type.  The
545                 // code that follows is the only reliable way I have
546                 // found to do a transform like i64 -> {i32,i32}.
547                 // Basically we dump the data onto the stack then memcpy it.
548                 //
549                 // Other approaches I tried:
550                 // - Casting rust ret pointer to the foreign type and using Store
551                 //   is (a) unsafe if size of foreign type > size of rust type and
552                 //   (b) runs afoul of strict aliasing rules, yielding invalid
553                 //   assembly under -O (specifically, the store gets removed).
554                 // - Truncating foreign type to correct integral type and then
555                 //   bitcasting to the struct type yields invalid cast errors.
556
557                 // We instead thus allocate some scratch space...
558                 let llscratch = bcx.alloca(ty, "abi_cast", None);
559                 base::Lifetime::Start.call(bcx, llscratch);
560
561                 // ...where we first store the value...
562                 bcx.store(val, llscratch, None);
563
564                 // ...and then memcpy it to the intended destination.
565                 base::call_memcpy(bcx,
566                                   bcx.pointercast(dst, Type::i8p(ccx)),
567                                   bcx.pointercast(llscratch, Type::i8p(ccx)),
568                                   C_usize(ccx, self.layout.size(ccx).bytes()),
569                                   cmp::min(self.layout.align(ccx).abi() as u32,
570                                            llalign_of_min(ccx, ty)));
571
572                 base::Lifetime::End.call(bcx, llscratch);
573             }
574         } else {
575             if self.layout.ty == ccx.tcx().types.bool {
576                 val = bcx.zext(val, Type::i8(ccx));
577             }
578             bcx.store(val, dst, None);
579         }
580     }
581
582     pub fn store_fn_arg(&self, bcx: &Builder<'a, 'tcx>, idx: &mut usize, dst: ValueRef) {
583         if self.pad.is_some() {
584             *idx += 1;
585         }
586         if self.is_ignore() {
587             return;
588         }
589         let val = llvm::get_param(bcx.llfn(), *idx as c_uint);
590         *idx += 1;
591         self.store(bcx, val, dst);
592     }
593 }
594
595 /// Metadata describing how the arguments to a native function
596 /// should be passed in order to respect the native ABI.
597 ///
598 /// I will do my best to describe this structure, but these
599 /// comments are reverse-engineered and may be inaccurate. -NDM
600 #[derive(Clone, Debug)]
601 pub struct FnType<'tcx> {
602     /// The LLVM types of each argument.
603     pub args: Vec<ArgType<'tcx>>,
604
605     /// LLVM return type.
606     pub ret: ArgType<'tcx>,
607
608     pub variadic: bool,
609
610     pub cconv: llvm::CallConv
611 }
612
613 impl<'a, 'tcx> FnType<'tcx> {
614     pub fn of_instance(ccx: &CrateContext<'a, 'tcx>, instance: &ty::Instance<'tcx>)
615                        -> Self {
616         let fn_ty = instance_ty(ccx.tcx(), &instance);
617         let sig = ty_fn_sig(ccx, fn_ty);
618         let sig = ccx.tcx().erase_late_bound_regions_and_normalize(&sig);
619         Self::new(ccx, sig, &[])
620     }
621
622     pub fn new(ccx: &CrateContext<'a, 'tcx>,
623                sig: ty::FnSig<'tcx>,
624                extra_args: &[Ty<'tcx>]) -> FnType<'tcx> {
625         let mut fn_ty = FnType::unadjusted(ccx, sig, extra_args);
626         fn_ty.adjust_for_abi(ccx, sig);
627         fn_ty
628     }
629
630     pub fn new_vtable(ccx: &CrateContext<'a, 'tcx>,
631                       sig: ty::FnSig<'tcx>,
632                       extra_args: &[Ty<'tcx>]) -> FnType<'tcx> {
633         let mut fn_ty = FnType::unadjusted(ccx, sig, extra_args);
634         // Don't pass the vtable, it's not an argument of the virtual fn.
635         fn_ty.args[1].ignore();
636         fn_ty.adjust_for_abi(ccx, sig);
637         fn_ty
638     }
639
640     pub fn unadjusted(ccx: &CrateContext<'a, 'tcx>,
641                       sig: ty::FnSig<'tcx>,
642                       extra_args: &[Ty<'tcx>]) -> FnType<'tcx> {
643         debug!("FnType::unadjusted({:?}, {:?})", sig, extra_args);
644
645         use self::Abi::*;
646         let cconv = match ccx.sess().target.target.adjust_abi(sig.abi) {
647             RustIntrinsic | PlatformIntrinsic |
648             Rust | RustCall => llvm::CCallConv,
649
650             // It's the ABI's job to select this, not us.
651             System => bug!("system abi should be selected elsewhere"),
652
653             Stdcall => llvm::X86StdcallCallConv,
654             Fastcall => llvm::X86FastcallCallConv,
655             Vectorcall => llvm::X86_VectorCall,
656             Thiscall => llvm::X86_ThisCall,
657             C => llvm::CCallConv,
658             Unadjusted => llvm::CCallConv,
659             Win64 => llvm::X86_64_Win64,
660             SysV64 => llvm::X86_64_SysV,
661             Aapcs => llvm::ArmAapcsCallConv,
662             PtxKernel => llvm::PtxKernel,
663             Msp430Interrupt => llvm::Msp430Intr,
664             X86Interrupt => llvm::X86_Intr,
665
666             // These API constants ought to be more specific...
667             Cdecl => llvm::CCallConv,
668         };
669
670         let mut inputs = sig.inputs();
671         let extra_args = if sig.abi == RustCall {
672             assert!(!sig.variadic && extra_args.is_empty());
673
674             match sig.inputs().last().unwrap().sty {
675                 ty::TyTuple(ref tupled_arguments, _) => {
676                     inputs = &sig.inputs()[0..sig.inputs().len() - 1];
677                     tupled_arguments
678                 }
679                 _ => {
680                     bug!("argument to function with \"rust-call\" ABI \
681                           is not a tuple");
682                 }
683             }
684         } else {
685             assert!(sig.variadic || extra_args.is_empty());
686             extra_args
687         };
688
689         let target = &ccx.sess().target.target;
690         let win_x64_gnu = target.target_os == "windows"
691                        && target.arch == "x86_64"
692                        && target.target_env == "gnu";
693         let linux_s390x = target.target_os == "linux"
694                        && target.arch == "s390x"
695                        && target.target_env == "gnu";
696         let rust_abi = match sig.abi {
697             RustIntrinsic | PlatformIntrinsic | Rust | RustCall => true,
698             _ => false
699         };
700
701         let arg_of = |ty: Ty<'tcx>, is_return: bool| {
702             let mut arg = ArgType::new(ccx.layout_of(ty));
703             if ty.is_bool() {
704                 arg.attrs.set(ArgAttribute::ZExt);
705             } else {
706                 if arg.layout.size(ccx).bytes() == 0 {
707                     // For some forsaken reason, x86_64-pc-windows-gnu
708                     // doesn't ignore zero-sized struct arguments.
709                     // The same is true for s390x-unknown-linux-gnu.
710                     if is_return || rust_abi ||
711                        (!win_x64_gnu && !linux_s390x) {
712                         arg.ignore();
713                     }
714                 }
715             }
716             arg
717         };
718
719         let ret_ty = sig.output();
720         let mut ret = arg_of(ret_ty, true);
721
722         if !type_is_fat_ptr(ccx, ret_ty) {
723             // The `noalias` attribute on the return value is useful to a
724             // function ptr caller.
725             if ret_ty.is_box() {
726                 // `Box` pointer return values never alias because ownership
727                 // is transferred
728                 ret.attrs.set(ArgAttribute::NoAlias);
729             }
730
731             // We can also mark the return value as `dereferenceable` in certain cases
732             match ret_ty.sty {
733                 // These are not really pointers but pairs, (pointer, len)
734                 ty::TyRef(_, ty::TypeAndMut { ty, .. }) => {
735                     ret.attrs.set_dereferenceable(ccx.size_of(ty));
736                 }
737                 ty::TyAdt(def, _) if def.is_box() => {
738                     ret.attrs.set_dereferenceable(ccx.size_of(ret_ty.boxed_ty()));
739                 }
740                 _ => {}
741             }
742         }
743
744         let mut args = Vec::with_capacity(inputs.len() + extra_args.len());
745
746         // Handle safe Rust thin and fat pointers.
747         let rust_ptr_attrs = |ty: Ty<'tcx>, arg: &mut ArgType| match ty.sty {
748             // `Box` pointer parameters never alias because ownership is transferred
749             ty::TyAdt(def, _) if def.is_box() => {
750                 arg.attrs.set(ArgAttribute::NoAlias);
751                 Some(ty.boxed_ty())
752             }
753
754             ty::TyRef(_, mt) => {
755                 // `&mut` pointer parameters never alias other parameters, or mutable global data
756                 //
757                 // `&T` where `T` contains no `UnsafeCell<U>` is immutable, and can be marked as
758                 // both `readonly` and `noalias`, as LLVM's definition of `noalias` is based solely
759                 // on memory dependencies rather than pointer equality
760                 let is_freeze = ccx.shared().type_is_freeze(mt.ty);
761
762                 let no_alias_is_safe =
763                     if ccx.shared().tcx().sess.opts.debugging_opts.mutable_noalias ||
764                        ccx.shared().tcx().sess.panic_strategy() == PanicStrategy::Abort {
765                         // Mutable refrences or immutable shared references
766                         mt.mutbl == hir::MutMutable || is_freeze
767                     } else {
768                         // Only immutable shared references
769                         mt.mutbl != hir::MutMutable && is_freeze
770                     };
771
772                 if no_alias_is_safe {
773                     arg.attrs.set(ArgAttribute::NoAlias);
774                 }
775
776                 if mt.mutbl == hir::MutImmutable && is_freeze {
777                     arg.attrs.set(ArgAttribute::ReadOnly);
778                 }
779
780                 Some(mt.ty)
781             }
782             _ => None
783         };
784
785         for ty in inputs.iter().chain(extra_args.iter()) {
786             let mut arg = arg_of(ty, false);
787
788             if let ty::layout::FatPointer { .. } = *arg.layout {
789                 let mut data = ArgType::new(arg.layout.field(ccx, 0));
790                 let mut info = ArgType::new(arg.layout.field(ccx, 1));
791
792                 if let Some(inner) = rust_ptr_attrs(ty, &mut data) {
793                     data.attrs.set(ArgAttribute::NonNull);
794                     if ccx.tcx().struct_tail(inner).is_trait() {
795                         // vtables can be safely marked non-null, readonly
796                         // and noalias.
797                         info.attrs.set(ArgAttribute::NonNull);
798                         info.attrs.set(ArgAttribute::ReadOnly);
799                         info.attrs.set(ArgAttribute::NoAlias);
800                     }
801                 }
802                 args.push(data);
803                 args.push(info);
804             } else {
805                 if let Some(inner) = rust_ptr_attrs(ty, &mut arg) {
806                     arg.attrs.set_dereferenceable(ccx.size_of(inner));
807                 }
808                 args.push(arg);
809             }
810         }
811
812         FnType {
813             args,
814             ret,
815             variadic: sig.variadic,
816             cconv,
817         }
818     }
819
820     fn adjust_for_abi(&mut self,
821                       ccx: &CrateContext<'a, 'tcx>,
822                       sig: ty::FnSig<'tcx>) {
823         let abi = sig.abi;
824         if abi == Abi::Unadjusted { return }
825
826         if abi == Abi::Rust || abi == Abi::RustCall ||
827            abi == Abi::RustIntrinsic || abi == Abi::PlatformIntrinsic {
828             let fixup = |arg: &mut ArgType<'tcx>| {
829                 if !arg.layout.is_aggregate() {
830                     return;
831                 }
832
833                 let size = arg.layout.size(ccx);
834
835                 if let Some(unit) = arg.layout.homogeneous_aggregate(ccx) {
836                     // Replace newtypes with their inner-most type.
837                     if unit.size == size {
838                         // Needs a cast as we've unpacked a newtype.
839                         arg.cast_to(ccx, unit);
840                         return;
841                     }
842
843                     // Pairs of floats.
844                     if unit.kind == RegKind::Float {
845                         if unit.size.checked_mul(2, ccx) == Some(size) {
846                             // FIXME(eddyb) This should be using Uniform instead of a pair,
847                             // but the resulting [2 x float/double] breaks emscripten.
848                             // See https://github.com/kripken/emscripten-fastcomp/issues/178.
849                             arg.cast_to(ccx, CastTarget::Pair(unit, unit));
850                             return;
851                         }
852                     }
853                 }
854
855                 if size > layout::Pointer.size(ccx) {
856                     arg.make_indirect(ccx);
857                 } else {
858                     // We want to pass small aggregates as immediates, but using
859                     // a LLVM aggregate type for this leads to bad optimizations,
860                     // so we pick an appropriately sized integer type instead.
861                     arg.cast_to(ccx, Reg {
862                         kind: RegKind::Integer,
863                         size
864                     });
865                 }
866             };
867             // Fat pointers are returned by-value.
868             if !self.ret.is_ignore() {
869                 if !type_is_fat_ptr(ccx, sig.output()) {
870                     fixup(&mut self.ret);
871                 }
872             }
873             for arg in &mut self.args {
874                 if arg.is_ignore() { continue; }
875                 fixup(arg);
876             }
877             if self.ret.is_indirect() {
878                 self.ret.attrs.set(ArgAttribute::StructRet);
879             }
880             return;
881         }
882
883         match &ccx.sess().target.target.arch[..] {
884             "x86" => {
885                 let flavor = if abi == Abi::Fastcall {
886                     cabi_x86::Flavor::Fastcall
887                 } else {
888                     cabi_x86::Flavor::General
889                 };
890                 cabi_x86::compute_abi_info(ccx, self, flavor);
891             },
892             "x86_64" => if abi == Abi::SysV64 {
893                 cabi_x86_64::compute_abi_info(ccx, self);
894             } else if abi == Abi::Win64 || ccx.sess().target.target.options.is_like_windows {
895                 cabi_x86_win64::compute_abi_info(ccx, self);
896             } else {
897                 cabi_x86_64::compute_abi_info(ccx, self);
898             },
899             "aarch64" => cabi_aarch64::compute_abi_info(ccx, self),
900             "arm" => cabi_arm::compute_abi_info(ccx, self),
901             "mips" => cabi_mips::compute_abi_info(ccx, self),
902             "mips64" => cabi_mips64::compute_abi_info(ccx, self),
903             "powerpc" => cabi_powerpc::compute_abi_info(ccx, self),
904             "powerpc64" => cabi_powerpc64::compute_abi_info(ccx, self),
905             "s390x" => cabi_s390x::compute_abi_info(ccx, self),
906             "asmjs" => cabi_asmjs::compute_abi_info(ccx, self),
907             "wasm32" => cabi_asmjs::compute_abi_info(ccx, self),
908             "msp430" => cabi_msp430::compute_abi_info(ccx, self),
909             "sparc" => cabi_sparc::compute_abi_info(ccx, self),
910             "sparc64" => cabi_sparc64::compute_abi_info(ccx, self),
911             "nvptx" => cabi_nvptx::compute_abi_info(ccx, self),
912             "nvptx64" => cabi_nvptx64::compute_abi_info(ccx, self),
913             "hexagon" => cabi_hexagon::compute_abi_info(ccx, self),
914             a => ccx.sess().fatal(&format!("unrecognized arch \"{}\" in target specification", a))
915         }
916
917         if self.ret.is_indirect() {
918             self.ret.attrs.set(ArgAttribute::StructRet);
919         }
920     }
921
922     pub fn llvm_type(&self, ccx: &CrateContext<'a, 'tcx>) -> Type {
923         let mut llargument_tys = Vec::new();
924
925         let llreturn_ty = if self.ret.is_ignore() {
926             Type::void(ccx)
927         } else if self.ret.is_indirect() {
928             llargument_tys.push(self.ret.memory_ty(ccx).ptr_to());
929             Type::void(ccx)
930         } else {
931             self.ret.cast.unwrap_or_else(|| {
932                 type_of::immediate_type_of(ccx, self.ret.layout.ty)
933             })
934         };
935
936         for arg in &self.args {
937             if arg.is_ignore() {
938                 continue;
939             }
940             // add padding
941             if let Some(ty) = arg.pad {
942                 llargument_tys.push(ty);
943             }
944
945             let llarg_ty = if arg.is_indirect() {
946                 arg.memory_ty(ccx).ptr_to()
947             } else {
948                 arg.cast.unwrap_or_else(|| {
949                     type_of::immediate_type_of(ccx, arg.layout.ty)
950                 })
951             };
952
953             llargument_tys.push(llarg_ty);
954         }
955
956         if self.variadic {
957             Type::variadic_func(&llargument_tys, &llreturn_ty)
958         } else {
959             Type::func(&llargument_tys, &llreturn_ty)
960         }
961     }
962
963     pub fn apply_attrs_llfn(&self, llfn: ValueRef) {
964         let mut i = if self.ret.is_indirect() { 1 } else { 0 };
965         if !self.ret.is_ignore() {
966             self.ret.attrs.apply_llfn(llvm::AttributePlace::Argument(i), llfn);
967         }
968         i += 1;
969         for arg in &self.args {
970             if !arg.is_ignore() {
971                 if arg.pad.is_some() { i += 1; }
972                 arg.attrs.apply_llfn(llvm::AttributePlace::Argument(i), llfn);
973                 i += 1;
974             }
975         }
976     }
977
978     pub fn apply_attrs_callsite(&self, callsite: ValueRef) {
979         let mut i = if self.ret.is_indirect() { 1 } else { 0 };
980         if !self.ret.is_ignore() {
981             self.ret.attrs.apply_callsite(llvm::AttributePlace::Argument(i), callsite);
982         }
983         i += 1;
984         for arg in &self.args {
985             if !arg.is_ignore() {
986                 if arg.pad.is_some() { i += 1; }
987                 arg.attrs.apply_callsite(llvm::AttributePlace::Argument(i), callsite);
988                 i += 1;
989             }
990         }
991
992         if self.cconv != llvm::CCallConv {
993             llvm::SetInstructionCallConv(callsite, self.cconv);
994         }
995     }
996 }
997
998 pub fn align_up_to(off: u64, a: u64) -> u64 {
999     (off + a - 1) / a * a
1000 }