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