]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/abi.rs
Auto merge of #40996 - alexcrichton:update-cargo, r=alexcrichton
[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, Integer, Pointer, Float, Double, Struct, Array, Vector, 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 machine::{llalign_of_min, llsize_of, llsize_of_alloc};
33 use type_::Type;
34 use type_of;
35
36 use rustc::hir;
37 use rustc::ty::{self, Ty};
38
39 use libc::c_uint;
40 use std::cmp;
41
42 pub use syntax::abi::Abi;
43 pub use rustc::ty::layout::{FAT_PTR_ADDR, FAT_PTR_EXTRA};
44 use rustc::ty::layout::Layout;
45
46 #[derive(Clone, Copy, PartialEq, Debug)]
47 enum ArgKind {
48     /// Pass the argument directly using the normal converted
49     /// LLVM type or by coercing to another specified type
50     Direct,
51     /// Pass the argument indirectly via a hidden pointer
52     Indirect,
53     /// Ignore the argument (useful for empty struct)
54     Ignore,
55 }
56
57 // Hack to disable non_upper_case_globals only for the bitflags! and not for the rest
58 // of this module
59 pub use self::attr_impl::ArgAttribute;
60
61 #[allow(non_upper_case_globals)]
62 #[allow(unused)]
63 mod attr_impl {
64     // The subset of llvm::Attribute needed for arguments, packed into a bitfield.
65     bitflags! {
66         #[derive(Default, Debug)]
67         flags ArgAttribute : u16 {
68             const ByVal     = 1 << 0,
69             const NoAlias   = 1 << 1,
70             const NoCapture = 1 << 2,
71             const NonNull   = 1 << 3,
72             const ReadOnly  = 1 << 4,
73             const SExt      = 1 << 5,
74             const StructRet = 1 << 6,
75             const ZExt      = 1 << 7,
76             const InReg     = 1 << 8,
77         }
78     }
79 }
80
81 macro_rules! for_each_kind {
82     ($flags: ident, $f: ident, $($kind: ident),+) => ({
83         $(if $flags.contains(ArgAttribute::$kind) { $f(llvm::Attribute::$kind) })+
84     })
85 }
86
87 impl ArgAttribute {
88     fn for_each_kind<F>(&self, mut f: F) where F: FnMut(llvm::Attribute) {
89         for_each_kind!(self, f,
90                        ByVal, NoAlias, NoCapture, NonNull, ReadOnly, SExt, StructRet, ZExt, InReg)
91     }
92 }
93
94 /// A compact representation of LLVM attributes (at least those relevant for this module)
95 /// that can be manipulated without interacting with LLVM's Attribute machinery.
96 #[derive(Copy, Clone, Debug, Default)]
97 pub struct ArgAttributes {
98     regular: ArgAttribute,
99     dereferenceable_bytes: u64,
100 }
101
102 impl ArgAttributes {
103     pub fn set(&mut self, attr: ArgAttribute) -> &mut Self {
104         self.regular = self.regular | attr;
105         self
106     }
107
108     pub fn set_dereferenceable(&mut self, bytes: u64) -> &mut Self {
109         self.dereferenceable_bytes = bytes;
110         self
111     }
112
113     pub fn apply_llfn(&self, idx: AttributePlace, llfn: ValueRef) {
114         unsafe {
115             self.regular.for_each_kind(|attr| attr.apply_llfn(idx, llfn));
116             if self.dereferenceable_bytes != 0 {
117                 llvm::LLVMRustAddDereferenceableAttr(llfn,
118                                                      idx.as_uint(),
119                                                      self.dereferenceable_bytes);
120             }
121         }
122     }
123
124     pub fn apply_callsite(&self, idx: AttributePlace, callsite: ValueRef) {
125         unsafe {
126             self.regular.for_each_kind(|attr| attr.apply_callsite(idx, callsite));
127             if self.dereferenceable_bytes != 0 {
128                 llvm::LLVMRustAddDereferenceableCallSiteAttr(callsite,
129                                                              idx.as_uint(),
130                                                              self.dereferenceable_bytes);
131             }
132         }
133     }
134 }
135
136 /// Information about how a specific C type
137 /// should be passed to or returned from a function
138 ///
139 /// This is borrowed from clang's ABIInfo.h
140 #[derive(Clone, Copy, Debug)]
141 pub struct ArgType {
142     kind: ArgKind,
143     /// Original LLVM type
144     pub original_ty: Type,
145     /// Sizing LLVM type (pointers are opaque).
146     /// Unlike original_ty, this is guaranteed to be complete.
147     ///
148     /// For example, while we're computing the function pointer type in
149     /// `struct Foo(fn(Foo));`, `original_ty` is still LLVM's `%Foo = {}`.
150     /// The field type will likely end up being `void(%Foo)*`, but we cannot
151     /// use `%Foo` to compute properties (e.g. size and alignment) of `Foo`,
152     /// until `%Foo` is completed by having all of its field types inserted,
153     /// so `ty` holds the "sizing type" of `Foo`, which replaces all pointers
154     /// with opaque ones, resulting in `{i8*}` for `Foo`.
155     /// ABI-specific logic can then look at the size, alignment and fields of
156     /// `{i8*}` in order to determine how the argument will be passed.
157     /// Only later will `original_ty` aka `%Foo` be used in the LLVM function
158     /// pointer type, without ever having introspected it.
159     pub ty: Type,
160     /// Signedness for integer types, None for other types
161     pub signedness: Option<bool>,
162     /// Coerced LLVM Type
163     pub cast: Option<Type>,
164     /// Dummy argument, which is emitted before the real argument
165     pub pad: Option<Type>,
166     /// LLVM attributes of argument
167     pub attrs: ArgAttributes
168 }
169
170 impl ArgType {
171     fn new(original_ty: Type, ty: Type) -> ArgType {
172         ArgType {
173             kind: ArgKind::Direct,
174             original_ty: original_ty,
175             ty: ty,
176             signedness: None,
177             cast: None,
178             pad: None,
179             attrs: ArgAttributes::default()
180         }
181     }
182
183     pub fn make_indirect(&mut self, ccx: &CrateContext) {
184         assert_eq!(self.kind, ArgKind::Direct);
185
186         // Wipe old attributes, likely not valid through indirection.
187         self.attrs = ArgAttributes::default();
188
189         let llarg_sz = llsize_of_alloc(ccx, self.ty);
190
191         // For non-immediate arguments the callee gets its own copy of
192         // the value on the stack, so there are no aliases. It's also
193         // program-invisible so can't possibly capture
194         self.attrs.set(ArgAttribute::NoAlias)
195                   .set(ArgAttribute::NoCapture)
196                   .set_dereferenceable(llarg_sz);
197
198         self.kind = ArgKind::Indirect;
199     }
200
201     pub fn ignore(&mut self) {
202         assert_eq!(self.kind, ArgKind::Direct);
203         self.kind = ArgKind::Ignore;
204     }
205
206     pub fn extend_integer_width_to(&mut self, bits: u64) {
207         // Only integers have signedness
208         if let Some(signed) = self.signedness {
209             if self.ty.int_width() < bits {
210                 self.attrs.set(if signed {
211                     ArgAttribute::SExt
212                 } else {
213                     ArgAttribute::ZExt
214                 });
215             }
216         }
217     }
218
219     pub fn is_indirect(&self) -> bool {
220         self.kind == ArgKind::Indirect
221     }
222
223     pub fn is_ignore(&self) -> bool {
224         self.kind == ArgKind::Ignore
225     }
226
227     /// Store a direct/indirect value described by this ArgType into a
228     /// lvalue for the original Rust type of this argument/return.
229     /// Can be used for both storing formal arguments into Rust variables
230     /// or results of call/invoke instructions into their destinations.
231     pub fn store(&self, bcx: &Builder, mut val: ValueRef, dst: ValueRef) {
232         if self.is_ignore() {
233             return;
234         }
235         let ccx = bcx.ccx;
236         if self.is_indirect() {
237             let llsz = llsize_of(ccx, self.ty);
238             let llalign = llalign_of_min(ccx, self.ty);
239             base::call_memcpy(bcx, dst, val, llsz, llalign as u32);
240         } else if let Some(ty) = self.cast {
241             // FIXME(eddyb): Figure out when the simpler Store is safe, clang
242             // uses it for i16 -> {i8, i8}, but not for i24 -> {i8, i8, i8}.
243             let can_store_through_cast_ptr = false;
244             if can_store_through_cast_ptr {
245                 let cast_dst = bcx.pointercast(dst, ty.ptr_to());
246                 let llalign = llalign_of_min(ccx, self.ty);
247                 bcx.store(val, cast_dst, Some(llalign));
248             } else {
249                 // The actual return type is a struct, but the ABI
250                 // adaptation code has cast it into some scalar type.  The
251                 // code that follows is the only reliable way I have
252                 // found to do a transform like i64 -> {i32,i32}.
253                 // Basically we dump the data onto the stack then memcpy it.
254                 //
255                 // Other approaches I tried:
256                 // - Casting rust ret pointer to the foreign type and using Store
257                 //   is (a) unsafe if size of foreign type > size of rust type and
258                 //   (b) runs afoul of strict aliasing rules, yielding invalid
259                 //   assembly under -O (specifically, the store gets removed).
260                 // - Truncating foreign type to correct integral type and then
261                 //   bitcasting to the struct type yields invalid cast errors.
262
263                 // We instead thus allocate some scratch space...
264                 let llscratch = bcx.alloca(ty, "abi_cast");
265                 base::Lifetime::Start.call(bcx, llscratch);
266
267                 // ...where we first store the value...
268                 bcx.store(val, llscratch, None);
269
270                 // ...and then memcpy it to the intended destination.
271                 base::call_memcpy(bcx,
272                                   bcx.pointercast(dst, Type::i8p(ccx)),
273                                   bcx.pointercast(llscratch, Type::i8p(ccx)),
274                                   C_uint(ccx, llsize_of_alloc(ccx, self.ty)),
275                                   cmp::min(llalign_of_min(ccx, self.ty),
276                                            llalign_of_min(ccx, ty)) as u32);
277
278                 base::Lifetime::End.call(bcx, llscratch);
279             }
280         } else {
281             if self.original_ty == Type::i1(ccx) {
282                 val = bcx.zext(val, Type::i8(ccx));
283             }
284             bcx.store(val, dst, None);
285         }
286     }
287
288     pub fn store_fn_arg(&self, bcx: &Builder, idx: &mut usize, dst: ValueRef) {
289         if self.pad.is_some() {
290             *idx += 1;
291         }
292         if self.is_ignore() {
293             return;
294         }
295         let val = llvm::get_param(bcx.llfn(), *idx as c_uint);
296         *idx += 1;
297         self.store(bcx, val, dst);
298     }
299 }
300
301 /// Metadata describing how the arguments to a native function
302 /// should be passed in order to respect the native ABI.
303 ///
304 /// I will do my best to describe this structure, but these
305 /// comments are reverse-engineered and may be inaccurate. -NDM
306 #[derive(Clone, Debug)]
307 pub struct FnType {
308     /// The LLVM types of each argument.
309     pub args: Vec<ArgType>,
310
311     /// LLVM return type.
312     pub ret: ArgType,
313
314     pub variadic: bool,
315
316     pub cconv: llvm::CallConv
317 }
318
319 impl FnType {
320     pub fn new<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
321                          sig: ty::FnSig<'tcx>,
322                          extra_args: &[Ty<'tcx>]) -> FnType {
323         let mut fn_ty = FnType::unadjusted(ccx, sig, extra_args);
324         fn_ty.adjust_for_abi(ccx, sig);
325         fn_ty
326     }
327
328     pub fn new_vtable<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
329                                 sig: ty::FnSig<'tcx>,
330                                 extra_args: &[Ty<'tcx>]) -> FnType {
331         let mut fn_ty = FnType::unadjusted(ccx, sig, extra_args);
332         // Don't pass the vtable, it's not an argument of the virtual fn.
333         fn_ty.args[1].ignore();
334         fn_ty.adjust_for_abi(ccx, sig);
335         fn_ty
336     }
337
338     fn unadjusted<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
339                             sig: ty::FnSig<'tcx>,
340                             extra_args: &[Ty<'tcx>]) -> FnType {
341         use self::Abi::*;
342         let cconv = match ccx.sess().target.target.adjust_abi(sig.abi) {
343             RustIntrinsic | PlatformIntrinsic |
344             Rust | RustCall => llvm::CCallConv,
345
346             // It's the ABI's job to select this, not us.
347             System => bug!("system abi should be selected elsewhere"),
348
349             Stdcall => llvm::X86StdcallCallConv,
350             Fastcall => llvm::X86FastcallCallConv,
351             Vectorcall => llvm::X86_VectorCall,
352             C => llvm::CCallConv,
353             Unadjusted => llvm::CCallConv,
354             Win64 => llvm::X86_64_Win64,
355             SysV64 => llvm::X86_64_SysV,
356             Aapcs => llvm::ArmAapcsCallConv,
357             PtxKernel => llvm::PtxKernel,
358             Msp430Interrupt => llvm::Msp430Intr,
359             X86Interrupt => llvm::X86_Intr,
360
361             // These API constants ought to be more specific...
362             Cdecl => llvm::CCallConv,
363         };
364
365         let mut inputs = sig.inputs();
366         let extra_args = if sig.abi == RustCall {
367             assert!(!sig.variadic && extra_args.is_empty());
368
369             match sig.inputs().last().unwrap().sty {
370                 ty::TyTuple(ref tupled_arguments, _) => {
371                     inputs = &sig.inputs()[0..sig.inputs().len() - 1];
372                     tupled_arguments
373                 }
374                 _ => {
375                     bug!("argument to function with \"rust-call\" ABI \
376                           is not a tuple");
377                 }
378             }
379         } else {
380             assert!(sig.variadic || extra_args.is_empty());
381             extra_args
382         };
383
384         let target = &ccx.sess().target.target;
385         let win_x64_gnu = target.target_os == "windows"
386                        && target.arch == "x86_64"
387                        && target.target_env == "gnu";
388         let linux_s390x = target.target_os == "linux"
389                        && target.arch == "s390x"
390                        && target.target_env == "gnu";
391         let rust_abi = match sig.abi {
392             RustIntrinsic | PlatformIntrinsic | Rust | RustCall => true,
393             _ => false
394         };
395
396         let arg_of = |ty: Ty<'tcx>, is_return: bool| {
397             if ty.is_bool() {
398                 let llty = Type::i1(ccx);
399                 let mut arg = ArgType::new(llty, llty);
400                 arg.attrs.set(ArgAttribute::ZExt);
401                 arg
402             } else {
403                 let mut arg = ArgType::new(type_of::type_of(ccx, ty),
404                                            type_of::sizing_type_of(ccx, ty));
405                 if ty.is_integral() {
406                     arg.signedness = Some(ty.is_signed());
407                 }
408                 // Rust enum types that map onto C enums also need to follow
409                 // the target ABI zero-/sign-extension rules.
410                 if let Layout::CEnum { signed, .. } = *ccx.layout_of(ty) {
411                     arg.signedness = Some(signed);
412                 }
413                 if llsize_of_alloc(ccx, arg.ty) == 0 {
414                     // For some forsaken reason, x86_64-pc-windows-gnu
415                     // doesn't ignore zero-sized struct arguments.
416                     // The same is true for s390x-unknown-linux-gnu.
417                     if is_return || rust_abi ||
418                        (!win_x64_gnu && !linux_s390x) {
419                         arg.ignore();
420                     }
421                 }
422                 arg
423             }
424         };
425
426         let ret_ty = sig.output();
427         let mut ret = arg_of(ret_ty, true);
428
429         if !type_is_fat_ptr(ccx, ret_ty) {
430             // The `noalias` attribute on the return value is useful to a
431             // function ptr caller.
432             if ret_ty.is_box() {
433                 // `Box` pointer return values never alias because ownership
434                 // is transferred
435                 ret.attrs.set(ArgAttribute::NoAlias);
436             }
437
438             // We can also mark the return value as `dereferenceable` in certain cases
439             match ret_ty.sty {
440                 // These are not really pointers but pairs, (pointer, len)
441                 ty::TyRef(_, ty::TypeAndMut { ty, .. }) => {
442                     let llty = type_of::sizing_type_of(ccx, ty);
443                     let llsz = llsize_of_alloc(ccx, llty);
444                     ret.attrs.set_dereferenceable(llsz);
445                 }
446                 ty::TyAdt(def, _) if def.is_box() => {
447                     let llty = type_of::sizing_type_of(ccx, ret_ty.boxed_ty());
448                     let llsz = llsize_of_alloc(ccx, llty);
449                     ret.attrs.set_dereferenceable(llsz);
450                 }
451                 _ => {}
452             }
453         }
454
455         let mut args = Vec::with_capacity(inputs.len() + extra_args.len());
456
457         // Handle safe Rust thin and fat pointers.
458         let rust_ptr_attrs = |ty: Ty<'tcx>, arg: &mut ArgType| match ty.sty {
459             // `Box` pointer parameters never alias because ownership is transferred
460             ty::TyAdt(def, _) if def.is_box() => {
461                 arg.attrs.set(ArgAttribute::NoAlias);
462                 Some(ty.boxed_ty())
463             }
464
465             ty::TyRef(b, mt) => {
466                 use rustc::ty::{BrAnon, ReLateBound};
467
468                 // `&mut` pointer parameters never alias other parameters, or mutable global data
469                 //
470                 // `&T` where `T` contains no `UnsafeCell<U>` is immutable, and can be marked as
471                 // both `readonly` and `noalias`, as LLVM's definition of `noalias` is based solely
472                 // on memory dependencies rather than pointer equality
473                 let interior_unsafe = mt.ty.type_contents(ccx.tcx()).interior_unsafe();
474
475                 if mt.mutbl != hir::MutMutable && !interior_unsafe {
476                     arg.attrs.set(ArgAttribute::NoAlias);
477                 }
478
479                 if mt.mutbl == hir::MutImmutable && !interior_unsafe {
480                     arg.attrs.set(ArgAttribute::ReadOnly);
481                 }
482
483                 // When a reference in an argument has no named lifetime, it's
484                 // impossible for that reference to escape this function
485                 // (returned or stored beyond the call by a closure).
486                 if let ReLateBound(_, BrAnon(_)) = *b {
487                     arg.attrs.set(ArgAttribute::NoCapture);
488                 }
489
490                 Some(mt.ty)
491             }
492             _ => None
493         };
494
495         for ty in inputs.iter().chain(extra_args.iter()) {
496             let mut arg = arg_of(ty, false);
497
498             if type_is_fat_ptr(ccx, ty) {
499                 let original_tys = arg.original_ty.field_types();
500                 let sizing_tys = arg.ty.field_types();
501                 assert_eq!((original_tys.len(), sizing_tys.len()), (2, 2));
502
503                 let mut data = ArgType::new(original_tys[0], sizing_tys[0]);
504                 let mut info = ArgType::new(original_tys[1], sizing_tys[1]);
505
506                 if let Some(inner) = rust_ptr_attrs(ty, &mut data) {
507                     data.attrs.set(ArgAttribute::NonNull);
508                     if ccx.tcx().struct_tail(inner).is_trait() {
509                         // vtables can be safely marked non-null, readonly
510                         // and noalias.
511                         info.attrs.set(ArgAttribute::NonNull);
512                         info.attrs.set(ArgAttribute::ReadOnly);
513                         info.attrs.set(ArgAttribute::NoAlias);
514                     }
515                 }
516                 args.push(data);
517                 args.push(info);
518             } else {
519                 if let Some(inner) = rust_ptr_attrs(ty, &mut arg) {
520                     let llty = type_of::sizing_type_of(ccx, inner);
521                     let llsz = llsize_of_alloc(ccx, llty);
522                     arg.attrs.set_dereferenceable(llsz);
523                 }
524                 args.push(arg);
525             }
526         }
527
528         FnType {
529             args: args,
530             ret: ret,
531             variadic: sig.variadic,
532             cconv: cconv
533         }
534     }
535
536     fn adjust_for_abi<'a, 'tcx>(&mut self,
537                                 ccx: &CrateContext<'a, 'tcx>,
538                                 sig: ty::FnSig<'tcx>) {
539         let abi = sig.abi;
540         if abi == Abi::Unadjusted { return }
541
542         if abi == Abi::Rust || abi == Abi::RustCall ||
543            abi == Abi::RustIntrinsic || abi == Abi::PlatformIntrinsic {
544             let fixup = |arg: &mut ArgType| {
545                 let mut llty = arg.ty;
546
547                 // Replace newtypes with their inner-most type.
548                 while llty.kind() == llvm::TypeKind::Struct {
549                     let inner = llty.field_types();
550                     if inner.len() != 1 {
551                         break;
552                     }
553                     llty = inner[0];
554                 }
555
556                 if !llty.is_aggregate() {
557                     // Scalars and vectors, always immediate.
558                     if llty != arg.ty {
559                         // Needs a cast as we've unpacked a newtype.
560                         arg.cast = Some(llty);
561                     }
562                     return;
563                 }
564
565                 let size = llsize_of_alloc(ccx, llty);
566                 if size > llsize_of_alloc(ccx, ccx.int_type()) {
567                     arg.make_indirect(ccx);
568                 } else if size > 0 {
569                     // We want to pass small aggregates as immediates, but using
570                     // a LLVM aggregate type for this leads to bad optimizations,
571                     // so we pick an appropriately sized integer type instead.
572                     arg.cast = Some(Type::ix(ccx, size * 8));
573                 }
574             };
575             // Fat pointers are returned by-value.
576             if !self.ret.is_ignore() {
577                 if !type_is_fat_ptr(ccx, sig.output()) {
578                     fixup(&mut self.ret);
579                 }
580             }
581             for arg in &mut self.args {
582                 if arg.is_ignore() { continue; }
583                 fixup(arg);
584             }
585             if self.ret.is_indirect() {
586                 self.ret.attrs.set(ArgAttribute::StructRet);
587             }
588             return;
589         }
590
591         match &ccx.sess().target.target.arch[..] {
592             "x86" => {
593                 let flavor = if abi == Abi::Fastcall {
594                     cabi_x86::Flavor::Fastcall
595                 } else {
596                     cabi_x86::Flavor::General
597                 };
598                 cabi_x86::compute_abi_info(ccx, self, flavor);
599             },
600             "x86_64" => if abi == Abi::SysV64 {
601                 cabi_x86_64::compute_abi_info(ccx, self);
602             } else if abi == Abi::Win64 || ccx.sess().target.target.options.is_like_windows {
603                 cabi_x86_win64::compute_abi_info(ccx, self);
604             } else {
605                 cabi_x86_64::compute_abi_info(ccx, self);
606             },
607             "aarch64" => cabi_aarch64::compute_abi_info(ccx, self),
608             "arm" => {
609                 let flavor = if ccx.sess().target.target.target_os == "ios" {
610                     cabi_arm::Flavor::Ios
611                 } else {
612                     cabi_arm::Flavor::General
613                 };
614                 cabi_arm::compute_abi_info(ccx, self, flavor);
615             },
616             "mips" => cabi_mips::compute_abi_info(ccx, self),
617             "mips64" => cabi_mips64::compute_abi_info(ccx, self),
618             "powerpc" => cabi_powerpc::compute_abi_info(ccx, self),
619             "powerpc64" => cabi_powerpc64::compute_abi_info(ccx, self),
620             "s390x" => cabi_s390x::compute_abi_info(ccx, self),
621             "asmjs" => cabi_asmjs::compute_abi_info(ccx, self),
622             "wasm32" => cabi_asmjs::compute_abi_info(ccx, self),
623             "msp430" => cabi_msp430::compute_abi_info(ccx, self),
624             "sparc" => cabi_sparc::compute_abi_info(ccx, self),
625             "sparc64" => cabi_sparc64::compute_abi_info(ccx, self),
626             "nvptx" => cabi_nvptx::compute_abi_info(ccx, self),
627             "nvptx64" => cabi_nvptx64::compute_abi_info(ccx, self),
628             a => ccx.sess().fatal(&format!("unrecognized arch \"{}\" in target specification", a))
629         }
630
631         if self.ret.is_indirect() {
632             self.ret.attrs.set(ArgAttribute::StructRet);
633         }
634     }
635
636     pub fn llvm_type(&self, ccx: &CrateContext) -> Type {
637         let mut llargument_tys = Vec::new();
638
639         let llreturn_ty = if self.ret.is_ignore() {
640             Type::void(ccx)
641         } else if self.ret.is_indirect() {
642             llargument_tys.push(self.ret.original_ty.ptr_to());
643             Type::void(ccx)
644         } else {
645             self.ret.cast.unwrap_or(self.ret.original_ty)
646         };
647
648         for arg in &self.args {
649             if arg.is_ignore() {
650                 continue;
651             }
652             // add padding
653             if let Some(ty) = arg.pad {
654                 llargument_tys.push(ty);
655             }
656
657             let llarg_ty = if arg.is_indirect() {
658                 arg.original_ty.ptr_to()
659             } else {
660                 arg.cast.unwrap_or(arg.original_ty)
661             };
662
663             llargument_tys.push(llarg_ty);
664         }
665
666         if self.variadic {
667             Type::variadic_func(&llargument_tys, &llreturn_ty)
668         } else {
669             Type::func(&llargument_tys, &llreturn_ty)
670         }
671     }
672
673     pub fn apply_attrs_llfn(&self, llfn: ValueRef) {
674         let mut i = if self.ret.is_indirect() { 1 } else { 0 };
675         if !self.ret.is_ignore() {
676             self.ret.attrs.apply_llfn(llvm::AttributePlace::Argument(i), llfn);
677         }
678         i += 1;
679         for arg in &self.args {
680             if !arg.is_ignore() {
681                 if arg.pad.is_some() { i += 1; }
682                 arg.attrs.apply_llfn(llvm::AttributePlace::Argument(i), llfn);
683                 i += 1;
684             }
685         }
686     }
687
688     pub fn apply_attrs_callsite(&self, callsite: ValueRef) {
689         let mut i = if self.ret.is_indirect() { 1 } else { 0 };
690         if !self.ret.is_ignore() {
691             self.ret.attrs.apply_callsite(llvm::AttributePlace::Argument(i), callsite);
692         }
693         i += 1;
694         for arg in &self.args {
695             if !arg.is_ignore() {
696                 if arg.pad.is_some() { i += 1; }
697                 arg.attrs.apply_callsite(llvm::AttributePlace::Argument(i), callsite);
698                 i += 1;
699             }
700         }
701
702         if self.cconv != llvm::CCallConv {
703             llvm::SetInstructionCallConv(callsite, self.cconv);
704         }
705     }
706 }
707
708 pub fn align_up_to(off: usize, a: usize) -> usize {
709     return (off + a - 1) / a * a;
710 }
711
712 fn align(off: usize, ty: Type, pointer: usize) -> usize {
713     let a = ty_align(ty, pointer);
714     return align_up_to(off, a);
715 }
716
717 pub fn ty_align(ty: Type, pointer: usize) -> usize {
718     match ty.kind() {
719         Integer => ((ty.int_width() as usize) + 7) / 8,
720         Pointer => pointer,
721         Float => 4,
722         Double => 8,
723         Struct => {
724             if ty.is_packed() {
725                 1
726             } else {
727                 let str_tys = ty.field_types();
728                 str_tys.iter().fold(1, |a, t| cmp::max(a, ty_align(*t, pointer)))
729             }
730         }
731         Array => {
732             let elt = ty.element_type();
733             ty_align(elt, pointer)
734         }
735         Vector => {
736             let len = ty.vector_length();
737             let elt = ty.element_type();
738             ty_align(elt, pointer) * len
739         }
740         _ => bug!("ty_align: unhandled type")
741     }
742 }
743
744 pub fn ty_size(ty: Type, pointer: usize) -> usize {
745     match ty.kind() {
746         Integer => ((ty.int_width() as usize) + 7) / 8,
747         Pointer => pointer,
748         Float => 4,
749         Double => 8,
750         Struct => {
751             if ty.is_packed() {
752                 let str_tys = ty.field_types();
753                 str_tys.iter().fold(0, |s, t| s + ty_size(*t, pointer))
754             } else {
755                 let str_tys = ty.field_types();
756                 let size = str_tys.iter().fold(0, |s, t| {
757                     align(s, *t, pointer) + ty_size(*t, pointer)
758                 });
759                 align(size, ty, pointer)
760             }
761         }
762         Array => {
763             let len = ty.array_length();
764             let elt = ty.element_type();
765             let eltsz = ty_size(elt, pointer);
766             len * eltsz
767         }
768         Vector => {
769             let len = ty.vector_length();
770             let elt = ty.element_type();
771             let eltsz = ty_size(elt, pointer);
772             len * eltsz
773         },
774         _ => bug!("ty_size: unhandled type")
775     }
776 }