]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/intrinsic.rs
Fix invalid associated type rendering in rustdoc
[rust.git] / src / librustc_trans / intrinsic.rs
1 // Copyright 2012-2014 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 #![allow(non_upper_case_globals)]
12
13 use intrinsics::{self, Intrinsic};
14 use libc;
15 use llvm;
16 use llvm::{ValueRef};
17 use abi::{Abi, FnType};
18 use adt;
19 use mir::lvalue::LvalueRef;
20 use base::*;
21 use common::*;
22 use declare;
23 use glue;
24 use type_of;
25 use machine;
26 use type_::Type;
27 use rustc::ty::{self, Ty};
28 use rustc::hir;
29 use syntax::ast;
30 use syntax::symbol::Symbol;
31 use builder::Builder;
32
33 use rustc::session::Session;
34 use syntax_pos::Span;
35
36 use std::cmp::Ordering;
37 use std::iter;
38
39 use mir::lvalue::Alignment;
40
41 fn get_simple_intrinsic(ccx: &CrateContext, name: &str) -> Option<ValueRef> {
42     let llvm_name = match name {
43         "sqrtf32" => "llvm.sqrt.f32",
44         "sqrtf64" => "llvm.sqrt.f64",
45         "powif32" => "llvm.powi.f32",
46         "powif64" => "llvm.powi.f64",
47         "sinf32" => "llvm.sin.f32",
48         "sinf64" => "llvm.sin.f64",
49         "cosf32" => "llvm.cos.f32",
50         "cosf64" => "llvm.cos.f64",
51         "powf32" => "llvm.pow.f32",
52         "powf64" => "llvm.pow.f64",
53         "expf32" => "llvm.exp.f32",
54         "expf64" => "llvm.exp.f64",
55         "exp2f32" => "llvm.exp2.f32",
56         "exp2f64" => "llvm.exp2.f64",
57         "logf32" => "llvm.log.f32",
58         "logf64" => "llvm.log.f64",
59         "log10f32" => "llvm.log10.f32",
60         "log10f64" => "llvm.log10.f64",
61         "log2f32" => "llvm.log2.f32",
62         "log2f64" => "llvm.log2.f64",
63         "fmaf32" => "llvm.fma.f32",
64         "fmaf64" => "llvm.fma.f64",
65         "fabsf32" => "llvm.fabs.f32",
66         "fabsf64" => "llvm.fabs.f64",
67         "copysignf32" => "llvm.copysign.f32",
68         "copysignf64" => "llvm.copysign.f64",
69         "floorf32" => "llvm.floor.f32",
70         "floorf64" => "llvm.floor.f64",
71         "ceilf32" => "llvm.ceil.f32",
72         "ceilf64" => "llvm.ceil.f64",
73         "truncf32" => "llvm.trunc.f32",
74         "truncf64" => "llvm.trunc.f64",
75         "rintf32" => "llvm.rint.f32",
76         "rintf64" => "llvm.rint.f64",
77         "nearbyintf32" => "llvm.nearbyint.f32",
78         "nearbyintf64" => "llvm.nearbyint.f64",
79         "roundf32" => "llvm.round.f32",
80         "roundf64" => "llvm.round.f64",
81         "assume" => "llvm.assume",
82         "abort" => "llvm.trap",
83         _ => return None
84     };
85     Some(ccx.get_intrinsic(&llvm_name))
86 }
87
88 /// Remember to add all intrinsics here, in librustc_typeck/check/mod.rs,
89 /// and in libcore/intrinsics.rs; if you need access to any llvm intrinsics,
90 /// add them to librustc_trans/trans/context.rs
91 pub fn trans_intrinsic_call<'a, 'tcx>(bcx: &Builder<'a, 'tcx>,
92                                       callee_ty: Ty<'tcx>,
93                                       fn_ty: &FnType,
94                                       llargs: &[ValueRef],
95                                       llresult: ValueRef,
96                                       span: Span) {
97     let ccx = bcx.ccx;
98     let tcx = ccx.tcx();
99
100     let (def_id, substs, sig) = match callee_ty.sty {
101         ty::TyFnDef(def_id, substs, sig) => (def_id, substs, sig),
102         _ => bug!("expected fn item type, found {}", callee_ty)
103     };
104
105     let sig = tcx.erase_late_bound_regions_and_normalize(&sig);
106     let arg_tys = sig.inputs();
107     let ret_ty = sig.output();
108     let name = &*tcx.item_name(def_id).as_str();
109
110     let llret_ty = type_of::type_of(ccx, ret_ty);
111
112     let simple = get_simple_intrinsic(ccx, name);
113     let llval = match name {
114         _ if simple.is_some() => {
115             bcx.call(simple.unwrap(), &llargs, None)
116         }
117         "unreachable" => {
118             return;
119         },
120         "likely" => {
121             let expect = ccx.get_intrinsic(&("llvm.expect.i1"));
122             bcx.call(expect, &[llargs[0], C_bool(ccx, true)], None)
123         }
124         "unlikely" => {
125             let expect = ccx.get_intrinsic(&("llvm.expect.i1"));
126             bcx.call(expect, &[llargs[0], C_bool(ccx, false)], None)
127         }
128         "try" => {
129             try_intrinsic(bcx, ccx, llargs[0], llargs[1], llargs[2], llresult);
130             C_nil(ccx)
131         }
132         "breakpoint" => {
133             let llfn = ccx.get_intrinsic(&("llvm.debugtrap"));
134             bcx.call(llfn, &[], None)
135         }
136         "size_of" => {
137             let tp_ty = substs.type_at(0);
138             let lltp_ty = type_of::type_of(ccx, tp_ty);
139             C_uint(ccx, machine::llsize_of_alloc(ccx, lltp_ty))
140         }
141         "size_of_val" => {
142             let tp_ty = substs.type_at(0);
143             if !bcx.ccx.shared().type_is_sized(tp_ty) {
144                 let (llsize, _) =
145                     glue::size_and_align_of_dst(bcx, tp_ty, llargs[1]);
146                 llsize
147             } else {
148                 let lltp_ty = type_of::type_of(ccx, tp_ty);
149                 C_uint(ccx, machine::llsize_of_alloc(ccx, lltp_ty))
150             }
151         }
152         "min_align_of" => {
153             let tp_ty = substs.type_at(0);
154             C_uint(ccx, ccx.align_of(tp_ty))
155         }
156         "min_align_of_val" => {
157             let tp_ty = substs.type_at(0);
158             if !bcx.ccx.shared().type_is_sized(tp_ty) {
159                 let (_, llalign) =
160                     glue::size_and_align_of_dst(bcx, tp_ty, llargs[1]);
161                 llalign
162             } else {
163                 C_uint(ccx, ccx.align_of(tp_ty))
164             }
165         }
166         "pref_align_of" => {
167             let tp_ty = substs.type_at(0);
168             let lltp_ty = type_of::type_of(ccx, tp_ty);
169             C_uint(ccx, machine::llalign_of_pref(ccx, lltp_ty))
170         }
171         "type_name" => {
172             let tp_ty = substs.type_at(0);
173             let ty_name = Symbol::intern(&tp_ty.to_string()).as_str();
174             C_str_slice(ccx, ty_name)
175         }
176         "type_id" => {
177             C_u64(ccx, ccx.tcx().type_id_hash(substs.type_at(0)))
178         }
179         "init" => {
180             let ty = substs.type_at(0);
181             if !type_is_zero_size(ccx, ty) {
182                 // Just zero out the stack slot.
183                 // If we store a zero constant, LLVM will drown in vreg allocation for large data
184                 // structures, and the generated code will be awful. (A telltale sign of this is
185                 // large quantities of `mov [byte ptr foo],0` in the generated code.)
186                 memset_intrinsic(bcx, false, ty, llresult, C_u8(ccx, 0), C_uint(ccx, 1usize));
187             }
188             C_nil(ccx)
189         }
190         // Effectively no-ops
191         "uninit" | "forget" => {
192             C_nil(ccx)
193         }
194         "needs_drop" => {
195             let tp_ty = substs.type_at(0);
196
197             C_bool(ccx, bcx.ccx.shared().type_needs_drop(tp_ty))
198         }
199         "offset" => {
200             let ptr = llargs[0];
201             let offset = llargs[1];
202             bcx.inbounds_gep(ptr, &[offset])
203         }
204         "arith_offset" => {
205             let ptr = llargs[0];
206             let offset = llargs[1];
207             bcx.gep(ptr, &[offset])
208         }
209
210         "copy_nonoverlapping" => {
211             copy_intrinsic(bcx, false, false, substs.type_at(0), llargs[1], llargs[0], llargs[2])
212         }
213         "copy" => {
214             copy_intrinsic(bcx, true, false, substs.type_at(0), llargs[1], llargs[0], llargs[2])
215         }
216         "write_bytes" => {
217             memset_intrinsic(bcx, false, substs.type_at(0), llargs[0], llargs[1], llargs[2])
218         }
219
220         "volatile_copy_nonoverlapping_memory" => {
221             copy_intrinsic(bcx, false, true, substs.type_at(0), llargs[0], llargs[1], llargs[2])
222         }
223         "volatile_copy_memory" => {
224             copy_intrinsic(bcx, true, true, substs.type_at(0), llargs[0], llargs[1], llargs[2])
225         }
226         "volatile_set_memory" => {
227             memset_intrinsic(bcx, true, substs.type_at(0), llargs[0], llargs[1], llargs[2])
228         }
229         "volatile_load" => {
230             let tp_ty = substs.type_at(0);
231             let mut ptr = llargs[0];
232             if let Some(ty) = fn_ty.ret.cast {
233                 ptr = bcx.pointercast(ptr, ty.ptr_to());
234             }
235             let load = bcx.volatile_load(ptr);
236             unsafe {
237                 llvm::LLVMSetAlignment(load, ccx.align_of(tp_ty));
238             }
239             to_immediate(bcx, load, tp_ty)
240         },
241         "volatile_store" => {
242             let tp_ty = substs.type_at(0);
243             if type_is_fat_ptr(bcx.ccx, tp_ty) {
244                 bcx.volatile_store(llargs[1], get_dataptr(bcx, llargs[0]));
245                 bcx.volatile_store(llargs[2], get_meta(bcx, llargs[0]));
246             } else {
247                 let val = if fn_ty.args[1].is_indirect() {
248                     bcx.load(llargs[1], None)
249                 } else {
250                     from_immediate(bcx, llargs[1])
251                 };
252                 let ptr = bcx.pointercast(llargs[0], val_ty(val).ptr_to());
253                 let store = bcx.volatile_store(val, ptr);
254                 unsafe {
255                     llvm::LLVMSetAlignment(store, ccx.align_of(tp_ty));
256                 }
257             }
258             C_nil(ccx)
259         },
260
261         "ctlz" | "cttz" | "ctpop" | "bswap" |
262         "add_with_overflow" | "sub_with_overflow" | "mul_with_overflow" |
263         "overflowing_add" | "overflowing_sub" | "overflowing_mul" |
264         "unchecked_div" | "unchecked_rem" | "unchecked_shl" | "unchecked_shr" => {
265             let sty = &arg_tys[0].sty;
266             match int_type_width_signed(sty, ccx) {
267                 Some((width, signed)) =>
268                     match name {
269                         "ctlz" | "cttz" => {
270                             let y = C_bool(bcx.ccx, false);
271                             let llfn = ccx.get_intrinsic(&format!("llvm.{}.i{}", name, width));
272                             bcx.call(llfn, &[llargs[0], y], None)
273                         }
274                         "ctpop" => bcx.call(ccx.get_intrinsic(&format!("llvm.ctpop.i{}", width)),
275                                         &llargs, None),
276                         "bswap" => {
277                             if width == 8 {
278                                 llargs[0] // byte swap a u8/i8 is just a no-op
279                             } else {
280                                 bcx.call(ccx.get_intrinsic(&format!("llvm.bswap.i{}", width)),
281                                         &llargs, None)
282                             }
283                         }
284                         "add_with_overflow" | "sub_with_overflow" | "mul_with_overflow" => {
285                             let intrinsic = format!("llvm.{}{}.with.overflow.i{}",
286                                                     if signed { 's' } else { 'u' },
287                                                     &name[..3], width);
288                             let llfn = bcx.ccx.get_intrinsic(&intrinsic);
289
290                             // Convert `i1` to a `bool`, and write it to the out parameter
291                             let val = bcx.call(llfn, &[llargs[0], llargs[1]], None);
292                             let result = bcx.extract_value(val, 0);
293                             let overflow = bcx.zext(bcx.extract_value(val, 1), Type::bool(ccx));
294                             bcx.store(result, bcx.struct_gep(llresult, 0), None);
295                             bcx.store(overflow, bcx.struct_gep(llresult, 1), None);
296
297                             C_nil(bcx.ccx)
298                         },
299                         "overflowing_add" => bcx.add(llargs[0], llargs[1]),
300                         "overflowing_sub" => bcx.sub(llargs[0], llargs[1]),
301                         "overflowing_mul" => bcx.mul(llargs[0], llargs[1]),
302                         "unchecked_div" =>
303                             if signed {
304                                 bcx.sdiv(llargs[0], llargs[1])
305                             } else {
306                                 bcx.udiv(llargs[0], llargs[1])
307                             },
308                         "unchecked_rem" =>
309                             if signed {
310                                 bcx.srem(llargs[0], llargs[1])
311                             } else {
312                                 bcx.urem(llargs[0], llargs[1])
313                             },
314                         "unchecked_shl" => bcx.shl(llargs[0], llargs[1]),
315                         "unchecked_shr" =>
316                             if signed {
317                                 bcx.ashr(llargs[0], llargs[1])
318                             } else {
319                                 bcx.lshr(llargs[0], llargs[1])
320                             },
321                         _ => bug!(),
322                     },
323                 None => {
324                     span_invalid_monomorphization_error(
325                         tcx.sess, span,
326                         &format!("invalid monomorphization of `{}` intrinsic: \
327                                   expected basic integer type, found `{}`", name, sty));
328                         C_nil(ccx)
329                 }
330             }
331
332         },
333         "fadd_fast" | "fsub_fast" | "fmul_fast" | "fdiv_fast" | "frem_fast" => {
334             let sty = &arg_tys[0].sty;
335             match float_type_width(sty) {
336                 Some(_width) =>
337                     match name {
338                         "fadd_fast" => bcx.fadd_fast(llargs[0], llargs[1]),
339                         "fsub_fast" => bcx.fsub_fast(llargs[0], llargs[1]),
340                         "fmul_fast" => bcx.fmul_fast(llargs[0], llargs[1]),
341                         "fdiv_fast" => bcx.fdiv_fast(llargs[0], llargs[1]),
342                         "frem_fast" => bcx.frem_fast(llargs[0], llargs[1]),
343                         _ => bug!(),
344                     },
345                 None => {
346                     span_invalid_monomorphization_error(
347                         tcx.sess, span,
348                         &format!("invalid monomorphization of `{}` intrinsic: \
349                                   expected basic float type, found `{}`", name, sty));
350                         C_nil(ccx)
351                 }
352             }
353
354         },
355
356         "discriminant_value" => {
357             let val_ty = substs.type_at(0);
358             match val_ty.sty {
359                 ty::TyAdt(adt, ..) if adt.is_enum() => {
360                     adt::trans_get_discr(bcx, val_ty, llargs[0], Alignment::AbiAligned,
361                                          Some(llret_ty), true)
362                 }
363                 _ => C_null(llret_ty)
364             }
365         }
366         name if name.starts_with("simd_") => {
367             generic_simd_intrinsic(bcx, name,
368                                    callee_ty,
369                                    &llargs,
370                                    ret_ty, llret_ty,
371                                    span)
372         }
373         // This requires that atomic intrinsics follow a specific naming pattern:
374         // "atomic_<operation>[_<ordering>]", and no ordering means SeqCst
375         name if name.starts_with("atomic_") => {
376             use llvm::AtomicOrdering::*;
377
378             let split: Vec<&str> = name.split('_').collect();
379
380             let is_cxchg = split[1] == "cxchg" || split[1] == "cxchgweak";
381             let (order, failorder) = match split.len() {
382                 2 => (SequentiallyConsistent, SequentiallyConsistent),
383                 3 => match split[2] {
384                     "unordered" => (Unordered, Unordered),
385                     "relaxed" => (Monotonic, Monotonic),
386                     "acq"     => (Acquire, Acquire),
387                     "rel"     => (Release, Monotonic),
388                     "acqrel"  => (AcquireRelease, Acquire),
389                     "failrelaxed" if is_cxchg =>
390                         (SequentiallyConsistent, Monotonic),
391                     "failacq" if is_cxchg =>
392                         (SequentiallyConsistent, Acquire),
393                     _ => ccx.sess().fatal("unknown ordering in atomic intrinsic")
394                 },
395                 4 => match (split[2], split[3]) {
396                     ("acq", "failrelaxed") if is_cxchg =>
397                         (Acquire, Monotonic),
398                     ("acqrel", "failrelaxed") if is_cxchg =>
399                         (AcquireRelease, Monotonic),
400                     _ => ccx.sess().fatal("unknown ordering in atomic intrinsic")
401                 },
402                 _ => ccx.sess().fatal("Atomic intrinsic not in correct format"),
403             };
404
405             let invalid_monomorphization = |sty| {
406                 span_invalid_monomorphization_error(tcx.sess, span,
407                     &format!("invalid monomorphization of `{}` intrinsic: \
408                               expected basic integer type, found `{}`", name, sty));
409             };
410
411             match split[1] {
412                 "cxchg" | "cxchgweak" => {
413                     let sty = &substs.type_at(0).sty;
414                     if int_type_width_signed(sty, ccx).is_some() {
415                         let weak = if split[1] == "cxchgweak" { llvm::True } else { llvm::False };
416                         let val = bcx.atomic_cmpxchg(llargs[0], llargs[1], llargs[2], order,
417                             failorder, weak);
418                         let result = bcx.extract_value(val, 0);
419                         let success = bcx.zext(bcx.extract_value(val, 1), Type::bool(bcx.ccx));
420                         bcx.store(result, bcx.struct_gep(llresult, 0), None);
421                         bcx.store(success, bcx.struct_gep(llresult, 1), None);
422                     } else {
423                         invalid_monomorphization(sty);
424                     }
425                     C_nil(ccx)
426                 }
427
428                 "load" => {
429                     let sty = &substs.type_at(0).sty;
430                     if int_type_width_signed(sty, ccx).is_some() {
431                         bcx.atomic_load(llargs[0], order)
432                     } else {
433                         invalid_monomorphization(sty);
434                         C_nil(ccx)
435                     }
436                 }
437
438                 "store" => {
439                     let sty = &substs.type_at(0).sty;
440                     if int_type_width_signed(sty, ccx).is_some() {
441                         bcx.atomic_store(llargs[1], llargs[0], order);
442                     } else {
443                         invalid_monomorphization(sty);
444                     }
445                     C_nil(ccx)
446                 }
447
448                 "fence" => {
449                     bcx.atomic_fence(order, llvm::SynchronizationScope::CrossThread);
450                     C_nil(ccx)
451                 }
452
453                 "singlethreadfence" => {
454                     bcx.atomic_fence(order, llvm::SynchronizationScope::SingleThread);
455                     C_nil(ccx)
456                 }
457
458                 // These are all AtomicRMW ops
459                 op => {
460                     let atom_op = match op {
461                         "xchg"  => llvm::AtomicXchg,
462                         "xadd"  => llvm::AtomicAdd,
463                         "xsub"  => llvm::AtomicSub,
464                         "and"   => llvm::AtomicAnd,
465                         "nand"  => llvm::AtomicNand,
466                         "or"    => llvm::AtomicOr,
467                         "xor"   => llvm::AtomicXor,
468                         "max"   => llvm::AtomicMax,
469                         "min"   => llvm::AtomicMin,
470                         "umax"  => llvm::AtomicUMax,
471                         "umin"  => llvm::AtomicUMin,
472                         _ => ccx.sess().fatal("unknown atomic operation")
473                     };
474
475                     let sty = &substs.type_at(0).sty;
476                     if int_type_width_signed(sty, ccx).is_some() {
477                         bcx.atomic_rmw(atom_op, llargs[0], llargs[1], order)
478                     } else {
479                         invalid_monomorphization(sty);
480                         C_nil(ccx)
481                     }
482                 }
483             }
484         }
485
486         _ => {
487             let intr = match Intrinsic::find(&name) {
488                 Some(intr) => intr,
489                 None => bug!("unknown intrinsic '{}'", name),
490             };
491             fn one<T>(x: Vec<T>) -> T {
492                 assert_eq!(x.len(), 1);
493                 x.into_iter().next().unwrap()
494             }
495             fn ty_to_type(ccx: &CrateContext, t: &intrinsics::Type,
496                           any_changes_needed: &mut bool) -> Vec<Type> {
497                 use intrinsics::Type::*;
498                 match *t {
499                     Void => vec![Type::void(ccx)],
500                     Integer(_signed, width, llvm_width) => {
501                         *any_changes_needed |= width != llvm_width;
502                         vec![Type::ix(ccx, llvm_width as u64)]
503                     }
504                     Float(x) => {
505                         match x {
506                             32 => vec![Type::f32(ccx)],
507                             64 => vec![Type::f64(ccx)],
508                             _ => bug!()
509                         }
510                     }
511                     Pointer(ref t, ref llvm_elem, _const) => {
512                         *any_changes_needed |= llvm_elem.is_some();
513
514                         let t = llvm_elem.as_ref().unwrap_or(t);
515                         let elem = one(ty_to_type(ccx, t, any_changes_needed));
516                         vec![elem.ptr_to()]
517                     }
518                     Vector(ref t, ref llvm_elem, length) => {
519                         *any_changes_needed |= llvm_elem.is_some();
520
521                         let t = llvm_elem.as_ref().unwrap_or(t);
522                         let elem = one(ty_to_type(ccx, t, any_changes_needed));
523                         vec![Type::vector(&elem, length as u64)]
524                     }
525                     Aggregate(false, ref contents) => {
526                         let elems = contents.iter()
527                                             .map(|t| one(ty_to_type(ccx, t, any_changes_needed)))
528                                             .collect::<Vec<_>>();
529                         vec![Type::struct_(ccx, &elems, false)]
530                     }
531                     Aggregate(true, ref contents) => {
532                         *any_changes_needed = true;
533                         contents.iter()
534                                 .flat_map(|t| ty_to_type(ccx, t, any_changes_needed))
535                                 .collect()
536                     }
537                 }
538             }
539
540             // This allows an argument list like `foo, (bar, baz),
541             // qux` to be converted into `foo, bar, baz, qux`, integer
542             // arguments to be truncated as needed and pointers to be
543             // cast.
544             fn modify_as_needed<'a, 'tcx>(bcx: &Builder<'a, 'tcx>,
545                                           t: &intrinsics::Type,
546                                           arg_type: Ty<'tcx>,
547                                           llarg: ValueRef)
548                                           -> Vec<ValueRef>
549             {
550                 match *t {
551                     intrinsics::Type::Aggregate(true, ref contents) => {
552                         // We found a tuple that needs squishing! So
553                         // run over the tuple and load each field.
554                         //
555                         // This assumes the type is "simple", i.e. no
556                         // destructors, and the contents are SIMD
557                         // etc.
558                         assert!(!bcx.ccx.shared().type_needs_drop(arg_type));
559                         let arg = LvalueRef::new_sized_ty(llarg, arg_type, Alignment::AbiAligned);
560                         (0..contents.len()).map(|i| {
561                             let (ptr, align) = arg.trans_field_ptr(bcx, i);
562                             bcx.load(ptr, align.to_align())
563                         }).collect()
564                     }
565                     intrinsics::Type::Pointer(_, Some(ref llvm_elem), _) => {
566                         let llvm_elem = one(ty_to_type(bcx.ccx, llvm_elem, &mut false));
567                         vec![bcx.pointercast(llarg, llvm_elem.ptr_to())]
568                     }
569                     intrinsics::Type::Vector(_, Some(ref llvm_elem), length) => {
570                         let llvm_elem = one(ty_to_type(bcx.ccx, llvm_elem, &mut false));
571                         vec![bcx.bitcast(llarg, Type::vector(&llvm_elem, length as u64))]
572                     }
573                     intrinsics::Type::Integer(_, width, llvm_width) if width != llvm_width => {
574                         // the LLVM intrinsic uses a smaller integer
575                         // size than the C intrinsic's signature, so
576                         // we have to trim it down here.
577                         vec![bcx.trunc(llarg, Type::ix(bcx.ccx, llvm_width as u64))]
578                     }
579                     _ => vec![llarg],
580                 }
581             }
582
583
584             let mut any_changes_needed = false;
585             let inputs = intr.inputs.iter()
586                                     .flat_map(|t| ty_to_type(ccx, t, &mut any_changes_needed))
587                                     .collect::<Vec<_>>();
588
589             let mut out_changes = false;
590             let outputs = one(ty_to_type(ccx, &intr.output, &mut out_changes));
591             // outputting a flattened aggregate is nonsense
592             assert!(!out_changes);
593
594             let llargs = if !any_changes_needed {
595                 // no aggregates to flatten, so no change needed
596                 llargs.to_vec()
597             } else {
598                 // there are some aggregates that need to be flattened
599                 // in the LLVM call, so we need to run over the types
600                 // again to find them and extract the arguments
601                 intr.inputs.iter()
602                            .zip(llargs)
603                            .zip(arg_tys)
604                            .flat_map(|((t, llarg), ty)| modify_as_needed(bcx, t, ty, *llarg))
605                            .collect()
606             };
607             assert_eq!(inputs.len(), llargs.len());
608
609             let val = match intr.definition {
610                 intrinsics::IntrinsicDef::Named(name) => {
611                     let f = declare::declare_cfn(ccx,
612                                                  name,
613                                                  Type::func(&inputs, &outputs));
614                     bcx.call(f, &llargs, None)
615                 }
616             };
617
618             match *intr.output {
619                 intrinsics::Type::Aggregate(flatten, ref elems) => {
620                     // the output is a tuple so we need to munge it properly
621                     assert!(!flatten);
622
623                     for i in 0..elems.len() {
624                         let val = bcx.extract_value(val, i);
625                         bcx.store(val, bcx.struct_gep(llresult, i), None);
626                     }
627                     C_nil(ccx)
628                 }
629                 _ => val,
630             }
631         }
632     };
633
634     if val_ty(llval) != Type::void(ccx) && machine::llsize_of_alloc(ccx, val_ty(llval)) != 0 {
635         if let Some(ty) = fn_ty.ret.cast {
636             let ptr = bcx.pointercast(llresult, ty.ptr_to());
637             bcx.store(llval, ptr, Some(ccx.align_of(ret_ty)));
638         } else {
639             store_ty(bcx, llval, llresult, Alignment::AbiAligned, ret_ty);
640         }
641     }
642 }
643
644 fn copy_intrinsic<'a, 'tcx>(bcx: &Builder<'a, 'tcx>,
645                             allow_overlap: bool,
646                             volatile: bool,
647                             tp_ty: Ty<'tcx>,
648                             dst: ValueRef,
649                             src: ValueRef,
650                             count: ValueRef)
651                             -> ValueRef {
652     let ccx = bcx.ccx;
653     let lltp_ty = type_of::type_of(ccx, tp_ty);
654     let align = C_i32(ccx, ccx.align_of(tp_ty) as i32);
655     let size = machine::llsize_of(ccx, lltp_ty);
656     let int_size = machine::llbitsize_of_real(ccx, ccx.int_type());
657
658     let operation = if allow_overlap {
659         "memmove"
660     } else {
661         "memcpy"
662     };
663
664     let name = format!("llvm.{}.p0i8.p0i8.i{}", operation, int_size);
665
666     let dst_ptr = bcx.pointercast(dst, Type::i8p(ccx));
667     let src_ptr = bcx.pointercast(src, Type::i8p(ccx));
668     let llfn = ccx.get_intrinsic(&name);
669
670     bcx.call(llfn,
671         &[dst_ptr,
672         src_ptr,
673         bcx.mul(size, count),
674         align,
675         C_bool(ccx, volatile)],
676         None)
677 }
678
679 fn memset_intrinsic<'a, 'tcx>(
680     bcx: &Builder<'a, 'tcx>,
681     volatile: bool,
682     ty: Ty<'tcx>,
683     dst: ValueRef,
684     val: ValueRef,
685     count: ValueRef
686 ) -> ValueRef {
687     let ccx = bcx.ccx;
688     let align = C_i32(ccx, ccx.align_of(ty) as i32);
689     let lltp_ty = type_of::type_of(ccx, ty);
690     let size = machine::llsize_of(ccx, lltp_ty);
691     let dst = bcx.pointercast(dst, Type::i8p(ccx));
692     call_memset(bcx, dst, val, bcx.mul(size, count), align, volatile)
693 }
694
695 fn try_intrinsic<'a, 'tcx>(
696     bcx: &Builder<'a, 'tcx>,
697     ccx: &CrateContext,
698     func: ValueRef,
699     data: ValueRef,
700     local_ptr: ValueRef,
701     dest: ValueRef,
702 ) {
703     if bcx.sess().no_landing_pads() {
704         bcx.call(func, &[data], None);
705         bcx.store(C_null(Type::i8p(&bcx.ccx)), dest, None);
706     } else if wants_msvc_seh(bcx.sess()) {
707         trans_msvc_try(bcx, ccx, func, data, local_ptr, dest);
708     } else {
709         trans_gnu_try(bcx, ccx, func, data, local_ptr, dest);
710     }
711 }
712
713 // MSVC's definition of the `rust_try` function.
714 //
715 // This implementation uses the new exception handling instructions in LLVM
716 // which have support in LLVM for SEH on MSVC targets. Although these
717 // instructions are meant to work for all targets, as of the time of this
718 // writing, however, LLVM does not recommend the usage of these new instructions
719 // as the old ones are still more optimized.
720 fn trans_msvc_try<'a, 'tcx>(bcx: &Builder<'a, 'tcx>,
721                             ccx: &CrateContext,
722                             func: ValueRef,
723                             data: ValueRef,
724                             local_ptr: ValueRef,
725                             dest: ValueRef) {
726     let llfn = get_rust_try_fn(ccx, &mut |bcx| {
727         let ccx = bcx.ccx;
728
729         bcx.set_personality_fn(bcx.ccx.eh_personality());
730
731         let normal = bcx.build_sibling_block("normal");
732         let catchswitch = bcx.build_sibling_block("catchswitch");
733         let catchpad = bcx.build_sibling_block("catchpad");
734         let caught = bcx.build_sibling_block("caught");
735
736         let func = llvm::get_param(bcx.llfn(), 0);
737         let data = llvm::get_param(bcx.llfn(), 1);
738         let local_ptr = llvm::get_param(bcx.llfn(), 2);
739
740         // We're generating an IR snippet that looks like:
741         //
742         //   declare i32 @rust_try(%func, %data, %ptr) {
743         //      %slot = alloca i64*
744         //      invoke %func(%data) to label %normal unwind label %catchswitch
745         //
746         //   normal:
747         //      ret i32 0
748         //
749         //   catchswitch:
750         //      %cs = catchswitch within none [%catchpad] unwind to caller
751         //
752         //   catchpad:
753         //      %tok = catchpad within %cs [%type_descriptor, 0, %slot]
754         //      %ptr[0] = %slot[0]
755         //      %ptr[1] = %slot[1]
756         //      catchret from %tok to label %caught
757         //
758         //   caught:
759         //      ret i32 1
760         //   }
761         //
762         // This structure follows the basic usage of throw/try/catch in LLVM.
763         // For example, compile this C++ snippet to see what LLVM generates:
764         //
765         //      #include <stdint.h>
766         //
767         //      int bar(void (*foo)(void), uint64_t *ret) {
768         //          try {
769         //              foo();
770         //              return 0;
771         //          } catch(uint64_t a[2]) {
772         //              ret[0] = a[0];
773         //              ret[1] = a[1];
774         //              return 1;
775         //          }
776         //      }
777         //
778         // More information can be found in libstd's seh.rs implementation.
779         let i64p = Type::i64(ccx).ptr_to();
780         let slot = bcx.alloca(i64p, "slot");
781         bcx.invoke(func, &[data], normal.llbb(), catchswitch.llbb(),
782             None);
783
784         normal.ret(C_i32(ccx, 0));
785
786         let cs = catchswitch.catch_switch(None, None, 1);
787         catchswitch.add_handler(cs, catchpad.llbb());
788
789         let tcx = ccx.tcx();
790         let tydesc = match tcx.lang_items.msvc_try_filter() {
791             Some(did) => ::consts::get_static(ccx, did),
792             None => bug!("msvc_try_filter not defined"),
793         };
794         let tok = catchpad.catch_pad(cs, &[tydesc, C_i32(ccx, 0), slot]);
795         let addr = catchpad.load(slot, None);
796         let arg1 = catchpad.load(addr, None);
797         let val1 = C_i32(ccx, 1);
798         let arg2 = catchpad.load(catchpad.inbounds_gep(addr, &[val1]), None);
799         let local_ptr = catchpad.bitcast(local_ptr, i64p);
800         catchpad.store(arg1, local_ptr, None);
801         catchpad.store(arg2, catchpad.inbounds_gep(local_ptr, &[val1]), None);
802         catchpad.catch_ret(tok, caught.llbb());
803
804         caught.ret(C_i32(ccx, 1));
805     });
806
807     // Note that no invoke is used here because by definition this function
808     // can't panic (that's what it's catching).
809     let ret = bcx.call(llfn, &[func, data, local_ptr], None);
810     bcx.store(ret, dest, None);
811 }
812
813 // Definition of the standard "try" function for Rust using the GNU-like model
814 // of exceptions (e.g. the normal semantics of LLVM's landingpad and invoke
815 // instructions).
816 //
817 // This translation is a little surprising because we always call a shim
818 // function instead of inlining the call to `invoke` manually here. This is done
819 // because in LLVM we're only allowed to have one personality per function
820 // definition. The call to the `try` intrinsic is being inlined into the
821 // function calling it, and that function may already have other personality
822 // functions in play. By calling a shim we're guaranteed that our shim will have
823 // the right personality function.
824 fn trans_gnu_try<'a, 'tcx>(bcx: &Builder<'a, 'tcx>,
825                            ccx: &CrateContext,
826                            func: ValueRef,
827                            data: ValueRef,
828                            local_ptr: ValueRef,
829                            dest: ValueRef) {
830     let llfn = get_rust_try_fn(ccx, &mut |bcx| {
831         let ccx = bcx.ccx;
832
833         // Translates the shims described above:
834         //
835         //   bcx:
836         //      invoke %func(%args...) normal %normal unwind %catch
837         //
838         //   normal:
839         //      ret 0
840         //
841         //   catch:
842         //      (ptr, _) = landingpad
843         //      store ptr, %local_ptr
844         //      ret 1
845         //
846         // Note that the `local_ptr` data passed into the `try` intrinsic is
847         // expected to be `*mut *mut u8` for this to actually work, but that's
848         // managed by the standard library.
849
850         let then = bcx.build_sibling_block("then");
851         let catch = bcx.build_sibling_block("catch");
852
853         let func = llvm::get_param(bcx.llfn(), 0);
854         let data = llvm::get_param(bcx.llfn(), 1);
855         let local_ptr = llvm::get_param(bcx.llfn(), 2);
856         bcx.invoke(func, &[data], then.llbb(), catch.llbb(), None);
857         then.ret(C_i32(ccx, 0));
858
859         // Type indicator for the exception being thrown.
860         //
861         // The first value in this tuple is a pointer to the exception object
862         // being thrown.  The second value is a "selector" indicating which of
863         // the landing pad clauses the exception's type had been matched to.
864         // rust_try ignores the selector.
865         let lpad_ty = Type::struct_(ccx, &[Type::i8p(ccx), Type::i32(ccx)],
866                                     false);
867         let vals = catch.landing_pad(lpad_ty, bcx.ccx.eh_personality(), 1, catch.llfn());
868         catch.add_clause(vals, C_null(Type::i8p(ccx)));
869         let ptr = catch.extract_value(vals, 0);
870         catch.store(ptr, catch.bitcast(local_ptr, Type::i8p(ccx).ptr_to()), None);
871         catch.ret(C_i32(ccx, 1));
872     });
873
874     // Note that no invoke is used here because by definition this function
875     // can't panic (that's what it's catching).
876     let ret = bcx.call(llfn, &[func, data, local_ptr], None);
877     bcx.store(ret, dest, None);
878 }
879
880 // Helper function to give a Block to a closure to translate a shim function.
881 // This is currently primarily used for the `try` intrinsic functions above.
882 fn gen_fn<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
883                     name: &str,
884                     inputs: Vec<Ty<'tcx>>,
885                     output: Ty<'tcx>,
886                     trans: &mut for<'b> FnMut(Builder<'b, 'tcx>))
887                     -> ValueRef {
888     let rust_fn_ty = ccx.tcx().mk_fn_ptr(ty::Binder(ccx.tcx().mk_fn_sig(
889         inputs.into_iter(),
890         output,
891         false,
892         hir::Unsafety::Unsafe,
893         Abi::Rust
894     )));
895     let llfn = declare::define_internal_fn(ccx, name, rust_fn_ty);
896     let bcx = Builder::new_block(ccx, llfn, "entry-block");
897     trans(bcx);
898     llfn
899 }
900
901 // Helper function used to get a handle to the `__rust_try` function used to
902 // catch exceptions.
903 //
904 // This function is only generated once and is then cached.
905 fn get_rust_try_fn<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
906                              trans: &mut for<'b> FnMut(Builder<'b, 'tcx>))
907                              -> ValueRef {
908     if let Some(llfn) = ccx.rust_try_fn().get() {
909         return llfn;
910     }
911
912     // Define the type up front for the signature of the rust_try function.
913     let tcx = ccx.tcx();
914     let i8p = tcx.mk_mut_ptr(tcx.types.i8);
915     let fn_ty = tcx.mk_fn_ptr(ty::Binder(tcx.mk_fn_sig(
916         iter::once(i8p),
917         tcx.mk_nil(),
918         false,
919         hir::Unsafety::Unsafe,
920         Abi::Rust
921     )));
922     let output = tcx.types.i32;
923     let rust_try = gen_fn(ccx, "__rust_try", vec![fn_ty, i8p, i8p], output, trans);
924     ccx.rust_try_fn().set(Some(rust_try));
925     return rust_try
926 }
927
928 fn span_invalid_monomorphization_error(a: &Session, b: Span, c: &str) {
929     span_err!(a, b, E0511, "{}", c);
930 }
931
932 fn generic_simd_intrinsic<'a, 'tcx>(
933     bcx: &Builder<'a, 'tcx>,
934     name: &str,
935     callee_ty: Ty<'tcx>,
936     llargs: &[ValueRef],
937     ret_ty: Ty<'tcx>,
938     llret_ty: Type,
939     span: Span
940 ) -> ValueRef {
941     // macros for error handling:
942     macro_rules! emit_error {
943         ($msg: tt) => {
944             emit_error!($msg, )
945         };
946         ($msg: tt, $($fmt: tt)*) => {
947             span_invalid_monomorphization_error(
948                 bcx.sess(), span,
949                 &format!(concat!("invalid monomorphization of `{}` intrinsic: ",
950                                  $msg),
951                          name, $($fmt)*));
952         }
953     }
954     macro_rules! require {
955         ($cond: expr, $($fmt: tt)*) => {
956             if !$cond {
957                 emit_error!($($fmt)*);
958                 return C_nil(bcx.ccx)
959             }
960         }
961     }
962     macro_rules! require_simd {
963         ($ty: expr, $position: expr) => {
964             require!($ty.is_simd(), "expected SIMD {} type, found non-SIMD `{}`", $position, $ty)
965         }
966     }
967
968
969
970     let tcx = bcx.tcx();
971     let sig = tcx.erase_late_bound_regions_and_normalize(&callee_ty.fn_sig());
972     let arg_tys = sig.inputs();
973
974     // every intrinsic takes a SIMD vector as its first argument
975     require_simd!(arg_tys[0], "input");
976     let in_ty = arg_tys[0];
977     let in_elem = arg_tys[0].simd_type(tcx);
978     let in_len = arg_tys[0].simd_size(tcx);
979
980     let comparison = match name {
981         "simd_eq" => Some(hir::BiEq),
982         "simd_ne" => Some(hir::BiNe),
983         "simd_lt" => Some(hir::BiLt),
984         "simd_le" => Some(hir::BiLe),
985         "simd_gt" => Some(hir::BiGt),
986         "simd_ge" => Some(hir::BiGe),
987         _ => None
988     };
989
990     if let Some(cmp_op) = comparison {
991         require_simd!(ret_ty, "return");
992
993         let out_len = ret_ty.simd_size(tcx);
994         require!(in_len == out_len,
995                  "expected return type with length {} (same as input type `{}`), \
996                   found `{}` with length {}",
997                  in_len, in_ty,
998                  ret_ty, out_len);
999         require!(llret_ty.element_type().kind() == llvm::Integer,
1000                  "expected return type with integer elements, found `{}` with non-integer `{}`",
1001                  ret_ty,
1002                  ret_ty.simd_type(tcx));
1003
1004         return compare_simd_types(bcx,
1005                                   llargs[0],
1006                                   llargs[1],
1007                                   in_elem,
1008                                   llret_ty,
1009                                   cmp_op)
1010     }
1011
1012     if name.starts_with("simd_shuffle") {
1013         let n: usize = match name["simd_shuffle".len()..].parse() {
1014             Ok(n) => n,
1015             Err(_) => span_bug!(span,
1016                                 "bad `simd_shuffle` instruction only caught in trans?")
1017         };
1018
1019         require_simd!(ret_ty, "return");
1020
1021         let out_len = ret_ty.simd_size(tcx);
1022         require!(out_len == n,
1023                  "expected return type of length {}, found `{}` with length {}",
1024                  n, ret_ty, out_len);
1025         require!(in_elem == ret_ty.simd_type(tcx),
1026                  "expected return element type `{}` (element of input `{}`), \
1027                   found `{}` with element type `{}`",
1028                  in_elem, in_ty,
1029                  ret_ty, ret_ty.simd_type(tcx));
1030
1031         let total_len = in_len as u128 * 2;
1032
1033         let vector = llargs[2];
1034
1035         let indices: Option<Vec<_>> = (0..n)
1036             .map(|i| {
1037                 let arg_idx = i;
1038                 let val = const_get_elt(vector, &[i as libc::c_uint]);
1039                 match const_to_opt_u128(val, true) {
1040                     None => {
1041                         emit_error!("shuffle index #{} is not a constant", arg_idx);
1042                         None
1043                     }
1044                     Some(idx) if idx >= total_len => {
1045                         emit_error!("shuffle index #{} is out of bounds (limit {})",
1046                                     arg_idx, total_len);
1047                         None
1048                     }
1049                     Some(idx) => Some(C_i32(bcx.ccx, idx as i32)),
1050                 }
1051             })
1052             .collect();
1053         let indices = match indices {
1054             Some(i) => i,
1055             None => return C_null(llret_ty)
1056         };
1057
1058         return bcx.shuffle_vector(llargs[0], llargs[1], C_vector(&indices))
1059     }
1060
1061     if name == "simd_insert" {
1062         require!(in_elem == arg_tys[2],
1063                  "expected inserted type `{}` (element of input `{}`), found `{}`",
1064                  in_elem, in_ty, arg_tys[2]);
1065         return bcx.insert_element(llargs[0], llargs[2], llargs[1])
1066     }
1067     if name == "simd_extract" {
1068         require!(ret_ty == in_elem,
1069                  "expected return type `{}` (element of input `{}`), found `{}`",
1070                  in_elem, in_ty, ret_ty);
1071         return bcx.extract_element(llargs[0], llargs[1])
1072     }
1073
1074     if name == "simd_cast" {
1075         require_simd!(ret_ty, "return");
1076         let out_len = ret_ty.simd_size(tcx);
1077         require!(in_len == out_len,
1078                  "expected return type with length {} (same as input type `{}`), \
1079                   found `{}` with length {}",
1080                  in_len, in_ty,
1081                  ret_ty, out_len);
1082         // casting cares about nominal type, not just structural type
1083         let out_elem = ret_ty.simd_type(tcx);
1084
1085         if in_elem == out_elem { return llargs[0]; }
1086
1087         enum Style { Float, Int(/* is signed? */ bool), Unsupported }
1088
1089         let (in_style, in_width) = match in_elem.sty {
1090             // vectors of pointer-sized integers should've been
1091             // disallowed before here, so this unwrap is safe.
1092             ty::TyInt(i) => (Style::Int(true), i.bit_width().unwrap()),
1093             ty::TyUint(u) => (Style::Int(false), u.bit_width().unwrap()),
1094             ty::TyFloat(f) => (Style::Float, f.bit_width()),
1095             _ => (Style::Unsupported, 0)
1096         };
1097         let (out_style, out_width) = match out_elem.sty {
1098             ty::TyInt(i) => (Style::Int(true), i.bit_width().unwrap()),
1099             ty::TyUint(u) => (Style::Int(false), u.bit_width().unwrap()),
1100             ty::TyFloat(f) => (Style::Float, f.bit_width()),
1101             _ => (Style::Unsupported, 0)
1102         };
1103
1104         match (in_style, out_style) {
1105             (Style::Int(in_is_signed), Style::Int(_)) => {
1106                 return match in_width.cmp(&out_width) {
1107                     Ordering::Greater => bcx.trunc(llargs[0], llret_ty),
1108                     Ordering::Equal => llargs[0],
1109                     Ordering::Less => if in_is_signed {
1110                         bcx.sext(llargs[0], llret_ty)
1111                     } else {
1112                         bcx.zext(llargs[0], llret_ty)
1113                     }
1114                 }
1115             }
1116             (Style::Int(in_is_signed), Style::Float) => {
1117                 return if in_is_signed {
1118                     bcx.sitofp(llargs[0], llret_ty)
1119                 } else {
1120                     bcx.uitofp(llargs[0], llret_ty)
1121                 }
1122             }
1123             (Style::Float, Style::Int(out_is_signed)) => {
1124                 return if out_is_signed {
1125                     bcx.fptosi(llargs[0], llret_ty)
1126                 } else {
1127                     bcx.fptoui(llargs[0], llret_ty)
1128                 }
1129             }
1130             (Style::Float, Style::Float) => {
1131                 return match in_width.cmp(&out_width) {
1132                     Ordering::Greater => bcx.fptrunc(llargs[0], llret_ty),
1133                     Ordering::Equal => llargs[0],
1134                     Ordering::Less => bcx.fpext(llargs[0], llret_ty)
1135                 }
1136             }
1137             _ => {/* Unsupported. Fallthrough. */}
1138         }
1139         require!(false,
1140                  "unsupported cast from `{}` with element `{}` to `{}` with element `{}`",
1141                  in_ty, in_elem,
1142                  ret_ty, out_elem);
1143     }
1144     macro_rules! arith {
1145         ($($name: ident: $($($p: ident),* => $call: ident),*;)*) => {
1146             $(
1147                 if name == stringify!($name) {
1148                     match in_elem.sty {
1149                         $(
1150                             $(ty::$p(_))|* => {
1151                                 return bcx.$call(llargs[0], llargs[1])
1152                             }
1153                             )*
1154                         _ => {},
1155                     }
1156                     require!(false,
1157                              "unsupported operation on `{}` with element `{}`",
1158                              in_ty,
1159                              in_elem)
1160                 })*
1161         }
1162     }
1163     arith! {
1164         simd_add: TyUint, TyInt => add, TyFloat => fadd;
1165         simd_sub: TyUint, TyInt => sub, TyFloat => fsub;
1166         simd_mul: TyUint, TyInt => mul, TyFloat => fmul;
1167         simd_div: TyFloat => fdiv;
1168         simd_shl: TyUint, TyInt => shl;
1169         simd_shr: TyUint => lshr, TyInt => ashr;
1170         simd_and: TyUint, TyInt => and;
1171         simd_or: TyUint, TyInt => or;
1172         simd_xor: TyUint, TyInt => xor;
1173     }
1174     span_bug!(span, "unknown SIMD intrinsic");
1175 }
1176
1177 // Returns the width of an int TypeVariant, and if it's signed or not
1178 // Returns None if the type is not an integer
1179 // FIXME: there’s multiple of this functions, investigate using some of the already existing
1180 // stuffs.
1181 fn int_type_width_signed<'tcx>(sty: &ty::TypeVariants<'tcx>, ccx: &CrateContext)
1182         -> Option<(u64, bool)> {
1183     use rustc::ty::{TyInt, TyUint};
1184     match *sty {
1185         TyInt(t) => Some((match t {
1186             ast::IntTy::Is => {
1187                 match &ccx.tcx().sess.target.target.target_pointer_width[..] {
1188                     "16" => 16,
1189                     "32" => 32,
1190                     "64" => 64,
1191                     tws => bug!("Unsupported target word size for isize: {}", tws),
1192                 }
1193             },
1194             ast::IntTy::I8 => 8,
1195             ast::IntTy::I16 => 16,
1196             ast::IntTy::I32 => 32,
1197             ast::IntTy::I64 => 64,
1198             ast::IntTy::I128 => 128,
1199         }, true)),
1200         TyUint(t) => Some((match t {
1201             ast::UintTy::Us => {
1202                 match &ccx.tcx().sess.target.target.target_pointer_width[..] {
1203                     "16" => 16,
1204                     "32" => 32,
1205                     "64" => 64,
1206                     tws => bug!("Unsupported target word size for usize: {}", tws),
1207                 }
1208             },
1209             ast::UintTy::U8 => 8,
1210             ast::UintTy::U16 => 16,
1211             ast::UintTy::U32 => 32,
1212             ast::UintTy::U64 => 64,
1213             ast::UintTy::U128 => 128,
1214         }, false)),
1215         _ => None,
1216     }
1217 }
1218
1219 // Returns the width of a float TypeVariant
1220 // Returns None if the type is not a float
1221 fn float_type_width<'tcx>(sty: &ty::TypeVariants<'tcx>)
1222         -> Option<u64> {
1223     use rustc::ty::TyFloat;
1224     match *sty {
1225         TyFloat(t) => Some(match t {
1226             ast::FloatTy::F32 => 32,
1227             ast::FloatTy::F64 => 64,
1228         }),
1229         _ => None,
1230     }
1231 }