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