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