]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/abi.rs
Rollup merge of #42230 - venkatagiri:ice_regression_tests, r=Mark-Simulacrum
[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             Thiscall => llvm::X86_ThisCall,
646             C => llvm::CCallConv,
647             Unadjusted => llvm::CCallConv,
648             Win64 => llvm::X86_64_Win64,
649             SysV64 => llvm::X86_64_SysV,
650             Aapcs => llvm::ArmAapcsCallConv,
651             PtxKernel => llvm::PtxKernel,
652             Msp430Interrupt => llvm::Msp430Intr,
653             X86Interrupt => llvm::X86_Intr,
654
655             // These API constants ought to be more specific...
656             Cdecl => llvm::CCallConv,
657         };
658
659         let mut inputs = sig.inputs();
660         let extra_args = if sig.abi == RustCall {
661             assert!(!sig.variadic && extra_args.is_empty());
662
663             match sig.inputs().last().unwrap().sty {
664                 ty::TyTuple(ref tupled_arguments, _) => {
665                     inputs = &sig.inputs()[0..sig.inputs().len() - 1];
666                     tupled_arguments
667                 }
668                 _ => {
669                     bug!("argument to function with \"rust-call\" ABI \
670                           is not a tuple");
671                 }
672             }
673         } else {
674             assert!(sig.variadic || extra_args.is_empty());
675             extra_args
676         };
677
678         let target = &ccx.sess().target.target;
679         let win_x64_gnu = target.target_os == "windows"
680                        && target.arch == "x86_64"
681                        && target.target_env == "gnu";
682         let linux_s390x = target.target_os == "linux"
683                        && target.arch == "s390x"
684                        && target.target_env == "gnu";
685         let rust_abi = match sig.abi {
686             RustIntrinsic | PlatformIntrinsic | Rust | RustCall => true,
687             _ => false
688         };
689
690         let arg_of = |ty: Ty<'tcx>, is_return: bool| {
691             let mut arg = ArgType::new(ccx.layout_of(ty));
692             if ty.is_bool() {
693                 arg.attrs.set(ArgAttribute::ZExt);
694             } else {
695                 if arg.layout.size(ccx).bytes() == 0 {
696                     // For some forsaken reason, x86_64-pc-windows-gnu
697                     // doesn't ignore zero-sized struct arguments.
698                     // The same is true for s390x-unknown-linux-gnu.
699                     if is_return || rust_abi ||
700                        (!win_x64_gnu && !linux_s390x) {
701                         arg.ignore();
702                     }
703                 }
704             }
705             arg
706         };
707
708         let ret_ty = sig.output();
709         let mut ret = arg_of(ret_ty, true);
710
711         if !type_is_fat_ptr(ccx, ret_ty) {
712             // The `noalias` attribute on the return value is useful to a
713             // function ptr caller.
714             if ret_ty.is_box() {
715                 // `Box` pointer return values never alias because ownership
716                 // is transferred
717                 ret.attrs.set(ArgAttribute::NoAlias);
718             }
719
720             // We can also mark the return value as `dereferenceable` in certain cases
721             match ret_ty.sty {
722                 // These are not really pointers but pairs, (pointer, len)
723                 ty::TyRef(_, ty::TypeAndMut { ty, .. }) => {
724                     ret.attrs.set_dereferenceable(ccx.size_of(ty));
725                 }
726                 ty::TyAdt(def, _) if def.is_box() => {
727                     ret.attrs.set_dereferenceable(ccx.size_of(ret_ty.boxed_ty()));
728                 }
729                 _ => {}
730             }
731         }
732
733         let mut args = Vec::with_capacity(inputs.len() + extra_args.len());
734
735         // Handle safe Rust thin and fat pointers.
736         let rust_ptr_attrs = |ty: Ty<'tcx>, arg: &mut ArgType| match ty.sty {
737             // `Box` pointer parameters never alias because ownership is transferred
738             ty::TyAdt(def, _) if def.is_box() => {
739                 arg.attrs.set(ArgAttribute::NoAlias);
740                 Some(ty.boxed_ty())
741             }
742
743             ty::TyRef(b, mt) => {
744                 use rustc::ty::{BrAnon, ReLateBound};
745
746                 // `&mut` pointer parameters never alias other parameters, or mutable global data
747                 //
748                 // `&T` where `T` contains no `UnsafeCell<U>` is immutable, and can be marked as
749                 // both `readonly` and `noalias`, as LLVM's definition of `noalias` is based solely
750                 // on memory dependencies rather than pointer equality
751                 let is_freeze = ccx.shared().type_is_freeze(mt.ty);
752
753                 if mt.mutbl != hir::MutMutable && is_freeze {
754                     arg.attrs.set(ArgAttribute::NoAlias);
755                 }
756
757                 if mt.mutbl == hir::MutImmutable && is_freeze {
758                     arg.attrs.set(ArgAttribute::ReadOnly);
759                 }
760
761                 // When a reference in an argument has no named lifetime, it's
762                 // impossible for that reference to escape this function
763                 // (returned or stored beyond the call by a closure).
764                 if let ReLateBound(_, BrAnon(_)) = *b {
765                     arg.attrs.set(ArgAttribute::NoCapture);
766                 }
767
768                 Some(mt.ty)
769             }
770             _ => None
771         };
772
773         for ty in inputs.iter().chain(extra_args.iter()) {
774             let mut arg = arg_of(ty, false);
775
776             if let ty::layout::FatPointer { .. } = *arg.layout {
777                 let mut data = ArgType::new(arg.layout.field(ccx, 0));
778                 let mut info = ArgType::new(arg.layout.field(ccx, 1));
779
780                 if let Some(inner) = rust_ptr_attrs(ty, &mut data) {
781                     data.attrs.set(ArgAttribute::NonNull);
782                     if ccx.tcx().struct_tail(inner).is_trait() {
783                         // vtables can be safely marked non-null, readonly
784                         // and noalias.
785                         info.attrs.set(ArgAttribute::NonNull);
786                         info.attrs.set(ArgAttribute::ReadOnly);
787                         info.attrs.set(ArgAttribute::NoAlias);
788                     }
789                 }
790                 args.push(data);
791                 args.push(info);
792             } else {
793                 if let Some(inner) = rust_ptr_attrs(ty, &mut arg) {
794                     arg.attrs.set_dereferenceable(ccx.size_of(inner));
795                 }
796                 args.push(arg);
797             }
798         }
799
800         FnType {
801             args: args,
802             ret: ret,
803             variadic: sig.variadic,
804             cconv: cconv
805         }
806     }
807
808     fn adjust_for_abi(&mut self,
809                       ccx: &CrateContext<'a, 'tcx>,
810                       sig: ty::FnSig<'tcx>) {
811         let abi = sig.abi;
812         if abi == Abi::Unadjusted { return }
813
814         if abi == Abi::Rust || abi == Abi::RustCall ||
815            abi == Abi::RustIntrinsic || abi == Abi::PlatformIntrinsic {
816             let fixup = |arg: &mut ArgType<'tcx>| {
817                 if !arg.layout.is_aggregate() {
818                     return;
819                 }
820
821                 let size = arg.layout.size(ccx);
822
823                 if let Some(unit) = arg.layout.homogenous_aggregate(ccx) {
824                     // Replace newtypes with their inner-most type.
825                     if unit.size == size {
826                         // Needs a cast as we've unpacked a newtype.
827                         arg.cast_to(ccx, unit);
828                         return;
829                     }
830
831                     // Pairs of floats.
832                     if unit.kind == RegKind::Float {
833                         if unit.size.checked_mul(2, ccx) == Some(size) {
834                             // FIXME(eddyb) This should be using Uniform instead of a pair,
835                             // but the resulting [2 x float/double] breaks emscripten.
836                             // See https://github.com/kripken/emscripten-fastcomp/issues/178.
837                             arg.cast_to(ccx, CastTarget::Pair(unit, unit));
838                             return;
839                         }
840                     }
841                 }
842
843                 if size > layout::Pointer.size(ccx) {
844                     arg.make_indirect(ccx);
845                 } else {
846                     // We want to pass small aggregates as immediates, but using
847                     // a LLVM aggregate type for this leads to bad optimizations,
848                     // so we pick an appropriately sized integer type instead.
849                     arg.cast_to(ccx, Reg {
850                         kind: RegKind::Integer,
851                         size
852                     });
853                 }
854             };
855             // Fat pointers are returned by-value.
856             if !self.ret.is_ignore() {
857                 if !type_is_fat_ptr(ccx, sig.output()) {
858                     fixup(&mut self.ret);
859                 }
860             }
861             for arg in &mut self.args {
862                 if arg.is_ignore() { continue; }
863                 fixup(arg);
864             }
865             if self.ret.is_indirect() {
866                 self.ret.attrs.set(ArgAttribute::StructRet);
867             }
868             return;
869         }
870
871         match &ccx.sess().target.target.arch[..] {
872             "x86" => {
873                 let flavor = if abi == Abi::Fastcall {
874                     cabi_x86::Flavor::Fastcall
875                 } else {
876                     cabi_x86::Flavor::General
877                 };
878                 cabi_x86::compute_abi_info(ccx, self, flavor);
879             },
880             "x86_64" => if abi == Abi::SysV64 {
881                 cabi_x86_64::compute_abi_info(ccx, self);
882             } else if abi == Abi::Win64 || ccx.sess().target.target.options.is_like_windows {
883                 cabi_x86_win64::compute_abi_info(ccx, self);
884             } else {
885                 cabi_x86_64::compute_abi_info(ccx, self);
886             },
887             "aarch64" => cabi_aarch64::compute_abi_info(ccx, self),
888             "arm" => cabi_arm::compute_abi_info(ccx, self),
889             "mips" => cabi_mips::compute_abi_info(ccx, self),
890             "mips64" => cabi_mips64::compute_abi_info(ccx, self),
891             "powerpc" => cabi_powerpc::compute_abi_info(ccx, self),
892             "powerpc64" => cabi_powerpc64::compute_abi_info(ccx, self),
893             "s390x" => cabi_s390x::compute_abi_info(ccx, self),
894             "asmjs" => cabi_asmjs::compute_abi_info(ccx, self),
895             "wasm32" => cabi_asmjs::compute_abi_info(ccx, self),
896             "msp430" => cabi_msp430::compute_abi_info(ccx, self),
897             "sparc" => cabi_sparc::compute_abi_info(ccx, self),
898             "sparc64" => cabi_sparc64::compute_abi_info(ccx, self),
899             "nvptx" => cabi_nvptx::compute_abi_info(ccx, self),
900             "nvptx64" => cabi_nvptx64::compute_abi_info(ccx, self),
901             "hexagon" => cabi_hexagon::compute_abi_info(ccx, self),
902             a => ccx.sess().fatal(&format!("unrecognized arch \"{}\" in target specification", a))
903         }
904
905         if self.ret.is_indirect() {
906             self.ret.attrs.set(ArgAttribute::StructRet);
907         }
908     }
909
910     pub fn llvm_type(&self, ccx: &CrateContext<'a, 'tcx>) -> Type {
911         let mut llargument_tys = Vec::new();
912
913         let llreturn_ty = if self.ret.is_ignore() {
914             Type::void(ccx)
915         } else if self.ret.is_indirect() {
916             llargument_tys.push(self.ret.memory_ty(ccx).ptr_to());
917             Type::void(ccx)
918         } else {
919             self.ret.cast.unwrap_or_else(|| {
920                 type_of::immediate_type_of(ccx, self.ret.layout.ty)
921             })
922         };
923
924         for arg in &self.args {
925             if arg.is_ignore() {
926                 continue;
927             }
928             // add padding
929             if let Some(ty) = arg.pad {
930                 llargument_tys.push(ty);
931             }
932
933             let llarg_ty = if arg.is_indirect() {
934                 arg.memory_ty(ccx).ptr_to()
935             } else {
936                 arg.cast.unwrap_or_else(|| {
937                     type_of::immediate_type_of(ccx, arg.layout.ty)
938                 })
939             };
940
941             llargument_tys.push(llarg_ty);
942         }
943
944         if self.variadic {
945             Type::variadic_func(&llargument_tys, &llreturn_ty)
946         } else {
947             Type::func(&llargument_tys, &llreturn_ty)
948         }
949     }
950
951     pub fn apply_attrs_llfn(&self, llfn: ValueRef) {
952         let mut i = if self.ret.is_indirect() { 1 } else { 0 };
953         if !self.ret.is_ignore() {
954             self.ret.attrs.apply_llfn(llvm::AttributePlace::Argument(i), llfn);
955         }
956         i += 1;
957         for arg in &self.args {
958             if !arg.is_ignore() {
959                 if arg.pad.is_some() { i += 1; }
960                 arg.attrs.apply_llfn(llvm::AttributePlace::Argument(i), llfn);
961                 i += 1;
962             }
963         }
964     }
965
966     pub fn apply_attrs_callsite(&self, callsite: ValueRef) {
967         let mut i = if self.ret.is_indirect() { 1 } else { 0 };
968         if !self.ret.is_ignore() {
969             self.ret.attrs.apply_callsite(llvm::AttributePlace::Argument(i), callsite);
970         }
971         i += 1;
972         for arg in &self.args {
973             if !arg.is_ignore() {
974                 if arg.pad.is_some() { i += 1; }
975                 arg.attrs.apply_callsite(llvm::AttributePlace::Argument(i), callsite);
976                 i += 1;
977             }
978         }
979
980         if self.cconv != llvm::CCallConv {
981             llvm::SetInstructionCallConv(callsite, self.cconv);
982         }
983     }
984 }
985
986 pub fn align_up_to(off: u64, a: u64) -> u64 {
987     (off + a - 1) / a * a
988 }