]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/abi.rs
rustc: add some abstractions to ty::layout for a more concise API.
[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 use rustc::ty::layout::{Layout, LayoutTyper};
39
40 use libc::c_uint;
41 use std::cmp;
42
43 pub use syntax::abi::Abi;
44 pub use rustc::ty::layout::{FAT_PTR_ADDR, FAT_PTR_EXTRA};
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                     ret.attrs.set_dereferenceable(ccx.size_of(ty));
443                 }
444                 ty::TyAdt(def, _) if def.is_box() => {
445                     ret.attrs.set_dereferenceable(ccx.size_of(ret_ty.boxed_ty()));
446                 }
447                 _ => {}
448             }
449         }
450
451         let mut args = Vec::with_capacity(inputs.len() + extra_args.len());
452
453         // Handle safe Rust thin and fat pointers.
454         let rust_ptr_attrs = |ty: Ty<'tcx>, arg: &mut ArgType| match ty.sty {
455             // `Box` pointer parameters never alias because ownership is transferred
456             ty::TyAdt(def, _) if def.is_box() => {
457                 arg.attrs.set(ArgAttribute::NoAlias);
458                 Some(ty.boxed_ty())
459             }
460
461             ty::TyRef(b, mt) => {
462                 use rustc::ty::{BrAnon, ReLateBound};
463
464                 // `&mut` pointer parameters never alias other parameters, or mutable global data
465                 //
466                 // `&T` where `T` contains no `UnsafeCell<U>` is immutable, and can be marked as
467                 // both `readonly` and `noalias`, as LLVM's definition of `noalias` is based solely
468                 // on memory dependencies rather than pointer equality
469                 let interior_unsafe = mt.ty.type_contents(ccx.tcx()).interior_unsafe();
470
471                 if mt.mutbl != hir::MutMutable && !interior_unsafe {
472                     arg.attrs.set(ArgAttribute::NoAlias);
473                 }
474
475                 if mt.mutbl == hir::MutImmutable && !interior_unsafe {
476                     arg.attrs.set(ArgAttribute::ReadOnly);
477                 }
478
479                 // When a reference in an argument has no named lifetime, it's
480                 // impossible for that reference to escape this function
481                 // (returned or stored beyond the call by a closure).
482                 if let ReLateBound(_, BrAnon(_)) = *b {
483                     arg.attrs.set(ArgAttribute::NoCapture);
484                 }
485
486                 Some(mt.ty)
487             }
488             _ => None
489         };
490
491         for ty in inputs.iter().chain(extra_args.iter()) {
492             let mut arg = arg_of(ty, false);
493
494             if type_is_fat_ptr(ccx, ty) {
495                 let original_tys = arg.original_ty.field_types();
496                 let sizing_tys = arg.ty.field_types();
497                 assert_eq!((original_tys.len(), sizing_tys.len()), (2, 2));
498
499                 let mut data = ArgType::new(original_tys[0], sizing_tys[0]);
500                 let mut info = ArgType::new(original_tys[1], sizing_tys[1]);
501
502                 if let Some(inner) = rust_ptr_attrs(ty, &mut data) {
503                     data.attrs.set(ArgAttribute::NonNull);
504                     if ccx.tcx().struct_tail(inner).is_trait() {
505                         // vtables can be safely marked non-null, readonly
506                         // and noalias.
507                         info.attrs.set(ArgAttribute::NonNull);
508                         info.attrs.set(ArgAttribute::ReadOnly);
509                         info.attrs.set(ArgAttribute::NoAlias);
510                     }
511                 }
512                 args.push(data);
513                 args.push(info);
514             } else {
515                 if let Some(inner) = rust_ptr_attrs(ty, &mut arg) {
516                     arg.attrs.set_dereferenceable(ccx.size_of(inner));
517                 }
518                 args.push(arg);
519             }
520         }
521
522         FnType {
523             args: args,
524             ret: ret,
525             variadic: sig.variadic,
526             cconv: cconv
527         }
528     }
529
530     fn adjust_for_abi<'a, 'tcx>(&mut self,
531                                 ccx: &CrateContext<'a, 'tcx>,
532                                 sig: ty::FnSig<'tcx>) {
533         let abi = sig.abi;
534         if abi == Abi::Unadjusted { return }
535
536         if abi == Abi::Rust || abi == Abi::RustCall ||
537            abi == Abi::RustIntrinsic || abi == Abi::PlatformIntrinsic {
538             let fixup = |arg: &mut ArgType| {
539                 let mut llty = arg.ty;
540
541                 // Replace newtypes with their inner-most type.
542                 while llty.kind() == llvm::TypeKind::Struct {
543                     let inner = llty.field_types();
544                     if inner.len() != 1 {
545                         break;
546                     }
547                     llty = inner[0];
548                 }
549
550                 if !llty.is_aggregate() {
551                     // Scalars and vectors, always immediate.
552                     if llty != arg.ty {
553                         // Needs a cast as we've unpacked a newtype.
554                         arg.cast = Some(llty);
555                     }
556                     return;
557                 }
558
559                 let size = llsize_of_alloc(ccx, llty);
560                 if size > llsize_of_alloc(ccx, ccx.int_type()) {
561                     arg.make_indirect(ccx);
562                 } else if size > 0 {
563                     // We want to pass small aggregates as immediates, but using
564                     // a LLVM aggregate type for this leads to bad optimizations,
565                     // so we pick an appropriately sized integer type instead.
566                     arg.cast = Some(Type::ix(ccx, size * 8));
567                 }
568             };
569             // Fat pointers are returned by-value.
570             if !self.ret.is_ignore() {
571                 if !type_is_fat_ptr(ccx, sig.output()) {
572                     fixup(&mut self.ret);
573                 }
574             }
575             for arg in &mut self.args {
576                 if arg.is_ignore() { continue; }
577                 fixup(arg);
578             }
579             if self.ret.is_indirect() {
580                 self.ret.attrs.set(ArgAttribute::StructRet);
581             }
582             return;
583         }
584
585         match &ccx.sess().target.target.arch[..] {
586             "x86" => {
587                 let flavor = if abi == Abi::Fastcall {
588                     cabi_x86::Flavor::Fastcall
589                 } else {
590                     cabi_x86::Flavor::General
591                 };
592                 cabi_x86::compute_abi_info(ccx, self, flavor);
593             },
594             "x86_64" => if abi == Abi::SysV64 {
595                 cabi_x86_64::compute_abi_info(ccx, self);
596             } else if abi == Abi::Win64 || ccx.sess().target.target.options.is_like_windows {
597                 cabi_x86_win64::compute_abi_info(ccx, self);
598             } else {
599                 cabi_x86_64::compute_abi_info(ccx, self);
600             },
601             "aarch64" => cabi_aarch64::compute_abi_info(ccx, self),
602             "arm" => {
603                 let flavor = if ccx.sess().target.target.target_os == "ios" {
604                     cabi_arm::Flavor::Ios
605                 } else {
606                     cabi_arm::Flavor::General
607                 };
608                 cabi_arm::compute_abi_info(ccx, self, flavor);
609             },
610             "mips" => cabi_mips::compute_abi_info(ccx, self),
611             "mips64" => cabi_mips64::compute_abi_info(ccx, self),
612             "powerpc" => cabi_powerpc::compute_abi_info(ccx, self),
613             "powerpc64" => cabi_powerpc64::compute_abi_info(ccx, self),
614             "s390x" => cabi_s390x::compute_abi_info(ccx, self),
615             "asmjs" => cabi_asmjs::compute_abi_info(ccx, self),
616             "wasm32" => cabi_asmjs::compute_abi_info(ccx, self),
617             "msp430" => cabi_msp430::compute_abi_info(ccx, self),
618             "sparc" => cabi_sparc::compute_abi_info(ccx, self),
619             "sparc64" => cabi_sparc64::compute_abi_info(ccx, self),
620             "nvptx" => cabi_nvptx::compute_abi_info(ccx, self),
621             "nvptx64" => cabi_nvptx64::compute_abi_info(ccx, self),
622             a => ccx.sess().fatal(&format!("unrecognized arch \"{}\" in target specification", a))
623         }
624
625         if self.ret.is_indirect() {
626             self.ret.attrs.set(ArgAttribute::StructRet);
627         }
628     }
629
630     pub fn llvm_type(&self, ccx: &CrateContext) -> Type {
631         let mut llargument_tys = Vec::new();
632
633         let llreturn_ty = if self.ret.is_ignore() {
634             Type::void(ccx)
635         } else if self.ret.is_indirect() {
636             llargument_tys.push(self.ret.original_ty.ptr_to());
637             Type::void(ccx)
638         } else {
639             self.ret.cast.unwrap_or(self.ret.original_ty)
640         };
641
642         for arg in &self.args {
643             if arg.is_ignore() {
644                 continue;
645             }
646             // add padding
647             if let Some(ty) = arg.pad {
648                 llargument_tys.push(ty);
649             }
650
651             let llarg_ty = if arg.is_indirect() {
652                 arg.original_ty.ptr_to()
653             } else {
654                 arg.cast.unwrap_or(arg.original_ty)
655             };
656
657             llargument_tys.push(llarg_ty);
658         }
659
660         if self.variadic {
661             Type::variadic_func(&llargument_tys, &llreturn_ty)
662         } else {
663             Type::func(&llargument_tys, &llreturn_ty)
664         }
665     }
666
667     pub fn apply_attrs_llfn(&self, llfn: ValueRef) {
668         let mut i = if self.ret.is_indirect() { 1 } else { 0 };
669         if !self.ret.is_ignore() {
670             self.ret.attrs.apply_llfn(llvm::AttributePlace::Argument(i), llfn);
671         }
672         i += 1;
673         for arg in &self.args {
674             if !arg.is_ignore() {
675                 if arg.pad.is_some() { i += 1; }
676                 arg.attrs.apply_llfn(llvm::AttributePlace::Argument(i), llfn);
677                 i += 1;
678             }
679         }
680     }
681
682     pub fn apply_attrs_callsite(&self, callsite: ValueRef) {
683         let mut i = if self.ret.is_indirect() { 1 } else { 0 };
684         if !self.ret.is_ignore() {
685             self.ret.attrs.apply_callsite(llvm::AttributePlace::Argument(i), callsite);
686         }
687         i += 1;
688         for arg in &self.args {
689             if !arg.is_ignore() {
690                 if arg.pad.is_some() { i += 1; }
691                 arg.attrs.apply_callsite(llvm::AttributePlace::Argument(i), callsite);
692                 i += 1;
693             }
694         }
695
696         if self.cconv != llvm::CCallConv {
697             llvm::SetInstructionCallConv(callsite, self.cconv);
698         }
699     }
700 }
701
702 pub fn align_up_to(off: usize, a: usize) -> usize {
703     return (off + a - 1) / a * a;
704 }
705
706 fn align(off: usize, ty: Type, pointer: usize) -> usize {
707     let a = ty_align(ty, pointer);
708     return align_up_to(off, a);
709 }
710
711 pub fn ty_align(ty: Type, pointer: usize) -> usize {
712     match ty.kind() {
713         Integer => ((ty.int_width() as usize) + 7) / 8,
714         Pointer => pointer,
715         Float => 4,
716         Double => 8,
717         Struct => {
718             if ty.is_packed() {
719                 1
720             } else {
721                 let str_tys = ty.field_types();
722                 str_tys.iter().fold(1, |a, t| cmp::max(a, ty_align(*t, pointer)))
723             }
724         }
725         Array => {
726             let elt = ty.element_type();
727             ty_align(elt, pointer)
728         }
729         Vector => {
730             let len = ty.vector_length();
731             let elt = ty.element_type();
732             ty_align(elt, pointer) * len
733         }
734         _ => bug!("ty_align: unhandled type")
735     }
736 }
737
738 pub fn ty_size(ty: Type, pointer: usize) -> usize {
739     match ty.kind() {
740         Integer => ((ty.int_width() as usize) + 7) / 8,
741         Pointer => pointer,
742         Float => 4,
743         Double => 8,
744         Struct => {
745             if ty.is_packed() {
746                 let str_tys = ty.field_types();
747                 str_tys.iter().fold(0, |s, t| s + ty_size(*t, pointer))
748             } else {
749                 let str_tys = ty.field_types();
750                 let size = str_tys.iter().fold(0, |s, t| {
751                     align(s, *t, pointer) + ty_size(*t, pointer)
752                 });
753                 align(size, ty, pointer)
754             }
755         }
756         Array => {
757             let len = ty.array_length();
758             let elt = ty.element_type();
759             let eltsz = ty_size(elt, pointer);
760             len * eltsz
761         }
762         Vector => {
763             let len = ty.vector_length();
764             let elt = ty.element_type();
765             let eltsz = ty_size(elt, pointer);
766             len * eltsz
767         },
768         _ => bug!("ty_size: unhandled type")
769     }
770 }